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(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>(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(LookupRD, cast<Decl>(FoundRD->getParent()))) {
150 Diag(NameLoc,
151 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(TD, 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(&II)) {
210 if (!isa<TypeDecl>(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(NameLoc, 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(RD)));
258 QualType T =
259 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS: 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(QualifiedLoc, diag_compat::implicit_typename)
353 << NestedNameSpecifier::Create(Context, SS->getScopeRep(), &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 PDiag(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(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(IDecl, 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(UD, NameLoc);
549 // Recover with 'int'
550 return ParsedType::make(P: Context.IntTy);
551 } else if (AllowDeducedTemplate) {
552 if (auto *TD = getAsTypeTemplateDecl(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, nullptr,
586 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(NameLoc, 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, nullptr, RD->getTypeForDecl());
629
630 // Diagnose that this identifier was undeclared, and retry the lookup during
631 // template instantiation.
632 Diag(NameLoc, 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(Corrected,
721 PDiag(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(Corrected,
729 PDiag(IsTemplateName ? diag::err_no_template_suggest
730 : diag::err_unknown_typename_suggest)
731 << II, 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(Corrected,
737 PDiag(IsTemplateName
738 ? diag::err_no_member_template_suggest
739 : diag::err_unknown_nested_typename_suggest)
740 << II << DC << DroppedSpecifier << SS->getRange(),
741 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(IILoc, IsTemplateName ? diag::err_no_template
783 : diag::err_unknown_typename)
784 << II;
785 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
786 Diag(IILoc, 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(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(NameLoc, diag::err_use_of_tag_name_without_tag)
858 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
859 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
860
861 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
862 I != IEnd; ++I)
863 SemaRef.Diag((*I)->getLocation(), 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(Corrected, PDiag(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(Corrected, PDiag(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(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(Type, 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(Class, 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(EmptyD, 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(K1: tok::amp, K2: 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(Type, 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(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(*I, 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(Param);
1465 IdResolver.AddDecl(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(*I) && D->declarationReplaces(OldD: *I)) {
1544 S->RemoveDecl(*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(*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(New->getLocation(), diag::err_mismatched_owning_module)
1659 << New
1660 << NewIsModuleInterface
1661 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1662 << OldIsModuleInterface
1663 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1664 Diag(Old->getLocation(), 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(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1714 Diag(Old->getLocation(), 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(*this, FD->getLocation()))
1872 return false;
1873 }
1874
1875 if (FD->doesThisDeclarationHaveABody() &&
1876 Context.DeclMustBeEmitted(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(*this, VD->getLocation()))
1883 return false;
1884
1885 if (Context.DeclMustBeEmitted(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(*this, 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(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(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>(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>(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 CharSourceRange::getCharRange(D->getBeginLoc(), 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>(TmpD))
2078 DiagnoseUnusedDecl(T, DiagReceiver);
2079 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2080 DiagnoseUnusedNestedTypedefs(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>(D) && cast<VarDecl>(D)->isExceptionVariable())
2105 DiagID = diag::warn_unused_exception_param;
2106 else if (isa<LabelDecl>(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(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>(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(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(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(D.Loc, D.PD);
2273 if (D.PreviousDeclLoc)
2274 Diag(*D.PreviousDeclLoc, 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(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(BuiltinAttr::CreateImplicit(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 Context, New, SourceLocation(), SourceLocation(), nullptr,
2336 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, 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, 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, diag::warn_implicit_decl_requires_sysheader)
2375 << getHeaderName(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, 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, 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(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(New, 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(New->getLocation(), 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(New->getLocation(), 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(New->getLocation(), 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(OldTag, &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, 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(New->getLocation(), 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(New->getLocation(), 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(ECD);
2653 IdResolver.RemoveDecl(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>(A);
2662 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2663 for (const auto *i : D->attrs())
2664 if (i->getKind() == A->getKind()) {
2665 if (Ann) {
2666 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2667 return true;
2668 continue;
2669 }
2670 // FIXME: Don't hardcode this check
2671 if (OA && isa<OwnershipAttr>(i))
2672 return OA->getOwnKind() == cast<OwnershipAttr>(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(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(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(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2755 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2756 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2757 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2758 }
2759 }
2760
2761 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(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(New->getLocation(), diag::err_alignas_missing_on_definition)
2771 << OldAlignasAttr;
2772 S.Diag(OldAlignasAttr->getLocation(), 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(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(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, 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>(Attr))
2819 NewAttr = S.mergeAvailabilityAttr(
2820 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2821 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2822 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2823 AA->getPriority(), AA->getEnvironment());
2824 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2825 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2826 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2827 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2828 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2829 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2830 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2831 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2832 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2833 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2834 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2835 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2836 FA->getFirstArg());
2837 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2838 NewAttr = S.mergeFormatMatchesAttr(
2839 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2840 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2841 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2842 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2843 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2844 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2845 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2846 IA->getInheritanceModel());
2847 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2848 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2849 &S.Context.Idents.get(AA->getSpelling()));
2850 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2851 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2852 isa<CUDAGlobalAttr>(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>(Attr))
2857 NewAttr = S.mergeMinSizeAttr(D, *MA);
2858 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2859 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2860 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2861 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2862 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2863 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2864 else if (isa<AlignedAttr>(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>(Attr) || isa<UnavailableAttr>(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>(Attr))
2874 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2875 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2876 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2877 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2878 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2879 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2880 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2881 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2882 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2883 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2884 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2885 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2886 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2887 NT->getZ());
2888 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2889 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2890 WS->getPreferred(),
2891 WS->getSpelledArgsCount());
2892 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2893 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2894 else if (isa<SuppressAttr>(Attr))
2895 // Do nothing. Each redeclaration should be suppressed separately.
2896 NewAttr = nullptr;
2897 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2898 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2899 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2900 NewAttr = cast<InheritableAttr>(Attr->clone(C&: S.Context));
2901
2902 if (NewAttr) {
2903 NewAttr->setInherited(true);
2904 D->addAttr(NewAttr);
2905 if (isa<MSInheritanceAttr>(NewAttr))
2906 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(D));
2907 return true;
2908 }
2909
2910 return false;
2911}
2912
2913static const NamedDecl *getDefinition(const Decl *D) {
2914 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2915 return TD->getDefinition();
2916 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2917 const VarDecl *Def = VD->getDefinition();
2918 if (Def)
2919 return Def;
2920 return VD->getActingDefinition();
2921 }
2922 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2923 const FunctionDecl *Def = nullptr;
2924 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
2925 return Def;
2926 }
2927 return nullptr;
2928}
2929
2930static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2931 for (const auto *Attribute : D->attrs())
2932 if (Attribute->getKind() == Kind)
2933 return true;
2934 return false;
2935}
2936
2937/// checkNewAttributesAfterDef - If we already have a definition, check that
2938/// there are no new attributes in this declaration.
2939static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2940 if (!New->hasAttrs())
2941 return;
2942
2943 const NamedDecl *Def = getDefinition(D: Old);
2944 if (!Def || Def == New)
2945 return;
2946
2947 AttrVec &NewAttributes = New->getAttrs();
2948 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2949 Attr *NewAttribute = NewAttributes[I];
2950
2951 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2952 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
2953 SkipBodyInfo SkipBody;
2954 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
2955
2956 // If we're skipping this definition, drop the "alias" attribute.
2957 if (SkipBody.ShouldSkip) {
2958 NewAttributes.erase(CI: NewAttributes.begin() + I);
2959 --E;
2960 continue;
2961 }
2962 } else {
2963 VarDecl *VD = cast<VarDecl>(Val: New);
2964 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2965 VarDecl::TentativeDefinition
2966 ? diag::err_alias_after_tentative
2967 : diag::err_redefinition;
2968 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2969 if (Diag == diag::err_redefinition)
2970 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
2971 else
2972 S.Diag(Def->getLocation(), diag::note_previous_definition);
2973 VD->setInvalidDecl();
2974 }
2975 ++I;
2976 continue;
2977 }
2978
2979 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
2980 // Tentative definitions are only interesting for the alias check above.
2981 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2982 ++I;
2983 continue;
2984 }
2985 }
2986
2987 if (hasAttribute(Def, NewAttribute->getKind())) {
2988 ++I;
2989 continue; // regular attr merging will take care of validating this.
2990 }
2991
2992 if (isa<C11NoReturnAttr>(NewAttribute)) {
2993 // C's _Noreturn is allowed to be added to a function after it is defined.
2994 ++I;
2995 continue;
2996 } else if (isa<UuidAttr>(NewAttribute)) {
2997 // msvc will allow a subsequent definition to add an uuid to a class
2998 ++I;
2999 continue;
3000 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3001 NewAttribute) &&
3002 NewAttribute->isStandardAttributeSyntax()) {
3003 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3004 // deprecated attribute can later be re-declared with the attribute and
3005 // vice-versa.
3006 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3007 // maybe_unused attribute can later be redeclared with the attribute and
3008 // vice versa.
3009 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3010 // nodiscard attribute can later be redeclared with the attribute and
3011 // vice-versa.
3012 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3013 ++I;
3014 continue;
3015 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3016 if (AA->isAlignas()) {
3017 // C++11 [dcl.align]p6:
3018 // if any declaration of an entity has an alignment-specifier,
3019 // every defining declaration of that entity shall specify an
3020 // equivalent alignment.
3021 // C11 6.7.5/7:
3022 // If the definition of an object does not have an alignment
3023 // specifier, any other declaration of that object shall also
3024 // have no alignment specifier.
3025 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3026 << AA;
3027 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3028 << AA;
3029 NewAttributes.erase(CI: NewAttributes.begin() + I);
3030 --E;
3031 continue;
3032 }
3033 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3034 // If there is a C definition followed by a redeclaration with this
3035 // attribute then there are two different definitions. In C++, prefer the
3036 // standard diagnostics.
3037 if (!S.getLangOpts().CPlusPlus) {
3038 S.Diag(NewAttribute->getLocation(),
3039 diag::err_loader_uninitialized_redeclaration);
3040 S.Diag(Def->getLocation(), diag::note_previous_definition);
3041 NewAttributes.erase(CI: NewAttributes.begin() + I);
3042 --E;
3043 continue;
3044 }
3045 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3046 cast<VarDecl>(New)->isInline() &&
3047 !cast<VarDecl>(New)->isInlineSpecified()) {
3048 // Don't warn about applying selectany to implicitly inline variables.
3049 // Older compilers and language modes would require the use of selectany
3050 // to make such variables inline, and it would have no effect if we
3051 // honored it.
3052 ++I;
3053 continue;
3054 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3055 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3056 // declarations after definitions.
3057 ++I;
3058 continue;
3059 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3060 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3061 // error since the definition will have already been created without
3062 // the semantic effects of the attribute having been applied.
3063 S.Diag(NewAttribute->getLocation(),
3064 diag::err_sycl_entry_point_after_definition);
3065 S.Diag(Def->getLocation(), diag::note_previous_definition);
3066 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3067 ++I;
3068 continue;
3069 }
3070
3071 S.Diag(NewAttribute->getLocation(),
3072 diag::warn_attribute_precede_definition);
3073 S.Diag(Def->getLocation(), diag::note_previous_definition);
3074 NewAttributes.erase(CI: NewAttributes.begin() + I);
3075 --E;
3076 }
3077}
3078
3079static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3080 const ConstInitAttr *CIAttr,
3081 bool AttrBeforeInit) {
3082 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3083
3084 // Figure out a good way to write this specifier on the old declaration.
3085 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3086 // enough of the attribute list spelling information to extract that without
3087 // heroics.
3088 std::string SuitableSpelling;
3089 if (S.getLangOpts().CPlusPlus20)
3090 SuitableSpelling = std::string(
3091 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3092 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3093 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3094 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3095 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3096 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3097 tok::r_square, tok::r_square}));
3098 if (SuitableSpelling.empty())
3099 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3100 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3101 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3102 tok::r_paren, tok::r_paren}));
3103 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3104 SuitableSpelling = "constinit";
3105 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3106 SuitableSpelling = "[[clang::require_constant_initialization]]";
3107 if (SuitableSpelling.empty())
3108 SuitableSpelling = "__attribute__((require_constant_initialization))";
3109 SuitableSpelling += " ";
3110
3111 if (AttrBeforeInit) {
3112 // extern constinit int a;
3113 // int a = 0; // error (missing 'constinit'), accepted as extension
3114 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3115 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3116 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3117 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3118 } else {
3119 // int a = 0;
3120 // constinit extern int a; // error (missing 'constinit')
3121 S.Diag(CIAttr->getLocation(),
3122 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3123 : diag::warn_require_const_init_added_too_late)
3124 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3125 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3126 << CIAttr->isConstinit()
3127 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3128 }
3129}
3130
3131void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3132 AvailabilityMergeKind AMK) {
3133 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3134 UsedAttr *NewAttr = OldAttr->clone(Context);
3135 NewAttr->setInherited(true);
3136 New->addAttr(A: NewAttr);
3137 }
3138 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3139 RetainAttr *NewAttr = OldAttr->clone(Context);
3140 NewAttr->setInherited(true);
3141 New->addAttr(A: NewAttr);
3142 }
3143
3144 if (!Old->hasAttrs() && !New->hasAttrs())
3145 return;
3146
3147 // [dcl.constinit]p1:
3148 // If the [constinit] specifier is applied to any declaration of a
3149 // variable, it shall be applied to the initializing declaration.
3150 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3151 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3152 if (bool(OldConstInit) != bool(NewConstInit)) {
3153 const auto *OldVD = cast<VarDecl>(Val: Old);
3154 auto *NewVD = cast<VarDecl>(Val: New);
3155
3156 // Find the initializing declaration. Note that we might not have linked
3157 // the new declaration into the redeclaration chain yet.
3158 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3159 if (!InitDecl &&
3160 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3161 InitDecl = NewVD;
3162
3163 if (InitDecl == NewVD) {
3164 // This is the initializing declaration. If it would inherit 'constinit',
3165 // that's ill-formed. (Note that we do not apply this to the attribute
3166 // form).
3167 if (OldConstInit && OldConstInit->isConstinit())
3168 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3169 /*AttrBeforeInit=*/true);
3170 } else if (NewConstInit) {
3171 // This is the first time we've been told that this declaration should
3172 // have a constant initializer. If we already saw the initializing
3173 // declaration, this is too late.
3174 if (InitDecl && InitDecl != NewVD) {
3175 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3176 /*AttrBeforeInit=*/false);
3177 NewVD->dropAttr<ConstInitAttr>();
3178 }
3179 }
3180 }
3181
3182 // Attributes declared post-definition are currently ignored.
3183 checkNewAttributesAfterDef(*this, New, Old);
3184
3185 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3186 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3187 if (!OldA->isEquivalent(NewA)) {
3188 // This redeclaration changes __asm__ label.
3189 Diag(New->getLocation(), diag::err_different_asm_label);
3190 Diag(OldA->getLocation(), diag::note_previous_declaration);
3191 }
3192 } else if (Old->isUsed()) {
3193 // This redeclaration adds an __asm__ label to a declaration that has
3194 // already been ODR-used.
3195 Diag(New->getLocation(), diag::err_late_asm_label_name)
3196 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3197 }
3198 }
3199
3200 // Re-declaration cannot add abi_tag's.
3201 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3202 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3203 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3204 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3205 Diag(NewAbiTagAttr->getLocation(),
3206 diag::err_new_abi_tag_on_redeclaration)
3207 << NewTag;
3208 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3209 }
3210 }
3211 } else {
3212 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3213 Diag(Old->getLocation(), diag::note_previous_declaration);
3214 }
3215 }
3216
3217 // This redeclaration adds a section attribute.
3218 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3219 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3220 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3221 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3222 Diag(Old->getLocation(), diag::note_previous_declaration);
3223 }
3224 }
3225 }
3226
3227 // Redeclaration adds code-seg attribute.
3228 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3229 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3230 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3231 Diag(New->getLocation(), diag::warn_mismatched_section)
3232 << 0 /*codeseg*/;
3233 Diag(Old->getLocation(), diag::note_previous_declaration);
3234 }
3235
3236 if (!Old->hasAttrs())
3237 return;
3238
3239 bool foundAny = New->hasAttrs();
3240
3241 // Ensure that any moving of objects within the allocated map is done before
3242 // we process them.
3243 if (!foundAny) New->setAttrs(AttrVec());
3244
3245 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3246 // Ignore deprecated/unavailable/availability attributes if requested.
3247 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3248 if (isa<DeprecatedAttr>(I) ||
3249 isa<UnavailableAttr>(I) ||
3250 isa<AvailabilityAttr>(I)) {
3251 switch (AMK) {
3252 case AvailabilityMergeKind::None:
3253 continue;
3254
3255 case AvailabilityMergeKind::Redeclaration:
3256 case AvailabilityMergeKind::Override:
3257 case AvailabilityMergeKind::ProtocolImplementation:
3258 case AvailabilityMergeKind::OptionalProtocolImplementation:
3259 LocalAMK = AMK;
3260 break;
3261 }
3262 }
3263
3264 // Already handled.
3265 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3266 continue;
3267
3268 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3269 foundAny = true;
3270 }
3271
3272 if (mergeAlignedAttrs(S&: *this, New, Old))
3273 foundAny = true;
3274
3275 if (!foundAny) New->dropAttrs();
3276}
3277
3278// Returns the number of added attributes.
3279template <class T>
3280static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3281 Sema &S) {
3282 unsigned found = 0;
3283 for (const auto *I : From->specific_attrs<T>()) {
3284 if (!DeclHasAttr(To, I)) {
3285 T *newAttr = cast<T>(I->clone(S.Context));
3286 newAttr->setInherited(true);
3287 To->addAttr(A: newAttr);
3288 ++found;
3289 }
3290 }
3291 return found;
3292}
3293
3294template <class F>
3295static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3296 F &&propagator) {
3297 if (!From->hasAttrs()) {
3298 return;
3299 }
3300
3301 bool foundAny = To->hasAttrs();
3302
3303 // Ensure that any moving of objects within the allocated map is
3304 // done before we process them.
3305 if (!foundAny)
3306 To->setAttrs(AttrVec());
3307
3308 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3309
3310 if (!foundAny)
3311 To->dropAttrs();
3312}
3313
3314/// mergeParamDeclAttributes - Copy attributes from the old parameter
3315/// to the new one.
3316static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3317 const ParmVarDecl *oldDecl,
3318 Sema &S) {
3319 // C++11 [dcl.attr.depend]p2:
3320 // The first declaration of a function shall specify the
3321 // carries_dependency attribute for its declarator-id if any declaration
3322 // of the function specifies the carries_dependency attribute.
3323 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3324 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3325 S.Diag(CDA->getLocation(),
3326 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3327 // Find the first declaration of the parameter.
3328 // FIXME: Should we build redeclaration chains for function parameters?
3329 const FunctionDecl *FirstFD =
3330 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3331 const ParmVarDecl *FirstVD =
3332 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3333 S.Diag(FirstVD->getLocation(),
3334 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3335 }
3336
3337 propagateAttributes(
3338 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3339 unsigned found = 0;
3340 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3341 // Propagate the lifetimebound attribute from parameters to the
3342 // most recent declaration. Note that this doesn't include the implicit
3343 // 'this' parameter, as the attribute is applied to the function type in
3344 // that case.
3345 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3346 return found;
3347 });
3348}
3349
3350static bool EquivalentArrayTypes(QualType Old, QualType New,
3351 const ASTContext &Ctx) {
3352
3353 auto NoSizeInfo = [&Ctx](QualType Ty) {
3354 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3355 return true;
3356 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3357 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3358 return false;
3359 };
3360
3361 // `type[]` is equivalent to `type *` and `type[*]`.
3362 if (NoSizeInfo(Old) && NoSizeInfo(New))
3363 return true;
3364
3365 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3366 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3367 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3368 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3369 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3370 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3371 return false;
3372 return true;
3373 }
3374
3375 // Only compare size, ignore Size modifiers and CVR.
3376 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3377 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3378 Ctx.getAsConstantArrayType(T: New)->getSize();
3379 }
3380
3381 // Don't try to compare dependent sized array
3382 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3383 return true;
3384 }
3385
3386 return Old == New;
3387}
3388
3389static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3390 const ParmVarDecl *OldParam,
3391 Sema &S) {
3392 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3393 if (auto Newnullability = NewParam->getType()->getNullability()) {
3394 if (*Oldnullability != *Newnullability) {
3395 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3396 << DiagNullabilityKind(
3397 *Newnullability,
3398 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3399 != 0))
3400 << DiagNullabilityKind(
3401 *Oldnullability,
3402 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3403 != 0));
3404 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3405 }
3406 } else {
3407 QualType NewT = NewParam->getType();
3408 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3409 NewParam->setType(NewT);
3410 }
3411 }
3412 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3413 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3414 if (OldParamDT && NewParamDT &&
3415 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3416 QualType OldParamOT = OldParamDT->getOriginalType();
3417 QualType NewParamOT = NewParamDT->getOriginalType();
3418 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3419 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3420 << NewParam << NewParamOT;
3421 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3422 << OldParamOT;
3423 }
3424 }
3425}
3426
3427namespace {
3428
3429/// Used in MergeFunctionDecl to keep track of function parameters in
3430/// C.
3431struct GNUCompatibleParamWarning {
3432 ParmVarDecl *OldParm;
3433 ParmVarDecl *NewParm;
3434 QualType PromotedType;
3435};
3436
3437} // end anonymous namespace
3438
3439// Determine whether the previous declaration was a definition, implicit
3440// declaration, or a declaration.
3441template <typename T>
3442static std::pair<diag::kind, SourceLocation>
3443getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3444 diag::kind PrevDiag;
3445 SourceLocation OldLocation = Old->getLocation();
3446 if (Old->isThisDeclarationADefinition())
3447 PrevDiag = diag::note_previous_definition;
3448 else if (Old->isImplicit()) {
3449 PrevDiag = diag::note_previous_implicit_declaration;
3450 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3451 if (FD->getBuiltinID())
3452 PrevDiag = diag::note_previous_builtin_declaration;
3453 }
3454 if (OldLocation.isInvalid())
3455 OldLocation = New->getLocation();
3456 } else
3457 PrevDiag = diag::note_previous_declaration;
3458 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3459}
3460
3461/// canRedefineFunction - checks if a function can be redefined. Currently,
3462/// only extern inline functions can be redefined, and even then only in
3463/// GNU89 mode.
3464static bool canRedefineFunction(const FunctionDecl *FD,
3465 const LangOptions& LangOpts) {
3466 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3467 !LangOpts.CPlusPlus &&
3468 FD->isInlineSpecified() &&
3469 FD->getStorageClass() == SC_Extern);
3470}
3471
3472const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3473 const AttributedType *AT = T->getAs<AttributedType>();
3474 while (AT && !AT->isCallingConv())
3475 AT = AT->getModifiedType()->getAs<AttributedType>();
3476 return AT;
3477}
3478
3479template <typename T>
3480static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3481 const DeclContext *DC = Old->getDeclContext();
3482 if (DC->isRecord())
3483 return false;
3484
3485 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3486 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3487 return true;
3488 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3489 return true;
3490 return false;
3491}
3492
3493template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3494static bool isExternC(VarTemplateDecl *) { return false; }
3495static bool isExternC(FunctionTemplateDecl *) { return false; }
3496
3497/// Check whether a redeclaration of an entity introduced by a
3498/// using-declaration is valid, given that we know it's not an overload
3499/// (nor a hidden tag declaration).
3500template<typename ExpectedDecl>
3501static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3502 ExpectedDecl *New) {
3503 // C++11 [basic.scope.declarative]p4:
3504 // Given a set of declarations in a single declarative region, each of
3505 // which specifies the same unqualified name,
3506 // -- they shall all refer to the same entity, or all refer to functions
3507 // and function templates; or
3508 // -- exactly one declaration shall declare a class name or enumeration
3509 // name that is not a typedef name and the other declarations shall all
3510 // refer to the same variable or enumerator, or all refer to functions
3511 // and function templates; in this case the class name or enumeration
3512 // name is hidden (3.3.10).
3513
3514 // C++11 [namespace.udecl]p14:
3515 // If a function declaration in namespace scope or block scope has the
3516 // same name and the same parameter-type-list as a function introduced
3517 // by a using-declaration, and the declarations do not declare the same
3518 // function, the program is ill-formed.
3519
3520 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3521 if (Old &&
3522 !Old->getDeclContext()->getRedeclContext()->Equals(
3523 New->getDeclContext()->getRedeclContext()) &&
3524 !(isExternC(Old) && isExternC(New)))
3525 Old = nullptr;
3526
3527 if (!Old) {
3528 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3529 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3530 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3531 return true;
3532 }
3533 return false;
3534}
3535
3536static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3537 const FunctionDecl *B) {
3538 assert(A->getNumParams() == B->getNumParams());
3539
3540 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3541 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3542 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3543 if (AttrA == AttrB)
3544 return true;
3545 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3546 AttrA->isDynamic() == AttrB->isDynamic();
3547 };
3548
3549 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3550}
3551
3552/// If necessary, adjust the semantic declaration context for a qualified
3553/// declaration to name the correct inline namespace within the qualifier.
3554static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3555 DeclaratorDecl *OldD) {
3556 // The only case where we need to update the DeclContext is when
3557 // redeclaration lookup for a qualified name finds a declaration
3558 // in an inline namespace within the context named by the qualifier:
3559 //
3560 // inline namespace N { int f(); }
3561 // int ::f(); // Sema DC needs adjusting from :: to N::.
3562 //
3563 // For unqualified declarations, the semantic context *can* change
3564 // along the redeclaration chain (for local extern declarations,
3565 // extern "C" declarations, and friend declarations in particular).
3566 if (!NewD->getQualifier())
3567 return;
3568
3569 // NewD is probably already in the right context.
3570 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3571 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3572 if (NamedDC->Equals(SemaDC))
3573 return;
3574
3575 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3576 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3577 "unexpected context for redeclaration");
3578
3579 auto *LexDC = NewD->getLexicalDeclContext();
3580 auto FixSemaDC = [=](NamedDecl *D) {
3581 if (!D)
3582 return;
3583 D->setDeclContext(SemaDC);
3584 D->setLexicalDeclContext(LexDC);
3585 };
3586
3587 FixSemaDC(NewD);
3588 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3589 FixSemaDC(FD->getDescribedFunctionTemplate());
3590 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3591 FixSemaDC(VD->getDescribedVarTemplate());
3592}
3593
3594bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3595 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3596 // Verify the old decl was also a function.
3597 FunctionDecl *Old = OldD->getAsFunction();
3598 if (!Old) {
3599 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3600 if (New->getFriendObjectKind()) {
3601 Diag(New->getLocation(), diag::err_using_decl_friend);
3602 Diag(Shadow->getTargetDecl()->getLocation(),
3603 diag::note_using_decl_target);
3604 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3605 << 0;
3606 return true;
3607 }
3608
3609 // Check whether the two declarations might declare the same function or
3610 // function template.
3611 if (FunctionTemplateDecl *NewTemplate =
3612 New->getDescribedFunctionTemplate()) {
3613 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3614 New: NewTemplate))
3615 return true;
3616 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3617 ->getAsFunction();
3618 } else {
3619 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3620 return true;
3621 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3622 }
3623 } else {
3624 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3625 << New->getDeclName();
3626 notePreviousDefinition(Old: OldD, New: New->getLocation());
3627 return true;
3628 }
3629 }
3630
3631 // If the old declaration was found in an inline namespace and the new
3632 // declaration was qualified, update the DeclContext to match.
3633 adjustDeclContextForDeclaratorDecl(New, Old);
3634
3635 // If the old declaration is invalid, just give up here.
3636 if (Old->isInvalidDecl())
3637 return true;
3638
3639 // Disallow redeclaration of some builtins.
3640 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3641 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3642 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3643 << Old << Old->getType();
3644 return true;
3645 }
3646
3647 diag::kind PrevDiag;
3648 SourceLocation OldLocation;
3649 std::tie(args&: PrevDiag, args&: OldLocation) =
3650 getNoteDiagForInvalidRedeclaration(Old, New);
3651
3652 // Don't complain about this if we're in GNU89 mode and the old function
3653 // is an extern inline function.
3654 // Don't complain about specializations. They are not supposed to have
3655 // storage classes.
3656 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3657 New->getStorageClass() == SC_Static &&
3658 Old->hasExternalFormalLinkage() &&
3659 !New->getTemplateSpecializationInfo() &&
3660 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3661 if (getLangOpts().MicrosoftExt) {
3662 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3663 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3664 } else {
3665 Diag(New->getLocation(), diag::err_static_non_static) << New;
3666 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3667 return true;
3668 }
3669 }
3670
3671 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3672 if (!Old->hasAttr<InternalLinkageAttr>()) {
3673 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3674 << ILA;
3675 Diag(Old->getLocation(), diag::note_previous_declaration);
3676 New->dropAttr<InternalLinkageAttr>();
3677 }
3678
3679 if (auto *EA = New->getAttr<ErrorAttr>()) {
3680 if (!Old->hasAttr<ErrorAttr>()) {
3681 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3682 Diag(Old->getLocation(), diag::note_previous_declaration);
3683 New->dropAttr<ErrorAttr>();
3684 }
3685 }
3686
3687 if (CheckRedeclarationInModule(New, Old))
3688 return true;
3689
3690 if (!getLangOpts().CPlusPlus) {
3691 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3692 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3693 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3694 << New << OldOvl;
3695
3696 // Try our best to find a decl that actually has the overloadable
3697 // attribute for the note. In most cases (e.g. programs with only one
3698 // broken declaration/definition), this won't matter.
3699 //
3700 // FIXME: We could do this if we juggled some extra state in
3701 // OverloadableAttr, rather than just removing it.
3702 const Decl *DiagOld = Old;
3703 if (OldOvl) {
3704 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3705 const auto *A = D->getAttr<OverloadableAttr>();
3706 return A && !A->isImplicit();
3707 });
3708 // If we've implicitly added *all* of the overloadable attrs to this
3709 // chain, emitting a "previous redecl" note is pointless.
3710 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3711 }
3712
3713 if (DiagOld)
3714 Diag(DiagOld->getLocation(),
3715 diag::note_attribute_overloadable_prev_overload)
3716 << OldOvl;
3717
3718 if (OldOvl)
3719 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3720 else
3721 New->dropAttr<OverloadableAttr>();
3722 }
3723 }
3724
3725 // It is not permitted to redeclare an SME function with different SME
3726 // attributes.
3727 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3728 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3729 << New->getType() << Old->getType();
3730 Diag(OldLocation, diag::note_previous_declaration);
3731 return true;
3732 }
3733
3734 // If a function is first declared with a calling convention, but is later
3735 // declared or defined without one, all following decls assume the calling
3736 // convention of the first.
3737 //
3738 // It's OK if a function is first declared without a calling convention,
3739 // but is later declared or defined with the default calling convention.
3740 //
3741 // To test if either decl has an explicit calling convention, we look for
3742 // AttributedType sugar nodes on the type as written. If they are missing or
3743 // were canonicalized away, we assume the calling convention was implicit.
3744 //
3745 // Note also that we DO NOT return at this point, because we still have
3746 // other tests to run.
3747 QualType OldQType = Context.getCanonicalType(Old->getType());
3748 QualType NewQType = Context.getCanonicalType(New->getType());
3749 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3750 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3751 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3752 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3753 bool RequiresAdjustment = false;
3754
3755 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3756 FunctionDecl *First = Old->getFirstDecl();
3757 const FunctionType *FT =
3758 First->getType().getCanonicalType()->castAs<FunctionType>();
3759 FunctionType::ExtInfo FI = FT->getExtInfo();
3760 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3761 if (!NewCCExplicit) {
3762 // Inherit the CC from the previous declaration if it was specified
3763 // there but not here.
3764 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3765 RequiresAdjustment = true;
3766 } else if (Old->getBuiltinID()) {
3767 // Builtin attribute isn't propagated to the new one yet at this point,
3768 // so we check if the old one is a builtin.
3769
3770 // Calling Conventions on a Builtin aren't really useful and setting a
3771 // default calling convention and cdecl'ing some builtin redeclarations is
3772 // common, so warn and ignore the calling convention on the redeclaration.
3773 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3774 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3775 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3776 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3777 RequiresAdjustment = true;
3778 } else {
3779 // Calling conventions aren't compatible, so complain.
3780 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3781 Diag(New->getLocation(), diag::err_cconv_change)
3782 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3783 << !FirstCCExplicit
3784 << (!FirstCCExplicit ? "" :
3785 FunctionType::getNameForCallConv(FI.getCC()));
3786
3787 // Put the note on the first decl, since it is the one that matters.
3788 Diag(First->getLocation(), diag::note_previous_declaration);
3789 return true;
3790 }
3791 }
3792
3793 // FIXME: diagnose the other way around?
3794 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3795 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3796 RequiresAdjustment = true;
3797 }
3798
3799 // Merge regparm attribute.
3800 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3801 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3802 if (NewTypeInfo.getHasRegParm()) {
3803 Diag(New->getLocation(), diag::err_regparm_mismatch)
3804 << NewType->getRegParmType()
3805 << OldType->getRegParmType();
3806 Diag(OldLocation, diag::note_previous_declaration);
3807 return true;
3808 }
3809
3810 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3811 RequiresAdjustment = true;
3812 }
3813
3814 // Merge ns_returns_retained attribute.
3815 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3816 if (NewTypeInfo.getProducesResult()) {
3817 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3818 << "'ns_returns_retained'";
3819 Diag(OldLocation, diag::note_previous_declaration);
3820 return true;
3821 }
3822
3823 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3824 RequiresAdjustment = true;
3825 }
3826
3827 if (OldTypeInfo.getNoCallerSavedRegs() !=
3828 NewTypeInfo.getNoCallerSavedRegs()) {
3829 if (NewTypeInfo.getNoCallerSavedRegs()) {
3830 AnyX86NoCallerSavedRegistersAttr *Attr =
3831 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3832 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3833 Diag(OldLocation, diag::note_previous_declaration);
3834 return true;
3835 }
3836
3837 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3838 RequiresAdjustment = true;
3839 }
3840
3841 if (RequiresAdjustment) {
3842 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3843 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3844 New->setType(QualType(AdjustedType, 0));
3845 NewQType = Context.getCanonicalType(New->getType());
3846 }
3847
3848 // If this redeclaration makes the function inline, we may need to add it to
3849 // UndefinedButUsed.
3850 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3851 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3852 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3853 UndefinedButUsed.insert(std::make_pair(x: Old->getCanonicalDecl(),
3854 y: SourceLocation()));
3855
3856 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3857 // about it.
3858 if (New->hasAttr<GNUInlineAttr>() &&
3859 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3860 UndefinedButUsed.erase(Old->getCanonicalDecl());
3861 }
3862
3863 // If pass_object_size params don't match up perfectly, this isn't a valid
3864 // redeclaration.
3865 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3866 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3867 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3868 << New->getDeclName();
3869 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3870 return true;
3871 }
3872
3873 QualType OldQTypeForComparison = OldQType;
3874 if (Context.hasAnyFunctionEffects()) {
3875 const auto OldFX = Old->getFunctionEffects();
3876 const auto NewFX = New->getFunctionEffects();
3877 if (OldFX != NewFX) {
3878 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3879 for (const auto &Diff : Diffs) {
3880 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3881 Diag(New->getLocation(),
3882 diag::warn_mismatched_func_effect_redeclaration)
3883 << Diff.effectName();
3884 Diag(Old->getLocation(), diag::note_previous_declaration);
3885 }
3886 }
3887 // Following a warning, we could skip merging effects from the previous
3888 // declaration, but that would trigger an additional "conflicting types"
3889 // error.
3890 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3891 FunctionEffectSet::Conflicts MergeErrs;
3892 FunctionEffectSet MergedFX =
3893 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3894 if (!MergeErrs.empty())
3895 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3896 Old->getLocation());
3897
3898 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3899 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3900 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
3901 Args: NewFPT->getParamTypes(), EPI);
3902
3903 New->setType(ModQT);
3904 NewQType = New->getType();
3905
3906 // Revise OldQTForComparison to include the merged effects,
3907 // so as not to fail due to differences later.
3908 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3909 EPI = OldFPT->getExtProtoInfo();
3910 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3911 OldQTypeForComparison = Context.getFunctionType(
3912 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
3913 }
3914 if (OldFX.empty()) {
3915 // A redeclaration may add the attribute to a previously seen function
3916 // body which needs to be verified.
3917 maybeAddDeclWithEffects(Old, MergedFX);
3918 }
3919 }
3920 }
3921 }
3922
3923 if (getLangOpts().CPlusPlus) {
3924 OldQType = Context.getCanonicalType(Old->getType());
3925 NewQType = Context.getCanonicalType(New->getType());
3926
3927 // Go back to the type source info to compare the declared return types,
3928 // per C++1y [dcl.type.auto]p13:
3929 // Redeclarations or specializations of a function or function template
3930 // with a declared return type that uses a placeholder type shall also
3931 // use that placeholder, not a deduced type.
3932 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3933 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3934 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
3935 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3936 OldDeclaredReturnType)) {
3937 QualType ResQT;
3938 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3939 OldDeclaredReturnType->isObjCObjectPointerType())
3940 // FIXME: This does the wrong thing for a deduced return type.
3941 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3942 if (ResQT.isNull()) {
3943 if (New->isCXXClassMember() && New->isOutOfLine())
3944 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3945 << New << New->getReturnTypeSourceRange();
3946 else if (Old->isExternC() && New->isExternC() &&
3947 !Old->hasAttr<OverloadableAttr>() &&
3948 !New->hasAttr<OverloadableAttr>())
3949 Diag(New->getLocation(), diag::err_conflicting_types) << New;
3950 else
3951 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3952 << New->getReturnTypeSourceRange();
3953 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3954 << Old->getReturnTypeSourceRange();
3955 return true;
3956 }
3957 else
3958 NewQType = ResQT;
3959 }
3960
3961 QualType OldReturnType = OldType->getReturnType();
3962 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
3963 if (OldReturnType != NewReturnType) {
3964 // If this function has a deduced return type and has already been
3965 // defined, copy the deduced value from the old declaration.
3966 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3967 if (OldAT && OldAT->isDeduced()) {
3968 QualType DT = OldAT->getDeducedType();
3969 if (DT.isNull()) {
3970 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
3971 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
3972 } else {
3973 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
3974 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
3975 }
3976 }
3977 }
3978
3979 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
3980 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
3981 if (OldMethod && NewMethod) {
3982 // Preserve triviality.
3983 NewMethod->setTrivial(OldMethod->isTrivial());
3984
3985 // MSVC allows explicit template specialization at class scope:
3986 // 2 CXXMethodDecls referring to the same function will be injected.
3987 // We don't want a redeclaration error.
3988 bool IsClassScopeExplicitSpecialization =
3989 OldMethod->isFunctionTemplateSpecialization() &&
3990 NewMethod->isFunctionTemplateSpecialization();
3991 bool isFriend = NewMethod->getFriendObjectKind();
3992
3993 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3994 !IsClassScopeExplicitSpecialization) {
3995 // -- Member function declarations with the same name and the
3996 // same parameter types cannot be overloaded if any of them
3997 // is a static member function declaration.
3998 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3999 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4000 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4001 return true;
4002 }
4003
4004 // C++ [class.mem]p1:
4005 // [...] A member shall not be declared twice in the
4006 // member-specification, except that a nested class or member
4007 // class template can be declared and then later defined.
4008 if (!inTemplateInstantiation()) {
4009 unsigned NewDiag;
4010 if (isa<CXXConstructorDecl>(OldMethod))
4011 NewDiag = diag::err_constructor_redeclared;
4012 else if (isa<CXXDestructorDecl>(NewMethod))
4013 NewDiag = diag::err_destructor_redeclared;
4014 else if (isa<CXXConversionDecl>(NewMethod))
4015 NewDiag = diag::err_conv_function_redeclared;
4016 else
4017 NewDiag = diag::err_member_redeclared;
4018
4019 Diag(New->getLocation(), NewDiag);
4020 } else {
4021 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4022 << New << New->getType();
4023 }
4024 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4025 return true;
4026
4027 // Complain if this is an explicit declaration of a special
4028 // member that was initially declared implicitly.
4029 //
4030 // As an exception, it's okay to befriend such methods in order
4031 // to permit the implicit constructor/destructor/operator calls.
4032 } else if (OldMethod->isImplicit()) {
4033 if (isFriend) {
4034 NewMethod->setImplicit();
4035 } else {
4036 Diag(NewMethod->getLocation(),
4037 diag::err_definition_of_implicitly_declared_member)
4038 << New << getSpecialMember(OldMethod);
4039 return true;
4040 }
4041 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4042 Diag(NewMethod->getLocation(),
4043 diag::err_definition_of_explicitly_defaulted_member)
4044 << getSpecialMember(OldMethod);
4045 return true;
4046 }
4047 }
4048
4049 // C++1z [over.load]p2
4050 // Certain function declarations cannot be overloaded:
4051 // -- Function declarations that differ only in the return type,
4052 // the exception specification, or both cannot be overloaded.
4053
4054 // Check the exception specifications match. This may recompute the type of
4055 // both Old and New if it resolved exception specifications, so grab the
4056 // types again after this. Because this updates the type, we do this before
4057 // any of the other checks below, which may update the "de facto" NewQType
4058 // but do not necessarily update the type of New.
4059 if (CheckEquivalentExceptionSpec(Old, New))
4060 return true;
4061
4062 // C++11 [dcl.attr.noreturn]p1:
4063 // The first declaration of a function shall specify the noreturn
4064 // attribute if any declaration of that function specifies the noreturn
4065 // attribute.
4066 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4067 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4068 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4069 << NRA;
4070 Diag(Old->getLocation(), diag::note_previous_declaration);
4071 }
4072
4073 // C++11 [dcl.attr.depend]p2:
4074 // The first declaration of a function shall specify the
4075 // carries_dependency attribute for its declarator-id if any declaration
4076 // of the function specifies the carries_dependency attribute.
4077 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4078 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4079 Diag(CDA->getLocation(),
4080 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4081 Diag(Old->getFirstDecl()->getLocation(),
4082 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4083 }
4084
4085 // (C++98 8.3.5p3):
4086 // All declarations for a function shall agree exactly in both the
4087 // return type and the parameter-type-list.
4088 // We also want to respect all the extended bits except noreturn.
4089
4090 // noreturn should now match unless the old type info didn't have it.
4091 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4092 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4093 const FunctionType *OldTypeForComparison
4094 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4095 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4096 assert(OldQTypeForComparison.isCanonical());
4097 }
4098
4099 if (haveIncompatibleLanguageLinkages(Old, New)) {
4100 // As a special case, retain the language linkage from previous
4101 // declarations of a friend function as an extension.
4102 //
4103 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4104 // and is useful because there's otherwise no way to specify language
4105 // linkage within class scope.
4106 //
4107 // Check cautiously as the friend object kind isn't yet complete.
4108 if (New->getFriendObjectKind() != Decl::FOK_None) {
4109 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4110 Diag(OldLocation, PrevDiag);
4111 } else {
4112 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4113 Diag(OldLocation, PrevDiag);
4114 return true;
4115 }
4116 }
4117
4118 // HLSL check parameters for matching ABI specifications.
4119 if (getLangOpts().HLSL) {
4120 if (HLSL().CheckCompatibleParameterABI(New, Old))
4121 return true;
4122
4123 // If no errors are generated when checking parameter ABIs we can check if
4124 // the two declarations have the same type ignoring the ABIs and if so,
4125 // the declarations can be merged. This case for merging is only valid in
4126 // HLSL because there are no valid cases of merging mismatched parameter
4127 // ABIs except the HLSL implicit in and explicit in.
4128 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4129 U: NewQType))
4130 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4131 // Fall through for conflicting redeclarations and redefinitions.
4132 }
4133
4134 // If the function types are compatible, merge the declarations. Ignore the
4135 // exception specifier because it was already checked above in
4136 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4137 // about incompatible types under -fms-compatibility.
4138 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4139 U: NewQType))
4140 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4141
4142 // If the types are imprecise (due to dependent constructs in friends or
4143 // local extern declarations), it's OK if they differ. We'll check again
4144 // during instantiation.
4145 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4146 return false;
4147
4148 // Fall through for conflicting redeclarations and redefinitions.
4149 }
4150
4151 // C: Function types need to be compatible, not identical. This handles
4152 // duplicate function decls like "void f(int); void f(enum X);" properly.
4153 if (!getLangOpts().CPlusPlus) {
4154 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4155 // type is specified by a function definition that contains a (possibly
4156 // empty) identifier list, both shall agree in the number of parameters
4157 // and the type of each parameter shall be compatible with the type that
4158 // results from the application of default argument promotions to the
4159 // type of the corresponding identifier. ...
4160 // This cannot be handled by ASTContext::typesAreCompatible() because that
4161 // doesn't know whether the function type is for a definition or not when
4162 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4163 // we need to cover here is that the number of arguments agree as the
4164 // default argument promotion rules were already checked by
4165 // ASTContext::typesAreCompatible().
4166 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4167 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4168 if (Old->hasInheritedPrototype())
4169 Old = Old->getCanonicalDecl();
4170 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4171 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4172 return true;
4173 }
4174
4175 // If we are merging two functions where only one of them has a prototype,
4176 // we may have enough information to decide to issue a diagnostic that the
4177 // function without a prototype will change behavior in C23. This handles
4178 // cases like:
4179 // void i(); void i(int j);
4180 // void i(int j); void i();
4181 // void i(); void i(int j) {}
4182 // See ActOnFinishFunctionBody() for other cases of the behavior change
4183 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4184 // type without a prototype.
4185 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4186 !New->isImplicit() && !Old->isImplicit()) {
4187 const FunctionDecl *WithProto, *WithoutProto;
4188 if (New->hasWrittenPrototype()) {
4189 WithProto = New;
4190 WithoutProto = Old;
4191 } else {
4192 WithProto = Old;
4193 WithoutProto = New;
4194 }
4195
4196 if (WithProto->getNumParams() != 0) {
4197 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4198 // The one without the prototype will be changing behavior in C23, so
4199 // warn about that one so long as it's a user-visible declaration.
4200 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4201 if (WithoutProto == New)
4202 IsWithoutProtoADef = NewDeclIsDefn;
4203 else
4204 IsWithProtoADef = NewDeclIsDefn;
4205 Diag(WithoutProto->getLocation(),
4206 diag::warn_non_prototype_changes_behavior)
4207 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4208 << (WithoutProto == Old) << IsWithProtoADef;
4209
4210 // The reason the one without the prototype will be changing behavior
4211 // is because of the one with the prototype, so note that so long as
4212 // it's a user-visible declaration. There is one exception to this:
4213 // when the new declaration is a definition without a prototype, the
4214 // old declaration with a prototype is not the cause of the issue,
4215 // and that does not need to be noted because the one with a
4216 // prototype will not change behavior in C23.
4217 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4218 !IsWithoutProtoADef)
4219 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4220 }
4221 }
4222 }
4223
4224 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4225 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4226 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4227 const FunctionProtoType *OldProto = nullptr;
4228 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4229 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4230 // The old declaration provided a function prototype, but the
4231 // new declaration does not. Merge in the prototype.
4232 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4233 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4234 Args: OldProto->getParamTypes(),
4235 EPI: OldProto->getExtProtoInfo());
4236 New->setType(NewQType);
4237 New->setHasInheritedPrototype();
4238
4239 // Synthesize parameters with the same types.
4240 SmallVector<ParmVarDecl *, 16> Params;
4241 for (const auto &ParamType : OldProto->param_types()) {
4242 ParmVarDecl *Param = ParmVarDecl::Create(
4243 Context, New, SourceLocation(), SourceLocation(), nullptr,
4244 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4245 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4246 Param->setImplicit();
4247 Params.push_back(Elt: Param);
4248 }
4249
4250 New->setParams(Params);
4251 }
4252
4253 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4254 }
4255 }
4256
4257 // Check if the function types are compatible when pointer size address
4258 // spaces are ignored.
4259 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4260 return false;
4261
4262 // GNU C permits a K&R definition to follow a prototype declaration
4263 // if the declared types of the parameters in the K&R definition
4264 // match the types in the prototype declaration, even when the
4265 // promoted types of the parameters from the K&R definition differ
4266 // from the types in the prototype. GCC then keeps the types from
4267 // the prototype.
4268 //
4269 // If a variadic prototype is followed by a non-variadic K&R definition,
4270 // the K&R definition becomes variadic. This is sort of an edge case, but
4271 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4272 // C99 6.9.1p8.
4273 if (!getLangOpts().CPlusPlus &&
4274 Old->hasPrototype() && !New->hasPrototype() &&
4275 New->getType()->getAs<FunctionProtoType>() &&
4276 Old->getNumParams() == New->getNumParams()) {
4277 SmallVector<QualType, 16> ArgTypes;
4278 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4279 const FunctionProtoType *OldProto
4280 = Old->getType()->getAs<FunctionProtoType>();
4281 const FunctionProtoType *NewProto
4282 = New->getType()->getAs<FunctionProtoType>();
4283
4284 // Determine whether this is the GNU C extension.
4285 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4286 NewProto->getReturnType());
4287 bool LooseCompatible = !MergedReturn.isNull();
4288 for (unsigned Idx = 0, End = Old->getNumParams();
4289 LooseCompatible && Idx != End; ++Idx) {
4290 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4291 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4292 if (Context.typesAreCompatible(T1: OldParm->getType(),
4293 T2: NewProto->getParamType(i: Idx))) {
4294 ArgTypes.push_back(Elt: NewParm->getType());
4295 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4296 T2: NewParm->getType(),
4297 /*CompareUnqualified=*/true)) {
4298 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4299 NewProto->getParamType(i: Idx) };
4300 Warnings.push_back(Elt: Warn);
4301 ArgTypes.push_back(Elt: NewParm->getType());
4302 } else
4303 LooseCompatible = false;
4304 }
4305
4306 if (LooseCompatible) {
4307 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4308 Diag(Warnings[Warn].NewParm->getLocation(),
4309 diag::ext_param_promoted_not_compatible_with_prototype)
4310 << Warnings[Warn].PromotedType
4311 << Warnings[Warn].OldParm->getType();
4312 if (Warnings[Warn].OldParm->getLocation().isValid())
4313 Diag(Warnings[Warn].OldParm->getLocation(),
4314 diag::note_previous_declaration);
4315 }
4316
4317 if (MergeTypeWithOld)
4318 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4319 EPI: OldProto->getExtProtoInfo()));
4320 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4321 }
4322
4323 // Fall through to diagnose conflicting types.
4324 }
4325
4326 // A function that has already been declared has been redeclared or
4327 // defined with a different type; show an appropriate diagnostic.
4328
4329 // If the previous declaration was an implicitly-generated builtin
4330 // declaration, then at the very least we should use a specialized note.
4331 unsigned BuiltinID;
4332 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4333 // If it's actually a library-defined builtin function like 'malloc'
4334 // or 'printf', just warn about the incompatible redeclaration.
4335 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4336 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4337 Diag(OldLocation, diag::note_previous_builtin_declaration)
4338 << Old << Old->getType();
4339 return false;
4340 }
4341
4342 PrevDiag = diag::note_previous_builtin_declaration;
4343 }
4344
4345 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4346 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4347 return true;
4348}
4349
4350bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4351 Scope *S, bool MergeTypeWithOld) {
4352 // Merge the attributes
4353 mergeDeclAttributes(New, Old);
4354
4355 // Merge "pure" flag.
4356 if (Old->isPureVirtual())
4357 New->setIsPureVirtual();
4358
4359 // Merge "used" flag.
4360 if (Old->getMostRecentDecl()->isUsed(false))
4361 New->setIsUsed();
4362
4363 // Merge attributes from the parameters. These can mismatch with K&R
4364 // declarations.
4365 if (New->getNumParams() == Old->getNumParams())
4366 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4367 ParmVarDecl *NewParam = New->getParamDecl(i);
4368 ParmVarDecl *OldParam = Old->getParamDecl(i);
4369 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4370 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4371 }
4372
4373 if (getLangOpts().CPlusPlus)
4374 return MergeCXXFunctionDecl(New, Old, S);
4375
4376 // Merge the function types so the we get the composite types for the return
4377 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4378 // was visible.
4379 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4380 if (!Merged.isNull() && MergeTypeWithOld)
4381 New->setType(Merged);
4382
4383 return false;
4384}
4385
4386void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4387 ObjCMethodDecl *oldMethod) {
4388 // Merge the attributes, including deprecated/unavailable
4389 AvailabilityMergeKind MergeKind =
4390 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4391 ? (oldMethod->isOptional()
4392 ? AvailabilityMergeKind::OptionalProtocolImplementation
4393 : AvailabilityMergeKind::ProtocolImplementation)
4394 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4395 ? AvailabilityMergeKind::Redeclaration
4396 : AvailabilityMergeKind::Override;
4397
4398 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4399
4400 // Merge attributes from the parameters.
4401 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4402 oe = oldMethod->param_end();
4403 for (ObjCMethodDecl::param_iterator
4404 ni = newMethod->param_begin(), ne = newMethod->param_end();
4405 ni != ne && oi != oe; ++ni, ++oi)
4406 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4407
4408 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4409}
4410
4411static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4412 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4413
4414 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4415 ? diag::err_redefinition_different_type
4416 : diag::err_redeclaration_different_type)
4417 << New->getDeclName() << New->getType() << Old->getType();
4418
4419 diag::kind PrevDiag;
4420 SourceLocation OldLocation;
4421 std::tie(args&: PrevDiag, args&: OldLocation)
4422 = getNoteDiagForInvalidRedeclaration(Old, New);
4423 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4424 New->setInvalidDecl();
4425}
4426
4427void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4428 bool MergeTypeWithOld) {
4429 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4430 return;
4431
4432 QualType MergedT;
4433 if (getLangOpts().CPlusPlus) {
4434 if (New->getType()->isUndeducedType()) {
4435 // We don't know what the new type is until the initializer is attached.
4436 return;
4437 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4438 // These could still be something that needs exception specs checked.
4439 return MergeVarDeclExceptionSpecs(New, Old);
4440 }
4441 // C++ [basic.link]p10:
4442 // [...] the types specified by all declarations referring to a given
4443 // object or function shall be identical, except that declarations for an
4444 // array object can specify array types that differ by the presence or
4445 // absence of a major array bound (8.3.4).
4446 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4447 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4448 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4449
4450 // We are merging a variable declaration New into Old. If it has an array
4451 // bound, and that bound differs from Old's bound, we should diagnose the
4452 // mismatch.
4453 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4454 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4455 PrevVD = PrevVD->getPreviousDecl()) {
4456 QualType PrevVDTy = PrevVD->getType();
4457 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4458 continue;
4459
4460 if (!Context.hasSameType(New->getType(), PrevVDTy))
4461 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4462 }
4463 }
4464
4465 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4466 if (Context.hasSameType(T1: OldArray->getElementType(),
4467 T2: NewArray->getElementType()))
4468 MergedT = New->getType();
4469 }
4470 // FIXME: Check visibility. New is hidden but has a complete type. If New
4471 // has no array bound, it should not inherit one from Old, if Old is not
4472 // visible.
4473 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4474 if (Context.hasSameType(T1: OldArray->getElementType(),
4475 T2: NewArray->getElementType()))
4476 MergedT = Old->getType();
4477 }
4478 }
4479 else if (New->getType()->isObjCObjectPointerType() &&
4480 Old->getType()->isObjCObjectPointerType()) {
4481 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4482 Old->getType());
4483 }
4484 } else {
4485 // C 6.2.7p2:
4486 // All declarations that refer to the same object or function shall have
4487 // compatible type.
4488 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4489 }
4490 if (MergedT.isNull()) {
4491 // It's OK if we couldn't merge types if either type is dependent, for a
4492 // block-scope variable. In other cases (static data members of class
4493 // templates, variable templates, ...), we require the types to be
4494 // equivalent.
4495 // FIXME: The C++ standard doesn't say anything about this.
4496 if ((New->getType()->isDependentType() ||
4497 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4498 // If the old type was dependent, we can't merge with it, so the new type
4499 // becomes dependent for now. We'll reproduce the original type when we
4500 // instantiate the TypeSourceInfo for the variable.
4501 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4502 New->setType(Context.DependentTy);
4503 return;
4504 }
4505 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4506 }
4507
4508 // Don't actually update the type on the new declaration if the old
4509 // declaration was an extern declaration in a different scope.
4510 if (MergeTypeWithOld)
4511 New->setType(MergedT);
4512}
4513
4514static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4515 LookupResult &Previous) {
4516 // C11 6.2.7p4:
4517 // For an identifier with internal or external linkage declared
4518 // in a scope in which a prior declaration of that identifier is
4519 // visible, if the prior declaration specifies internal or
4520 // external linkage, the type of the identifier at the later
4521 // declaration becomes the composite type.
4522 //
4523 // If the variable isn't visible, we do not merge with its type.
4524 if (Previous.isShadowed())
4525 return false;
4526
4527 if (S.getLangOpts().CPlusPlus) {
4528 // C++11 [dcl.array]p3:
4529 // If there is a preceding declaration of the entity in the same
4530 // scope in which the bound was specified, an omitted array bound
4531 // is taken to be the same as in that earlier declaration.
4532 return NewVD->isPreviousDeclInSameBlockScope() ||
4533 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4534 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4535 } else {
4536 // If the old declaration was function-local, don't merge with its
4537 // type unless we're in the same function.
4538 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4539 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4540 }
4541}
4542
4543void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4544 // If the new decl is already invalid, don't do any other checking.
4545 if (New->isInvalidDecl())
4546 return;
4547
4548 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4549 return;
4550
4551 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4552
4553 // Verify the old decl was also a variable or variable template.
4554 VarDecl *Old = nullptr;
4555 VarTemplateDecl *OldTemplate = nullptr;
4556 if (Previous.isSingleResult()) {
4557 if (NewTemplate) {
4558 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4559 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4560
4561 if (auto *Shadow =
4562 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4563 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4564 return New->setInvalidDecl();
4565 } else {
4566 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4567
4568 if (auto *Shadow =
4569 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4570 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4571 return New->setInvalidDecl();
4572 }
4573 }
4574 if (!Old) {
4575 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4576 << New->getDeclName();
4577 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4578 New: New->getLocation());
4579 return New->setInvalidDecl();
4580 }
4581
4582 // If the old declaration was found in an inline namespace and the new
4583 // declaration was qualified, update the DeclContext to match.
4584 adjustDeclContextForDeclaratorDecl(New, Old);
4585
4586 // Ensure the template parameters are compatible.
4587 if (NewTemplate &&
4588 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4589 OldTemplate->getTemplateParameters(),
4590 /*Complain=*/true, TPL_TemplateMatch))
4591 return New->setInvalidDecl();
4592
4593 // C++ [class.mem]p1:
4594 // A member shall not be declared twice in the member-specification [...]
4595 //
4596 // Here, we need only consider static data members.
4597 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4598 Diag(New->getLocation(), diag::err_duplicate_member)
4599 << New->getIdentifier();
4600 Diag(Old->getLocation(), diag::note_previous_declaration);
4601 New->setInvalidDecl();
4602 }
4603
4604 mergeDeclAttributes(New, Old);
4605 // Warn if an already-defined variable is made a weak_import in a subsequent
4606 // declaration
4607 if (New->hasAttr<WeakImportAttr>())
4608 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4609 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4610 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4611 Diag(D->getLocation(), diag::note_previous_definition);
4612 // Remove weak_import attribute on new declaration.
4613 New->dropAttr<WeakImportAttr>();
4614 break;
4615 }
4616 }
4617
4618 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4619 if (!Old->hasAttr<InternalLinkageAttr>()) {
4620 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4621 << ILA;
4622 Diag(Old->getLocation(), diag::note_previous_declaration);
4623 New->dropAttr<InternalLinkageAttr>();
4624 }
4625
4626 // Merge the types.
4627 VarDecl *MostRecent = Old->getMostRecentDecl();
4628 if (MostRecent != Old) {
4629 MergeVarDeclTypes(New, Old: MostRecent,
4630 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4631 if (New->isInvalidDecl())
4632 return;
4633 }
4634
4635 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4636 if (New->isInvalidDecl())
4637 return;
4638
4639 diag::kind PrevDiag;
4640 SourceLocation OldLocation;
4641 std::tie(args&: PrevDiag, args&: OldLocation) =
4642 getNoteDiagForInvalidRedeclaration(Old, New);
4643
4644 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4645 if (New->getStorageClass() == SC_Static &&
4646 !New->isStaticDataMember() &&
4647 Old->hasExternalFormalLinkage()) {
4648 if (getLangOpts().MicrosoftExt) {
4649 Diag(New->getLocation(), diag::ext_static_non_static)
4650 << New->getDeclName();
4651 Diag(OldLocation, PrevDiag);
4652 } else {
4653 Diag(New->getLocation(), diag::err_static_non_static)
4654 << New->getDeclName();
4655 Diag(OldLocation, PrevDiag);
4656 return New->setInvalidDecl();
4657 }
4658 }
4659 // C99 6.2.2p4:
4660 // For an identifier declared with the storage-class specifier
4661 // extern in a scope in which a prior declaration of that
4662 // identifier is visible,23) if the prior declaration specifies
4663 // internal or external linkage, the linkage of the identifier at
4664 // the later declaration is the same as the linkage specified at
4665 // the prior declaration. If no prior declaration is visible, or
4666 // if the prior declaration specifies no linkage, then the
4667 // identifier has external linkage.
4668 if (New->hasExternalStorage() && Old->hasLinkage())
4669 /* Okay */;
4670 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4671 !New->isStaticDataMember() &&
4672 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4673 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4674 Diag(OldLocation, PrevDiag);
4675 return New->setInvalidDecl();
4676 }
4677
4678 // Check if extern is followed by non-extern and vice-versa.
4679 if (New->hasExternalStorage() &&
4680 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4681 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4682 Diag(OldLocation, PrevDiag);
4683 return New->setInvalidDecl();
4684 }
4685 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4686 !New->hasExternalStorage()) {
4687 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4688 Diag(OldLocation, PrevDiag);
4689 return New->setInvalidDecl();
4690 }
4691
4692 if (CheckRedeclarationInModule(New, Old))
4693 return;
4694
4695 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4696
4697 // FIXME: The test for external storage here seems wrong? We still
4698 // need to check for mismatches.
4699 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4700 // Don't complain about out-of-line definitions of static members.
4701 !(Old->getLexicalDeclContext()->isRecord() &&
4702 !New->getLexicalDeclContext()->isRecord())) {
4703 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4704 Diag(OldLocation, PrevDiag);
4705 return New->setInvalidDecl();
4706 }
4707
4708 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4709 if (VarDecl *Def = Old->getDefinition()) {
4710 // C++1z [dcl.fcn.spec]p4:
4711 // If the definition of a variable appears in a translation unit before
4712 // its first declaration as inline, the program is ill-formed.
4713 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4714 Diag(Def->getLocation(), diag::note_previous_definition);
4715 }
4716 }
4717
4718 // If this redeclaration makes the variable inline, we may need to add it to
4719 // UndefinedButUsed.
4720 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4721 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4722 !Old->isInAnotherModuleUnit())
4723 UndefinedButUsed.insert(std::make_pair(x: Old->getCanonicalDecl(),
4724 y: SourceLocation()));
4725
4726 if (New->getTLSKind() != Old->getTLSKind()) {
4727 if (!Old->getTLSKind()) {
4728 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4729 Diag(OldLocation, PrevDiag);
4730 } else if (!New->getTLSKind()) {
4731 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4732 Diag(OldLocation, PrevDiag);
4733 } else {
4734 // Do not allow redeclaration to change the variable between requiring
4735 // static and dynamic initialization.
4736 // FIXME: GCC allows this, but uses the TLS keyword on the first
4737 // declaration to determine the kind. Do we need to be compatible here?
4738 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4739 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4740 Diag(OldLocation, PrevDiag);
4741 }
4742 }
4743
4744 // C++ doesn't have tentative definitions, so go right ahead and check here.
4745 if (getLangOpts().CPlusPlus) {
4746 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4747 Old->getCanonicalDecl()->isConstexpr()) {
4748 // This definition won't be a definition any more once it's been merged.
4749 Diag(New->getLocation(),
4750 diag::warn_deprecated_redundant_constexpr_static_def);
4751 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4752 VarDecl *Def = Old->getDefinition();
4753 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4754 return;
4755 }
4756 } else {
4757 // C++ may not have a tentative definition rule, but it has a different
4758 // rule about what constitutes a definition in the first place. See
4759 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4760 // contains the extern specifier and doesn't have an initializer, it's fine
4761 // in C++.
4762 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4763 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4764 << New;
4765 Diag(Old->getLocation(), diag::note_previous_declaration);
4766 }
4767 }
4768
4769 if (haveIncompatibleLanguageLinkages(Old, New)) {
4770 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4771 Diag(OldLocation, PrevDiag);
4772 New->setInvalidDecl();
4773 return;
4774 }
4775
4776 // Merge "used" flag.
4777 if (Old->getMostRecentDecl()->isUsed(false))
4778 New->setIsUsed();
4779
4780 // Keep a chain of previous declarations.
4781 New->setPreviousDecl(Old);
4782 if (NewTemplate)
4783 NewTemplate->setPreviousDecl(OldTemplate);
4784
4785 // Inherit access appropriately.
4786 New->setAccess(Old->getAccess());
4787 if (NewTemplate)
4788 NewTemplate->setAccess(New->getAccess());
4789
4790 if (Old->isInline())
4791 New->setImplicitlyInline();
4792}
4793
4794void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4795 SourceManager &SrcMgr = getSourceManager();
4796 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4797 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4798 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4799 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4800 auto &HSI = PP.getHeaderSearchInfo();
4801 StringRef HdrFilename =
4802 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4803
4804 auto noteFromModuleOrInclude = [&](Module *Mod,
4805 SourceLocation IncLoc) -> bool {
4806 // Redefinition errors with modules are common with non modular mapped
4807 // headers, example: a non-modular header H in module A that also gets
4808 // included directly in a TU. Pointing twice to the same header/definition
4809 // is confusing, try to get better diagnostics when modules is on.
4810 if (IncLoc.isValid()) {
4811 if (Mod) {
4812 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4813 << HdrFilename.str() << Mod->getFullModuleName();
4814 if (!Mod->DefinitionLoc.isInvalid())
4815 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4816 << Mod->getFullModuleName();
4817 } else {
4818 Diag(IncLoc, diag::note_redefinition_include_same_file)
4819 << HdrFilename.str();
4820 }
4821 return true;
4822 }
4823
4824 return false;
4825 };
4826
4827 // Is it the same file and same offset? Provide more information on why
4828 // this leads to a redefinition error.
4829 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4830 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4831 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4832 bool EmittedDiag =
4833 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4834 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4835
4836 // If the header has no guards, emit a note suggesting one.
4837 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4838 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4839
4840 if (EmittedDiag)
4841 return;
4842 }
4843
4844 // Redefinition coming from different files or couldn't do better above.
4845 if (Old->getLocation().isValid())
4846 Diag(Old->getLocation(), diag::note_previous_definition);
4847}
4848
4849bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4850 if (!hasVisibleDefinition(Old) &&
4851 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4852 isa<VarTemplateSpecializationDecl>(New) ||
4853 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4854 New->getDeclContext()->isDependentContext() ||
4855 New->hasAttr<SelectAnyAttr>())) {
4856 // The previous definition is hidden, and multiple definitions are
4857 // permitted (in separate TUs). Demote this to a declaration.
4858 New->demoteThisDefinitionToDeclaration();
4859
4860 // Make the canonical definition visible.
4861 if (auto *OldTD = Old->getDescribedVarTemplate())
4862 makeMergedDefinitionVisible(OldTD);
4863 makeMergedDefinitionVisible(Old);
4864 return false;
4865 } else {
4866 Diag(New->getLocation(), diag::err_redefinition) << New;
4867 notePreviousDefinition(Old, New: New->getLocation());
4868 New->setInvalidDecl();
4869 return true;
4870 }
4871}
4872
4873Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4874 DeclSpec &DS,
4875 const ParsedAttributesView &DeclAttrs,
4876 RecordDecl *&AnonRecord) {
4877 return ParsedFreeStandingDeclSpec(
4878 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
4879}
4880
4881// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4882// disambiguate entities defined in different scopes.
4883// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4884// compatibility.
4885// We will pick our mangling number depending on which version of MSVC is being
4886// targeted.
4887static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4888 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
4889 ? S->getMSCurManglingNumber()
4890 : S->getMSLastManglingNumber();
4891}
4892
4893void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4894 if (!Context.getLangOpts().CPlusPlus)
4895 return;
4896
4897 if (isa<CXXRecordDecl>(Tag->getParent())) {
4898 // If this tag is the direct child of a class, number it if
4899 // it is anonymous.
4900 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4901 return;
4902 MangleNumberingContext &MCtx =
4903 Context.getManglingNumberContext(Tag->getParent());
4904 Context.setManglingNumber(
4905 Tag, MCtx.getManglingNumber(
4906 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4907 return;
4908 }
4909
4910 // If this tag isn't a direct child of a class, number it if it is local.
4911 MangleNumberingContext *MCtx;
4912 Decl *ManglingContextDecl;
4913 std::tie(args&: MCtx, args&: ManglingContextDecl) =
4914 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
4915 if (MCtx) {
4916 Context.setManglingNumber(
4917 Tag, MCtx->getManglingNumber(
4918 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4919 }
4920}
4921
4922namespace {
4923struct NonCLikeKind {
4924 enum {
4925 None,
4926 BaseClass,
4927 DefaultMemberInit,
4928 Lambda,
4929 Friend,
4930 OtherMember,
4931 Invalid,
4932 } Kind = None;
4933 SourceRange Range;
4934
4935 explicit operator bool() { return Kind != None; }
4936};
4937}
4938
4939/// Determine whether a class is C-like, according to the rules of C++
4940/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4941static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4942 if (RD->isInvalidDecl())
4943 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
4944
4945 // C++ [dcl.typedef]p9: [P1766R1]
4946 // An unnamed class with a typedef name for linkage purposes shall not
4947 //
4948 // -- have any base classes
4949 if (RD->getNumBases())
4950 return {.Kind: NonCLikeKind::BaseClass,
4951 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
4952 RD->bases_end()[-1].getEndLoc())};
4953 bool Invalid = false;
4954 for (Decl *D : RD->decls()) {
4955 // Don't complain about things we already diagnosed.
4956 if (D->isInvalidDecl()) {
4957 Invalid = true;
4958 continue;
4959 }
4960
4961 // -- have any [...] default member initializers
4962 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4963 if (FD->hasInClassInitializer()) {
4964 auto *Init = FD->getInClassInitializer();
4965 return {NonCLikeKind::DefaultMemberInit,
4966 Init ? Init->getSourceRange() : D->getSourceRange()};
4967 }
4968 continue;
4969 }
4970
4971 // FIXME: We don't allow friend declarations. This violates the wording of
4972 // P1766, but not the intent.
4973 if (isa<FriendDecl>(D))
4974 return {NonCLikeKind::Friend, D->getSourceRange()};
4975
4976 // -- declare any members other than non-static data members, member
4977 // enumerations, or member classes,
4978 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4979 isa<EnumDecl>(D))
4980 continue;
4981 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4982 if (!MemberRD) {
4983 if (D->isImplicit())
4984 continue;
4985 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4986 }
4987
4988 // -- contain a lambda-expression,
4989 if (MemberRD->isLambda())
4990 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4991
4992 // and all member classes shall also satisfy these requirements
4993 // (recursively).
4994 if (MemberRD->isThisDeclarationADefinition()) {
4995 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4996 return Kind;
4997 }
4998 }
4999
5000 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5001}
5002
5003void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5004 TypedefNameDecl *NewTD) {
5005 if (TagFromDeclSpec->isInvalidDecl())
5006 return;
5007
5008 // Do nothing if the tag already has a name for linkage purposes.
5009 if (TagFromDeclSpec->hasNameForLinkage())
5010 return;
5011
5012 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5013 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5014
5015 // The type must match the tag exactly; no qualifiers allowed.
5016 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5017 T2: Context.getTagDeclType(Decl: TagFromDeclSpec))) {
5018 if (getLangOpts().CPlusPlus)
5019 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5020 return;
5021 }
5022
5023 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5024 // An unnamed class with a typedef name for linkage purposes shall [be
5025 // C-like].
5026 //
5027 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5028 // shouldn't happen, but there are constructs that the language rule doesn't
5029 // disallow for which we can't reasonably avoid computing linkage early.
5030 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5031 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5032 : NonCLikeKind();
5033 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5034 if (NonCLike || ChangesLinkage) {
5035 if (NonCLike.Kind == NonCLikeKind::Invalid)
5036 return;
5037
5038 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5039 if (ChangesLinkage) {
5040 // If the linkage changes, we can't accept this as an extension.
5041 if (NonCLike.Kind == NonCLikeKind::None)
5042 DiagID = diag::err_typedef_changes_linkage;
5043 else
5044 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5045 }
5046
5047 SourceLocation FixitLoc =
5048 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5049 llvm::SmallString<40> TextToInsert;
5050 TextToInsert += ' ';
5051 TextToInsert += NewTD->getIdentifier()->getName();
5052
5053 Diag(FixitLoc, DiagID)
5054 << isa<TypeAliasDecl>(Val: NewTD)
5055 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5056 if (NonCLike.Kind != NonCLikeKind::None) {
5057 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5058 << NonCLike.Kind - 1 << NonCLike.Range;
5059 }
5060 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5061 << NewTD << isa<TypeAliasDecl>(NewTD);
5062
5063 if (ChangesLinkage)
5064 return;
5065 }
5066
5067 // Otherwise, set this as the anon-decl typedef for the tag.
5068 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5069
5070 // Now that we have a name for the tag, process API notes again.
5071 ProcessAPINotes(TagFromDeclSpec);
5072}
5073
5074static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5075 DeclSpec::TST T = DS.getTypeSpecType();
5076 switch (T) {
5077 case DeclSpec::TST_class:
5078 return 0;
5079 case DeclSpec::TST_struct:
5080 return 1;
5081 case DeclSpec::TST_interface:
5082 return 2;
5083 case DeclSpec::TST_union:
5084 return 3;
5085 case DeclSpec::TST_enum:
5086 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5087 if (ED->isScopedUsingClassTag())
5088 return 5;
5089 if (ED->isScoped())
5090 return 6;
5091 }
5092 return 4;
5093 default:
5094 llvm_unreachable("unexpected type specifier");
5095 }
5096}
5097
5098Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5099 DeclSpec &DS,
5100 const ParsedAttributesView &DeclAttrs,
5101 MultiTemplateParamsArg TemplateParams,
5102 bool IsExplicitInstantiation,
5103 RecordDecl *&AnonRecord,
5104 SourceLocation EllipsisLoc) {
5105 Decl *TagD = nullptr;
5106 TagDecl *Tag = nullptr;
5107 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5108 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5109 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5110 DS.getTypeSpecType() == DeclSpec::TST_union ||
5111 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5112 TagD = DS.getRepAsDecl();
5113
5114 if (!TagD) // We probably had an error
5115 return nullptr;
5116
5117 // Note that the above type specs guarantee that the
5118 // type rep is a Decl, whereas in many of the others
5119 // it's a Type.
5120 if (isa<TagDecl>(Val: TagD))
5121 Tag = cast<TagDecl>(Val: TagD);
5122 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5123 Tag = CTD->getTemplatedDecl();
5124 }
5125
5126 if (Tag) {
5127 handleTagNumbering(Tag, TagScope: S);
5128 Tag->setFreeStanding();
5129 if (Tag->isInvalidDecl())
5130 return Tag;
5131 }
5132
5133 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5134 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5135 // or incomplete types shall not be restrict-qualified."
5136 if (TypeQuals & DeclSpec::TQ_restrict)
5137 Diag(DS.getRestrictSpecLoc(),
5138 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5139 << DS.getSourceRange();
5140 }
5141
5142 if (DS.isInlineSpecified())
5143 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5144 << getLangOpts().CPlusPlus17;
5145
5146 if (DS.hasConstexprSpecifier()) {
5147 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5148 // and definitions of functions and variables.
5149 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5150 // the declaration of a function or function template
5151 if (Tag)
5152 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5153 << GetDiagnosticTypeSpecifierID(DS)
5154 << static_cast<int>(DS.getConstexprSpecifier());
5155 else if (getLangOpts().C23)
5156 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5157 else
5158 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5159 << static_cast<int>(DS.getConstexprSpecifier());
5160 // Don't emit warnings after this error.
5161 return TagD;
5162 }
5163
5164 DiagnoseFunctionSpecifiers(DS);
5165
5166 if (DS.isFriendSpecified()) {
5167 // If we're dealing with a decl but not a TagDecl, assume that
5168 // whatever routines created it handled the friendship aspect.
5169 if (TagD && !Tag)
5170 return nullptr;
5171 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5172 }
5173
5174 assert(EllipsisLoc.isInvalid() &&
5175 "Friend ellipsis but not friend-specified?");
5176
5177 // Track whether this decl-specifier declares anything.
5178 bool DeclaresAnything = true;
5179
5180 // Handle anonymous struct definitions.
5181 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5182 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5183 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5184 if (getLangOpts().CPlusPlus ||
5185 Record->getDeclContext()->isRecord()) {
5186 // If CurContext is a DeclContext that can contain statements,
5187 // RecursiveASTVisitor won't visit the decls that
5188 // BuildAnonymousStructOrUnion() will put into CurContext.
5189 // Also store them here so that they can be part of the
5190 // DeclStmt that gets created in this case.
5191 // FIXME: Also return the IndirectFieldDecls created by
5192 // BuildAnonymousStructOr union, for the same reason?
5193 if (CurContext->isFunctionOrMethod())
5194 AnonRecord = Record;
5195 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5196 Policy: Context.getPrintingPolicy());
5197 }
5198
5199 DeclaresAnything = false;
5200 }
5201 }
5202
5203 // C11 6.7.2.1p2:
5204 // A struct-declaration that does not declare an anonymous structure or
5205 // anonymous union shall contain a struct-declarator-list.
5206 //
5207 // This rule also existed in C89 and C99; the grammar for struct-declaration
5208 // did not permit a struct-declaration without a struct-declarator-list.
5209 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5210 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5211 // Check for Microsoft C extension: anonymous struct/union member.
5212 // Handle 2 kinds of anonymous struct/union:
5213 // struct STRUCT;
5214 // union UNION;
5215 // and
5216 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5217 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5218 if ((Tag && Tag->getDeclName()) ||
5219 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5220 RecordDecl *Record = nullptr;
5221 if (Tag)
5222 Record = dyn_cast<RecordDecl>(Val: Tag);
5223 else if (const RecordType *RT =
5224 DS.getRepAsType().get()->getAsStructureType())
5225 Record = RT->getDecl();
5226 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5227 Record = UT->getDecl();
5228
5229 if (Record && getLangOpts().MicrosoftExt) {
5230 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5231 << Record->isUnion() << DS.getSourceRange();
5232 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5233 }
5234
5235 DeclaresAnything = false;
5236 }
5237 }
5238
5239 // Skip all the checks below if we have a type error.
5240 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5241 (TagD && TagD->isInvalidDecl()))
5242 return TagD;
5243
5244 if (getLangOpts().CPlusPlus &&
5245 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5246 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5247 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5248 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5249 DeclaresAnything = false;
5250
5251 if (!DS.isMissingDeclaratorOk()) {
5252 // Customize diagnostic for a typedef missing a name.
5253 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5254 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5255 << DS.getSourceRange();
5256 else
5257 DeclaresAnything = false;
5258 }
5259
5260 if (DS.isModulePrivateSpecified() &&
5261 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5262 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5263 << Tag->getTagKind()
5264 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5265
5266 ActOnDocumentableDecl(D: TagD);
5267
5268 // C 6.7/2:
5269 // A declaration [...] shall declare at least a declarator [...], a tag,
5270 // or the members of an enumeration.
5271 // C++ [dcl.dcl]p3:
5272 // [If there are no declarators], and except for the declaration of an
5273 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5274 // names into the program, or shall redeclare a name introduced by a
5275 // previous declaration.
5276 if (!DeclaresAnything) {
5277 // In C, we allow this as a (popular) extension / bug. Don't bother
5278 // producing further diagnostics for redundant qualifiers after this.
5279 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5280 ? diag::err_no_declarators
5281 : diag::ext_no_declarators)
5282 << DS.getSourceRange();
5283 return TagD;
5284 }
5285
5286 // C++ [dcl.stc]p1:
5287 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5288 // init-declarator-list of the declaration shall not be empty.
5289 // C++ [dcl.fct.spec]p1:
5290 // If a cv-qualifier appears in a decl-specifier-seq, the
5291 // init-declarator-list of the declaration shall not be empty.
5292 //
5293 // Spurious qualifiers here appear to be valid in C.
5294 unsigned DiagID = diag::warn_standalone_specifier;
5295 if (getLangOpts().CPlusPlus)
5296 DiagID = diag::ext_standalone_specifier;
5297
5298 // Note that a linkage-specification sets a storage class, but
5299 // 'extern "C" struct foo;' is actually valid and not theoretically
5300 // useless.
5301 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5302 if (SCS == DeclSpec::SCS_mutable)
5303 // Since mutable is not a viable storage class specifier in C, there is
5304 // no reason to treat it as an extension. Instead, diagnose as an error.
5305 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5306 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5307 Diag(DS.getStorageClassSpecLoc(), DiagID)
5308 << DeclSpec::getSpecifierName(S: SCS);
5309 }
5310
5311 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5312 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5313 << DeclSpec::getSpecifierName(S: TSCS);
5314 if (DS.getTypeQualifiers()) {
5315 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5316 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5317 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5318 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5319 // Restrict is covered above.
5320 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5321 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5322 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5323 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5324 }
5325
5326 // Warn about ignored type attributes, for example:
5327 // __attribute__((aligned)) struct A;
5328 // Attributes should be placed after tag to apply to type declaration.
5329 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5330 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5331 if (TypeSpecType == DeclSpec::TST_class ||
5332 TypeSpecType == DeclSpec::TST_struct ||
5333 TypeSpecType == DeclSpec::TST_interface ||
5334 TypeSpecType == DeclSpec::TST_union ||
5335 TypeSpecType == DeclSpec::TST_enum) {
5336
5337 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5338 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5339 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5340 DiagnosticId = diag::warn_attribute_ignored;
5341 else if (AL.isRegularKeywordAttribute())
5342 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5343 else
5344 DiagnosticId = diag::warn_declspec_attribute_ignored;
5345 Diag(AL.getLoc(), DiagnosticId)
5346 << AL << GetDiagnosticTypeSpecifierID(DS);
5347 };
5348
5349 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5350 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5351 }
5352 }
5353
5354 return TagD;
5355}
5356
5357/// We are trying to inject an anonymous member into the given scope;
5358/// check if there's an existing declaration that can't be overloaded.
5359///
5360/// \return true if this is a forbidden redeclaration
5361static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5362 DeclContext *Owner,
5363 DeclarationName Name,
5364 SourceLocation NameLoc, bool IsUnion,
5365 StorageClass SC) {
5366 LookupResult R(SemaRef, Name, NameLoc,
5367 Owner->isRecord() ? Sema::LookupMemberName
5368 : Sema::LookupOrdinaryName,
5369 RedeclarationKind::ForVisibleRedeclaration);
5370 if (!SemaRef.LookupName(R, S)) return false;
5371
5372 // Pick a representative declaration.
5373 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5374 assert(PrevDecl && "Expected a non-null Decl");
5375
5376 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5377 return false;
5378
5379 if (SC == StorageClass::SC_None &&
5380 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5381 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5382 if (!Owner->isRecord())
5383 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5384 return false;
5385 }
5386
5387 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5388 << IsUnion << Name;
5389 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5390
5391 return true;
5392}
5393
5394void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5395 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5396 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5397}
5398
5399void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5400 if (!getLangOpts().CPlusPlus)
5401 return;
5402
5403 // This function can be parsed before we have validated the
5404 // structure as an anonymous struct
5405 if (Record->isAnonymousStructOrUnion())
5406 return;
5407
5408 const NamedDecl *First = 0;
5409 for (const Decl *D : Record->decls()) {
5410 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5411 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5412 continue;
5413 if (!First)
5414 First = ND;
5415 else
5416 DiagPlaceholderVariableDefinition(ND->getLocation());
5417 }
5418}
5419
5420/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5421/// anonymous struct or union AnonRecord into the owning context Owner
5422/// and scope S. This routine will be invoked just after we realize
5423/// that an unnamed union or struct is actually an anonymous union or
5424/// struct, e.g.,
5425///
5426/// @code
5427/// union {
5428/// int i;
5429/// float f;
5430/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5431/// // f into the surrounding scope.x
5432/// @endcode
5433///
5434/// This routine is recursive, injecting the names of nested anonymous
5435/// structs/unions into the owning context and scope as well.
5436static bool
5437InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5438 RecordDecl *AnonRecord, AccessSpecifier AS,
5439 StorageClass SC,
5440 SmallVectorImpl<NamedDecl *> &Chaining) {
5441 bool Invalid = false;
5442
5443 // Look every FieldDecl and IndirectFieldDecl with a name.
5444 for (auto *D : AnonRecord->decls()) {
5445 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5446 cast<NamedDecl>(D)->getDeclName()) {
5447 ValueDecl *VD = cast<ValueDecl>(D);
5448 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5449 VD->getLocation(), AnonRecord->isUnion(),
5450 SC)) {
5451 // C++ [class.union]p2:
5452 // The names of the members of an anonymous union shall be
5453 // distinct from the names of any other entity in the
5454 // scope in which the anonymous union is declared.
5455 Invalid = true;
5456 } else {
5457 // C++ [class.union]p2:
5458 // For the purpose of name lookup, after the anonymous union
5459 // definition, the members of the anonymous union are
5460 // considered to have been defined in the scope in which the
5461 // anonymous union is declared.
5462 unsigned OldChainingSize = Chaining.size();
5463 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5464 Chaining.append(IF->chain_begin(), IF->chain_end());
5465 else
5466 Chaining.push_back(VD);
5467
5468 assert(Chaining.size() >= 2);
5469 NamedDecl **NamedChain =
5470 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5471 for (unsigned i = 0; i < Chaining.size(); i++)
5472 NamedChain[i] = Chaining[i];
5473
5474 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5475 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5476 VD->getType(), {NamedChain, Chaining.size()});
5477
5478 for (const auto *Attr : VD->attrs())
5479 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5480
5481 IndirectField->setAccess(AS);
5482 IndirectField->setImplicit();
5483 SemaRef.PushOnScopeChains(IndirectField, S);
5484
5485 // That includes picking up the appropriate access specifier.
5486 if (AS != AS_none) IndirectField->setAccess(AS);
5487
5488 Chaining.resize(OldChainingSize);
5489 }
5490 }
5491 }
5492
5493 return Invalid;
5494}
5495
5496/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5497/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5498/// illegal input values are mapped to SC_None.
5499static StorageClass
5500StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5501 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5502 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5503 "Parser allowed 'typedef' as storage class VarDecl.");
5504 switch (StorageClassSpec) {
5505 case DeclSpec::SCS_unspecified: return SC_None;
5506 case DeclSpec::SCS_extern:
5507 if (DS.isExternInLinkageSpec())
5508 return SC_None;
5509 return SC_Extern;
5510 case DeclSpec::SCS_static: return SC_Static;
5511 case DeclSpec::SCS_auto: return SC_Auto;
5512 case DeclSpec::SCS_register: return SC_Register;
5513 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5514 // Illegal SCSs map to None: error reporting is up to the caller.
5515 case DeclSpec::SCS_mutable: // Fall through.
5516 case DeclSpec::SCS_typedef: return SC_None;
5517 }
5518 llvm_unreachable("unknown storage class specifier");
5519}
5520
5521static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5522 assert(Record->hasInClassInitializer());
5523
5524 for (const auto *I : Record->decls()) {
5525 const auto *FD = dyn_cast<FieldDecl>(I);
5526 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5527 FD = IFD->getAnonField();
5528 if (FD && FD->hasInClassInitializer())
5529 return FD->getLocation();
5530 }
5531
5532 llvm_unreachable("couldn't find in-class initializer");
5533}
5534
5535static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5536 SourceLocation DefaultInitLoc) {
5537 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5538 return;
5539
5540 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5541 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5542}
5543
5544static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5545 CXXRecordDecl *AnonUnion) {
5546 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5547 return;
5548
5549 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5550}
5551
5552Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5553 AccessSpecifier AS,
5554 RecordDecl *Record,
5555 const PrintingPolicy &Policy) {
5556 DeclContext *Owner = Record->getDeclContext();
5557
5558 // Diagnose whether this anonymous struct/union is an extension.
5559 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5560 Diag(Record->getLocation(), diag::ext_anonymous_union);
5561 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5562 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5563 else if (!Record->isUnion() && !getLangOpts().C11)
5564 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5565
5566 // C and C++ require different kinds of checks for anonymous
5567 // structs/unions.
5568 bool Invalid = false;
5569 if (getLangOpts().CPlusPlus) {
5570 const char *PrevSpec = nullptr;
5571 if (Record->isUnion()) {
5572 // C++ [class.union]p6:
5573 // C++17 [class.union.anon]p2:
5574 // Anonymous unions declared in a named namespace or in the
5575 // global namespace shall be declared static.
5576 unsigned DiagID;
5577 DeclContext *OwnerScope = Owner->getRedeclContext();
5578 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5579 (OwnerScope->isTranslationUnit() ||
5580 (OwnerScope->isNamespace() &&
5581 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5582 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5583 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5584
5585 // Recover by adding 'static'.
5586 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5587 PrevSpec, DiagID, Policy);
5588 }
5589 // C++ [class.union]p6:
5590 // A storage class is not allowed in a declaration of an
5591 // anonymous union in a class scope.
5592 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5593 isa<RecordDecl>(Val: Owner)) {
5594 Diag(DS.getStorageClassSpecLoc(),
5595 diag::err_anonymous_union_with_storage_spec)
5596 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5597
5598 // Recover by removing the storage specifier.
5599 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5600 Loc: SourceLocation(),
5601 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5602 }
5603 }
5604
5605 // Ignore const/volatile/restrict qualifiers.
5606 if (DS.getTypeQualifiers()) {
5607 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5608 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5609 << Record->isUnion() << "const"
5610 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5611 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5612 Diag(DS.getVolatileSpecLoc(),
5613 diag::ext_anonymous_struct_union_qualified)
5614 << Record->isUnion() << "volatile"
5615 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5616 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5617 Diag(DS.getRestrictSpecLoc(),
5618 diag::ext_anonymous_struct_union_qualified)
5619 << Record->isUnion() << "restrict"
5620 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5621 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5622 Diag(DS.getAtomicSpecLoc(),
5623 diag::ext_anonymous_struct_union_qualified)
5624 << Record->isUnion() << "_Atomic"
5625 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5626 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5627 Diag(DS.getUnalignedSpecLoc(),
5628 diag::ext_anonymous_struct_union_qualified)
5629 << Record->isUnion() << "__unaligned"
5630 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5631
5632 DS.ClearTypeQualifiers();
5633 }
5634
5635 // C++ [class.union]p2:
5636 // The member-specification of an anonymous union shall only
5637 // define non-static data members. [Note: nested types and
5638 // functions cannot be declared within an anonymous union. ]
5639 for (auto *Mem : Record->decls()) {
5640 // Ignore invalid declarations; we already diagnosed them.
5641 if (Mem->isInvalidDecl())
5642 continue;
5643
5644 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5645 // C++ [class.union]p3:
5646 // An anonymous union shall not have private or protected
5647 // members (clause 11).
5648 assert(FD->getAccess() != AS_none);
5649 if (FD->getAccess() != AS_public) {
5650 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5651 << Record->isUnion() << (FD->getAccess() == AS_protected);
5652 Invalid = true;
5653 }
5654
5655 // C++ [class.union]p1
5656 // An object of a class with a non-trivial constructor, a non-trivial
5657 // copy constructor, a non-trivial destructor, or a non-trivial copy
5658 // assignment operator cannot be a member of a union, nor can an
5659 // array of such objects.
5660 if (CheckNontrivialField(FD))
5661 Invalid = true;
5662 } else if (Mem->isImplicit()) {
5663 // Any implicit members are fine.
5664 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5665 // This is a type that showed up in an
5666 // elaborated-type-specifier inside the anonymous struct or
5667 // union, but which actually declares a type outside of the
5668 // anonymous struct or union. It's okay.
5669 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5670 if (!MemRecord->isAnonymousStructOrUnion() &&
5671 MemRecord->getDeclName()) {
5672 // Visual C++ allows type definition in anonymous struct or union.
5673 if (getLangOpts().MicrosoftExt)
5674 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5675 << Record->isUnion();
5676 else {
5677 // This is a nested type declaration.
5678 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5679 << Record->isUnion();
5680 Invalid = true;
5681 }
5682 } else {
5683 // This is an anonymous type definition within another anonymous type.
5684 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5685 // not part of standard C++.
5686 Diag(MemRecord->getLocation(),
5687 diag::ext_anonymous_record_with_anonymous_type)
5688 << Record->isUnion();
5689 }
5690 } else if (isa<AccessSpecDecl>(Mem)) {
5691 // Any access specifier is fine.
5692 } else if (isa<StaticAssertDecl>(Mem)) {
5693 // In C++1z, static_assert declarations are also fine.
5694 } else {
5695 // We have something that isn't a non-static data
5696 // member. Complain about it.
5697 unsigned DK = diag::err_anonymous_record_bad_member;
5698 if (isa<TypeDecl>(Mem))
5699 DK = diag::err_anonymous_record_with_type;
5700 else if (isa<FunctionDecl>(Mem))
5701 DK = diag::err_anonymous_record_with_function;
5702 else if (isa<VarDecl>(Mem))
5703 DK = diag::err_anonymous_record_with_static;
5704
5705 // Visual C++ allows type definition in anonymous struct or union.
5706 if (getLangOpts().MicrosoftExt &&
5707 DK == diag::err_anonymous_record_with_type)
5708 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5709 << Record->isUnion();
5710 else {
5711 Diag(Mem->getLocation(), DK) << Record->isUnion();
5712 Invalid = true;
5713 }
5714 }
5715 }
5716
5717 // C++11 [class.union]p8 (DR1460):
5718 // At most one variant member of a union may have a
5719 // brace-or-equal-initializer.
5720 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5721 Owner->isRecord())
5722 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5723 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5724 }
5725
5726 if (!Record->isUnion() && !Owner->isRecord()) {
5727 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5728 << getLangOpts().CPlusPlus;
5729 Invalid = true;
5730 }
5731
5732 // C++ [dcl.dcl]p3:
5733 // [If there are no declarators], and except for the declaration of an
5734 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5735 // names into the program
5736 // C++ [class.mem]p2:
5737 // each such member-declaration shall either declare at least one member
5738 // name of the class or declare at least one unnamed bit-field
5739 //
5740 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5741 if (getLangOpts().CPlusPlus && Record->field_empty())
5742 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5743
5744 // Mock up a declarator.
5745 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5746 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5747 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5748 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5749
5750 // Create a declaration for this anonymous struct/union.
5751 NamedDecl *Anon = nullptr;
5752 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5753 Anon = FieldDecl::Create(
5754 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5755 /*IdentifierInfo=*/Id: nullptr, T: Context.getTypeDeclType(Record), TInfo,
5756 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5757 /*InitStyle=*/ICIS_NoInit);
5758 Anon->setAccess(AS);
5759 ProcessDeclAttributes(S, Anon, Dc);
5760
5761 if (getLangOpts().CPlusPlus)
5762 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5763 } else {
5764 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5765 if (SCSpec == DeclSpec::SCS_mutable) {
5766 // mutable can only appear on non-static class members, so it's always
5767 // an error here
5768 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5769 Invalid = true;
5770 SC = SC_None;
5771 }
5772
5773 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5774 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5775 T: Context.getTypeDeclType(Record), TInfo, S: SC);
5776 if (Invalid)
5777 Anon->setInvalidDecl();
5778
5779 ProcessDeclAttributes(S, Anon, Dc);
5780
5781 // Default-initialize the implicit variable. This initialization will be
5782 // trivial in almost all cases, except if a union member has an in-class
5783 // initializer:
5784 // union { int n = 0; };
5785 ActOnUninitializedDecl(Anon);
5786 }
5787 Anon->setImplicit();
5788
5789 // Mark this as an anonymous struct/union type.
5790 Record->setAnonymousStructOrUnion(true);
5791
5792 // Add the anonymous struct/union object to the current
5793 // context. We'll be referencing this object when we refer to one of
5794 // its members.
5795 Owner->addDecl(Anon);
5796
5797 // Inject the members of the anonymous struct/union into the owning
5798 // context and into the identifier resolver chain for name lookup
5799 // purposes.
5800 SmallVector<NamedDecl*, 2> Chain;
5801 Chain.push_back(Elt: Anon);
5802
5803 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5804 Chaining&: Chain))
5805 Invalid = true;
5806
5807 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5808 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5809 MangleNumberingContext *MCtx;
5810 Decl *ManglingContextDecl;
5811 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5812 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5813 if (MCtx) {
5814 Context.setManglingNumber(
5815 NewVD, MCtx->getManglingNumber(
5816 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5817 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5818 }
5819 }
5820 }
5821
5822 if (Invalid)
5823 Anon->setInvalidDecl();
5824
5825 return Anon;
5826}
5827
5828Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5829 RecordDecl *Record) {
5830 assert(Record && "expected a record!");
5831
5832 // Mock up a declarator.
5833 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5834 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5835 assert(TInfo && "couldn't build declarator info for anonymous struct");
5836
5837 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5838 QualType RecTy = Context.getTypeDeclType(Record);
5839
5840 // Create a declaration for this anonymous struct.
5841 NamedDecl *Anon =
5842 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5843 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5844 /*BitWidth=*/nullptr, /*Mutable=*/false,
5845 /*InitStyle=*/ICIS_NoInit);
5846 Anon->setImplicit();
5847
5848 // Add the anonymous struct object to the current context.
5849 CurContext->addDecl(Anon);
5850
5851 // Inject the members of the anonymous struct into the current
5852 // context and into the identifier resolver chain for name lookup
5853 // purposes.
5854 SmallVector<NamedDecl*, 2> Chain;
5855 Chain.push_back(Elt: Anon);
5856
5857 RecordDecl *RecordDef = Record->getDefinition();
5858 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5859 diag::err_field_incomplete_or_sizeless) ||
5860 InjectAnonymousStructOrUnionMembers(
5861 *this, S, CurContext, RecordDef, AS_none,
5862 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5863 Anon->setInvalidDecl();
5864 ParentDecl->setInvalidDecl();
5865 }
5866
5867 return Anon;
5868}
5869
5870DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5871 return GetNameFromUnqualifiedId(Name: D.getName());
5872}
5873
5874DeclarationNameInfo
5875Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5876 DeclarationNameInfo NameInfo;
5877 NameInfo.setLoc(Name.StartLocation);
5878
5879 switch (Name.getKind()) {
5880
5881 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5882 case UnqualifiedIdKind::IK_Identifier:
5883 NameInfo.setName(Name.Identifier);
5884 return NameInfo;
5885
5886 case UnqualifiedIdKind::IK_DeductionGuideName: {
5887 // C++ [temp.deduct.guide]p3:
5888 // The simple-template-id shall name a class template specialization.
5889 // The template-name shall be the same identifier as the template-name
5890 // of the simple-template-id.
5891 // These together intend to imply that the template-name shall name a
5892 // class template.
5893 // FIXME: template<typename T> struct X {};
5894 // template<typename T> using Y = X<T>;
5895 // Y(int) -> Y<int>;
5896 // satisfies these rules but does not name a class template.
5897 TemplateName TN = Name.TemplateName.get().get();
5898 auto *Template = TN.getAsTemplateDecl();
5899 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
5900 Diag(Name.StartLocation,
5901 diag::err_deduction_guide_name_not_class_template)
5902 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5903 if (Template)
5904 NoteTemplateLocation(*Template);
5905 return DeclarationNameInfo();
5906 }
5907
5908 NameInfo.setName(
5909 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
5910 return NameInfo;
5911 }
5912
5913 case UnqualifiedIdKind::IK_OperatorFunctionId:
5914 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5915 Op: Name.OperatorFunctionId.Operator));
5916 NameInfo.setCXXOperatorNameRange(SourceRange(
5917 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5918 return NameInfo;
5919
5920 case UnqualifiedIdKind::IK_LiteralOperatorId:
5921 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5922 II: Name.Identifier));
5923 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5924 return NameInfo;
5925
5926 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5927 TypeSourceInfo *TInfo;
5928 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
5929 if (Ty.isNull())
5930 return DeclarationNameInfo();
5931 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5932 Ty: Context.getCanonicalType(T: Ty)));
5933 NameInfo.setNamedTypeInfo(TInfo);
5934 return NameInfo;
5935 }
5936
5937 case UnqualifiedIdKind::IK_ConstructorName: {
5938 TypeSourceInfo *TInfo;
5939 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
5940 if (Ty.isNull())
5941 return DeclarationNameInfo();
5942 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5943 Ty: Context.getCanonicalType(T: Ty)));
5944 NameInfo.setNamedTypeInfo(TInfo);
5945 return NameInfo;
5946 }
5947
5948 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5949 // In well-formed code, we can only have a constructor
5950 // template-id that refers to the current context, so go there
5951 // to find the actual type being constructed.
5952 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
5953 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5954 return DeclarationNameInfo();
5955
5956 // Determine the type of the class being constructed.
5957 QualType CurClassType = Context.getTypeDeclType(CurClass);
5958
5959 // FIXME: Check two things: that the template-id names the same type as
5960 // CurClassType, and that the template-id does not occur when the name
5961 // was qualified.
5962
5963 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5964 Ty: Context.getCanonicalType(T: CurClassType)));
5965 // FIXME: should we retrieve TypeSourceInfo?
5966 NameInfo.setNamedTypeInfo(nullptr);
5967 return NameInfo;
5968 }
5969
5970 case UnqualifiedIdKind::IK_DestructorName: {
5971 TypeSourceInfo *TInfo;
5972 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
5973 if (Ty.isNull())
5974 return DeclarationNameInfo();
5975 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5976 Ty: Context.getCanonicalType(T: Ty)));
5977 NameInfo.setNamedTypeInfo(TInfo);
5978 return NameInfo;
5979 }
5980
5981 case UnqualifiedIdKind::IK_TemplateId: {
5982 TemplateName TName = Name.TemplateId->Template.get();
5983 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5984 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
5985 }
5986
5987 } // switch (Name.getKind())
5988
5989 llvm_unreachable("Unknown name kind");
5990}
5991
5992static QualType getCoreType(QualType Ty) {
5993 do {
5994 if (Ty->isPointerOrReferenceType())
5995 Ty = Ty->getPointeeType();
5996 else if (Ty->isArrayType())
5997 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5998 else
5999 return Ty.withoutLocalFastQualifiers();
6000 } while (true);
6001}
6002
6003/// hasSimilarParameters - Determine whether the C++ functions Declaration
6004/// and Definition have "nearly" matching parameters. This heuristic is
6005/// used to improve diagnostics in the case where an out-of-line function
6006/// definition doesn't match any declaration within the class or namespace.
6007/// Also sets Params to the list of indices to the parameters that differ
6008/// between the declaration and the definition. If hasSimilarParameters
6009/// returns true and Params is empty, then all of the parameters match.
6010static bool hasSimilarParameters(ASTContext &Context,
6011 FunctionDecl *Declaration,
6012 FunctionDecl *Definition,
6013 SmallVectorImpl<unsigned> &Params) {
6014 Params.clear();
6015 if (Declaration->param_size() != Definition->param_size())
6016 return false;
6017 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6018 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6019 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6020
6021 // The parameter types are identical
6022 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6023 continue;
6024
6025 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6026 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6027 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6028 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6029
6030 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6031 (DeclTyName && DeclTyName == DefTyName))
6032 Params.push_back(Elt: Idx);
6033 else // The two parameters aren't even close
6034 return false;
6035 }
6036
6037 return true;
6038}
6039
6040/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6041/// declarator needs to be rebuilt in the current instantiation.
6042/// Any bits of declarator which appear before the name are valid for
6043/// consideration here. That's specifically the type in the decl spec
6044/// and the base type in any member-pointer chunks.
6045static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6046 DeclarationName Name) {
6047 // The types we specifically need to rebuild are:
6048 // - typenames, typeofs, and decltypes
6049 // - types which will become injected class names
6050 // Of course, we also need to rebuild any type referencing such a
6051 // type. It's safest to just say "dependent", but we call out a
6052 // few cases here.
6053
6054 DeclSpec &DS = D.getMutableDeclSpec();
6055 switch (DS.getTypeSpecType()) {
6056 case DeclSpec::TST_typename:
6057 case DeclSpec::TST_typeofType:
6058 case DeclSpec::TST_typeof_unqualType:
6059#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6060#include "clang/Basic/TransformTypeTraits.def"
6061 case DeclSpec::TST_atomic: {
6062 // Grab the type from the parser.
6063 TypeSourceInfo *TSI = nullptr;
6064 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6065 if (T.isNull() || !T->isInstantiationDependentType()) break;
6066
6067 // Make sure there's a type source info. This isn't really much
6068 // of a waste; most dependent types should have type source info
6069 // attached already.
6070 if (!TSI)
6071 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6072
6073 // Rebuild the type in the current instantiation.
6074 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6075 if (!TSI) return true;
6076
6077 // Store the new type back in the decl spec.
6078 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6079 DS.UpdateTypeRep(Rep: LocType);
6080 break;
6081 }
6082
6083 case DeclSpec::TST_decltype:
6084 case DeclSpec::TST_typeof_unqualExpr:
6085 case DeclSpec::TST_typeofExpr: {
6086 Expr *E = DS.getRepAsExpr();
6087 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6088 if (Result.isInvalid()) return true;
6089 DS.UpdateExprRep(Rep: Result.get());
6090 break;
6091 }
6092
6093 default:
6094 // Nothing to do for these decl specs.
6095 break;
6096 }
6097
6098 // It doesn't matter what order we do this in.
6099 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6100 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6101
6102 // The only type information in the declarator which can come
6103 // before the declaration name is the base type of a member
6104 // pointer.
6105 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6106 continue;
6107
6108 // Rebuild the scope specifier in-place.
6109 CXXScopeSpec &SS = Chunk.Mem.Scope();
6110 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6111 return true;
6112 }
6113
6114 return false;
6115}
6116
6117/// Returns true if the declaration is declared in a system header or from a
6118/// system macro.
6119static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6120 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6121 SM.isInSystemMacro(loc: D->getLocation());
6122}
6123
6124void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6125 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6126 // of system decl.
6127 if (D->getPreviousDecl() || D->isImplicit())
6128 return;
6129 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6130 if (Status != ReservedIdentifierStatus::NotReserved &&
6131 !isFromSystemHeader(Context.getSourceManager(), D)) {
6132 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6133 << D << static_cast<int>(Status);
6134 }
6135}
6136
6137Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6138 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6139
6140 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6141 // declaration only if the `bind_to_declaration` extension is set.
6142 SmallVector<FunctionDecl *, 4> Bases;
6143 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6144 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6145 TP: llvm::omp::TraitProperty::
6146 implementation_extension_bind_to_declaration))
6147 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6148 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6149
6150 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6151
6152 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6153 Dcl && Dcl->getDeclContext()->isFileContext())
6154 Dcl->setTopLevelDeclInObjCContainer();
6155
6156 if (!Bases.empty())
6157 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6158 Bases);
6159
6160 return Dcl;
6161}
6162
6163bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6164 DeclarationNameInfo NameInfo) {
6165 DeclarationName Name = NameInfo.getName();
6166
6167 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6168 while (Record && Record->isAnonymousStructOrUnion())
6169 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6170 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6171 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6172 return true;
6173 }
6174
6175 return false;
6176}
6177
6178bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6179 DeclarationName Name,
6180 SourceLocation Loc,
6181 TemplateIdAnnotation *TemplateId,
6182 bool IsMemberSpecialization) {
6183 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6184 "without nested-name-specifier");
6185 DeclContext *Cur = CurContext;
6186 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6187 Cur = Cur->getParent();
6188
6189 // If the user provided a superfluous scope specifier that refers back to the
6190 // class in which the entity is already declared, diagnose and ignore it.
6191 //
6192 // class X {
6193 // void X::f();
6194 // };
6195 //
6196 // Note, it was once ill-formed to give redundant qualification in all
6197 // contexts, but that rule was removed by DR482.
6198 if (Cur->Equals(DC)) {
6199 if (Cur->isRecord()) {
6200 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6201 : diag::err_member_extra_qualification)
6202 << Name << FixItHint::CreateRemoval(SS.getRange());
6203 SS.clear();
6204 } else {
6205 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6206 }
6207 return false;
6208 }
6209
6210 // Check whether the qualifying scope encloses the scope of the original
6211 // declaration. For a template-id, we perform the checks in
6212 // CheckTemplateSpecializationScope.
6213 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6214 if (Cur->isRecord())
6215 Diag(Loc, diag::err_member_qualification)
6216 << Name << SS.getRange();
6217 else if (isa<TranslationUnitDecl>(Val: DC))
6218 Diag(Loc, diag::err_invalid_declarator_global_scope)
6219 << Name << SS.getRange();
6220 else if (isa<FunctionDecl>(Val: Cur))
6221 Diag(Loc, diag::err_invalid_declarator_in_function)
6222 << Name << SS.getRange();
6223 else if (isa<BlockDecl>(Val: Cur))
6224 Diag(Loc, diag::err_invalid_declarator_in_block)
6225 << Name << SS.getRange();
6226 else if (isa<ExportDecl>(Val: Cur)) {
6227 if (!isa<NamespaceDecl>(Val: DC))
6228 Diag(Loc, diag::err_export_non_namespace_scope_name)
6229 << Name << SS.getRange();
6230 else
6231 // The cases that DC is not NamespaceDecl should be handled in
6232 // CheckRedeclarationExported.
6233 return false;
6234 } else
6235 Diag(Loc, diag::err_invalid_declarator_scope)
6236 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6237
6238 return true;
6239 }
6240
6241 if (Cur->isRecord()) {
6242 // Cannot qualify members within a class.
6243 Diag(Loc, diag::err_member_qualification)
6244 << Name << SS.getRange();
6245 SS.clear();
6246
6247 // C++ constructors and destructors with incorrect scopes can break
6248 // our AST invariants by having the wrong underlying types. If
6249 // that's the case, then drop this declaration entirely.
6250 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6251 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6252 !Context.hasSameType(T1: Name.getCXXNameType(),
6253 T2: Context.getTypeDeclType(cast<CXXRecordDecl>(Val: Cur))))
6254 return true;
6255
6256 return false;
6257 }
6258
6259 // C++23 [temp.names]p5:
6260 // The keyword template shall not appear immediately after a declarative
6261 // nested-name-specifier.
6262 //
6263 // First check the template-id (if any), and then check each component of the
6264 // nested-name-specifier in reverse order.
6265 //
6266 // FIXME: nested-name-specifiers in friend declarations are declarative,
6267 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6268 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6269 Diag(Loc, diag::ext_template_after_declarative_nns)
6270 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6271
6272 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6273 do {
6274 if (TypeLoc TL = SpecLoc.getTypeLoc()) {
6275 if (SourceLocation TemplateKeywordLoc = TL.getTemplateKeywordLoc();
6276 TemplateKeywordLoc.isValid())
6277 Diag(Loc, diag::ext_template_after_declarative_nns)
6278 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6279 }
6280
6281 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6282 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6283 // C++23 [expr.prim.id.qual]p3:
6284 // [...] If a nested-name-specifier N is declarative and has a
6285 // simple-template-id with a template argument list A that involves a
6286 // template parameter, let T be the template nominated by N without A.
6287 // T shall be a class template.
6288 if (TST->isDependentType() && TST->isTypeAlias())
6289 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6290 << SpecLoc.getLocalSourceRange();
6291 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6292 // C++23 [expr.prim.id.qual]p2:
6293 // [...] A declarative nested-name-specifier shall not have a
6294 // computed-type-specifier.
6295 //
6296 // CWG2858 changed this from 'decltype-specifier' to
6297 // 'computed-type-specifier'.
6298 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6299 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6300 }
6301 }
6302 } while ((SpecLoc = SpecLoc.getPrefix()));
6303
6304 return false;
6305}
6306
6307NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6308 MultiTemplateParamsArg TemplateParamLists) {
6309 // TODO: consider using NameInfo for diagnostic.
6310 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6311 DeclarationName Name = NameInfo.getName();
6312
6313 // All of these full declarators require an identifier. If it doesn't have
6314 // one, the ParsedFreeStandingDeclSpec action should be used.
6315 if (D.isDecompositionDeclarator()) {
6316 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6317 } else if (!Name) {
6318 if (!D.isInvalidType()) // Reject this if we think it is valid.
6319 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6320 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6321 return nullptr;
6322 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6323 return nullptr;
6324
6325 DeclContext *DC = CurContext;
6326 if (D.getCXXScopeSpec().isInvalid())
6327 D.setInvalidType();
6328 else if (D.getCXXScopeSpec().isSet()) {
6329 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6330 UPPC: UPPC_DeclarationQualifier))
6331 return nullptr;
6332
6333 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6334 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6335 if (!DC || isa<EnumDecl>(Val: DC)) {
6336 // If we could not compute the declaration context, it's because the
6337 // declaration context is dependent but does not refer to a class,
6338 // class template, or class template partial specialization. Complain
6339 // and return early, to avoid the coming semantic disaster.
6340 Diag(D.getIdentifierLoc(),
6341 diag::err_template_qualified_declarator_no_match)
6342 << D.getCXXScopeSpec().getScopeRep()
6343 << D.getCXXScopeSpec().getRange();
6344 return nullptr;
6345 }
6346 bool IsDependentContext = DC->isDependentContext();
6347
6348 if (!IsDependentContext &&
6349 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6350 return nullptr;
6351
6352 // If a class is incomplete, do not parse entities inside it.
6353 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6354 Diag(D.getIdentifierLoc(),
6355 diag::err_member_def_undefined_record)
6356 << Name << DC << D.getCXXScopeSpec().getRange();
6357 return nullptr;
6358 }
6359 if (!D.getDeclSpec().isFriendSpecified()) {
6360 TemplateIdAnnotation *TemplateId =
6361 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6362 ? D.getName().TemplateId
6363 : nullptr;
6364 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6365 Loc: D.getIdentifierLoc(), TemplateId,
6366 /*IsMemberSpecialization=*/false)) {
6367 if (DC->isRecord())
6368 return nullptr;
6369
6370 D.setInvalidType();
6371 }
6372 }
6373
6374 // Check whether we need to rebuild the type of the given
6375 // declaration in the current instantiation.
6376 if (EnteringContext && IsDependentContext &&
6377 TemplateParamLists.size() != 0) {
6378 ContextRAII SavedContext(*this, DC);
6379 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6380 D.setInvalidType();
6381 }
6382 }
6383
6384 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6385 QualType R = TInfo->getType();
6386
6387 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6388 UPPC: UPPC_DeclarationType))
6389 D.setInvalidType();
6390
6391 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6392 forRedeclarationInCurContext());
6393
6394 // See if this is a redefinition of a variable in the same scope.
6395 if (!D.getCXXScopeSpec().isSet()) {
6396 bool IsLinkageLookup = false;
6397 bool CreateBuiltins = false;
6398
6399 // If the declaration we're planning to build will be a function
6400 // or object with linkage, then look for another declaration with
6401 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6402 //
6403 // If the declaration we're planning to build will be declared with
6404 // external linkage in the translation unit, create any builtin with
6405 // the same name.
6406 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6407 /* Do nothing*/;
6408 else if (CurContext->isFunctionOrMethod() &&
6409 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6410 R->isFunctionType())) {
6411 IsLinkageLookup = true;
6412 CreateBuiltins =
6413 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6414 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6415 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6416 CreateBuiltins = true;
6417
6418 if (IsLinkageLookup) {
6419 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6420 Previous.setRedeclarationKind(
6421 RedeclarationKind::ForExternalRedeclaration);
6422 }
6423
6424 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6425 } else { // Something like "int foo::x;"
6426 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6427
6428 // C++ [dcl.meaning]p1:
6429 // When the declarator-id is qualified, the declaration shall refer to a
6430 // previously declared member of the class or namespace to which the
6431 // qualifier refers (or, in the case of a namespace, of an element of the
6432 // inline namespace set of that namespace (7.3.1)) or to a specialization
6433 // thereof; [...]
6434 //
6435 // Note that we already checked the context above, and that we do not have
6436 // enough information to make sure that Previous contains the declaration
6437 // we want to match. For example, given:
6438 //
6439 // class X {
6440 // void f();
6441 // void f(float);
6442 // };
6443 //
6444 // void X::f(int) { } // ill-formed
6445 //
6446 // In this case, Previous will point to the overload set
6447 // containing the two f's declared in X, but neither of them
6448 // matches.
6449
6450 RemoveUsingDecls(R&: Previous);
6451 }
6452
6453 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6454 TPD && TPD->isTemplateParameter()) {
6455 // Older versions of clang allowed the names of function/variable templates
6456 // to shadow the names of their template parameters. For the compatibility
6457 // purposes we detect such cases and issue a default-to-error warning that
6458 // can be disabled with -Wno-strict-primary-template-shadow.
6459 if (!D.isInvalidType()) {
6460 bool AllowForCompatibility = false;
6461 if (Scope *DeclParent = S->getDeclParent();
6462 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6463 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6464 TemplateParamParent->isDeclScope(TPD);
6465 }
6466 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6467 AllowForCompatibility);
6468 }
6469
6470 // Just pretend that we didn't see the previous declaration.
6471 Previous.clear();
6472 }
6473
6474 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6475 // Forget that the previous declaration is the injected-class-name.
6476 Previous.clear();
6477
6478 // In C++, the previous declaration we find might be a tag type
6479 // (class or enum). In this case, the new declaration will hide the
6480 // tag type. Note that this applies to functions, function templates, and
6481 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6482 if (Previous.isSingleTagDecl() &&
6483 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6484 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6485 Previous.clear();
6486
6487 // Check that there are no default arguments other than in the parameters
6488 // of a function declaration (C++ only).
6489 if (getLangOpts().CPlusPlus)
6490 CheckExtraCXXDefaultArguments(D);
6491
6492 /// Get the innermost enclosing declaration scope.
6493 S = S->getDeclParent();
6494
6495 NamedDecl *New;
6496
6497 bool AddToScope = true;
6498 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6499 if (TemplateParamLists.size()) {
6500 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6501 return nullptr;
6502 }
6503
6504 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6505 } else if (R->isFunctionType()) {
6506 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6507 TemplateParamLists,
6508 AddToScope);
6509 } else {
6510 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6511 AddToScope);
6512 }
6513
6514 if (!New)
6515 return nullptr;
6516
6517 warnOnCTypeHiddenInCPlusPlus(D: New);
6518
6519 // If this has an identifier and is not a function template specialization,
6520 // add it to the scope stack.
6521 if (New->getDeclName() && AddToScope)
6522 PushOnScopeChains(D: New, S);
6523
6524 if (OpenMP().isInOpenMPDeclareTargetContext())
6525 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6526
6527 return New;
6528}
6529
6530/// Helper method to turn variable array types into constant array
6531/// types in certain situations which would otherwise be errors (for
6532/// GCC compatibility).
6533static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6534 ASTContext &Context,
6535 bool &SizeIsNegative,
6536 llvm::APSInt &Oversized) {
6537 // This method tries to turn a variable array into a constant
6538 // array even when the size isn't an ICE. This is necessary
6539 // for compatibility with code that depends on gcc's buggy
6540 // constant expression folding, like struct {char x[(int)(char*)2];}
6541 SizeIsNegative = false;
6542 Oversized = 0;
6543
6544 if (T->isDependentType())
6545 return QualType();
6546
6547 QualifierCollector Qs;
6548 const Type *Ty = Qs.strip(type: T);
6549
6550 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6551 QualType Pointee = PTy->getPointeeType();
6552 QualType FixedType =
6553 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6554 Oversized);
6555 if (FixedType.isNull()) return FixedType;
6556 FixedType = Context.getPointerType(T: FixedType);
6557 return Qs.apply(Context, QT: FixedType);
6558 }
6559 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6560 QualType Inner = PTy->getInnerType();
6561 QualType FixedType =
6562 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6563 Oversized);
6564 if (FixedType.isNull()) return FixedType;
6565 FixedType = Context.getParenType(NamedType: FixedType);
6566 return Qs.apply(Context, QT: FixedType);
6567 }
6568
6569 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6570 if (!VLATy)
6571 return QualType();
6572
6573 QualType ElemTy = VLATy->getElementType();
6574 if (ElemTy->isVariablyModifiedType()) {
6575 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6576 SizeIsNegative, Oversized);
6577 if (ElemTy.isNull())
6578 return QualType();
6579 }
6580
6581 Expr::EvalResult Result;
6582 if (!VLATy->getSizeExpr() ||
6583 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6584 return QualType();
6585
6586 llvm::APSInt Res = Result.Val.getInt();
6587
6588 // Check whether the array size is negative.
6589 if (Res.isSigned() && Res.isNegative()) {
6590 SizeIsNegative = true;
6591 return QualType();
6592 }
6593
6594 // Check whether the array is too large to be addressed.
6595 unsigned ActiveSizeBits =
6596 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6597 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6598 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6599 : Res.getActiveBits();
6600 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6601 Oversized = Res;
6602 return QualType();
6603 }
6604
6605 QualType FoldedArrayType = Context.getConstantArrayType(
6606 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6607 return Qs.apply(Context, QT: FoldedArrayType);
6608}
6609
6610static void
6611FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6612 SrcTL = SrcTL.getUnqualifiedLoc();
6613 DstTL = DstTL.getUnqualifiedLoc();
6614 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6615 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6616 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6617 DstPTL.getPointeeLoc());
6618 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6619 return;
6620 }
6621 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6622 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6623 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6624 DstTL: DstPTL.getInnerLoc());
6625 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6626 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6627 return;
6628 }
6629 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6630 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6631 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6632 TypeLoc DstElemTL = DstATL.getElementLoc();
6633 if (VariableArrayTypeLoc SrcElemATL =
6634 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6635 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6636 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6637 } else {
6638 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6639 }
6640 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6641 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6642 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6643}
6644
6645/// Helper method to turn variable array types into constant array
6646/// types in certain situations which would otherwise be errors (for
6647/// GCC compatibility).
6648static TypeSourceInfo*
6649TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6650 ASTContext &Context,
6651 bool &SizeIsNegative,
6652 llvm::APSInt &Oversized) {
6653 QualType FixedTy
6654 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6655 SizeIsNegative, Oversized);
6656 if (FixedTy.isNull())
6657 return nullptr;
6658 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6659 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6660 DstTL: FixedTInfo->getTypeLoc());
6661 return FixedTInfo;
6662}
6663
6664bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6665 QualType &T, SourceLocation Loc,
6666 unsigned FailedFoldDiagID) {
6667 bool SizeIsNegative;
6668 llvm::APSInt Oversized;
6669 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6670 TInfo, Context, SizeIsNegative, Oversized);
6671 if (FixedTInfo) {
6672 Diag(Loc, diag::ext_vla_folded_to_constant);
6673 TInfo = FixedTInfo;
6674 T = FixedTInfo->getType();
6675 return true;
6676 }
6677
6678 if (SizeIsNegative)
6679 Diag(Loc, diag::err_typecheck_negative_array_size);
6680 else if (Oversized.getBoolValue())
6681 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6682 else if (FailedFoldDiagID)
6683 Diag(Loc, FailedFoldDiagID);
6684 return false;
6685}
6686
6687void
6688Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6689 if (!getLangOpts().CPlusPlus &&
6690 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6691 // Don't need to track declarations in the TU in C.
6692 return;
6693
6694 // Note that we have a locally-scoped external with this name.
6695 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6696}
6697
6698NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6699 // FIXME: We can have multiple results via __attribute__((overloadable)).
6700 auto Result = Context.getExternCContextDecl()->lookup(Name);
6701 return Result.empty() ? nullptr : *Result.begin();
6702}
6703
6704void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6705 // FIXME: We should probably indicate the identifier in question to avoid
6706 // confusion for constructs like "virtual int a(), b;"
6707 if (DS.isVirtualSpecified())
6708 Diag(DS.getVirtualSpecLoc(),
6709 diag::err_virtual_non_function);
6710
6711 if (DS.hasExplicitSpecifier())
6712 Diag(DS.getExplicitSpecLoc(),
6713 diag::err_explicit_non_function);
6714
6715 if (DS.isNoreturnSpecified())
6716 Diag(DS.getNoreturnSpecLoc(),
6717 diag::err_noreturn_non_function);
6718}
6719
6720NamedDecl*
6721Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6722 TypeSourceInfo *TInfo, LookupResult &Previous) {
6723 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6724 if (D.getCXXScopeSpec().isSet()) {
6725 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6726 << D.getCXXScopeSpec().getRange();
6727 D.setInvalidType();
6728 // Pretend we didn't see the scope specifier.
6729 DC = CurContext;
6730 Previous.clear();
6731 }
6732
6733 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6734
6735 if (D.getDeclSpec().isInlineSpecified())
6736 Diag(D.getDeclSpec().getInlineSpecLoc(),
6737 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6738 ? diag::warn_ms_inline_non_function
6739 : diag::err_inline_non_function)
6740 << getLangOpts().CPlusPlus17;
6741 if (D.getDeclSpec().hasConstexprSpecifier())
6742 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6743 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6744
6745 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6746 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6747 Diag(D.getName().StartLocation,
6748 diag::err_deduction_guide_invalid_specifier)
6749 << "typedef";
6750 else
6751 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6752 << D.getName().getSourceRange();
6753 return nullptr;
6754 }
6755
6756 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6757 if (!NewTD) return nullptr;
6758
6759 // Handle attributes prior to checking for duplicates in MergeVarDecl
6760 ProcessDeclAttributes(S, NewTD, D);
6761
6762 CheckTypedefForVariablyModifiedType(S, NewTD);
6763
6764 bool Redeclaration = D.isRedeclaration();
6765 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6766 D.setRedeclaration(Redeclaration);
6767 return ND;
6768}
6769
6770void
6771Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6772 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6773 // then it shall have block scope.
6774 // Note that variably modified types must be fixed before merging the decl so
6775 // that redeclarations will match.
6776 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6777 QualType T = TInfo->getType();
6778 if (T->isVariablyModifiedType()) {
6779 setFunctionHasBranchProtectedScope();
6780
6781 if (S->getFnParent() == nullptr) {
6782 bool SizeIsNegative;
6783 llvm::APSInt Oversized;
6784 TypeSourceInfo *FixedTInfo =
6785 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6786 SizeIsNegative,
6787 Oversized);
6788 if (FixedTInfo) {
6789 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6790 NewTD->setTypeSourceInfo(FixedTInfo);
6791 } else {
6792 if (SizeIsNegative)
6793 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6794 else if (T->isVariableArrayType())
6795 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6796 else if (Oversized.getBoolValue())
6797 Diag(NewTD->getLocation(), diag::err_array_too_large)
6798 << toString(Oversized, 10);
6799 else
6800 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6801 NewTD->setInvalidDecl();
6802 }
6803 }
6804 }
6805}
6806
6807NamedDecl*
6808Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6809 LookupResult &Previous, bool &Redeclaration) {
6810
6811 // Find the shadowed declaration before filtering for scope.
6812 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6813
6814 // Merge the decl with the existing one if appropriate. If the decl is
6815 // in an outer scope, it isn't the same thing.
6816 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6817 /*AllowInlineNamespace*/false);
6818 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6819 if (!Previous.empty()) {
6820 Redeclaration = true;
6821 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6822 } else {
6823 inferGslPointerAttribute(TD: NewTD);
6824 }
6825
6826 if (ShadowedDecl && !Redeclaration)
6827 CheckShadow(NewTD, ShadowedDecl, Previous);
6828
6829 // If this is the C FILE type, notify the AST context.
6830 if (IdentifierInfo *II = NewTD->getIdentifier())
6831 if (!NewTD->isInvalidDecl() &&
6832 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6833 switch (II->getNotableIdentifierID()) {
6834 case tok::NotableIdentifierKind::FILE:
6835 Context.setFILEDecl(NewTD);
6836 break;
6837 case tok::NotableIdentifierKind::jmp_buf:
6838 Context.setjmp_bufDecl(NewTD);
6839 break;
6840 case tok::NotableIdentifierKind::sigjmp_buf:
6841 Context.setsigjmp_bufDecl(NewTD);
6842 break;
6843 case tok::NotableIdentifierKind::ucontext_t:
6844 Context.setucontext_tDecl(NewTD);
6845 break;
6846 case tok::NotableIdentifierKind::float_t:
6847 case tok::NotableIdentifierKind::double_t:
6848 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6849 break;
6850 default:
6851 break;
6852 }
6853 }
6854
6855 return NewTD;
6856}
6857
6858/// Determines whether the given declaration is an out-of-scope
6859/// previous declaration.
6860///
6861/// This routine should be invoked when name lookup has found a
6862/// previous declaration (PrevDecl) that is not in the scope where a
6863/// new declaration by the same name is being introduced. If the new
6864/// declaration occurs in a local scope, previous declarations with
6865/// linkage may still be considered previous declarations (C99
6866/// 6.2.2p4-5, C++ [basic.link]p6).
6867///
6868/// \param PrevDecl the previous declaration found by name
6869/// lookup
6870///
6871/// \param DC the context in which the new declaration is being
6872/// declared.
6873///
6874/// \returns true if PrevDecl is an out-of-scope previous declaration
6875/// for a new delcaration with the same name.
6876static bool
6877isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6878 ASTContext &Context) {
6879 if (!PrevDecl)
6880 return false;
6881
6882 if (!PrevDecl->hasLinkage())
6883 return false;
6884
6885 if (Context.getLangOpts().CPlusPlus) {
6886 // C++ [basic.link]p6:
6887 // If there is a visible declaration of an entity with linkage
6888 // having the same name and type, ignoring entities declared
6889 // outside the innermost enclosing namespace scope, the block
6890 // scope declaration declares that same entity and receives the
6891 // linkage of the previous declaration.
6892 DeclContext *OuterContext = DC->getRedeclContext();
6893 if (!OuterContext->isFunctionOrMethod())
6894 // This rule only applies to block-scope declarations.
6895 return false;
6896
6897 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6898 if (PrevOuterContext->isRecord())
6899 // We found a member function: ignore it.
6900 return false;
6901
6902 // Find the innermost enclosing namespace for the new and
6903 // previous declarations.
6904 OuterContext = OuterContext->getEnclosingNamespaceContext();
6905 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6906
6907 // The previous declaration is in a different namespace, so it
6908 // isn't the same function.
6909 if (!OuterContext->Equals(DC: PrevOuterContext))
6910 return false;
6911 }
6912
6913 return true;
6914}
6915
6916static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6917 CXXScopeSpec &SS = D.getCXXScopeSpec();
6918 if (!SS.isSet()) return;
6919 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
6920}
6921
6922void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6923 if (Decl->getType().hasAddressSpace())
6924 return;
6925 if (Decl->getType()->isDependentType())
6926 return;
6927 if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) {
6928 QualType Type = Var->getType();
6929 if (Type->isSamplerT() || Type->isVoidType())
6930 return;
6931 LangAS ImplAS = LangAS::opencl_private;
6932 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6933 // __opencl_c_program_scope_global_variables feature, the address space
6934 // for a variable at program scope or a static or extern variable inside
6935 // a function are inferred to be __global.
6936 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
6937 Var->hasGlobalStorage())
6938 ImplAS = LangAS::opencl_global;
6939 // If the original type from a decayed type is an array type and that array
6940 // type has no address space yet, deduce it now.
6941 if (auto DT = dyn_cast<DecayedType>(Type)) {
6942 auto OrigTy = DT->getOriginalType();
6943 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6944 // Add the address space to the original array type and then propagate
6945 // that to the element type through `getAsArrayType`.
6946 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
6947 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
6948 // Re-generate the decayed type.
6949 Type = Context.getDecayedType(OrigTy);
6950 }
6951 }
6952 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6953 // Apply any qualifiers (including address space) from the array type to
6954 // the element type. This implements C99 6.7.3p8: "If the specification of
6955 // an array type includes any type qualifiers, the element type is so
6956 // qualified, not the array type."
6957 if (Type->isArrayType())
6958 Type = QualType(Context.getAsArrayType(T: Type), 0);
6959 Decl->setType(Type);
6960 }
6961}
6962
6963static void checkWeakAttr(Sema &S, NamedDecl &ND) {
6964 // 'weak' only applies to declarations with external linkage.
6965 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6966 if (!ND.isExternallyVisible()) {
6967 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6968 ND.dropAttr<WeakAttr>();
6969 }
6970 }
6971}
6972
6973static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6974 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6975 if (ND.isExternallyVisible()) {
6976 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6977 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6978 }
6979 }
6980}
6981
6982static void checkAliasAttr(Sema &S, NamedDecl &ND) {
6983 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
6984 if (VD->hasInit()) {
6985 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6986 assert(VD->isThisDeclarationADefinition() &&
6987 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6988 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6989 VD->dropAttr<AliasAttr>();
6990 }
6991 }
6992 }
6993}
6994
6995static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
6996 // 'selectany' only applies to externally visible variable declarations.
6997 // It does not apply to functions.
6998 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6999 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7000 S.Diag(Attr->getLocation(),
7001 diag::err_attribute_selectany_non_extern_data);
7002 ND.dropAttr<SelectAnyAttr>();
7003 }
7004 }
7005}
7006
7007static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7008 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7009 if (!ND.isExternallyVisible())
7010 S.Diag(Attr->getLocation(),
7011 diag::warn_attribute_hybrid_patchable_non_extern);
7012 }
7013}
7014
7015static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7016 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7017 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7018 bool IsAnonymousNS = false;
7019 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7020 if (VD) {
7021 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7022 while (NS && !IsAnonymousNS) {
7023 IsAnonymousNS = NS->isAnonymousNamespace();
7024 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7025 }
7026 }
7027 // dll attributes require external linkage. Static locals may have external
7028 // linkage but still cannot be explicitly imported or exported.
7029 // In Microsoft mode, a variable defined in anonymous namespace must have
7030 // external linkage in order to be exported.
7031 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7032 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7033 (!AnonNSInMicrosoftMode &&
7034 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7035 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7036 << &ND << Attr;
7037 ND.setInvalidDecl();
7038 }
7039 }
7040}
7041
7042static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7043 // Check the attributes on the function type and function params, if any.
7044 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7045 FD = FD->getMostRecentDecl();
7046 // Don't declare this variable in the second operand of the for-statement;
7047 // GCC miscompiles that by ending its lifetime before evaluating the
7048 // third operand. See gcc.gnu.org/PR86769.
7049 AttributedTypeLoc ATL;
7050 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7051 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7052 TL = ATL.getModifiedLoc()) {
7053 // The [[lifetimebound]] attribute can be applied to the implicit object
7054 // parameter of a non-static member function (other than a ctor or dtor)
7055 // by applying it to the function type.
7056 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7057 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7058 int NoImplicitObjectError = -1;
7059 if (!MD)
7060 NoImplicitObjectError = 0;
7061 else if (MD->isStatic())
7062 NoImplicitObjectError = 1;
7063 else if (MD->isExplicitObjectMemberFunction())
7064 NoImplicitObjectError = 2;
7065 if (NoImplicitObjectError != -1) {
7066 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7067 << NoImplicitObjectError << A->getRange();
7068 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7069 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7070 << isa<CXXDestructorDecl>(MD) << A->getRange();
7071 } else if (MD->getReturnType()->isVoidType()) {
7072 S.Diag(
7073 MD->getLocation(),
7074 diag::
7075 err_lifetimebound_implicit_object_parameter_void_return_type);
7076 }
7077 }
7078 }
7079
7080 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7081 const ParmVarDecl *P = FD->getParamDecl(i: I);
7082
7083 // The [[lifetimebound]] attribute can be applied to a function parameter
7084 // only if the function returns a value.
7085 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7086 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7087 S.Diag(A->getLocation(),
7088 diag::err_lifetimebound_parameter_void_return_type);
7089 }
7090 }
7091 }
7092 }
7093}
7094
7095static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7096 // Ensure that an auto decl is deduced otherwise the checks below might cache
7097 // the wrong linkage.
7098 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7099
7100 checkWeakAttr(S, ND);
7101 checkWeakRefAttr(S, ND);
7102 checkAliasAttr(S, ND);
7103 checkSelectAnyAttr(S, ND);
7104 checkHybridPatchableAttr(S, ND);
7105 checkInheritableAttr(S, ND);
7106 checkLifetimeBoundAttr(S, ND);
7107}
7108
7109static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7110 NamedDecl *NewDecl,
7111 bool IsSpecialization,
7112 bool IsDefinition) {
7113 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7114 return;
7115
7116 bool IsTemplate = false;
7117 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7118 OldDecl = OldTD->getTemplatedDecl();
7119 IsTemplate = true;
7120 if (!IsSpecialization)
7121 IsDefinition = false;
7122 }
7123 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7124 NewDecl = NewTD->getTemplatedDecl();
7125 IsTemplate = true;
7126 }
7127
7128 if (!OldDecl || !NewDecl)
7129 return;
7130
7131 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7132 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7133 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7134 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7135
7136 // dllimport and dllexport are inheritable attributes so we have to exclude
7137 // inherited attribute instances.
7138 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7139 (NewExportAttr && !NewExportAttr->isInherited());
7140
7141 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7142 // the only exception being explicit specializations.
7143 // Implicitly generated declarations are also excluded for now because there
7144 // is no other way to switch these to use dllimport or dllexport.
7145 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7146
7147 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7148 // Allow with a warning for free functions and global variables.
7149 bool JustWarn = false;
7150 if (!OldDecl->isCXXClassMember()) {
7151 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7152 if (VD && !VD->getDescribedVarTemplate())
7153 JustWarn = true;
7154 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7155 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7156 JustWarn = true;
7157 }
7158
7159 // We cannot change a declaration that's been used because IR has already
7160 // been emitted. Dllimported functions will still work though (modulo
7161 // address equality) as they can use the thunk.
7162 if (OldDecl->isUsed())
7163 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7164 JustWarn = false;
7165
7166 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7167 : diag::err_attribute_dll_redeclaration;
7168 S.Diag(NewDecl->getLocation(), DiagID)
7169 << NewDecl
7170 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7171 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7172 if (!JustWarn) {
7173 NewDecl->setInvalidDecl();
7174 return;
7175 }
7176 }
7177
7178 // A redeclaration is not allowed to drop a dllimport attribute, the only
7179 // exceptions being inline function definitions (except for function
7180 // templates), local extern declarations, qualified friend declarations or
7181 // special MSVC extension: in the last case, the declaration is treated as if
7182 // it were marked dllexport.
7183 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7184 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7185 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7186 // Ignore static data because out-of-line definitions are diagnosed
7187 // separately.
7188 IsStaticDataMember = VD->isStaticDataMember();
7189 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7190 VarDecl::DeclarationOnly;
7191 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7192 IsInline = FD->isInlined();
7193 IsQualifiedFriend = FD->getQualifier() &&
7194 FD->getFriendObjectKind() == Decl::FOK_Declared;
7195 }
7196
7197 if (OldImportAttr && !HasNewAttr &&
7198 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7199 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7200 if (IsMicrosoftABI && IsDefinition) {
7201 if (IsSpecialization) {
7202 S.Diag(
7203 NewDecl->getLocation(),
7204 diag::err_attribute_dllimport_function_specialization_definition);
7205 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7206 NewDecl->dropAttr<DLLImportAttr>();
7207 } else {
7208 S.Diag(NewDecl->getLocation(),
7209 diag::warn_redeclaration_without_import_attribute)
7210 << NewDecl;
7211 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7212 NewDecl->dropAttr<DLLImportAttr>();
7213 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7214 S.Context, NewImportAttr->getRange()));
7215 }
7216 } else if (IsMicrosoftABI && IsSpecialization) {
7217 assert(!IsDefinition);
7218 // MSVC allows this. Keep the inherited attribute.
7219 } else {
7220 S.Diag(NewDecl->getLocation(),
7221 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7222 << NewDecl << OldImportAttr;
7223 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7224 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7225 OldDecl->dropAttr<DLLImportAttr>();
7226 NewDecl->dropAttr<DLLImportAttr>();
7227 }
7228 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7229 // In MinGW, seeing a function declared inline drops the dllimport
7230 // attribute.
7231 OldDecl->dropAttr<DLLImportAttr>();
7232 NewDecl->dropAttr<DLLImportAttr>();
7233 S.Diag(NewDecl->getLocation(),
7234 diag::warn_dllimport_dropped_from_inline_function)
7235 << NewDecl << OldImportAttr;
7236 }
7237
7238 // A specialization of a class template member function is processed here
7239 // since it's a redeclaration. If the parent class is dllexport, the
7240 // specialization inherits that attribute. This doesn't happen automatically
7241 // since the parent class isn't instantiated until later.
7242 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7243 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7244 !NewImportAttr && !NewExportAttr) {
7245 if (const DLLExportAttr *ParentExportAttr =
7246 MD->getParent()->getAttr<DLLExportAttr>()) {
7247 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7248 NewAttr->setInherited(true);
7249 NewDecl->addAttr(A: NewAttr);
7250 }
7251 }
7252 }
7253}
7254
7255/// Given that we are within the definition of the given function,
7256/// will that definition behave like C99's 'inline', where the
7257/// definition is discarded except for optimization purposes?
7258static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7259 // Try to avoid calling GetGVALinkageForFunction.
7260
7261 // All cases of this require the 'inline' keyword.
7262 if (!FD->isInlined()) return false;
7263
7264 // This is only possible in C++ with the gnu_inline attribute.
7265 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7266 return false;
7267
7268 // Okay, go ahead and call the relatively-more-expensive function.
7269 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7270}
7271
7272/// Determine whether a variable is extern "C" prior to attaching
7273/// an initializer. We can't just call isExternC() here, because that
7274/// will also compute and cache whether the declaration is externally
7275/// visible, which might change when we attach the initializer.
7276///
7277/// This can only be used if the declaration is known to not be a
7278/// redeclaration of an internal linkage declaration.
7279///
7280/// For instance:
7281///
7282/// auto x = []{};
7283///
7284/// Attaching the initializer here makes this declaration not externally
7285/// visible, because its type has internal linkage.
7286///
7287/// FIXME: This is a hack.
7288template<typename T>
7289static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7290 if (S.getLangOpts().CPlusPlus) {
7291 // In C++, the overloadable attribute negates the effects of extern "C".
7292 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7293 return false;
7294
7295 // So do CUDA's host/device attributes.
7296 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7297 D->template hasAttr<CUDAHostAttr>()))
7298 return false;
7299 }
7300 return D->isExternC();
7301}
7302
7303static bool shouldConsiderLinkage(const VarDecl *VD) {
7304 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7305 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7306 isa<OMPDeclareMapperDecl>(Val: DC))
7307 return VD->hasExternalStorage();
7308 if (DC->isFileContext())
7309 return true;
7310 if (DC->isRecord())
7311 return false;
7312 if (DC->getDeclKind() == Decl::HLSLBuffer)
7313 return false;
7314
7315 if (isa<RequiresExprBodyDecl>(Val: DC))
7316 return false;
7317 llvm_unreachable("Unexpected context");
7318}
7319
7320static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7321 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7322 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7323 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7324 return true;
7325 if (DC->isRecord())
7326 return false;
7327 llvm_unreachable("Unexpected context");
7328}
7329
7330static bool hasParsedAttr(Scope *S, const Declarator &PD,
7331 ParsedAttr::Kind Kind) {
7332 // Check decl attributes on the DeclSpec.
7333 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7334 return true;
7335
7336 // Walk the declarator structure, checking decl attributes that were in a type
7337 // position to the decl itself.
7338 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7339 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7340 return true;
7341 }
7342
7343 // Finally, check attributes on the decl itself.
7344 return PD.getAttributes().hasAttribute(K: Kind) ||
7345 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7346}
7347
7348bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7349 if (!DC->isFunctionOrMethod())
7350 return false;
7351
7352 // If this is a local extern function or variable declared within a function
7353 // template, don't add it into the enclosing namespace scope until it is
7354 // instantiated; it might have a dependent type right now.
7355 if (DC->isDependentContext())
7356 return true;
7357
7358 // C++11 [basic.link]p7:
7359 // When a block scope declaration of an entity with linkage is not found to
7360 // refer to some other declaration, then that entity is a member of the
7361 // innermost enclosing namespace.
7362 //
7363 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7364 // semantically-enclosing namespace, not a lexically-enclosing one.
7365 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7366 DC = DC->getParent();
7367 return true;
7368}
7369
7370/// Returns true if given declaration has external C language linkage.
7371static bool isDeclExternC(const Decl *D) {
7372 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7373 return FD->isExternC();
7374 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7375 return VD->isExternC();
7376
7377 llvm_unreachable("Unknown type of decl!");
7378}
7379
7380/// Returns true if there hasn't been any invalid type diagnosed.
7381static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7382 DeclContext *DC = NewVD->getDeclContext();
7383 QualType R = NewVD->getType();
7384
7385 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7386 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7387 // argument.
7388 if (R->isImageType() || R->isPipeType()) {
7389 Se.Diag(NewVD->getLocation(),
7390 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7391 << R;
7392 NewVD->setInvalidDecl();
7393 return false;
7394 }
7395
7396 // OpenCL v1.2 s6.9.r:
7397 // The event type cannot be used to declare a program scope variable.
7398 // OpenCL v2.0 s6.9.q:
7399 // The clk_event_t and reserve_id_t types cannot be declared in program
7400 // scope.
7401 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7402 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7403 Se.Diag(NewVD->getLocation(),
7404 diag::err_invalid_type_for_program_scope_var)
7405 << R;
7406 NewVD->setInvalidDecl();
7407 return false;
7408 }
7409 }
7410
7411 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7412 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7413 LO: Se.getLangOpts())) {
7414 QualType NR = R.getCanonicalType();
7415 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7416 NR->isReferenceType()) {
7417 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7418 NR->isFunctionReferenceType()) {
7419 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7420 << NR->isReferenceType();
7421 NewVD->setInvalidDecl();
7422 return false;
7423 }
7424 NR = NR->getPointeeType();
7425 }
7426 }
7427
7428 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7429 LO: Se.getLangOpts())) {
7430 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7431 // half array type (unless the cl_khr_fp16 extension is enabled).
7432 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7433 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7434 NewVD->setInvalidDecl();
7435 return false;
7436 }
7437 }
7438
7439 // OpenCL v1.2 s6.9.r:
7440 // The event type cannot be used with the __local, __constant and __global
7441 // address space qualifiers.
7442 if (R->isEventT()) {
7443 if (R.getAddressSpace() != LangAS::opencl_private) {
7444 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7445 NewVD->setInvalidDecl();
7446 return false;
7447 }
7448 }
7449
7450 if (R->isSamplerT()) {
7451 // OpenCL v1.2 s6.9.b p4:
7452 // The sampler type cannot be used with the __local and __global address
7453 // space qualifiers.
7454 if (R.getAddressSpace() == LangAS::opencl_local ||
7455 R.getAddressSpace() == LangAS::opencl_global) {
7456 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7457 NewVD->setInvalidDecl();
7458 }
7459
7460 // OpenCL v1.2 s6.12.14.1:
7461 // A global sampler must be declared with either the constant address
7462 // space qualifier or with the const qualifier.
7463 if (DC->isTranslationUnit() &&
7464 !(R.getAddressSpace() == LangAS::opencl_constant ||
7465 R.isConstQualified())) {
7466 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7467 NewVD->setInvalidDecl();
7468 }
7469 if (NewVD->isInvalidDecl())
7470 return false;
7471 }
7472
7473 return true;
7474}
7475
7476template <typename AttrTy>
7477static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7478 const TypedefNameDecl *TND = TT->getDecl();
7479 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7480 AttrTy *Clone = Attribute->clone(S.Context);
7481 Clone->setInherited(true);
7482 D->addAttr(A: Clone);
7483 }
7484}
7485
7486// This function emits warning and a corresponding note based on the
7487// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7488// declarations of an annotated type must be const qualified.
7489static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7490 QualType VarType = VD->getType().getCanonicalType();
7491
7492 // Ignore local declarations (for now) and those with const qualification.
7493 // TODO: Local variables should not be allowed if their type declaration has
7494 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7495 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7496 return;
7497
7498 if (VarType->isArrayType()) {
7499 // Retrieve element type for array declarations.
7500 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7501 }
7502
7503 const RecordDecl *RD = VarType->getAsRecordDecl();
7504
7505 // Check if the record declaration is present and if it has any attributes.
7506 if (RD == nullptr)
7507 return;
7508
7509 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7510 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7511 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7512 return;
7513 }
7514}
7515
7516// Checks if VD is declared at global scope or with C language linkage.
7517static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7518 return Name.getAsIdentifierInfo() &&
7519 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7520 !VD->getDescribedVarTemplate() &&
7521 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7522 VD->isExternC());
7523}
7524
7525NamedDecl *Sema::ActOnVariableDeclarator(
7526 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7527 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7528 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7529 QualType R = TInfo->getType();
7530 DeclarationName Name = GetNameForDeclarator(D).getName();
7531
7532 IdentifierInfo *II = Name.getAsIdentifierInfo();
7533 bool IsPlaceholderVariable = false;
7534
7535 if (D.isDecompositionDeclarator()) {
7536 // Take the name of the first declarator as our name for diagnostic
7537 // purposes.
7538 auto &Decomp = D.getDecompositionDeclarator();
7539 if (!Decomp.bindings().empty()) {
7540 II = Decomp.bindings()[0].Name;
7541 Name = II;
7542 }
7543 } else if (!II) {
7544 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7545 return nullptr;
7546 }
7547
7548
7549 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7550 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7551 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7552 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7553
7554 IsPlaceholderVariable = true;
7555
7556 if (!Previous.empty()) {
7557 NamedDecl *PrevDecl = *Previous.begin();
7558 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7559 DC->getRedeclContext());
7560 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7561 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7562 if (IsPlaceholderVariable)
7563 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7564 }
7565 }
7566 }
7567
7568 // dllimport globals without explicit storage class are treated as extern. We
7569 // have to change the storage class this early to get the right DeclContext.
7570 if (SC == SC_None && !DC->isRecord() &&
7571 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7572 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7573 SC = SC_Extern;
7574
7575 DeclContext *OriginalDC = DC;
7576 bool IsLocalExternDecl = SC == SC_Extern &&
7577 adjustContextForLocalExternDecl(DC);
7578
7579 if (SCSpec == DeclSpec::SCS_mutable) {
7580 // mutable can only appear on non-static class members, so it's always
7581 // an error here
7582 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7583 D.setInvalidType();
7584 SC = SC_None;
7585 }
7586
7587 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7588 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7589 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7590 // In C++11, the 'register' storage class specifier is deprecated.
7591 // Suppress the warning in system macros, it's used in macros in some
7592 // popular C system headers, such as in glibc's htonl() macro.
7593 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7594 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7595 : diag::warn_deprecated_register)
7596 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7597 }
7598
7599 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7600
7601 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7602 // C99 6.9p2: The storage-class specifiers auto and register shall not
7603 // appear in the declaration specifiers in an external declaration.
7604 // Global Register+Asm is a GNU extension we support.
7605 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7606 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7607 D.setInvalidType();
7608 }
7609 }
7610
7611 // If this variable has a VLA type and an initializer, try to
7612 // fold to a constant-sized type. This is otherwise invalid.
7613 if (D.hasInitializer() && R->isVariableArrayType())
7614 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7615 /*DiagID=*/FailedFoldDiagID: 0);
7616
7617 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7618 const AutoType *AT = TL.getTypePtr();
7619 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7620 }
7621
7622 bool IsMemberSpecialization = false;
7623 bool IsVariableTemplateSpecialization = false;
7624 bool IsPartialSpecialization = false;
7625 bool IsVariableTemplate = false;
7626 VarDecl *NewVD = nullptr;
7627 VarTemplateDecl *NewTemplate = nullptr;
7628 TemplateParameterList *TemplateParams = nullptr;
7629 if (!getLangOpts().CPlusPlus) {
7630 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7631 Id: II, T: R, TInfo, S: SC);
7632
7633 if (R->getContainedDeducedType())
7634 ParsingInitForAutoVars.insert(NewVD);
7635
7636 if (D.isInvalidType())
7637 NewVD->setInvalidDecl();
7638
7639 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7640 NewVD->hasLocalStorage())
7641 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7642 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7643 } else {
7644 bool Invalid = false;
7645 // Match up the template parameter lists with the scope specifier, then
7646 // determine whether we have a template or a template specialization.
7647 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7648 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7649 SS: D.getCXXScopeSpec(),
7650 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7651 ? D.getName().TemplateId
7652 : nullptr,
7653 ParamLists: TemplateParamLists,
7654 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7655
7656 if (TemplateParams) {
7657 if (DC->isDependentContext()) {
7658 ContextRAII SavedContext(*this, DC);
7659 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7660 Invalid = true;
7661 }
7662
7663 if (!TemplateParams->size() &&
7664 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7665 // There is an extraneous 'template<>' for this variable. Complain
7666 // about it, but allow the declaration of the variable.
7667 Diag(TemplateParams->getTemplateLoc(),
7668 diag::err_template_variable_noparams)
7669 << II
7670 << SourceRange(TemplateParams->getTemplateLoc(),
7671 TemplateParams->getRAngleLoc());
7672 TemplateParams = nullptr;
7673 } else {
7674 // Check that we can declare a template here.
7675 if (CheckTemplateDeclScope(S, TemplateParams))
7676 return nullptr;
7677
7678 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7679 // This is an explicit specialization or a partial specialization.
7680 IsVariableTemplateSpecialization = true;
7681 IsPartialSpecialization = TemplateParams->size() > 0;
7682 } else { // if (TemplateParams->size() > 0)
7683 // This is a template declaration.
7684 IsVariableTemplate = true;
7685
7686 // Only C++1y supports variable templates (N3651).
7687 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7688 }
7689 }
7690 } else {
7691 // Check that we can declare a member specialization here.
7692 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7693 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7694 return nullptr;
7695 assert((Invalid ||
7696 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7697 "should have a 'template<>' for this decl");
7698 }
7699
7700 bool IsExplicitSpecialization =
7701 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7702
7703 // C++ [temp.expl.spec]p2:
7704 // The declaration in an explicit-specialization shall not be an
7705 // export-declaration. An explicit specialization shall not use a
7706 // storage-class-specifier other than thread_local.
7707 //
7708 // We use the storage-class-specifier from DeclSpec because we may have
7709 // added implicit 'extern' for declarations with __declspec(dllimport)!
7710 if (SCSpec != DeclSpec::SCS_unspecified &&
7711 (IsExplicitSpecialization || IsMemberSpecialization)) {
7712 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7713 diag::ext_explicit_specialization_storage_class)
7714 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7715 }
7716
7717 if (CurContext->isRecord()) {
7718 if (SC == SC_Static) {
7719 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7720 // Walk up the enclosing DeclContexts to check for any that are
7721 // incompatible with static data members.
7722 const DeclContext *FunctionOrMethod = nullptr;
7723 const CXXRecordDecl *AnonStruct = nullptr;
7724 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7725 if (Ctxt->isFunctionOrMethod()) {
7726 FunctionOrMethod = Ctxt;
7727 break;
7728 }
7729 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7730 if (ParentDecl && !ParentDecl->getDeclName()) {
7731 AnonStruct = ParentDecl;
7732 break;
7733 }
7734 }
7735 if (FunctionOrMethod) {
7736 // C++ [class.static.data]p5: A local class shall not have static
7737 // data members.
7738 Diag(D.getIdentifierLoc(),
7739 diag::err_static_data_member_not_allowed_in_local_class)
7740 << Name << RD->getDeclName() << RD->getTagKind();
7741 } else if (AnonStruct) {
7742 // C++ [class.static.data]p4: Unnamed classes and classes contained
7743 // directly or indirectly within unnamed classes shall not contain
7744 // static data members.
7745 Diag(D.getIdentifierLoc(),
7746 diag::err_static_data_member_not_allowed_in_anon_struct)
7747 << Name << AnonStruct->getTagKind();
7748 Invalid = true;
7749 } else if (RD->isUnion()) {
7750 // C++98 [class.union]p1: If a union contains a static data member,
7751 // the program is ill-formed. C++11 drops this restriction.
7752 DiagCompat(D.getIdentifierLoc(),
7753 diag_compat::static_data_member_in_union)
7754 << Name;
7755 }
7756 }
7757 } else if (IsVariableTemplate || IsPartialSpecialization) {
7758 // There is no such thing as a member field template.
7759 Diag(D.getIdentifierLoc(), diag::err_template_member)
7760 << II << TemplateParams->getSourceRange();
7761 // Recover by pretending this is a static data member template.
7762 SC = SC_Static;
7763 }
7764 } else if (DC->isRecord()) {
7765 // This is an out-of-line definition of a static data member.
7766 switch (SC) {
7767 case SC_None:
7768 break;
7769 case SC_Static:
7770 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7771 diag::err_static_out_of_line)
7772 << FixItHint::CreateRemoval(
7773 D.getDeclSpec().getStorageClassSpecLoc());
7774 break;
7775 case SC_Auto:
7776 case SC_Register:
7777 case SC_Extern:
7778 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7779 // to names of variables declared in a block or to function parameters.
7780 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7781 // of class members
7782
7783 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7784 diag::err_storage_class_for_static_member)
7785 << FixItHint::CreateRemoval(
7786 D.getDeclSpec().getStorageClassSpecLoc());
7787 break;
7788 case SC_PrivateExtern:
7789 llvm_unreachable("C storage class in c++!");
7790 }
7791 }
7792
7793 if (IsVariableTemplateSpecialization) {
7794 SourceLocation TemplateKWLoc =
7795 TemplateParamLists.size() > 0
7796 ? TemplateParamLists[0]->getTemplateLoc()
7797 : SourceLocation();
7798 DeclResult Res = ActOnVarTemplateSpecialization(
7799 S, D, DI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7800 IsPartialSpecialization);
7801 if (Res.isInvalid())
7802 return nullptr;
7803 NewVD = cast<VarDecl>(Val: Res.get());
7804 AddToScope = false;
7805 } else if (D.isDecompositionDeclarator()) {
7806 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7807 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
7808 Bindings);
7809 } else
7810 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7811 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
7812
7813 // If this is supposed to be a variable template, create it as such.
7814 if (IsVariableTemplate) {
7815 NewTemplate =
7816 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
7817 Params: TemplateParams, Decl: NewVD);
7818 NewVD->setDescribedVarTemplate(NewTemplate);
7819 }
7820
7821 // If this decl has an auto type in need of deduction, make a note of the
7822 // Decl so we can diagnose uses of it in its own initializer.
7823 if (R->getContainedDeducedType())
7824 ParsingInitForAutoVars.insert(NewVD);
7825
7826 if (D.isInvalidType() || Invalid) {
7827 NewVD->setInvalidDecl();
7828 if (NewTemplate)
7829 NewTemplate->setInvalidDecl();
7830 }
7831
7832 SetNestedNameSpecifier(*this, NewVD, D);
7833
7834 // If we have any template parameter lists that don't directly belong to
7835 // the variable (matching the scope specifier), store them.
7836 // An explicit variable template specialization does not own any template
7837 // parameter lists.
7838 unsigned VDTemplateParamLists =
7839 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7840 if (TemplateParamLists.size() > VDTemplateParamLists)
7841 NewVD->setTemplateParameterListsInfo(
7842 Context, TemplateParamLists.drop_back(N: VDTemplateParamLists));
7843 }
7844
7845 if (D.getDeclSpec().isInlineSpecified()) {
7846 if (!getLangOpts().CPlusPlus) {
7847 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7848 << 0;
7849 } else if (CurContext->isFunctionOrMethod()) {
7850 // 'inline' is not allowed on block scope variable declaration.
7851 Diag(D.getDeclSpec().getInlineSpecLoc(),
7852 diag::err_inline_declaration_block_scope) << Name
7853 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7854 } else {
7855 Diag(D.getDeclSpec().getInlineSpecLoc(),
7856 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
7857 : diag::compat_pre_cxx17_inline_variable);
7858 NewVD->setInlineSpecified();
7859 }
7860 }
7861
7862 // Set the lexical context. If the declarator has a C++ scope specifier, the
7863 // lexical context will be different from the semantic context.
7864 NewVD->setLexicalDeclContext(CurContext);
7865 if (NewTemplate)
7866 NewTemplate->setLexicalDeclContext(CurContext);
7867
7868 if (IsLocalExternDecl) {
7869 if (D.isDecompositionDeclarator())
7870 for (auto *B : Bindings)
7871 B->setLocalExternDecl();
7872 else
7873 NewVD->setLocalExternDecl();
7874 }
7875
7876 bool EmitTLSUnsupportedError = false;
7877 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7878 // C++11 [dcl.stc]p4:
7879 // When thread_local is applied to a variable of block scope the
7880 // storage-class-specifier static is implied if it does not appear
7881 // explicitly.
7882 // Core issue: 'static' is not implied if the variable is declared
7883 // 'extern'.
7884 if (NewVD->hasLocalStorage() &&
7885 (SCSpec != DeclSpec::SCS_unspecified ||
7886 TSCS != DeclSpec::TSCS_thread_local ||
7887 !DC->isFunctionOrMethod()))
7888 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7889 diag::err_thread_non_global)
7890 << DeclSpec::getSpecifierName(TSCS);
7891 else if (!Context.getTargetInfo().isTLSSupported()) {
7892 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
7893 // Postpone error emission until we've collected attributes required to
7894 // figure out whether it's a host or device variable and whether the
7895 // error should be ignored.
7896 EmitTLSUnsupportedError = true;
7897 // We still need to mark the variable as TLS so it shows up in AST with
7898 // proper storage class for other tools to use even if we're not going
7899 // to emit any code for it.
7900 NewVD->setTSCSpec(TSCS);
7901 } else
7902 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7903 diag::err_thread_unsupported);
7904 } else
7905 NewVD->setTSCSpec(TSCS);
7906 }
7907
7908 switch (D.getDeclSpec().getConstexprSpecifier()) {
7909 case ConstexprSpecKind::Unspecified:
7910 break;
7911
7912 case ConstexprSpecKind::Consteval:
7913 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7914 diag::err_constexpr_wrong_decl_kind)
7915 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7916 [[fallthrough]];
7917
7918 case ConstexprSpecKind::Constexpr:
7919 NewVD->setConstexpr(true);
7920 // C++1z [dcl.spec.constexpr]p1:
7921 // A static data member declared with the constexpr specifier is
7922 // implicitly an inline variable.
7923 if (NewVD->isStaticDataMember() &&
7924 (getLangOpts().CPlusPlus17 ||
7925 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7926 NewVD->setImplicitlyInline();
7927 break;
7928
7929 case ConstexprSpecKind::Constinit:
7930 if (!NewVD->hasGlobalStorage())
7931 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7932 diag::err_constinit_local_variable);
7933 else
7934 NewVD->addAttr(
7935 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7936 ConstInitAttr::Keyword_constinit));
7937 break;
7938 }
7939
7940 // C99 6.7.4p3
7941 // An inline definition of a function with external linkage shall
7942 // not contain a definition of a modifiable object with static or
7943 // thread storage duration...
7944 // We only apply this when the function is required to be defined
7945 // elsewhere, i.e. when the function is not 'extern inline'. Note
7946 // that a local variable with thread storage duration still has to
7947 // be marked 'static'. Also note that it's possible to get these
7948 // semantics in C++ using __attribute__((gnu_inline)).
7949 if (SC == SC_Static && S->getFnParent() != nullptr &&
7950 !NewVD->getType().isConstQualified()) {
7951 FunctionDecl *CurFD = getCurFunctionDecl();
7952 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
7953 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7954 diag::warn_static_local_in_extern_inline);
7955 MaybeSuggestAddingStaticToDecl(D: CurFD);
7956 }
7957 }
7958
7959 if (D.getDeclSpec().isModulePrivateSpecified()) {
7960 if (IsVariableTemplateSpecialization)
7961 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7962 << (IsPartialSpecialization ? 1 : 0)
7963 << FixItHint::CreateRemoval(
7964 D.getDeclSpec().getModulePrivateSpecLoc());
7965 else if (IsMemberSpecialization)
7966 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7967 << 2
7968 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7969 else if (NewVD->hasLocalStorage())
7970 Diag(NewVD->getLocation(), diag::err_module_private_local)
7971 << 0 << NewVD
7972 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7973 << FixItHint::CreateRemoval(
7974 D.getDeclSpec().getModulePrivateSpecLoc());
7975 else {
7976 NewVD->setModulePrivate();
7977 if (NewTemplate)
7978 NewTemplate->setModulePrivate();
7979 for (auto *B : Bindings)
7980 B->setModulePrivate();
7981 }
7982 }
7983
7984 if (getLangOpts().OpenCL) {
7985 deduceOpenCLAddressSpace(NewVD);
7986
7987 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7988 if (TSC != TSCS_unspecified) {
7989 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7990 diag::err_opencl_unknown_type_specifier)
7991 << getLangOpts().getOpenCLVersionString()
7992 << DeclSpec::getSpecifierName(TSC) << 1;
7993 NewVD->setInvalidDecl();
7994 }
7995 }
7996
7997 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7998 // address space if the table has local storage (semantic checks elsewhere
7999 // will produce an error anyway).
8000 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8001 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8002 !NewVD->hasLocalStorage()) {
8003 QualType Type = Context.getAddrSpaceQualType(
8004 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8005 NewVD->setType(Type);
8006 }
8007 }
8008
8009 // Handle attributes prior to checking for duplicates in MergeVarDecl
8010 ProcessDeclAttributes(S, NewVD, D);
8011
8012 if (getLangOpts().HLSL)
8013 HLSL().ActOnVariableDeclarator(VD: NewVD);
8014
8015 if (getLangOpts().OpenACC)
8016 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8017
8018 // FIXME: This is probably the wrong location to be doing this and we should
8019 // probably be doing this for more attributes (especially for function
8020 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8021 // the code to copy attributes would be generated by TableGen.
8022 if (R->isFunctionPointerType())
8023 if (const auto *TT = R->getAs<TypedefType>())
8024 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8025
8026 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8027 if (EmitTLSUnsupportedError &&
8028 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
8029 (getLangOpts().OpenMPIsTargetDevice &&
8030 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8031 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8032 diag::err_thread_unsupported);
8033
8034 if (EmitTLSUnsupportedError &&
8035 (LangOpts.SYCLIsDevice ||
8036 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8037 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8038 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8039 // storage [duration]."
8040 if (SC == SC_None && S->getFnParent() != nullptr &&
8041 (NewVD->hasAttr<CUDASharedAttr>() ||
8042 NewVD->hasAttr<CUDAConstantAttr>())) {
8043 NewVD->setStorageClass(SC_Static);
8044 }
8045 }
8046
8047 // Ensure that dllimport globals without explicit storage class are treated as
8048 // extern. The storage class is set above using parsed attributes. Now we can
8049 // check the VarDecl itself.
8050 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8051 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8052 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8053
8054 // In auto-retain/release, infer strong retension for variables of
8055 // retainable type.
8056 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8057 NewVD->setInvalidDecl();
8058
8059 // Handle GNU asm-label extension (encoded as an attribute).
8060 if (Expr *E = (Expr*)D.getAsmLabel()) {
8061 // The parser guarantees this is a string.
8062 StringLiteral *SE = cast<StringLiteral>(Val: E);
8063 StringRef Label = SE->getString();
8064 if (S->getFnParent() != nullptr) {
8065 switch (SC) {
8066 case SC_None:
8067 case SC_Auto:
8068 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8069 break;
8070 case SC_Register:
8071 // Local Named register
8072 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8073 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8074 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8075 break;
8076 case SC_Static:
8077 case SC_Extern:
8078 case SC_PrivateExtern:
8079 break;
8080 }
8081 } else if (SC == SC_Register) {
8082 // Global Named register
8083 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8084 const auto &TI = Context.getTargetInfo();
8085 bool HasSizeMismatch;
8086
8087 if (!TI.isValidGCCRegisterName(Label))
8088 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8089 else if (!TI.validateGlobalRegisterVariable(Label,
8090 Context.getTypeSize(R),
8091 HasSizeMismatch))
8092 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8093 else if (HasSizeMismatch)
8094 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8095 }
8096
8097 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
8098 Diag(TInfo->getTypeLoc().getBeginLoc(),
8099 diag::err_asm_unsupported_register_type)
8100 << TInfo->getTypeLoc().getSourceRange();
8101 NewVD->setInvalidDecl(true);
8102 }
8103 }
8104
8105 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8106 /*IsLiteralLabel=*/true,
8107 SE->getStrTokenLoc(0)));
8108 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8109 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8110 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8111 if (I != ExtnameUndeclaredIdentifiers.end()) {
8112 if (isDeclExternC(NewVD)) {
8113 NewVD->addAttr(A: I->second);
8114 ExtnameUndeclaredIdentifiers.erase(I);
8115 } else
8116 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8117 << /*Variable*/1 << NewVD;
8118 }
8119 }
8120
8121 // Find the shadowed declaration before filtering for scope.
8122 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8123 ? getShadowedDeclaration(D: NewVD, R: Previous)
8124 : nullptr;
8125
8126 // Don't consider existing declarations that are in a different
8127 // scope and are out-of-semantic-context declarations (if the new
8128 // declaration has linkage).
8129 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8130 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8131 IsMemberSpecialization ||
8132 IsVariableTemplateSpecialization);
8133
8134 // Check whether the previous declaration is in the same block scope. This
8135 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8136 if (getLangOpts().CPlusPlus &&
8137 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8138 NewVD->setPreviousDeclInSameBlockScope(
8139 Previous.isSingleResult() && !Previous.isShadowed() &&
8140 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8141
8142 if (!getLangOpts().CPlusPlus) {
8143 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8144 } else {
8145 // If this is an explicit specialization of a static data member, check it.
8146 if (IsMemberSpecialization && !IsVariableTemplate &&
8147 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8148 CheckMemberSpecialization(NewVD, Previous))
8149 NewVD->setInvalidDecl();
8150
8151 // Merge the decl with the existing one if appropriate.
8152 if (!Previous.empty()) {
8153 if (Previous.isSingleResult() &&
8154 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8155 D.getCXXScopeSpec().isSet()) {
8156 // The user tried to define a non-static data member
8157 // out-of-line (C++ [dcl.meaning]p1).
8158 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8159 << D.getCXXScopeSpec().getRange();
8160 Previous.clear();
8161 NewVD->setInvalidDecl();
8162 }
8163 } else if (D.getCXXScopeSpec().isSet() &&
8164 !IsVariableTemplateSpecialization) {
8165 // No previous declaration in the qualifying scope.
8166 Diag(D.getIdentifierLoc(), diag::err_no_member)
8167 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8168 << D.getCXXScopeSpec().getRange();
8169 NewVD->setInvalidDecl();
8170 }
8171
8172 if (!IsPlaceholderVariable)
8173 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8174
8175 // CheckVariableDeclaration will set NewVD as invalid if something is in
8176 // error like WebAssembly tables being declared as arrays with a non-zero
8177 // size, but then parsing continues and emits further errors on that line.
8178 // To avoid that we check here if it happened and return nullptr.
8179 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8180 return nullptr;
8181
8182 if (NewTemplate) {
8183 VarTemplateDecl *PrevVarTemplate =
8184 NewVD->getPreviousDecl()
8185 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8186 : nullptr;
8187
8188 // Check the template parameter list of this declaration, possibly
8189 // merging in the template parameter list from the previous variable
8190 // template declaration.
8191 if (CheckTemplateParameterList(
8192 NewParams: TemplateParams,
8193 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8194 : nullptr,
8195 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8196 DC->isDependentContext())
8197 ? TPC_ClassTemplateMember
8198 : TPC_Other))
8199 NewVD->setInvalidDecl();
8200
8201 // If we are providing an explicit specialization of a static variable
8202 // template, make a note of that.
8203 if (PrevVarTemplate &&
8204 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8205 PrevVarTemplate->setMemberSpecialization();
8206 }
8207 }
8208
8209 // Diagnose shadowed variables iff this isn't a redeclaration.
8210 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8211 CheckShadow(NewVD, ShadowedDecl, Previous);
8212
8213 ProcessPragmaWeak(S, NewVD);
8214
8215 // If this is the first declaration of an extern C variable, update
8216 // the map of such variables.
8217 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8218 isIncompleteDeclExternC(S&: *this, D: NewVD))
8219 RegisterLocallyScopedExternCDecl(NewVD, S);
8220
8221 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8222 MangleNumberingContext *MCtx;
8223 Decl *ManglingContextDecl;
8224 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8225 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8226 if (MCtx) {
8227 Context.setManglingNumber(
8228 NewVD, MCtx->getManglingNumber(
8229 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8230 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8231 }
8232 }
8233
8234 // Special handling of variable named 'main'.
8235 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8236 // C++ [basic.start.main]p3:
8237 // A program that declares
8238 // - a variable main at global scope, or
8239 // - an entity named main with C language linkage (in any namespace)
8240 // is ill-formed
8241 if (getLangOpts().CPlusPlus)
8242 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8243 << NewVD->isExternC();
8244
8245 // In C, and external-linkage variable named main results in undefined
8246 // behavior.
8247 else if (NewVD->hasExternalFormalLinkage())
8248 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8249 }
8250
8251 if (D.isRedeclaration() && !Previous.empty()) {
8252 NamedDecl *Prev = Previous.getRepresentativeDecl();
8253 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8254 D.isFunctionDefinition());
8255 }
8256
8257 if (NewTemplate) {
8258 if (NewVD->isInvalidDecl())
8259 NewTemplate->setInvalidDecl();
8260 ActOnDocumentableDecl(NewTemplate);
8261 return NewTemplate;
8262 }
8263
8264 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8265 CompleteMemberSpecialization(NewVD, Previous);
8266
8267 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8268
8269 return NewVD;
8270}
8271
8272/// Enum describing the %select options in diag::warn_decl_shadow.
8273enum ShadowedDeclKind {
8274 SDK_Local,
8275 SDK_Global,
8276 SDK_StaticMember,
8277 SDK_Field,
8278 SDK_Typedef,
8279 SDK_Using,
8280 SDK_StructuredBinding
8281};
8282
8283/// Determine what kind of declaration we're shadowing.
8284static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8285 const DeclContext *OldDC) {
8286 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8287 return SDK_Using;
8288 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8289 return SDK_Typedef;
8290 else if (isa<BindingDecl>(Val: ShadowedDecl))
8291 return SDK_StructuredBinding;
8292 else if (isa<RecordDecl>(Val: OldDC))
8293 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8294
8295 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8296}
8297
8298/// Return the location of the capture if the given lambda captures the given
8299/// variable \p VD, or an invalid source location otherwise.
8300static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8301 const VarDecl *VD) {
8302 for (const Capture &Capture : LSI->Captures) {
8303 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8304 return Capture.getLocation();
8305 }
8306 return SourceLocation();
8307}
8308
8309static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8310 const LookupResult &R) {
8311 // Only diagnose if we're shadowing an unambiguous field or variable.
8312 if (R.getResultKind() != LookupResultKind::Found)
8313 return false;
8314
8315 // Return false if warning is ignored.
8316 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8317}
8318
8319NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8320 const LookupResult &R) {
8321 if (!shouldWarnIfShadowedDecl(Diags, R))
8322 return nullptr;
8323
8324 // Don't diagnose declarations at file scope.
8325 if (D->hasGlobalStorage() && !D->isStaticLocal())
8326 return nullptr;
8327
8328 NamedDecl *ShadowedDecl = R.getFoundDecl();
8329 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8330 : nullptr;
8331}
8332
8333NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8334 const LookupResult &R) {
8335 // Don't warn if typedef declaration is part of a class
8336 if (D->getDeclContext()->isRecord())
8337 return nullptr;
8338
8339 if (!shouldWarnIfShadowedDecl(Diags, R))
8340 return nullptr;
8341
8342 NamedDecl *ShadowedDecl = R.getFoundDecl();
8343 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8344}
8345
8346NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8347 const LookupResult &R) {
8348 if (!shouldWarnIfShadowedDecl(Diags, R))
8349 return nullptr;
8350
8351 NamedDecl *ShadowedDecl = R.getFoundDecl();
8352 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8353 : nullptr;
8354}
8355
8356void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8357 const LookupResult &R) {
8358 DeclContext *NewDC = D->getDeclContext();
8359
8360 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8361 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDC)) {
8362 // Fields are not shadowed by variables in C++ static methods.
8363 if (MD->isStatic())
8364 return;
8365
8366 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8367 return;
8368 }
8369 // Fields shadowed by constructor parameters are a special case. Usually
8370 // the constructor initializes the field with the parameter.
8371 if (isa<CXXConstructorDecl>(Val: NewDC))
8372 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8373 // Remember that this was shadowed so we can either warn about its
8374 // modification or its existence depending on warning settings.
8375 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8376 return;
8377 }
8378 }
8379
8380 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8381 if (shadowedVar->isExternC()) {
8382 // For shadowing external vars, make sure that we point to the global
8383 // declaration, not a locally scoped extern declaration.
8384 for (auto *I : shadowedVar->redecls())
8385 if (I->isFileVarDecl()) {
8386 ShadowedDecl = I;
8387 break;
8388 }
8389 }
8390
8391 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8392
8393 unsigned WarningDiag = diag::warn_decl_shadow;
8394 SourceLocation CaptureLoc;
8395 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8396 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8397 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8398 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8399 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8400 if (RD->getLambdaCaptureDefault() == LCD_None) {
8401 // Try to avoid warnings for lambdas with an explicit capture
8402 // list. Warn only when the lambda captures the shadowed decl
8403 // explicitly.
8404 CaptureLoc = getCaptureLocation(LSI, VD);
8405 if (CaptureLoc.isInvalid())
8406 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8407 } else {
8408 // Remember that this was shadowed so we can avoid the warning if
8409 // the shadowed decl isn't captured and the warning settings allow
8410 // it.
8411 cast<LambdaScopeInfo>(Val: getCurFunction())
8412 ->ShadowingDecls.push_back({.VD: D, VD});
8413 return;
8414 }
8415 }
8416 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8417 // If lambda can capture this, then emit default shadowing warning,
8418 // Otherwise it is not really a shadowing case since field is not
8419 // available in lambda's body.
8420 // At this point we don't know that lambda can capture this, so
8421 // remember that this was shadowed and delay until we know.
8422 cast<LambdaScopeInfo>(Val: getCurFunction())
8423 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8424 return;
8425 }
8426 }
8427 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl);
8428 VD && VD->hasLocalStorage()) {
8429 // A variable can't shadow a local variable in an enclosing scope, if
8430 // they are separated by a non-capturing declaration context.
8431 for (DeclContext *ParentDC = NewDC;
8432 ParentDC && !ParentDC->Equals(DC: OldDC);
8433 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8434 // Only block literals, captured statements, and lambda expressions
8435 // can capture; other scopes don't.
8436 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8437 !isLambdaCallOperator(DC: ParentDC)) {
8438 return;
8439 }
8440 }
8441 }
8442 }
8443 }
8444
8445 // Never warn about shadowing a placeholder variable.
8446 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8447 return;
8448
8449 // Only warn about certain kinds of shadowing for class members.
8450 if (NewDC) {
8451 // In particular, don't warn about shadowing non-class members.
8452 if (NewDC->isRecord() && !OldDC->isRecord())
8453 return;
8454
8455 // Skip shadowing check if we're in a class scope, dealing with an enum
8456 // constant in a different context.
8457 DeclContext *ReDC = NewDC->getRedeclContext();
8458 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8459 return;
8460
8461 // TODO: should we warn about static data members shadowing
8462 // static data members from base classes?
8463
8464 // TODO: don't diagnose for inaccessible shadowed members.
8465 // This is hard to do perfectly because we might friend the
8466 // shadowing context, but that's just a false negative.
8467 }
8468
8469 DeclarationName Name = R.getLookupName();
8470
8471 // Emit warning and note.
8472 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8473 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8474 if (!CaptureLoc.isInvalid())
8475 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8476 << Name << /*explicitly*/ 1;
8477 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8478}
8479
8480void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8481 for (const auto &Shadow : LSI->ShadowingDecls) {
8482 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8483 // Try to avoid the warning when the shadowed decl isn't captured.
8484 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8485 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8486 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8487 Diag(Shadow.VD->getLocation(),
8488 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8489 : diag::warn_decl_shadow)
8490 << Shadow.VD->getDeclName()
8491 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8492 if (CaptureLoc.isValid())
8493 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8494 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8495 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8496 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8497 Diag(Shadow.VD->getLocation(),
8498 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8499 : diag::warn_decl_shadow_uncaptured_local)
8500 << Shadow.VD->getDeclName()
8501 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8502 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8503 }
8504 }
8505}
8506
8507void Sema::CheckShadow(Scope *S, VarDecl *D) {
8508 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8509 return;
8510
8511 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8512 Sema::LookupOrdinaryName,
8513 RedeclarationKind::ForVisibleRedeclaration);
8514 LookupName(R, S);
8515 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8516 CheckShadow(D, ShadowedDecl, R);
8517}
8518
8519/// Check if 'E', which is an expression that is about to be modified, refers
8520/// to a constructor parameter that shadows a field.
8521void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8522 // Quickly ignore expressions that can't be shadowing ctor parameters.
8523 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8524 return;
8525 E = E->IgnoreParenImpCasts();
8526 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8527 if (!DRE)
8528 return;
8529 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8530 auto I = ShadowingDecls.find(Val: D);
8531 if (I == ShadowingDecls.end())
8532 return;
8533 const NamedDecl *ShadowedDecl = I->second;
8534 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8535 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8536 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8537 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8538
8539 // Avoid issuing multiple warnings about the same decl.
8540 ShadowingDecls.erase(I);
8541}
8542
8543/// Check for conflict between this global or extern "C" declaration and
8544/// previous global or extern "C" declarations. This is only used in C++.
8545template<typename T>
8546static bool checkGlobalOrExternCConflict(
8547 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8548 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8549 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8550
8551 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8552 // The common case: this global doesn't conflict with any extern "C"
8553 // declaration.
8554 return false;
8555 }
8556
8557 if (Prev) {
8558 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8559 // Both the old and new declarations have C language linkage. This is a
8560 // redeclaration.
8561 Previous.clear();
8562 Previous.addDecl(D: Prev);
8563 return true;
8564 }
8565
8566 // This is a global, non-extern "C" declaration, and there is a previous
8567 // non-global extern "C" declaration. Diagnose if this is a variable
8568 // declaration.
8569 if (!isa<VarDecl>(ND))
8570 return false;
8571 } else {
8572 // The declaration is extern "C". Check for any declaration in the
8573 // translation unit which might conflict.
8574 if (IsGlobal) {
8575 // We have already performed the lookup into the translation unit.
8576 IsGlobal = false;
8577 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8578 I != E; ++I) {
8579 if (isa<VarDecl>(Val: *I)) {
8580 Prev = *I;
8581 break;
8582 }
8583 }
8584 } else {
8585 DeclContext::lookup_result R =
8586 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8587 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8588 I != E; ++I) {
8589 if (isa<VarDecl>(Val: *I)) {
8590 Prev = *I;
8591 break;
8592 }
8593 // FIXME: If we have any other entity with this name in global scope,
8594 // the declaration is ill-formed, but that is a defect: it breaks the
8595 // 'stat' hack, for instance. Only variables can have mangled name
8596 // clashes with extern "C" declarations, so only they deserve a
8597 // diagnostic.
8598 }
8599 }
8600
8601 if (!Prev)
8602 return false;
8603 }
8604
8605 // Use the first declaration's location to ensure we point at something which
8606 // is lexically inside an extern "C" linkage-spec.
8607 assert(Prev && "should have found a previous declaration to diagnose");
8608 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8609 Prev = FD->getFirstDecl();
8610 else
8611 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8612
8613 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8614 << IsGlobal << ND;
8615 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8616 << IsGlobal;
8617 return false;
8618}
8619
8620/// Apply special rules for handling extern "C" declarations. Returns \c true
8621/// if we have found that this is a redeclaration of some prior entity.
8622///
8623/// Per C++ [dcl.link]p6:
8624/// Two declarations [for a function or variable] with C language linkage
8625/// with the same name that appear in different scopes refer to the same
8626/// [entity]. An entity with C language linkage shall not be declared with
8627/// the same name as an entity in global scope.
8628template<typename T>
8629static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8630 LookupResult &Previous) {
8631 if (!S.getLangOpts().CPlusPlus) {
8632 // In C, when declaring a global variable, look for a corresponding 'extern'
8633 // variable declared in function scope. We don't need this in C++, because
8634 // we find local extern decls in the surrounding file-scope DeclContext.
8635 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8636 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8637 Previous.clear();
8638 Previous.addDecl(D: Prev);
8639 return true;
8640 }
8641 }
8642 return false;
8643 }
8644
8645 // A declaration in the translation unit can conflict with an extern "C"
8646 // declaration.
8647 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8648 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8649
8650 // An extern "C" declaration can conflict with a declaration in the
8651 // translation unit or can be a redeclaration of an extern "C" declaration
8652 // in another scope.
8653 if (isIncompleteDeclExternC(S,ND))
8654 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8655
8656 // Neither global nor extern "C": nothing to do.
8657 return false;
8658}
8659
8660static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8661 QualType T) {
8662 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8663 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8664 // any of its members, even recursively, shall not have an atomic type, or a
8665 // variably modified type, or a type that is volatile or restrict qualified.
8666 if (CanonT->isVariablyModifiedType()) {
8667 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8668 return true;
8669 }
8670
8671 // Arrays are qualified by their element type, so get the base type (this
8672 // works on non-arrays as well).
8673 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8674
8675 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8676 CanonT.isRestrictQualified()) {
8677 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8678 return true;
8679 }
8680
8681 if (CanonT->isRecordType()) {
8682 const RecordDecl *RD = CanonT->getAsRecordDecl();
8683 if (!RD->isInvalidDecl() &&
8684 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8685 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8686 }))
8687 return true;
8688 }
8689
8690 return false;
8691}
8692
8693void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8694 // If the decl is already known invalid, don't check it.
8695 if (NewVD->isInvalidDecl())
8696 return;
8697
8698 QualType T = NewVD->getType();
8699
8700 // Defer checking an 'auto' type until its initializer is attached.
8701 if (T->isUndeducedType())
8702 return;
8703
8704 if (NewVD->hasAttrs())
8705 CheckAlignasUnderalignment(NewVD);
8706
8707 if (T->isObjCObjectType()) {
8708 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8709 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8710 T = Context.getObjCObjectPointerType(OIT: T);
8711 NewVD->setType(T);
8712 }
8713
8714 // Emit an error if an address space was applied to decl with local storage.
8715 // This includes arrays of objects with address space qualifiers, but not
8716 // automatic variables that point to other address spaces.
8717 // ISO/IEC TR 18037 S5.1.2
8718 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8719 T.getAddressSpace() != LangAS::Default) {
8720 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8721 NewVD->setInvalidDecl();
8722 return;
8723 }
8724
8725 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8726 // scope.
8727 if (getLangOpts().OpenCLVersion == 120 &&
8728 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8729 LO: getLangOpts()) &&
8730 NewVD->isStaticLocal()) {
8731 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8732 NewVD->setInvalidDecl();
8733 return;
8734 }
8735
8736 if (getLangOpts().OpenCL) {
8737 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8738 return;
8739
8740 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8741 if (NewVD->hasAttr<BlocksAttr>()) {
8742 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8743 return;
8744 }
8745
8746 if (T->isBlockPointerType()) {
8747 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8748 // can't use 'extern' storage class.
8749 if (!T.isConstQualified()) {
8750 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8751 << 0 /*const*/;
8752 NewVD->setInvalidDecl();
8753 return;
8754 }
8755 if (NewVD->hasExternalStorage()) {
8756 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8757 NewVD->setInvalidDecl();
8758 return;
8759 }
8760 }
8761
8762 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8763 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8764 NewVD->hasExternalStorage()) {
8765 if (!T->isSamplerT() && !T->isDependentType() &&
8766 !(T.getAddressSpace() == LangAS::opencl_constant ||
8767 (T.getAddressSpace() == LangAS::opencl_global &&
8768 getOpenCLOptions().areProgramScopeVariablesSupported(
8769 Opts: getLangOpts())))) {
8770 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8771 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8772 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8773 << Scope << "global or constant";
8774 else
8775 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8776 << Scope << "constant";
8777 NewVD->setInvalidDecl();
8778 return;
8779 }
8780 } else {
8781 if (T.getAddressSpace() == LangAS::opencl_global) {
8782 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8783 << 1 /*is any function*/ << "global";
8784 NewVD->setInvalidDecl();
8785 return;
8786 }
8787 if (T.getAddressSpace() == LangAS::opencl_constant ||
8788 T.getAddressSpace() == LangAS::opencl_local) {
8789 FunctionDecl *FD = getCurFunctionDecl();
8790 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8791 // in functions.
8792 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8793 if (T.getAddressSpace() == LangAS::opencl_constant)
8794 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8795 << 0 /*non-kernel only*/ << "constant";
8796 else
8797 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8798 << 0 /*non-kernel only*/ << "local";
8799 NewVD->setInvalidDecl();
8800 return;
8801 }
8802 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8803 // in the outermost scope of a kernel function.
8804 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8805 if (!getCurScope()->isFunctionScope()) {
8806 if (T.getAddressSpace() == LangAS::opencl_constant)
8807 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8808 << "constant";
8809 else
8810 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8811 << "local";
8812 NewVD->setInvalidDecl();
8813 return;
8814 }
8815 }
8816 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8817 // If we are parsing a template we didn't deduce an addr
8818 // space yet.
8819 T.getAddressSpace() != LangAS::Default) {
8820 // Do not allow other address spaces on automatic variable.
8821 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8822 NewVD->setInvalidDecl();
8823 return;
8824 }
8825 }
8826 }
8827
8828 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8829 && !NewVD->hasAttr<BlocksAttr>()) {
8830 if (getLangOpts().getGC() != LangOptions::NonGC)
8831 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8832 else {
8833 assert(!getLangOpts().ObjCAutoRefCount);
8834 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8835 }
8836 }
8837
8838 // WebAssembly tables must be static with a zero length and can't be
8839 // declared within functions.
8840 if (T->isWebAssemblyTableType()) {
8841 if (getCurScope()->getParent()) { // Parent is null at top-level
8842 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8843 NewVD->setInvalidDecl();
8844 return;
8845 }
8846 if (NewVD->getStorageClass() != SC_Static) {
8847 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8848 NewVD->setInvalidDecl();
8849 return;
8850 }
8851 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
8852 if (!ATy || ATy->getZExtSize() != 0) {
8853 Diag(NewVD->getLocation(),
8854 diag::err_typecheck_wasm_table_must_have_zero_length);
8855 NewVD->setInvalidDecl();
8856 return;
8857 }
8858 }
8859
8860 // zero sized static arrays are not allowed in HIP device functions
8861 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8862 if (FunctionDecl *FD = getCurFunctionDecl();
8863 FD &&
8864 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8865 if (const ConstantArrayType *ArrayT =
8866 getASTContext().getAsConstantArrayType(T);
8867 ArrayT && ArrayT->isZeroSize()) {
8868 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8869 }
8870 }
8871 }
8872
8873 bool isVM = T->isVariablyModifiedType();
8874 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8875 NewVD->hasAttr<BlocksAttr>())
8876 setFunctionHasBranchProtectedScope();
8877
8878 if ((isVM && NewVD->hasLinkage()) ||
8879 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8880 bool SizeIsNegative;
8881 llvm::APSInt Oversized;
8882 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8883 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8884 QualType FixedT;
8885 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8886 FixedT = FixedTInfo->getType();
8887 else if (FixedTInfo) {
8888 // Type and type-as-written are canonically different. We need to fix up
8889 // both types separately.
8890 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8891 Oversized);
8892 }
8893 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8894 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8895 // FIXME: This won't give the correct result for
8896 // int a[10][n];
8897 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8898
8899 if (NewVD->isFileVarDecl())
8900 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8901 << SizeRange;
8902 else if (NewVD->isStaticLocal())
8903 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8904 << SizeRange;
8905 else
8906 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8907 << SizeRange;
8908 NewVD->setInvalidDecl();
8909 return;
8910 }
8911
8912 if (!FixedTInfo) {
8913 if (NewVD->isFileVarDecl())
8914 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8915 else
8916 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8917 NewVD->setInvalidDecl();
8918 return;
8919 }
8920
8921 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8922 NewVD->setType(FixedT);
8923 NewVD->setTypeSourceInfo(FixedTInfo);
8924 }
8925
8926 if (T->isVoidType()) {
8927 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8928 // of objects and functions.
8929 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8930 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8931 << T;
8932 NewVD->setInvalidDecl();
8933 return;
8934 }
8935 }
8936
8937 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8938 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8939 NewVD->setInvalidDecl();
8940 return;
8941 }
8942
8943 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8944 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8945 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8946 NewVD->setInvalidDecl();
8947 return;
8948 }
8949
8950 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8951 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8952 NewVD->setInvalidDecl();
8953 return;
8954 }
8955
8956 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8957 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8958 NewVD->setInvalidDecl();
8959 return;
8960 }
8961
8962 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8963 !T->isDependentType() &&
8964 RequireLiteralType(NewVD->getLocation(), T,
8965 diag::err_constexpr_var_non_literal)) {
8966 NewVD->setInvalidDecl();
8967 return;
8968 }
8969
8970 // PPC MMA non-pointer types are not allowed as non-local variable types.
8971 if (Context.getTargetInfo().getTriple().isPPC64() &&
8972 !NewVD->isLocalVarDecl() &&
8973 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
8974 NewVD->setInvalidDecl();
8975 return;
8976 }
8977
8978 // Check that SVE types are only used in functions with SVE available.
8979 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
8980 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
8981 llvm::StringMap<bool> CallerFeatureMap;
8982 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8983
8984 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8985 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8986 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8987 NewVD->setInvalidDecl();
8988 return;
8989 } else if (!IsArmStreamingFunction(FD,
8990 /*IncludeLocallyStreaming=*/true)) {
8991 Diag(NewVD->getLocation(),
8992 diag::err_sve_vector_in_non_streaming_function)
8993 << T;
8994 NewVD->setInvalidDecl();
8995 return;
8996 }
8997 }
8998 }
8999
9000 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9001 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9002 llvm::StringMap<bool> CallerFeatureMap;
9003 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9004 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9005 FeatureMap: CallerFeatureMap);
9006 }
9007}
9008
9009bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9010 CheckVariableDeclarationType(NewVD);
9011
9012 // If the decl is already known invalid, don't check it.
9013 if (NewVD->isInvalidDecl())
9014 return false;
9015
9016 // If we did not find anything by this name, look for a non-visible
9017 // extern "C" declaration with the same name.
9018 if (Previous.empty() &&
9019 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9020 Previous.setShadowed();
9021
9022 if (!Previous.empty()) {
9023 MergeVarDecl(New: NewVD, Previous);
9024 return true;
9025 }
9026 return false;
9027}
9028
9029bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9030 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9031
9032 // Look for methods in base classes that this method might override.
9033 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9034 /*DetectVirtual=*/false);
9035 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9036 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9037 DeclarationName Name = MD->getDeclName();
9038
9039 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9040 // We really want to find the base class destructor here.
9041 QualType T = Context.getTypeDeclType(BaseRecord);
9042 CanQualType CT = Context.getCanonicalType(T);
9043 Name = Context.DeclarationNames.getCXXDestructorName(Ty: CT);
9044 }
9045
9046 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9047 CXXMethodDecl *BaseMD =
9048 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9049 if (!BaseMD || !BaseMD->isVirtual() ||
9050 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9051 /*ConsiderCudaAttrs=*/true))
9052 continue;
9053 if (!CheckExplicitObjectOverride(MD, BaseMD))
9054 continue;
9055 if (Overridden.insert(BaseMD).second) {
9056 MD->addOverriddenMethod(BaseMD);
9057 CheckOverridingFunctionReturnType(MD, BaseMD);
9058 CheckOverridingFunctionAttributes(MD, BaseMD);
9059 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
9060 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
9061 }
9062
9063 // A method can only override one function from each base class. We
9064 // don't track indirectly overridden methods from bases of bases.
9065 return true;
9066 }
9067
9068 return false;
9069 };
9070
9071 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9072 return !Overridden.empty();
9073}
9074
9075namespace {
9076 // Struct for holding all of the extra arguments needed by
9077 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9078 struct ActOnFDArgs {
9079 Scope *S;
9080 Declarator &D;
9081 MultiTemplateParamsArg TemplateParamLists;
9082 bool AddToScope;
9083 };
9084} // end anonymous namespace
9085
9086namespace {
9087
9088// Callback to only accept typo corrections that have a non-zero edit distance.
9089// Also only accept corrections that have the same parent decl.
9090class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9091 public:
9092 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9093 CXXRecordDecl *Parent)
9094 : Context(Context), OriginalFD(TypoFD),
9095 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9096
9097 bool ValidateCandidate(const TypoCorrection &candidate) override {
9098 if (candidate.getEditDistance() == 0)
9099 return false;
9100
9101 SmallVector<unsigned, 1> MismatchedParams;
9102 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9103 CDeclEnd = candidate.end();
9104 CDecl != CDeclEnd; ++CDecl) {
9105 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9106
9107 if (FD && !FD->hasBody() &&
9108 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9109 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9110 CXXRecordDecl *Parent = MD->getParent();
9111 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9112 return true;
9113 } else if (!ExpectedParent) {
9114 return true;
9115 }
9116 }
9117 }
9118
9119 return false;
9120 }
9121
9122 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9123 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9124 }
9125
9126 private:
9127 ASTContext &Context;
9128 FunctionDecl *OriginalFD;
9129 CXXRecordDecl *ExpectedParent;
9130};
9131
9132} // end anonymous namespace
9133
9134void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9135 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9136}
9137
9138/// Generate diagnostics for an invalid function redeclaration.
9139///
9140/// This routine handles generating the diagnostic messages for an invalid
9141/// function redeclaration, including finding possible similar declarations
9142/// or performing typo correction if there are no previous declarations with
9143/// the same name.
9144///
9145/// Returns a NamedDecl iff typo correction was performed and substituting in
9146/// the new declaration name does not cause new errors.
9147static NamedDecl *DiagnoseInvalidRedeclaration(
9148 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9149 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9150 DeclarationName Name = NewFD->getDeclName();
9151 DeclContext *NewDC = NewFD->getDeclContext();
9152 SmallVector<unsigned, 1> MismatchedParams;
9153 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9154 TypoCorrection Correction;
9155 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9156 unsigned DiagMsg =
9157 IsLocalFriend ? diag::err_no_matching_local_friend :
9158 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9159 diag::err_member_decl_does_not_match;
9160 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9161 IsLocalFriend ? Sema::LookupLocalFriendName
9162 : Sema::LookupOrdinaryName,
9163 RedeclarationKind::ForVisibleRedeclaration);
9164
9165 NewFD->setInvalidDecl();
9166 if (IsLocalFriend)
9167 SemaRef.LookupName(R&: Prev, S);
9168 else
9169 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9170 assert(!Prev.isAmbiguous() &&
9171 "Cannot have an ambiguity in previous-declaration lookup");
9172 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9173 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9174 MD ? MD->getParent() : nullptr);
9175 if (!Prev.empty()) {
9176 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9177 Func != FuncEnd; ++Func) {
9178 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9179 if (FD &&
9180 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9181 // Add 1 to the index so that 0 can mean the mismatch didn't
9182 // involve a parameter
9183 unsigned ParamNum =
9184 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9185 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9186 }
9187 }
9188 // If the qualified name lookup yielded nothing, try typo correction
9189 } else if ((Correction = SemaRef.CorrectTypo(
9190 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9191 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9192 Mode: CorrectTypoKind::ErrorRecovery,
9193 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9194 // Set up everything for the call to ActOnFunctionDeclarator
9195 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9196 IdLoc: ExtraArgs.D.getIdentifierLoc());
9197 Previous.clear();
9198 Previous.setLookupName(Correction.getCorrection());
9199 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9200 CDeclEnd = Correction.end();
9201 CDecl != CDeclEnd; ++CDecl) {
9202 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9203 if (FD && !FD->hasBody() &&
9204 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9205 Previous.addDecl(FD);
9206 }
9207 }
9208 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9209
9210 NamedDecl *Result;
9211 // Retry building the function declaration with the new previous
9212 // declarations, and with errors suppressed.
9213 {
9214 // Trap errors.
9215 Sema::SFINAETrap Trap(SemaRef);
9216
9217 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9218 // pieces need to verify the typo-corrected C++ declaration and hopefully
9219 // eliminate the need for the parameter pack ExtraArgs.
9220 Result = SemaRef.ActOnFunctionDeclarator(
9221 S: ExtraArgs.S, D&: ExtraArgs.D,
9222 DC: Correction.getCorrectionDecl()->getDeclContext(),
9223 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9224 AddToScope&: ExtraArgs.AddToScope);
9225
9226 if (Trap.hasErrorOccurred())
9227 Result = nullptr;
9228 }
9229
9230 if (Result) {
9231 // Determine which correction we picked.
9232 Decl *Canonical = Result->getCanonicalDecl();
9233 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9234 I != E; ++I)
9235 if ((*I)->getCanonicalDecl() == Canonical)
9236 Correction.setCorrectionDecl(*I);
9237
9238 // Let Sema know about the correction.
9239 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9240 SemaRef.diagnoseTypo(
9241 Correction,
9242 SemaRef.PDiag(IsLocalFriend
9243 ? diag::err_no_matching_local_friend_suggest
9244 : diag::err_member_decl_does_not_match_suggest)
9245 << Name << NewDC << IsDefinition);
9246 return Result;
9247 }
9248
9249 // Pretend the typo correction never occurred
9250 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9251 IdLoc: ExtraArgs.D.getIdentifierLoc());
9252 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9253 Previous.clear();
9254 Previous.setLookupName(Name);
9255 }
9256
9257 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9258 << Name << NewDC << IsDefinition << NewFD->getLocation();
9259
9260 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9261 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9262 CXXRecordDecl *RD = NewMD->getParent();
9263 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9264 << RD->getName() << RD->getLocation();
9265 }
9266
9267 bool NewFDisConst = NewMD && NewMD->isConst();
9268
9269 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9270 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9271 NearMatch != NearMatchEnd; ++NearMatch) {
9272 FunctionDecl *FD = NearMatch->first;
9273 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9274 bool FDisConst = MD && MD->isConst();
9275 bool IsMember = MD || !IsLocalFriend;
9276
9277 // FIXME: These notes are poorly worded for the local friend case.
9278 if (unsigned Idx = NearMatch->second) {
9279 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9280 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9281 if (Loc.isInvalid()) Loc = FD->getLocation();
9282 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9283 : diag::note_local_decl_close_param_match)
9284 << Idx << FDParam->getType()
9285 << NewFD->getParamDecl(Idx - 1)->getType();
9286 } else if (FDisConst != NewFDisConst) {
9287 auto DB = SemaRef.Diag(FD->getLocation(),
9288 diag::note_member_def_close_const_match)
9289 << NewFDisConst << FD->getSourceRange().getEnd();
9290 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9291 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9292 Code: " const");
9293 else if (FTI.hasMethodTypeQualifiers() &&
9294 FTI.getConstQualifierLoc().isValid())
9295 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9296 } else {
9297 SemaRef.Diag(FD->getLocation(),
9298 IsMember ? diag::note_member_def_close_match
9299 : diag::note_local_decl_close_match);
9300 }
9301 }
9302 return nullptr;
9303}
9304
9305static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9306 switch (D.getDeclSpec().getStorageClassSpec()) {
9307 default: llvm_unreachable("Unknown storage class!");
9308 case DeclSpec::SCS_auto:
9309 case DeclSpec::SCS_register:
9310 case DeclSpec::SCS_mutable:
9311 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9312 diag::err_typecheck_sclass_func);
9313 D.getMutableDeclSpec().ClearStorageClassSpecs();
9314 D.setInvalidType();
9315 break;
9316 case DeclSpec::SCS_unspecified: break;
9317 case DeclSpec::SCS_extern:
9318 if (D.getDeclSpec().isExternInLinkageSpec())
9319 return SC_None;
9320 return SC_Extern;
9321 case DeclSpec::SCS_static: {
9322 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9323 // C99 6.7.1p5:
9324 // The declaration of an identifier for a function that has
9325 // block scope shall have no explicit storage-class specifier
9326 // other than extern
9327 // See also (C++ [dcl.stc]p4).
9328 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9329 diag::err_static_block_func);
9330 break;
9331 } else
9332 return SC_Static;
9333 }
9334 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9335 }
9336
9337 // No explicit storage class has already been returned
9338 return SC_None;
9339}
9340
9341static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9342 DeclContext *DC, QualType &R,
9343 TypeSourceInfo *TInfo,
9344 StorageClass SC,
9345 bool &IsVirtualOkay) {
9346 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9347 DeclarationName Name = NameInfo.getName();
9348
9349 FunctionDecl *NewFD = nullptr;
9350 bool isInline = D.getDeclSpec().isInlineSpecified();
9351
9352 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9353 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9354 (SemaRef.getLangOpts().C23 &&
9355 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9356
9357 if (SemaRef.getLangOpts().C23)
9358 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9359 diag::err_c23_constexpr_not_variable);
9360 else
9361 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9362 diag::err_constexpr_wrong_decl_kind)
9363 << static_cast<int>(ConstexprKind);
9364 ConstexprKind = ConstexprSpecKind::Unspecified;
9365 D.getMutableDeclSpec().ClearConstexprSpec();
9366 }
9367
9368 if (!SemaRef.getLangOpts().CPlusPlus) {
9369 // Determine whether the function was written with a prototype. This is
9370 // true when:
9371 // - there is a prototype in the declarator, or
9372 // - the type R of the function is some kind of typedef or other non-
9373 // attributed reference to a type name (which eventually refers to a
9374 // function type). Note, we can't always look at the adjusted type to
9375 // check this case because attributes may cause a non-function
9376 // declarator to still have a function type. e.g.,
9377 // typedef void func(int a);
9378 // __attribute__((noreturn)) func other_func; // This has a prototype
9379 bool HasPrototype =
9380 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9381 (D.getDeclSpec().isTypeRep() &&
9382 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9383 ->isFunctionProtoType()) ||
9384 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9385 assert(
9386 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9387 "Strict prototypes are required");
9388
9389 NewFD = FunctionDecl::Create(
9390 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9391 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9392 ConstexprKind: ConstexprSpecKind::Unspecified,
9393 /*TrailingRequiresClause=*/{});
9394 if (D.isInvalidType())
9395 NewFD->setInvalidDecl();
9396
9397 return NewFD;
9398 }
9399
9400 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9401 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9402
9403 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9404
9405 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9406 // This is a C++ constructor declaration.
9407 assert(DC->isRecord() &&
9408 "Constructors can only be declared in a member context");
9409
9410 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9411 return CXXConstructorDecl::Create(
9412 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9413 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9414 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9415 Inherited: InheritedConstructor(), TrailingRequiresClause);
9416
9417 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9418 // This is a C++ destructor declaration.
9419 if (DC->isRecord()) {
9420 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9421 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9422 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9423 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9424 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9425 /*isImplicitlyDeclared=*/false, ConstexprKind,
9426 TrailingRequiresClause);
9427 // User defined destructors start as not selected if the class definition is still
9428 // not done.
9429 if (Record->isBeingDefined())
9430 NewDD->setIneligibleOrNotSelected(true);
9431
9432 // If the destructor needs an implicit exception specification, set it
9433 // now. FIXME: It'd be nice to be able to create the right type to start
9434 // with, but the type needs to reference the destructor declaration.
9435 if (SemaRef.getLangOpts().CPlusPlus11)
9436 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9437
9438 IsVirtualOkay = true;
9439 return NewDD;
9440
9441 } else {
9442 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9443 D.setInvalidType();
9444
9445 // Create a FunctionDecl to satisfy the function definition parsing
9446 // code path.
9447 return FunctionDecl::Create(
9448 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9449 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9450 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9451 }
9452
9453 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9454 if (!DC->isRecord()) {
9455 SemaRef.Diag(D.getIdentifierLoc(),
9456 diag::err_conv_function_not_member);
9457 return nullptr;
9458 }
9459
9460 SemaRef.CheckConversionDeclarator(D, R, SC);
9461 if (D.isInvalidType())
9462 return nullptr;
9463
9464 IsVirtualOkay = true;
9465 return CXXConversionDecl::Create(
9466 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9467 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9468 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9469 TrailingRequiresClause);
9470
9471 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9472 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9473 return nullptr;
9474 return CXXDeductionGuideDecl::Create(
9475 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9476 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9477 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9478 } else if (DC->isRecord()) {
9479 // If the name of the function is the same as the name of the record,
9480 // then this must be an invalid constructor that has a return type.
9481 // (The parser checks for a return type and makes the declarator a
9482 // constructor if it has no return type).
9483 if (Name.getAsIdentifierInfo() &&
9484 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9485 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9486 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9487 << SourceRange(D.getIdentifierLoc());
9488 return nullptr;
9489 }
9490
9491 // This is a C++ method declaration.
9492 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9493 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9494 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9495 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9496 IsVirtualOkay = !Ret->isStatic();
9497 return Ret;
9498 } else {
9499 bool isFriend =
9500 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9501 if (!isFriend && SemaRef.CurContext->isRecord())
9502 return nullptr;
9503
9504 // Determine whether the function was written with a
9505 // prototype. This true when:
9506 // - we're in C++ (where every function has a prototype),
9507 return FunctionDecl::Create(
9508 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9509 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9510 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9511 }
9512}
9513
9514enum OpenCLParamType {
9515 ValidKernelParam,
9516 PtrPtrKernelParam,
9517 PtrKernelParam,
9518 InvalidAddrSpacePtrKernelParam,
9519 InvalidKernelParam,
9520 RecordKernelParam
9521};
9522
9523static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9524 // Size dependent types are just typedefs to normal integer types
9525 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9526 // integers other than by their names.
9527 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9528
9529 // Remove typedefs one by one until we reach a typedef
9530 // for a size dependent type.
9531 QualType DesugaredTy = Ty;
9532 do {
9533 ArrayRef<StringRef> Names(SizeTypeNames);
9534 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9535 if (Names.end() != Match)
9536 return true;
9537
9538 Ty = DesugaredTy;
9539 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9540 } while (DesugaredTy != Ty);
9541
9542 return false;
9543}
9544
9545static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9546 if (PT->isDependentType())
9547 return InvalidKernelParam;
9548
9549 if (PT->isPointerOrReferenceType()) {
9550 QualType PointeeType = PT->getPointeeType();
9551 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9552 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9553 PointeeType.getAddressSpace() == LangAS::Default)
9554 return InvalidAddrSpacePtrKernelParam;
9555
9556 if (PointeeType->isPointerType()) {
9557 // This is a pointer to pointer parameter.
9558 // Recursively check inner type.
9559 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9560 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9561 ParamKind == InvalidKernelParam)
9562 return ParamKind;
9563
9564 // OpenCL v3.0 s6.11.a:
9565 // A restriction to pass pointers to pointers only applies to OpenCL C
9566 // v1.2 or below.
9567 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9568 return ValidKernelParam;
9569
9570 return PtrPtrKernelParam;
9571 }
9572
9573 // C++ for OpenCL v1.0 s2.4:
9574 // Moreover the types used in parameters of the kernel functions must be:
9575 // Standard layout types for pointer parameters. The same applies to
9576 // reference if an implementation supports them in kernel parameters.
9577 if (S.getLangOpts().OpenCLCPlusPlus &&
9578 !S.getOpenCLOptions().isAvailableOption(
9579 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9580 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9581 bool IsStandardLayoutType = true;
9582 if (CXXRec) {
9583 // If template type is not ODR-used its definition is only available
9584 // in the template definition not its instantiation.
9585 // FIXME: This logic doesn't work for types that depend on template
9586 // parameter (PR58590).
9587 if (!CXXRec->hasDefinition())
9588 CXXRec = CXXRec->getTemplateInstantiationPattern();
9589 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9590 IsStandardLayoutType = false;
9591 }
9592 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9593 !IsStandardLayoutType)
9594 return InvalidKernelParam;
9595 }
9596
9597 // OpenCL v1.2 s6.9.p:
9598 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9599 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9600 return ValidKernelParam;
9601
9602 return PtrKernelParam;
9603 }
9604
9605 // OpenCL v1.2 s6.9.k:
9606 // Arguments to kernel functions in a program cannot be declared with the
9607 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9608 // uintptr_t or a struct and/or union that contain fields declared to be one
9609 // of these built-in scalar types.
9610 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9611 return InvalidKernelParam;
9612
9613 if (PT->isImageType())
9614 return PtrKernelParam;
9615
9616 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9617 return InvalidKernelParam;
9618
9619 // OpenCL extension spec v1.2 s9.5:
9620 // This extension adds support for half scalar and vector types as built-in
9621 // types that can be used for arithmetic operations, conversions etc.
9622 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9623 PT->isHalfType())
9624 return InvalidKernelParam;
9625
9626 // Look into an array argument to check if it has a forbidden type.
9627 if (PT->isArrayType()) {
9628 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9629 // Call ourself to check an underlying type of an array. Since the
9630 // getPointeeOrArrayElementType returns an innermost type which is not an
9631 // array, this recursive call only happens once.
9632 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9633 }
9634
9635 // C++ for OpenCL v1.0 s2.4:
9636 // Moreover the types used in parameters of the kernel functions must be:
9637 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9638 // types) for parameters passed by value;
9639 if (S.getLangOpts().OpenCLCPlusPlus &&
9640 !S.getOpenCLOptions().isAvailableOption(
9641 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9642 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9643 return InvalidKernelParam;
9644
9645 if (PT->isRecordType())
9646 return RecordKernelParam;
9647
9648 return ValidKernelParam;
9649}
9650
9651static void checkIsValidOpenCLKernelParameter(
9652 Sema &S,
9653 Declarator &D,
9654 ParmVarDecl *Param,
9655 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9656 QualType PT = Param->getType();
9657
9658 // Cache the valid types we encounter to avoid rechecking structs that are
9659 // used again
9660 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9661 return;
9662
9663 switch (getOpenCLKernelParameterType(S, PT)) {
9664 case PtrPtrKernelParam:
9665 // OpenCL v3.0 s6.11.a:
9666 // A kernel function argument cannot be declared as a pointer to a pointer
9667 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9668 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9669 D.setInvalidType();
9670 return;
9671
9672 case InvalidAddrSpacePtrKernelParam:
9673 // OpenCL v1.0 s6.5:
9674 // __kernel function arguments declared to be a pointer of a type can point
9675 // to one of the following address spaces only : __global, __local or
9676 // __constant.
9677 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9678 D.setInvalidType();
9679 return;
9680
9681 // OpenCL v1.2 s6.9.k:
9682 // Arguments to kernel functions in a program cannot be declared with the
9683 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9684 // uintptr_t or a struct and/or union that contain fields declared to be
9685 // one of these built-in scalar types.
9686
9687 case InvalidKernelParam:
9688 // OpenCL v1.2 s6.8 n:
9689 // A kernel function argument cannot be declared
9690 // of event_t type.
9691 // Do not diagnose half type since it is diagnosed as invalid argument
9692 // type for any function elsewhere.
9693 if (!PT->isHalfType()) {
9694 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9695
9696 // Explain what typedefs are involved.
9697 const TypedefType *Typedef = nullptr;
9698 while ((Typedef = PT->getAs<TypedefType>())) {
9699 SourceLocation Loc = Typedef->getDecl()->getLocation();
9700 // SourceLocation may be invalid for a built-in type.
9701 if (Loc.isValid())
9702 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9703 PT = Typedef->desugar();
9704 }
9705 }
9706
9707 D.setInvalidType();
9708 return;
9709
9710 case PtrKernelParam:
9711 case ValidKernelParam:
9712 ValidTypes.insert(Ptr: PT.getTypePtr());
9713 return;
9714
9715 case RecordKernelParam:
9716 break;
9717 }
9718
9719 // Track nested structs we will inspect
9720 SmallVector<const Decl *, 4> VisitStack;
9721
9722 // Track where we are in the nested structs. Items will migrate from
9723 // VisitStack to HistoryStack as we do the DFS for bad field.
9724 SmallVector<const FieldDecl *, 4> HistoryStack;
9725 HistoryStack.push_back(Elt: nullptr);
9726
9727 // At this point we already handled everything except of a RecordType.
9728 assert(PT->isRecordType() && "Unexpected type.");
9729 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
9730 VisitStack.push_back(PD);
9731 assert(VisitStack.back() && "First decl null?");
9732
9733 do {
9734 const Decl *Next = VisitStack.pop_back_val();
9735 if (!Next) {
9736 assert(!HistoryStack.empty());
9737 // Found a marker, we have gone up a level
9738 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9739 ValidTypes.insert(Hist->getType().getTypePtr());
9740
9741 continue;
9742 }
9743
9744 // Adds everything except the original parameter declaration (which is not a
9745 // field itself) to the history stack.
9746 const RecordDecl *RD;
9747 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9748 HistoryStack.push_back(Elt: Field);
9749
9750 QualType FieldTy = Field->getType();
9751 // Other field types (known to be valid or invalid) are handled while we
9752 // walk around RecordDecl::fields().
9753 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9754 "Unexpected type.");
9755 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9756
9757 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9758 } else {
9759 RD = cast<RecordDecl>(Val: Next);
9760 }
9761
9762 // Add a null marker so we know when we've gone back up a level
9763 VisitStack.push_back(Elt: nullptr);
9764
9765 for (const auto *FD : RD->fields()) {
9766 QualType QT = FD->getType();
9767
9768 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9769 continue;
9770
9771 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9772 if (ParamType == ValidKernelParam)
9773 continue;
9774
9775 if (ParamType == RecordKernelParam) {
9776 VisitStack.push_back(FD);
9777 continue;
9778 }
9779
9780 // OpenCL v1.2 s6.9.p:
9781 // Arguments to kernel functions that are declared to be a struct or union
9782 // do not allow OpenCL objects to be passed as elements of the struct or
9783 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9784 // of SVM.
9785 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9786 ParamType == InvalidAddrSpacePtrKernelParam) {
9787 S.Diag(Param->getLocation(),
9788 diag::err_record_with_pointers_kernel_param)
9789 << PT->isUnionType()
9790 << PT;
9791 } else {
9792 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9793 }
9794
9795 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9796 << PD->getDeclName();
9797
9798 // We have an error, now let's go back up through history and show where
9799 // the offending field came from
9800 for (ArrayRef<const FieldDecl *>::const_iterator
9801 I = HistoryStack.begin() + 1,
9802 E = HistoryStack.end();
9803 I != E; ++I) {
9804 const FieldDecl *OuterField = *I;
9805 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9806 << OuterField->getType();
9807 }
9808
9809 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9810 << QT->isPointerType()
9811 << QT;
9812 D.setInvalidType();
9813 return;
9814 }
9815 } while (!VisitStack.empty());
9816}
9817
9818/// Find the DeclContext in which a tag is implicitly declared if we see an
9819/// elaborated type specifier in the specified context, and lookup finds
9820/// nothing.
9821static DeclContext *getTagInjectionContext(DeclContext *DC) {
9822 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9823 DC = DC->getParent();
9824 return DC;
9825}
9826
9827/// Find the Scope in which a tag is implicitly declared if we see an
9828/// elaborated type specifier in the specified context, and lookup finds
9829/// nothing.
9830static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9831 while (S->isClassScope() ||
9832 (LangOpts.CPlusPlus &&
9833 S->isFunctionPrototypeScope()) ||
9834 ((S->getFlags() & Scope::DeclScope) == 0) ||
9835 (S->getEntity() && S->getEntity()->isTransparentContext()))
9836 S = S->getParent();
9837 return S;
9838}
9839
9840/// Determine whether a declaration matches a known function in namespace std.
9841static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9842 unsigned BuiltinID) {
9843 switch (BuiltinID) {
9844 case Builtin::BI__GetExceptionInfo:
9845 // No type checking whatsoever.
9846 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9847
9848 case Builtin::BIaddressof:
9849 case Builtin::BI__addressof:
9850 case Builtin::BIforward:
9851 case Builtin::BIforward_like:
9852 case Builtin::BImove:
9853 case Builtin::BImove_if_noexcept:
9854 case Builtin::BIas_const: {
9855 // Ensure that we don't treat the algorithm
9856 // OutputIt std::move(InputIt, InputIt, OutputIt)
9857 // as the builtin std::move.
9858 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9859 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9860 }
9861
9862 default:
9863 return false;
9864 }
9865}
9866
9867NamedDecl*
9868Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9869 TypeSourceInfo *TInfo, LookupResult &Previous,
9870 MultiTemplateParamsArg TemplateParamListsRef,
9871 bool &AddToScope) {
9872 QualType R = TInfo->getType();
9873
9874 assert(R->isFunctionType());
9875 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9876 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9877
9878 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9879 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
9880 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9881 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9882 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9883 TemplateParamLists.back() = Invented;
9884 else
9885 TemplateParamLists.push_back(Elt: Invented);
9886 }
9887
9888 // TODO: consider using NameInfo for diagnostic.
9889 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9890 DeclarationName Name = NameInfo.getName();
9891 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
9892
9893 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9894 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9895 diag::err_invalid_thread)
9896 << DeclSpec::getSpecifierName(TSCS);
9897
9898 if (D.isFirstDeclarationOfMember())
9899 adjustMemberFunctionCC(
9900 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9901 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
9902
9903 bool isFriend = false;
9904 FunctionTemplateDecl *FunctionTemplate = nullptr;
9905 bool isMemberSpecialization = false;
9906 bool isFunctionTemplateSpecialization = false;
9907
9908 bool HasExplicitTemplateArgs = false;
9909 TemplateArgumentListInfo TemplateArgs;
9910
9911 bool isVirtualOkay = false;
9912
9913 DeclContext *OriginalDC = DC;
9914 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9915
9916 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
9917 IsVirtualOkay&: isVirtualOkay);
9918 if (!NewFD) return nullptr;
9919
9920 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9921 NewFD->setTopLevelDeclInObjCContainer();
9922
9923 // Set the lexical context. If this is a function-scope declaration, or has a
9924 // C++ scope specifier, or is the object of a friend declaration, the lexical
9925 // context will be different from the semantic context.
9926 NewFD->setLexicalDeclContext(CurContext);
9927
9928 if (IsLocalExternDecl)
9929 NewFD->setLocalExternDecl();
9930
9931 if (getLangOpts().CPlusPlus) {
9932 // The rules for implicit inlines changed in C++20 for methods and friends
9933 // with an in-class definition (when such a definition is not attached to
9934 // the global module). This does not affect declarations that are already
9935 // inline (whether explicitly or implicitly by being declared constexpr,
9936 // consteval, etc).
9937 // FIXME: We need a better way to separate C++ standard and clang modules.
9938 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9939 !NewFD->getOwningModule() ||
9940 NewFD->isFromGlobalModule() ||
9941 NewFD->getOwningModule()->isHeaderLikeModule();
9942 bool isInline = D.getDeclSpec().isInlineSpecified();
9943 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9944 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9945 isFriend = D.getDeclSpec().isFriendSpecified();
9946 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9947 // Pre-C++20 [class.friend]p5
9948 // A function can be defined in a friend declaration of a
9949 // class . . . . Such a function is implicitly inline.
9950 // Post C++20 [class.friend]p7
9951 // Such a function is implicitly an inline function if it is attached
9952 // to the global module.
9953 NewFD->setImplicitlyInline();
9954 }
9955
9956 // If this is a method defined in an __interface, and is not a constructor
9957 // or an overloaded operator, then set the pure flag (isVirtual will already
9958 // return true).
9959 if (const CXXRecordDecl *Parent =
9960 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9961 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
9962 NewFD->setIsPureVirtual(true);
9963
9964 // C++ [class.union]p2
9965 // A union can have member functions, but not virtual functions.
9966 if (isVirtual && Parent->isUnion()) {
9967 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9968 NewFD->setInvalidDecl();
9969 }
9970 if ((Parent->isClass() || Parent->isStruct()) &&
9971 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9972 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9973 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9974 if (auto *Def = Parent->getDefinition())
9975 Def->setInitMethod(true);
9976 }
9977 }
9978
9979 SetNestedNameSpecifier(*this, NewFD, D);
9980 isMemberSpecialization = false;
9981 isFunctionTemplateSpecialization = false;
9982 if (D.isInvalidType())
9983 NewFD->setInvalidDecl();
9984
9985 // Match up the template parameter lists with the scope specifier, then
9986 // determine whether we have a template or a template specialization.
9987 bool Invalid = false;
9988 TemplateIdAnnotation *TemplateId =
9989 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9990 ? D.getName().TemplateId
9991 : nullptr;
9992 TemplateParameterList *TemplateParams =
9993 MatchTemplateParametersToScopeSpecifier(
9994 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
9995 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
9996 IsMemberSpecialization&: isMemberSpecialization, Invalid);
9997 if (TemplateParams) {
9998 // Check that we can declare a template here.
9999 if (CheckTemplateDeclScope(S, TemplateParams))
10000 NewFD->setInvalidDecl();
10001
10002 if (TemplateParams->size() > 0) {
10003 // This is a function template
10004
10005 // A destructor cannot be a template.
10006 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10007 Diag(NewFD->getLocation(), diag::err_destructor_template);
10008 NewFD->setInvalidDecl();
10009 // Function template with explicit template arguments.
10010 } else if (TemplateId) {
10011 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10012 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10013 NewFD->setInvalidDecl();
10014 }
10015
10016 // If we're adding a template to a dependent context, we may need to
10017 // rebuilding some of the types used within the template parameter list,
10018 // now that we know what the current instantiation is.
10019 if (DC->isDependentContext()) {
10020 ContextRAII SavedContext(*this, DC);
10021 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10022 Invalid = true;
10023 }
10024
10025 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10026 L: NewFD->getLocation(),
10027 Name, Params: TemplateParams,
10028 Decl: NewFD);
10029 FunctionTemplate->setLexicalDeclContext(CurContext);
10030 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10031
10032 // For source fidelity, store the other template param lists.
10033 if (TemplateParamLists.size() > 1) {
10034 NewFD->setTemplateParameterListsInfo(Context,
10035 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10036 .drop_back(N: 1));
10037 }
10038 } else {
10039 // This is a function template specialization.
10040 isFunctionTemplateSpecialization = true;
10041 // For source fidelity, store all the template param lists.
10042 if (TemplateParamLists.size() > 0)
10043 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10044
10045 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10046 if (isFriend) {
10047 // We want to remove the "template<>", found here.
10048 SourceRange RemoveRange = TemplateParams->getSourceRange();
10049
10050 // If we remove the template<> and the name is not a
10051 // template-id, we're actually silently creating a problem:
10052 // the friend declaration will refer to an untemplated decl,
10053 // and clearly the user wants a template specialization. So
10054 // we need to insert '<>' after the name.
10055 SourceLocation InsertLoc;
10056 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10057 InsertLoc = D.getName().getSourceRange().getEnd();
10058 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10059 }
10060
10061 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10062 << Name << RemoveRange
10063 << FixItHint::CreateRemoval(RemoveRange)
10064 << FixItHint::CreateInsertion(InsertLoc, "<>");
10065 Invalid = true;
10066
10067 // Recover by faking up an empty template argument list.
10068 HasExplicitTemplateArgs = true;
10069 TemplateArgs.setLAngleLoc(InsertLoc);
10070 TemplateArgs.setRAngleLoc(InsertLoc);
10071 }
10072 }
10073 } else {
10074 // Check that we can declare a template here.
10075 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10076 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10077 NewFD->setInvalidDecl();
10078
10079 // All template param lists were matched against the scope specifier:
10080 // this is NOT (an explicit specialization of) a template.
10081 if (TemplateParamLists.size() > 0)
10082 // For source fidelity, store all the template param lists.
10083 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10084
10085 // "friend void foo<>(int);" is an implicit specialization decl.
10086 if (isFriend && TemplateId)
10087 isFunctionTemplateSpecialization = true;
10088 }
10089
10090 // If this is a function template specialization and the unqualified-id of
10091 // the declarator-id is a template-id, convert the template argument list
10092 // into our AST format and check for unexpanded packs.
10093 if (isFunctionTemplateSpecialization && TemplateId) {
10094 HasExplicitTemplateArgs = true;
10095
10096 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10097 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10098 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10099 TemplateId->NumArgs);
10100 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10101
10102 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10103 // declaration of a function template partial specialization? Should we
10104 // consider the unexpanded pack context to be a partial specialization?
10105 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10106 if (DiagnoseUnexpandedParameterPack(
10107 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10108 : UPPC_ExplicitSpecialization))
10109 NewFD->setInvalidDecl();
10110 }
10111 }
10112
10113 if (Invalid) {
10114 NewFD->setInvalidDecl();
10115 if (FunctionTemplate)
10116 FunctionTemplate->setInvalidDecl();
10117 }
10118
10119 // C++ [dcl.fct.spec]p5:
10120 // The virtual specifier shall only be used in declarations of
10121 // nonstatic class member functions that appear within a
10122 // member-specification of a class declaration; see 10.3.
10123 //
10124 if (isVirtual && !NewFD->isInvalidDecl()) {
10125 if (!isVirtualOkay) {
10126 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10127 diag::err_virtual_non_function);
10128 } else if (!CurContext->isRecord()) {
10129 // 'virtual' was specified outside of the class.
10130 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10131 diag::err_virtual_out_of_class)
10132 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10133 } else if (NewFD->getDescribedFunctionTemplate()) {
10134 // C++ [temp.mem]p3:
10135 // A member function template shall not be virtual.
10136 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10137 diag::err_virtual_member_function_template)
10138 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10139 } else {
10140 // Okay: Add virtual to the method.
10141 NewFD->setVirtualAsWritten(true);
10142 }
10143
10144 if (getLangOpts().CPlusPlus14 &&
10145 NewFD->getReturnType()->isUndeducedType())
10146 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10147 }
10148
10149 // C++ [dcl.fct.spec]p3:
10150 // The inline specifier shall not appear on a block scope function
10151 // declaration.
10152 if (isInline && !NewFD->isInvalidDecl()) {
10153 if (CurContext->isFunctionOrMethod()) {
10154 // 'inline' is not allowed on block scope function declaration.
10155 Diag(D.getDeclSpec().getInlineSpecLoc(),
10156 diag::err_inline_declaration_block_scope) << Name
10157 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10158 }
10159 }
10160
10161 // C++ [dcl.fct.spec]p6:
10162 // The explicit specifier shall be used only in the declaration of a
10163 // constructor or conversion function within its class definition;
10164 // see 12.3.1 and 12.3.2.
10165 if (hasExplicit && !NewFD->isInvalidDecl() &&
10166 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10167 if (!CurContext->isRecord()) {
10168 // 'explicit' was specified outside of the class.
10169 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10170 diag::err_explicit_out_of_class)
10171 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10172 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10173 !isa<CXXConversionDecl>(Val: NewFD)) {
10174 // 'explicit' was specified on a function that wasn't a constructor
10175 // or conversion function.
10176 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10177 diag::err_explicit_non_ctor_or_conv_function)
10178 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10179 }
10180 }
10181
10182 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10183 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10184 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10185 // are implicitly inline.
10186 NewFD->setImplicitlyInline();
10187
10188 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10189 // be either constructors or to return a literal type. Therefore,
10190 // destructors cannot be declared constexpr.
10191 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10192 (!getLangOpts().CPlusPlus20 ||
10193 ConstexprKind == ConstexprSpecKind::Consteval)) {
10194 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10195 << static_cast<int>(ConstexprKind);
10196 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10197 ? ConstexprSpecKind::Unspecified
10198 : ConstexprSpecKind::Constexpr);
10199 }
10200 // C++20 [dcl.constexpr]p2: An allocation function, or a
10201 // deallocation function shall not be declared with the consteval
10202 // specifier.
10203 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10204 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10205 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10206 diag::err_invalid_consteval_decl_kind)
10207 << NewFD;
10208 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10209 }
10210 }
10211
10212 // If __module_private__ was specified, mark the function accordingly.
10213 if (D.getDeclSpec().isModulePrivateSpecified()) {
10214 if (isFunctionTemplateSpecialization) {
10215 SourceLocation ModulePrivateLoc
10216 = D.getDeclSpec().getModulePrivateSpecLoc();
10217 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10218 << 0
10219 << FixItHint::CreateRemoval(ModulePrivateLoc);
10220 } else {
10221 NewFD->setModulePrivate();
10222 if (FunctionTemplate)
10223 FunctionTemplate->setModulePrivate();
10224 }
10225 }
10226
10227 if (isFriend) {
10228 if (FunctionTemplate) {
10229 FunctionTemplate->setObjectOfFriendDecl();
10230 FunctionTemplate->setAccess(AS_public);
10231 }
10232 NewFD->setObjectOfFriendDecl();
10233 NewFD->setAccess(AS_public);
10234 }
10235
10236 // If a function is defined as defaulted or deleted, mark it as such now.
10237 // We'll do the relevant checks on defaulted / deleted functions later.
10238 switch (D.getFunctionDefinitionKind()) {
10239 case FunctionDefinitionKind::Declaration:
10240 case FunctionDefinitionKind::Definition:
10241 break;
10242
10243 case FunctionDefinitionKind::Defaulted:
10244 NewFD->setDefaulted();
10245 break;
10246
10247 case FunctionDefinitionKind::Deleted:
10248 NewFD->setDeletedAsWritten();
10249 break;
10250 }
10251
10252 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10253 D.isFunctionDefinition()) {
10254 // Pre C++20 [class.mfct]p2:
10255 // A member function may be defined (8.4) in its class definition, in
10256 // which case it is an inline member function (7.1.2)
10257 // Post C++20 [class.mfct]p1:
10258 // If a member function is attached to the global module and is defined
10259 // in its class definition, it is inline.
10260 NewFD->setImplicitlyInline();
10261 }
10262
10263 if (!isFriend && SC != SC_None) {
10264 // C++ [temp.expl.spec]p2:
10265 // The declaration in an explicit-specialization shall not be an
10266 // export-declaration. An explicit specialization shall not use a
10267 // storage-class-specifier other than thread_local.
10268 //
10269 // We diagnose friend declarations with storage-class-specifiers
10270 // elsewhere.
10271 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10272 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10273 diag::ext_explicit_specialization_storage_class)
10274 << FixItHint::CreateRemoval(
10275 D.getDeclSpec().getStorageClassSpecLoc());
10276 }
10277
10278 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10279 assert(isa<CXXMethodDecl>(NewFD) &&
10280 "Out-of-line member function should be a CXXMethodDecl");
10281 // C++ [class.static]p1:
10282 // A data or function member of a class may be declared static
10283 // in a class definition, in which case it is a static member of
10284 // the class.
10285
10286 // Complain about the 'static' specifier if it's on an out-of-line
10287 // member function definition.
10288
10289 // MSVC permits the use of a 'static' storage specifier on an
10290 // out-of-line member function template declaration and class member
10291 // template declaration (MSVC versions before 2015), warn about this.
10292 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10293 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10294 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10295 (getLangOpts().MSVCCompat &&
10296 NewFD->getDescribedFunctionTemplate()))
10297 ? diag::ext_static_out_of_line
10298 : diag::err_static_out_of_line)
10299 << FixItHint::CreateRemoval(
10300 D.getDeclSpec().getStorageClassSpecLoc());
10301 }
10302 }
10303
10304 // C++11 [except.spec]p15:
10305 // A deallocation function with no exception-specification is treated
10306 // as if it were specified with noexcept(true).
10307 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10308 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10309 !FPT->hasExceptionSpec())
10310 NewFD->setType(Context.getFunctionType(
10311 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10312 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10313
10314 // C++20 [dcl.inline]/7
10315 // If an inline function or variable that is attached to a named module
10316 // is declared in a definition domain, it shall be defined in that
10317 // domain.
10318 // So, if the current declaration does not have a definition, we must
10319 // check at the end of the TU (or when the PMF starts) to see that we
10320 // have a definition at that point.
10321 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10322 NewFD->isInNamedModule()) {
10323 PendingInlineFuncDecls.insert(Ptr: NewFD);
10324 }
10325 }
10326
10327 // Filter out previous declarations that don't match the scope.
10328 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10329 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10330 isMemberSpecialization ||
10331 isFunctionTemplateSpecialization);
10332
10333 // Handle GNU asm-label extension (encoded as an attribute).
10334 if (Expr *E = (Expr*) D.getAsmLabel()) {
10335 // The parser guarantees this is a string.
10336 StringLiteral *SE = cast<StringLiteral>(Val: E);
10337 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10338 /*IsLiteralLabel=*/true,
10339 SE->getStrTokenLoc(0)));
10340 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10341 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10342 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10343 if (I != ExtnameUndeclaredIdentifiers.end()) {
10344 if (isDeclExternC(NewFD)) {
10345 NewFD->addAttr(A: I->second);
10346 ExtnameUndeclaredIdentifiers.erase(I);
10347 } else
10348 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10349 << /*Variable*/0 << NewFD;
10350 }
10351 }
10352
10353 // Copy the parameter declarations from the declarator D to the function
10354 // declaration NewFD, if they are available. First scavenge them into Params.
10355 SmallVector<ParmVarDecl*, 16> Params;
10356 unsigned FTIIdx;
10357 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10358 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10359
10360 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10361 // function that takes no arguments, not a function that takes a
10362 // single void argument.
10363 // We let through "const void" here because Sema::GetTypeForDeclarator
10364 // already checks for that case.
10365 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10366 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10367 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10368 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10369 Param->setDeclContext(NewFD);
10370 Params.push_back(Elt: Param);
10371
10372 if (Param->isInvalidDecl())
10373 NewFD->setInvalidDecl();
10374 }
10375 }
10376
10377 if (!getLangOpts().CPlusPlus) {
10378 // In C, find all the tag declarations from the prototype and move them
10379 // into the function DeclContext. Remove them from the surrounding tag
10380 // injection context of the function, which is typically but not always
10381 // the TU.
10382 DeclContext *PrototypeTagContext =
10383 getTagInjectionContext(NewFD->getLexicalDeclContext());
10384 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10385 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10386
10387 // We don't want to reparent enumerators. Look at their parent enum
10388 // instead.
10389 if (!TD) {
10390 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10391 TD = cast<EnumDecl>(ECD->getDeclContext());
10392 }
10393 if (!TD)
10394 continue;
10395 DeclContext *TagDC = TD->getLexicalDeclContext();
10396 if (!TagDC->containsDecl(TD))
10397 continue;
10398 TagDC->removeDecl(TD);
10399 TD->setDeclContext(NewFD);
10400 NewFD->addDecl(TD);
10401
10402 // Preserve the lexical DeclContext if it is not the surrounding tag
10403 // injection context of the FD. In this example, the semantic context of
10404 // E will be f and the lexical context will be S, while both the
10405 // semantic and lexical contexts of S will be f:
10406 // void f(struct S { enum E { a } f; } s);
10407 if (TagDC != PrototypeTagContext)
10408 TD->setLexicalDeclContext(TagDC);
10409 }
10410 }
10411 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10412 // When we're declaring a function with a typedef, typeof, etc as in the
10413 // following example, we'll need to synthesize (unnamed)
10414 // parameters for use in the declaration.
10415 //
10416 // @code
10417 // typedef void fn(int);
10418 // fn f;
10419 // @endcode
10420
10421 // Synthesize a parameter for each argument type.
10422 for (const auto &AI : FT->param_types()) {
10423 ParmVarDecl *Param =
10424 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10425 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10426 Params.push_back(Elt: Param);
10427 }
10428 } else {
10429 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10430 "Should not need args for typedef of non-prototype fn");
10431 }
10432
10433 // Finally, we know we have the right number of parameters, install them.
10434 NewFD->setParams(Params);
10435
10436 // If this declarator is a declaration and not a definition, its parameters
10437 // will not be pushed onto a scope chain. That means we will not issue any
10438 // reserved identifier warnings for the declaration, but we will for the
10439 // definition. Handle those here.
10440 if (!D.isFunctionDefinition()) {
10441 for (const ParmVarDecl *PVD : Params)
10442 warnOnReservedIdentifier(PVD);
10443 }
10444
10445 if (D.getDeclSpec().isNoreturnSpecified())
10446 NewFD->addAttr(
10447 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10448
10449 // Functions returning a variably modified type violate C99 6.7.5.2p2
10450 // because all functions have linkage.
10451 if (!NewFD->isInvalidDecl() &&
10452 NewFD->getReturnType()->isVariablyModifiedType()) {
10453 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10454 NewFD->setInvalidDecl();
10455 }
10456
10457 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10458 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10459 !NewFD->hasAttr<SectionAttr>())
10460 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10461 Context, PragmaClangTextSection.SectionName,
10462 PragmaClangTextSection.PragmaLocation));
10463
10464 // Apply an implicit SectionAttr if #pragma code_seg is active.
10465 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10466 !NewFD->hasAttr<SectionAttr>()) {
10467 NewFD->addAttr(SectionAttr::CreateImplicit(
10468 Context, CodeSegStack.CurrentValue->getString(),
10469 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10470 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10471 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10472 ASTContext::PSF_Read,
10473 NewFD))
10474 NewFD->dropAttr<SectionAttr>();
10475 }
10476
10477 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10478 // active.
10479 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10480 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10481 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10482 Context, PragmaClangTextSection.PragmaLocation));
10483
10484 // Apply an implicit CodeSegAttr from class declspec or
10485 // apply an implicit SectionAttr from #pragma code_seg if active.
10486 if (!NewFD->hasAttr<CodeSegAttr>()) {
10487 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10488 IsDefinition: D.isFunctionDefinition())) {
10489 NewFD->addAttr(SAttr);
10490 }
10491 }
10492
10493 // Handle attributes.
10494 ProcessDeclAttributes(S, NewFD, D);
10495 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10496 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10497 !NewTVA->isDefaultVersion() &&
10498 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10499 // Don't add to scope fmv functions declarations if fmv disabled
10500 AddToScope = false;
10501 return NewFD;
10502 }
10503
10504 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10505 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10506 // type.
10507 //
10508 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10509 // type declaration will generate a compilation error.
10510 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10511 if (AddressSpace != LangAS::Default) {
10512 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10513 NewFD->setInvalidDecl();
10514 }
10515 }
10516
10517 if (!getLangOpts().CPlusPlus) {
10518 // Perform semantic checking on the function declaration.
10519 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10520 CheckMain(FD: NewFD, D: D.getDeclSpec());
10521
10522 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10523 CheckMSVCRTEntryPoint(FD: NewFD);
10524
10525 if (!NewFD->isInvalidDecl())
10526 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10527 IsMemberSpecialization: isMemberSpecialization,
10528 DeclIsDefn: D.isFunctionDefinition()));
10529 else if (!Previous.empty())
10530 // Recover gracefully from an invalid redeclaration.
10531 D.setRedeclaration(true);
10532 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10533 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10534 "previous declaration set still overloaded");
10535
10536 // Diagnose no-prototype function declarations with calling conventions that
10537 // don't support variadic calls. Only do this in C and do it after merging
10538 // possibly prototyped redeclarations.
10539 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10540 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10541 CallingConv CC = FT->getExtInfo().getCC();
10542 if (!supportsVariadicCall(CC)) {
10543 // Windows system headers sometimes accidentally use stdcall without
10544 // (void) parameters, so we relax this to a warning.
10545 int DiagID =
10546 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10547 Diag(NewFD->getLocation(), DiagID)
10548 << FunctionType::getNameForCallConv(CC);
10549 }
10550 }
10551
10552 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10553 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10554 checkNonTrivialCUnion(
10555 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10556 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10557 } else {
10558 // C++11 [replacement.functions]p3:
10559 // The program's definitions shall not be specified as inline.
10560 //
10561 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10562 //
10563 // Suppress the diagnostic if the function is __attribute__((used)), since
10564 // that forces an external definition to be emitted.
10565 if (D.getDeclSpec().isInlineSpecified() &&
10566 NewFD->isReplaceableGlobalAllocationFunction() &&
10567 !NewFD->hasAttr<UsedAttr>())
10568 Diag(D.getDeclSpec().getInlineSpecLoc(),
10569 diag::ext_operator_new_delete_declared_inline)
10570 << NewFD->getDeclName();
10571
10572 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10573 // C++20 [dcl.decl.general]p4:
10574 // The optional requires-clause in an init-declarator or
10575 // member-declarator shall be present only if the declarator declares a
10576 // templated function.
10577 //
10578 // C++20 [temp.pre]p8:
10579 // An entity is templated if it is
10580 // - a template,
10581 // - an entity defined or created in a templated entity,
10582 // - a member of a templated entity,
10583 // - an enumerator for an enumeration that is a templated entity, or
10584 // - the closure type of a lambda-expression appearing in the
10585 // declaration of a templated entity.
10586 //
10587 // [Note 6: A local class, a local or block variable, or a friend
10588 // function defined in a templated entity is a templated entity.
10589 // — end note]
10590 //
10591 // A templated function is a function template or a function that is
10592 // templated. A templated class is a class template or a class that is
10593 // templated. A templated variable is a variable template or a variable
10594 // that is templated.
10595 if (!FunctionTemplate) {
10596 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10597 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10598 // An explicit specialization shall not have a trailing
10599 // requires-clause unless it declares a function template.
10600 //
10601 // Since a friend function template specialization cannot be
10602 // definition, and since a non-template friend declaration with a
10603 // trailing requires-clause must be a definition, we diagnose
10604 // friend function template specializations with trailing
10605 // requires-clauses on the same path as explicit specializations
10606 // even though they aren't necessarily prohibited by the same
10607 // language rule.
10608 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10609 << isFriend;
10610 } else if (isFriend && NewFD->isTemplated() &&
10611 !D.isFunctionDefinition()) {
10612 // C++ [temp.friend]p9:
10613 // A non-template friend declaration with a requires-clause shall be
10614 // a definition.
10615 Diag(NewFD->getBeginLoc(),
10616 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10617 NewFD->setInvalidDecl();
10618 } else if (!NewFD->isTemplated() ||
10619 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10620 Diag(TRC->getBeginLoc(),
10621 diag::err_constrained_non_templated_function);
10622 }
10623 }
10624 }
10625
10626 // We do not add HD attributes to specializations here because
10627 // they may have different constexpr-ness compared to their
10628 // templates and, after maybeAddHostDeviceAttrs() is applied,
10629 // may end up with different effective targets. Instead, a
10630 // specialization inherits its target attributes from its template
10631 // in the CheckFunctionTemplateSpecialization() call below.
10632 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10633 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10634
10635 // Handle explicit specializations of function templates
10636 // and friend function declarations with an explicit
10637 // template argument list.
10638 if (isFunctionTemplateSpecialization) {
10639 bool isDependentSpecialization = false;
10640 if (isFriend) {
10641 // For friend function specializations, this is a dependent
10642 // specialization if its semantic context is dependent, its
10643 // type is dependent, or if its template-id is dependent.
10644 isDependentSpecialization =
10645 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10646 (HasExplicitTemplateArgs &&
10647 TemplateSpecializationType::
10648 anyInstantiationDependentTemplateArguments(
10649 Args: TemplateArgs.arguments()));
10650 assert((!isDependentSpecialization ||
10651 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10652 "dependent friend function specialization without template "
10653 "args");
10654 } else {
10655 // For class-scope explicit specializations of function templates,
10656 // if the lexical context is dependent, then the specialization
10657 // is dependent.
10658 isDependentSpecialization =
10659 CurContext->isRecord() && CurContext->isDependentContext();
10660 }
10661
10662 TemplateArgumentListInfo *ExplicitTemplateArgs =
10663 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10664 if (isDependentSpecialization) {
10665 // If it's a dependent specialization, it may not be possible
10666 // to determine the primary template (for explicit specializations)
10667 // or befriended declaration (for friends) until the enclosing
10668 // template is instantiated. In such cases, we store the declarations
10669 // found by name lookup and defer resolution until instantiation.
10670 if (CheckDependentFunctionTemplateSpecialization(
10671 FD: NewFD, ExplicitTemplateArgs, Previous))
10672 NewFD->setInvalidDecl();
10673 } else if (!NewFD->isInvalidDecl()) {
10674 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10675 Previous))
10676 NewFD->setInvalidDecl();
10677 }
10678 } else if (isMemberSpecialization && !FunctionTemplate) {
10679 if (CheckMemberSpecialization(NewFD, Previous))
10680 NewFD->setInvalidDecl();
10681 }
10682
10683 // Perform semantic checking on the function declaration.
10684 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10685 CheckMain(FD: NewFD, D: D.getDeclSpec());
10686
10687 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10688 CheckMSVCRTEntryPoint(FD: NewFD);
10689
10690 if (!NewFD->isInvalidDecl())
10691 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10692 IsMemberSpecialization: isMemberSpecialization,
10693 DeclIsDefn: D.isFunctionDefinition()));
10694 else if (!Previous.empty())
10695 // Recover gracefully from an invalid redeclaration.
10696 D.setRedeclaration(true);
10697
10698 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10699 !D.isRedeclaration() ||
10700 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10701 "previous declaration set still overloaded");
10702
10703 NamedDecl *PrincipalDecl = (FunctionTemplate
10704 ? cast<NamedDecl>(Val: FunctionTemplate)
10705 : NewFD);
10706
10707 if (isFriend && NewFD->getPreviousDecl()) {
10708 AccessSpecifier Access = AS_public;
10709 if (!NewFD->isInvalidDecl())
10710 Access = NewFD->getPreviousDecl()->getAccess();
10711
10712 NewFD->setAccess(Access);
10713 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10714 }
10715
10716 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10717 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10718 PrincipalDecl->setNonMemberOperator();
10719
10720 // If we have a function template, check the template parameter
10721 // list. This will check and merge default template arguments.
10722 if (FunctionTemplate) {
10723 FunctionTemplateDecl *PrevTemplate =
10724 FunctionTemplate->getPreviousDecl();
10725 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10726 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10727 : nullptr,
10728 TPC: D.getDeclSpec().isFriendSpecified()
10729 ? (D.isFunctionDefinition()
10730 ? TPC_FriendFunctionTemplateDefinition
10731 : TPC_FriendFunctionTemplate)
10732 : (D.getCXXScopeSpec().isSet() &&
10733 DC && DC->isRecord() &&
10734 DC->isDependentContext())
10735 ? TPC_ClassTemplateMember
10736 : TPC_FunctionTemplate);
10737 }
10738
10739 if (NewFD->isInvalidDecl()) {
10740 // Ignore all the rest of this.
10741 } else if (!D.isRedeclaration()) {
10742 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10743 .AddToScope: AddToScope };
10744 // Fake up an access specifier if it's supposed to be a class member.
10745 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10746 NewFD->setAccess(AS_public);
10747
10748 // Qualified decls generally require a previous declaration.
10749 if (D.getCXXScopeSpec().isSet()) {
10750 // ...with the major exception of templated-scope or
10751 // dependent-scope friend declarations.
10752
10753 // TODO: we currently also suppress this check in dependent
10754 // contexts because (1) the parameter depth will be off when
10755 // matching friend templates and (2) we might actually be
10756 // selecting a friend based on a dependent factor. But there
10757 // are situations where these conditions don't apply and we
10758 // can actually do this check immediately.
10759 //
10760 // Unless the scope is dependent, it's always an error if qualified
10761 // redeclaration lookup found nothing at all. Diagnose that now;
10762 // nothing will diagnose that error later.
10763 if (isFriend &&
10764 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10765 (!Previous.empty() && CurContext->isDependentContext()))) {
10766 // ignore these
10767 } else if (NewFD->isCPUDispatchMultiVersion() ||
10768 NewFD->isCPUSpecificMultiVersion()) {
10769 // ignore this, we allow the redeclaration behavior here to create new
10770 // versions of the function.
10771 } else {
10772 // The user tried to provide an out-of-line definition for a
10773 // function that is a member of a class or namespace, but there
10774 // was no such member function declared (C++ [class.mfct]p2,
10775 // C++ [namespace.memdef]p2). For example:
10776 //
10777 // class X {
10778 // void f() const;
10779 // };
10780 //
10781 // void X::f() { } // ill-formed
10782 //
10783 // Complain about this problem, and attempt to suggest close
10784 // matches (e.g., those that differ only in cv-qualifiers and
10785 // whether the parameter types are references).
10786
10787 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10788 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10789 AddToScope = ExtraArgs.AddToScope;
10790 return Result;
10791 }
10792 }
10793
10794 // Unqualified local friend declarations are required to resolve
10795 // to something.
10796 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10797 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10798 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10799 AddToScope = ExtraArgs.AddToScope;
10800 return Result;
10801 }
10802 }
10803 } else if (!D.isFunctionDefinition() &&
10804 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10805 !isFriend && !isFunctionTemplateSpecialization &&
10806 !isMemberSpecialization) {
10807 // An out-of-line member function declaration must also be a
10808 // definition (C++ [class.mfct]p2).
10809 // Note that this is not the case for explicit specializations of
10810 // function templates or member functions of class templates, per
10811 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10812 // extension for compatibility with old SWIG code which likes to
10813 // generate them.
10814 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10815 << D.getCXXScopeSpec().getRange();
10816 }
10817 }
10818
10819 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10820 // Any top level function could potentially be specified as an entry.
10821 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10822 HLSL().ActOnTopLevelFunction(FD: NewFD);
10823
10824 if (NewFD->hasAttr<HLSLShaderAttr>())
10825 HLSL().CheckEntryPoint(FD: NewFD);
10826 }
10827
10828 // If this is the first declaration of a library builtin function, add
10829 // attributes as appropriate.
10830 if (!D.isRedeclaration()) {
10831 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10832 if (unsigned BuiltinID = II->getBuiltinID()) {
10833 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
10834 if (!InStdNamespace &&
10835 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10836 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10837 // Validate the type matches unless this builtin is specified as
10838 // matching regardless of its declared type.
10839 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
10840 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10841 } else {
10842 ASTContext::GetBuiltinTypeError Error;
10843 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
10844 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
10845
10846 if (!Error && !BuiltinType.isNull() &&
10847 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10848 NewFD->getType(), BuiltinType))
10849 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10850 }
10851 }
10852 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10853 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
10854 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10855 }
10856 }
10857 }
10858 }
10859
10860 ProcessPragmaWeak(S, NewFD);
10861 checkAttributesAfterMerging(*this, *NewFD);
10862
10863 AddKnownFunctionAttributes(FD: NewFD);
10864
10865 if (NewFD->hasAttr<OverloadableAttr>() &&
10866 !NewFD->getType()->getAs<FunctionProtoType>()) {
10867 Diag(NewFD->getLocation(),
10868 diag::err_attribute_overloadable_no_prototype)
10869 << NewFD;
10870 NewFD->dropAttr<OverloadableAttr>();
10871 }
10872
10873 // If there's a #pragma GCC visibility in scope, and this isn't a class
10874 // member, set the visibility of this function.
10875 if (!DC->isRecord() && NewFD->isExternallyVisible())
10876 AddPushedVisibilityAttribute(NewFD);
10877
10878 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10879 // marking the function.
10880 ObjC().AddCFAuditedAttribute(NewFD);
10881
10882 // If this is a function definition, check if we have to apply any
10883 // attributes (i.e. optnone and no_builtin) due to a pragma.
10884 if (D.isFunctionDefinition()) {
10885 AddRangeBasedOptnone(FD: NewFD);
10886 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
10887 AddSectionMSAllocText(FD: NewFD);
10888 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
10889 }
10890
10891 // If this is the first declaration of an extern C variable, update
10892 // the map of such variables.
10893 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10894 isIncompleteDeclExternC(S&: *this, D: NewFD))
10895 RegisterLocallyScopedExternCDecl(NewFD, S);
10896
10897 // Set this FunctionDecl's range up to the right paren.
10898 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10899
10900 if (D.isRedeclaration() && !Previous.empty()) {
10901 NamedDecl *Prev = Previous.getRepresentativeDecl();
10902 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10903 isMemberSpecialization ||
10904 isFunctionTemplateSpecialization,
10905 D.isFunctionDefinition());
10906 }
10907
10908 if (getLangOpts().CUDA) {
10909 IdentifierInfo *II = NewFD->getIdentifier();
10910 if (II && II->isStr(Str: CUDA().getConfigureFuncName()) &&
10911 !NewFD->isInvalidDecl() &&
10912 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10913 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10914 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10915 << CUDA().getConfigureFuncName();
10916 Context.setcudaConfigureCallDecl(NewFD);
10917 }
10918
10919 // Variadic functions, other than a *declaration* of printf, are not allowed
10920 // in device-side CUDA code, unless someone passed
10921 // -fcuda-allow-variadic-functions.
10922 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10923 (NewFD->hasAttr<CUDADeviceAttr>() ||
10924 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10925 !(II && II->isStr("printf") && NewFD->isExternC() &&
10926 !D.isFunctionDefinition())) {
10927 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10928 }
10929 }
10930
10931 MarkUnusedFileScopedDecl(NewFD);
10932
10933 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
10934 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10935 if (SC == SC_Static) {
10936 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10937 D.setInvalidType();
10938 }
10939
10940 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10941 if (!NewFD->getReturnType()->isVoidType()) {
10942 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10943 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10944 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10945 : FixItHint());
10946 D.setInvalidType();
10947 }
10948
10949 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10950 for (auto *Param : NewFD->parameters())
10951 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
10952
10953 if (getLangOpts().OpenCLCPlusPlus) {
10954 if (DC->isRecord()) {
10955 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10956 D.setInvalidType();
10957 }
10958 if (FunctionTemplate) {
10959 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10960 D.setInvalidType();
10961 }
10962 }
10963 }
10964
10965 if (getLangOpts().CPlusPlus) {
10966 // Precalculate whether this is a friend function template with a constraint
10967 // that depends on an enclosing template, per [temp.friend]p9.
10968 if (isFriend && FunctionTemplate &&
10969 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
10970 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10971
10972 // C++ [temp.friend]p9:
10973 // A friend function template with a constraint that depends on a
10974 // template parameter from an enclosing template shall be a definition.
10975 if (!D.isFunctionDefinition()) {
10976 Diag(NewFD->getBeginLoc(),
10977 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10978 NewFD->setInvalidDecl();
10979 }
10980 }
10981
10982 if (FunctionTemplate) {
10983 if (NewFD->isInvalidDecl())
10984 FunctionTemplate->setInvalidDecl();
10985 return FunctionTemplate;
10986 }
10987
10988 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10989 CompleteMemberSpecialization(NewFD, Previous);
10990 }
10991
10992 for (const ParmVarDecl *Param : NewFD->parameters()) {
10993 QualType PT = Param->getType();
10994
10995 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10996 // types.
10997 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10998 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10999 QualType ElemTy = PipeTy->getElementType();
11000 if (ElemTy->isPointerOrReferenceType()) {
11001 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11002 D.setInvalidType();
11003 }
11004 }
11005 }
11006 // WebAssembly tables can't be used as function parameters.
11007 if (Context.getTargetInfo().getTriple().isWasm()) {
11008 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11009 Diag(Param->getTypeSpecStartLoc(),
11010 diag::err_wasm_table_as_function_parameter);
11011 D.setInvalidType();
11012 }
11013 }
11014 }
11015
11016 // Diagnose availability attributes. Availability cannot be used on functions
11017 // that are run during load/unload.
11018 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11019 if (NewFD->hasAttr<ConstructorAttr>()) {
11020 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11021 << 1;
11022 NewFD->dropAttr<AvailabilityAttr>();
11023 }
11024 if (NewFD->hasAttr<DestructorAttr>()) {
11025 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11026 << 2;
11027 NewFD->dropAttr<AvailabilityAttr>();
11028 }
11029 }
11030
11031 // Diagnose no_builtin attribute on function declaration that are not a
11032 // definition.
11033 // FIXME: We should really be doing this in
11034 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11035 // the FunctionDecl and at this point of the code
11036 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11037 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11038 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11039 switch (D.getFunctionDefinitionKind()) {
11040 case FunctionDefinitionKind::Defaulted:
11041 case FunctionDefinitionKind::Deleted:
11042 Diag(NBA->getLocation(),
11043 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11044 << NBA->getSpelling();
11045 break;
11046 case FunctionDefinitionKind::Declaration:
11047 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11048 << NBA->getSpelling();
11049 break;
11050 case FunctionDefinitionKind::Definition:
11051 break;
11052 }
11053
11054 // Similar to no_builtin logic above, at this point of the code
11055 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11056 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11057 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11058 !NewFD->isInvalidDecl() &&
11059 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11060 ExternalDeclarations.push_back(NewFD);
11061
11062 // Used for a warning on the 'next' declaration when used with a
11063 // `routine(name)`.
11064 if (getLangOpts().OpenACC)
11065 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11066
11067 return NewFD;
11068}
11069
11070/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11071/// when __declspec(code_seg) "is applied to a class, all member functions of
11072/// the class and nested classes -- this includes compiler-generated special
11073/// member functions -- are put in the specified segment."
11074/// The actual behavior is a little more complicated. The Microsoft compiler
11075/// won't check outer classes if there is an active value from #pragma code_seg.
11076/// The CodeSeg is always applied from the direct parent but only from outer
11077/// classes when the #pragma code_seg stack is empty. See:
11078/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11079/// available since MS has removed the page.
11080static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11081 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11082 if (!Method)
11083 return nullptr;
11084 const CXXRecordDecl *Parent = Method->getParent();
11085 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11086 Attr *NewAttr = SAttr->clone(S.getASTContext());
11087 NewAttr->setImplicit(true);
11088 return NewAttr;
11089 }
11090
11091 // The Microsoft compiler won't check outer classes for the CodeSeg
11092 // when the #pragma code_seg stack is active.
11093 if (S.CodeSegStack.CurrentValue)
11094 return nullptr;
11095
11096 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11097 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11098 Attr *NewAttr = SAttr->clone(S.getASTContext());
11099 NewAttr->setImplicit(true);
11100 return NewAttr;
11101 }
11102 }
11103 return nullptr;
11104}
11105
11106Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11107 bool IsDefinition) {
11108 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11109 return A;
11110 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11111 CodeSegStack.CurrentValue)
11112 return SectionAttr::CreateImplicit(
11113 getASTContext(), CodeSegStack.CurrentValue->getString(),
11114 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11115 return nullptr;
11116}
11117
11118bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11119 QualType NewT, QualType OldT) {
11120 if (!NewD->getLexicalDeclContext()->isDependentContext())
11121 return true;
11122
11123 // For dependently-typed local extern declarations and friends, we can't
11124 // perform a correct type check in general until instantiation:
11125 //
11126 // int f();
11127 // template<typename T> void g() { T f(); }
11128 //
11129 // (valid if g() is only instantiated with T = int).
11130 if (NewT->isDependentType() &&
11131 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11132 return false;
11133
11134 // Similarly, if the previous declaration was a dependent local extern
11135 // declaration, we don't really know its type yet.
11136 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11137 return false;
11138
11139 return true;
11140}
11141
11142bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11143 if (!D->getLexicalDeclContext()->isDependentContext())
11144 return true;
11145
11146 // Don't chain dependent friend function definitions until instantiation, to
11147 // permit cases like
11148 //
11149 // void func();
11150 // template<typename T> class C1 { friend void func() {} };
11151 // template<typename T> class C2 { friend void func() {} };
11152 //
11153 // ... which is valid if only one of C1 and C2 is ever instantiated.
11154 //
11155 // FIXME: This need only apply to function definitions. For now, we proxy
11156 // this by checking for a file-scope function. We do not want this to apply
11157 // to friend declarations nominating member functions, because that gets in
11158 // the way of access checks.
11159 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11160 return false;
11161
11162 auto *VD = dyn_cast<ValueDecl>(Val: D);
11163 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11164 return !VD || !PrevVD ||
11165 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11166 OldT: PrevVD->getType());
11167}
11168
11169/// Check the target or target_version attribute of the function for
11170/// MultiVersion validity.
11171///
11172/// Returns true if there was an error, false otherwise.
11173static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11174 const auto *TA = FD->getAttr<TargetAttr>();
11175 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11176
11177 assert((TA || TVA) && "Expecting target or target_version attribute");
11178
11179 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11180 enum ErrType { Feature = 0, Architecture = 1 };
11181
11182 if (TA) {
11183 ParsedTargetAttr ParseInfo =
11184 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11185 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11186 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11187 << Architecture << ParseInfo.CPU;
11188 return true;
11189 }
11190 for (const auto &Feat : ParseInfo.Features) {
11191 auto BareFeat = StringRef{Feat}.substr(1);
11192 if (Feat[0] == '-') {
11193 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11194 << Feature << ("no-" + BareFeat).str();
11195 return true;
11196 }
11197
11198 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11199 !TargetInfo.isValidFeatureName(BareFeat) ||
11200 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11201 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11202 << Feature << BareFeat;
11203 return true;
11204 }
11205 }
11206 }
11207
11208 if (TVA) {
11209 llvm::SmallVector<StringRef, 8> Feats;
11210 ParsedTargetAttr ParseInfo;
11211 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11212 ParseInfo =
11213 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11214 for (auto &Feat : ParseInfo.Features)
11215 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11216 } else {
11217 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11218 TVA->getFeatures(Feats);
11219 }
11220 for (const auto &Feat : Feats) {
11221 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11222 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11223 << Feature << Feat;
11224 return true;
11225 }
11226 }
11227 }
11228 return false;
11229}
11230
11231// Provide a white-list of attributes that are allowed to be combined with
11232// multiversion functions.
11233static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11234 MultiVersionKind MVKind) {
11235 // Note: this list/diagnosis must match the list in
11236 // checkMultiversionAttributesAllSame.
11237 switch (Kind) {
11238 default:
11239 return false;
11240 case attr::ArmLocallyStreaming:
11241 return MVKind == MultiVersionKind::TargetVersion ||
11242 MVKind == MultiVersionKind::TargetClones;
11243 case attr::Used:
11244 return MVKind == MultiVersionKind::Target;
11245 case attr::NonNull:
11246 case attr::NoThrow:
11247 return true;
11248 }
11249}
11250
11251static bool checkNonMultiVersionCompatAttributes(Sema &S,
11252 const FunctionDecl *FD,
11253 const FunctionDecl *CausedFD,
11254 MultiVersionKind MVKind) {
11255 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11256 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11257 << static_cast<unsigned>(MVKind) << A;
11258 if (CausedFD)
11259 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11260 return true;
11261 };
11262
11263 for (const Attr *A : FD->attrs()) {
11264 switch (A->getKind()) {
11265 case attr::CPUDispatch:
11266 case attr::CPUSpecific:
11267 if (MVKind != MultiVersionKind::CPUDispatch &&
11268 MVKind != MultiVersionKind::CPUSpecific)
11269 return Diagnose(S, A);
11270 break;
11271 case attr::Target:
11272 if (MVKind != MultiVersionKind::Target)
11273 return Diagnose(S, A);
11274 break;
11275 case attr::TargetVersion:
11276 if (MVKind != MultiVersionKind::TargetVersion &&
11277 MVKind != MultiVersionKind::TargetClones)
11278 return Diagnose(S, A);
11279 break;
11280 case attr::TargetClones:
11281 if (MVKind != MultiVersionKind::TargetClones &&
11282 MVKind != MultiVersionKind::TargetVersion)
11283 return Diagnose(S, A);
11284 break;
11285 default:
11286 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11287 return Diagnose(S, A);
11288 break;
11289 }
11290 }
11291 return false;
11292}
11293
11294bool Sema::areMultiversionVariantFunctionsCompatible(
11295 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11296 const PartialDiagnostic &NoProtoDiagID,
11297 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11298 const PartialDiagnosticAt &NoSupportDiagIDAt,
11299 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11300 bool ConstexprSupported, bool CLinkageMayDiffer) {
11301 enum DoesntSupport {
11302 FuncTemplates = 0,
11303 VirtFuncs = 1,
11304 DeducedReturn = 2,
11305 Constructors = 3,
11306 Destructors = 4,
11307 DeletedFuncs = 5,
11308 DefaultedFuncs = 6,
11309 ConstexprFuncs = 7,
11310 ConstevalFuncs = 8,
11311 Lambda = 9,
11312 };
11313 enum Different {
11314 CallingConv = 0,
11315 ReturnType = 1,
11316 ConstexprSpec = 2,
11317 InlineSpec = 3,
11318 Linkage = 4,
11319 LanguageLinkage = 5,
11320 };
11321
11322 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11323 !OldFD->getType()->getAs<FunctionProtoType>()) {
11324 Diag(OldFD->getLocation(), NoProtoDiagID);
11325 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11326 return true;
11327 }
11328
11329 if (NoProtoDiagID.getDiagID() != 0 &&
11330 !NewFD->getType()->getAs<FunctionProtoType>())
11331 return Diag(NewFD->getLocation(), NoProtoDiagID);
11332
11333 if (!TemplatesSupported &&
11334 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11335 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11336 << FuncTemplates;
11337
11338 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11339 if (NewCXXFD->isVirtual())
11340 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11341 << VirtFuncs;
11342
11343 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11344 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11345 << Constructors;
11346
11347 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11348 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11349 << Destructors;
11350 }
11351
11352 if (NewFD->isDeleted())
11353 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11354 << DeletedFuncs;
11355
11356 if (NewFD->isDefaulted())
11357 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11358 << DefaultedFuncs;
11359
11360 if (!ConstexprSupported && NewFD->isConstexpr())
11361 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11362 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11363
11364 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11365 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11366 QualType NewReturnType = NewType->getReturnType();
11367
11368 if (NewReturnType->isUndeducedType())
11369 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11370 << DeducedReturn;
11371
11372 // Ensure the return type is identical.
11373 if (OldFD) {
11374 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11375 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11376 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11377 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11378
11379 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11380 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11381
11382 bool ArmStreamingCCMismatched = false;
11383 if (OldFPT && NewFPT) {
11384 unsigned Diff =
11385 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11386 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11387 // cannot be mixed.
11388 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11389 FunctionType::SME_PStateSMCompatibleMask))
11390 ArmStreamingCCMismatched = true;
11391 }
11392
11393 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11394 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11395
11396 QualType OldReturnType = OldType->getReturnType();
11397
11398 if (OldReturnType != NewReturnType)
11399 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11400
11401 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11402 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11403
11404 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11405 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11406
11407 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11408 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11409
11410 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11411 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11412
11413 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11414 NewFD->getLocation()))
11415 return true;
11416 }
11417 return false;
11418}
11419
11420static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11421 const FunctionDecl *NewFD,
11422 bool CausesMV,
11423 MultiVersionKind MVKind) {
11424 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11425 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11426 if (OldFD)
11427 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11428 return true;
11429 }
11430
11431 bool IsCPUSpecificCPUDispatchMVKind =
11432 MVKind == MultiVersionKind::CPUDispatch ||
11433 MVKind == MultiVersionKind::CPUSpecific;
11434
11435 if (CausesMV && OldFD &&
11436 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11437 return true;
11438
11439 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11440 return true;
11441
11442 // Only allow transition to MultiVersion if it hasn't been used.
11443 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11444 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11445 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11446 return true;
11447 }
11448
11449 return S.areMultiversionVariantFunctionsCompatible(
11450 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11451 PartialDiagnosticAt(NewFD->getLocation(),
11452 S.PDiag(diag::note_multiversioning_caused_here)),
11453 PartialDiagnosticAt(NewFD->getLocation(),
11454 S.PDiag(diag::err_multiversion_doesnt_support)
11455 << static_cast<unsigned>(MVKind)),
11456 PartialDiagnosticAt(NewFD->getLocation(),
11457 S.PDiag(diag::err_multiversion_diff)),
11458 /*TemplatesSupported=*/false,
11459 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11460 /*CLinkageMayDiffer=*/false);
11461}
11462
11463/// Check the validity of a multiversion function declaration that is the
11464/// first of its kind. Also sets the multiversion'ness' of the function itself.
11465///
11466/// This sets NewFD->isInvalidDecl() to true if there was an error.
11467///
11468/// Returns true if there was an error, false otherwise.
11469static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11470 MultiVersionKind MVKind = FD->getMultiVersionKind();
11471 assert(MVKind != MultiVersionKind::None &&
11472 "Function lacks multiversion attribute");
11473 const auto *TA = FD->getAttr<TargetAttr>();
11474 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11475 // The target attribute only causes MV if this declaration is the default,
11476 // otherwise it is treated as a normal function.
11477 if (TA && !TA->isDefaultVersion())
11478 return false;
11479
11480 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11481 FD->setInvalidDecl();
11482 return true;
11483 }
11484
11485 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11486 FD->setInvalidDecl();
11487 return true;
11488 }
11489
11490 FD->setIsMultiVersion();
11491 return false;
11492}
11493
11494static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11495 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11496 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11497 return true;
11498 }
11499
11500 return false;
11501}
11502
11503static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11504 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11505 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11506 return;
11507
11508 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11509 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11510
11511 if (MVKindTo == MultiVersionKind::None &&
11512 (MVKindFrom == MultiVersionKind::TargetVersion ||
11513 MVKindFrom == MultiVersionKind::TargetClones))
11514 To->addAttr(TargetVersionAttr::CreateImplicit(
11515 To->getASTContext(), "default", To->getSourceRange()));
11516}
11517
11518static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11519 FunctionDecl *NewFD,
11520 bool &Redeclaration,
11521 NamedDecl *&OldDecl,
11522 LookupResult &Previous) {
11523 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11524
11525 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11526 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11527 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11528 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11529
11530 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11531
11532 // The definitions should be allowed in any order. If we have discovered
11533 // a new target version and the preceeding was the default, then add the
11534 // corresponding attribute to it.
11535 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11536
11537 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11538 // to change, this is a simple redeclaration.
11539 if (NewTA && !NewTA->isDefaultVersion() &&
11540 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11541 return false;
11542
11543 // Otherwise, this decl causes MultiVersioning.
11544 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11545 NewTVA ? MultiVersionKind::TargetVersion
11546 : MultiVersionKind::Target)) {
11547 NewFD->setInvalidDecl();
11548 return true;
11549 }
11550
11551 if (CheckMultiVersionValue(S, FD: NewFD)) {
11552 NewFD->setInvalidDecl();
11553 return true;
11554 }
11555
11556 // If this is 'default', permit the forward declaration.
11557 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11558 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11559 Redeclaration = true;
11560 OldDecl = OldFD;
11561 OldFD->setIsMultiVersion();
11562 NewFD->setIsMultiVersion();
11563 return false;
11564 }
11565
11566 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11567 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11568 NewFD->setInvalidDecl();
11569 return true;
11570 }
11571
11572 if (NewTA) {
11573 ParsedTargetAttr OldParsed =
11574 S.getASTContext().getTargetInfo().parseTargetAttr(
11575 Str: OldTA->getFeaturesStr());
11576 llvm::sort(C&: OldParsed.Features);
11577 ParsedTargetAttr NewParsed =
11578 S.getASTContext().getTargetInfo().parseTargetAttr(
11579 Str: NewTA->getFeaturesStr());
11580 // Sort order doesn't matter, it just needs to be consistent.
11581 llvm::sort(C&: NewParsed.Features);
11582 if (OldParsed == NewParsed) {
11583 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11584 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11585 NewFD->setInvalidDecl();
11586 return true;
11587 }
11588 }
11589
11590 for (const auto *FD : OldFD->redecls()) {
11591 const auto *CurTA = FD->getAttr<TargetAttr>();
11592 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11593 // We allow forward declarations before ANY multiversioning attributes, but
11594 // nothing after the fact.
11595 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11596 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11597 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11598 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11599 << (NewTA ? 0 : 2);
11600 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11601 NewFD->setInvalidDecl();
11602 return true;
11603 }
11604 }
11605
11606 OldFD->setIsMultiVersion();
11607 NewFD->setIsMultiVersion();
11608 Redeclaration = false;
11609 OldDecl = nullptr;
11610 Previous.clear();
11611 return false;
11612}
11613
11614static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11615 MultiVersionKind OldKind = Old->getMultiVersionKind();
11616 MultiVersionKind NewKind = New->getMultiVersionKind();
11617
11618 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11619 NewKind == MultiVersionKind::None)
11620 return true;
11621
11622 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11623 switch (OldKind) {
11624 case MultiVersionKind::TargetVersion:
11625 return NewKind == MultiVersionKind::TargetClones;
11626 case MultiVersionKind::TargetClones:
11627 return NewKind == MultiVersionKind::TargetVersion;
11628 default:
11629 return false;
11630 }
11631 } else {
11632 switch (OldKind) {
11633 case MultiVersionKind::CPUDispatch:
11634 return NewKind == MultiVersionKind::CPUSpecific;
11635 case MultiVersionKind::CPUSpecific:
11636 return NewKind == MultiVersionKind::CPUDispatch;
11637 default:
11638 return false;
11639 }
11640 }
11641}
11642
11643/// Check the validity of a new function declaration being added to an existing
11644/// multiversioned declaration collection.
11645static bool CheckMultiVersionAdditionalDecl(
11646 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11647 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11648 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11649 LookupResult &Previous) {
11650
11651 // Disallow mixing of multiversioning types.
11652 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11653 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11654 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11655 NewFD->setInvalidDecl();
11656 return true;
11657 }
11658
11659 // Add the default target_version attribute if it's missing.
11660 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11661 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11662
11663 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11664 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11665 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11666 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11667
11668 ParsedTargetAttr NewParsed;
11669 if (NewTA) {
11670 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11671 Str: NewTA->getFeaturesStr());
11672 llvm::sort(C&: NewParsed.Features);
11673 }
11674 llvm::SmallVector<StringRef, 8> NewFeats;
11675 if (NewTVA) {
11676 NewTVA->getFeatures(NewFeats);
11677 llvm::sort(C&: NewFeats);
11678 }
11679
11680 bool UseMemberUsingDeclRules =
11681 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11682
11683 bool MayNeedOverloadableChecks =
11684 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11685
11686 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11687 // of a previous member of the MultiVersion set.
11688 for (NamedDecl *ND : Previous) {
11689 FunctionDecl *CurFD = ND->getAsFunction();
11690 if (!CurFD || CurFD->isInvalidDecl())
11691 continue;
11692 if (MayNeedOverloadableChecks &&
11693 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11694 continue;
11695
11696 switch (NewMVKind) {
11697 case MultiVersionKind::None:
11698 assert(OldMVKind == MultiVersionKind::TargetClones &&
11699 "Only target_clones can be omitted in subsequent declarations");
11700 break;
11701 case MultiVersionKind::Target: {
11702 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11703 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11704 NewFD->setIsMultiVersion();
11705 Redeclaration = true;
11706 OldDecl = ND;
11707 return false;
11708 }
11709
11710 ParsedTargetAttr CurParsed =
11711 S.getASTContext().getTargetInfo().parseTargetAttr(
11712 Str: CurTA->getFeaturesStr());
11713 llvm::sort(C&: CurParsed.Features);
11714 if (CurParsed == NewParsed) {
11715 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11716 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11717 NewFD->setInvalidDecl();
11718 return true;
11719 }
11720 break;
11721 }
11722 case MultiVersionKind::TargetVersion: {
11723 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11724 if (CurTVA->getName() == NewTVA->getName()) {
11725 NewFD->setIsMultiVersion();
11726 Redeclaration = true;
11727 OldDecl = ND;
11728 return false;
11729 }
11730 llvm::SmallVector<StringRef, 8> CurFeats;
11731 CurTVA->getFeatures(CurFeats);
11732 llvm::sort(C&: CurFeats);
11733
11734 if (CurFeats == NewFeats) {
11735 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11736 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11737 NewFD->setInvalidDecl();
11738 return true;
11739 }
11740 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11741 // Default
11742 if (NewFeats.empty())
11743 break;
11744
11745 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11746 llvm::SmallVector<StringRef, 8> CurFeats;
11747 CurClones->getFeatures(CurFeats, I);
11748 llvm::sort(C&: CurFeats);
11749
11750 if (CurFeats == NewFeats) {
11751 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11752 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11753 NewFD->setInvalidDecl();
11754 return true;
11755 }
11756 }
11757 }
11758 break;
11759 }
11760 case MultiVersionKind::TargetClones: {
11761 assert(NewClones && "MultiVersionKind does not match attribute type");
11762 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11763 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11764 !std::equal(CurClones->featuresStrs_begin(),
11765 CurClones->featuresStrs_end(),
11766 NewClones->featuresStrs_begin())) {
11767 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11768 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11769 NewFD->setInvalidDecl();
11770 return true;
11771 }
11772 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11773 llvm::SmallVector<StringRef, 8> CurFeats;
11774 CurTVA->getFeatures(CurFeats);
11775 llvm::sort(C&: CurFeats);
11776
11777 // Default
11778 if (CurFeats.empty())
11779 break;
11780
11781 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11782 NewFeats.clear();
11783 NewClones->getFeatures(NewFeats, I);
11784 llvm::sort(C&: NewFeats);
11785
11786 if (CurFeats == NewFeats) {
11787 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11788 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11789 NewFD->setInvalidDecl();
11790 return true;
11791 }
11792 }
11793 break;
11794 }
11795 Redeclaration = true;
11796 OldDecl = CurFD;
11797 NewFD->setIsMultiVersion();
11798 return false;
11799 }
11800 case MultiVersionKind::CPUSpecific:
11801 case MultiVersionKind::CPUDispatch: {
11802 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11803 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11804 // Handle CPUDispatch/CPUSpecific versions.
11805 // Only 1 CPUDispatch function is allowed, this will make it go through
11806 // the redeclaration errors.
11807 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11808 CurFD->hasAttr<CPUDispatchAttr>()) {
11809 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11810 std::equal(
11811 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11812 NewCPUDisp->cpus_begin(),
11813 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11814 return Cur->getName() == New->getName();
11815 })) {
11816 NewFD->setIsMultiVersion();
11817 Redeclaration = true;
11818 OldDecl = ND;
11819 return false;
11820 }
11821
11822 // If the declarations don't match, this is an error condition.
11823 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11824 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11825 NewFD->setInvalidDecl();
11826 return true;
11827 }
11828 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11829 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11830 std::equal(
11831 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11832 NewCPUSpec->cpus_begin(),
11833 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11834 return Cur->getName() == New->getName();
11835 })) {
11836 NewFD->setIsMultiVersion();
11837 Redeclaration = true;
11838 OldDecl = ND;
11839 return false;
11840 }
11841
11842 // Only 1 version of CPUSpecific is allowed for each CPU.
11843 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11844 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11845 if (CurII == NewII) {
11846 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11847 << NewII;
11848 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11849 NewFD->setInvalidDecl();
11850 return true;
11851 }
11852 }
11853 }
11854 }
11855 break;
11856 }
11857 }
11858 }
11859
11860 // Else, this is simply a non-redecl case. Checking the 'value' is only
11861 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11862 // handled in the attribute adding step.
11863 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
11864 NewFD->setInvalidDecl();
11865 return true;
11866 }
11867
11868 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11869 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
11870 NewFD->setInvalidDecl();
11871 return true;
11872 }
11873
11874 // Permit forward declarations in the case where these two are compatible.
11875 if (!OldFD->isMultiVersion()) {
11876 OldFD->setIsMultiVersion();
11877 NewFD->setIsMultiVersion();
11878 Redeclaration = true;
11879 OldDecl = OldFD;
11880 return false;
11881 }
11882
11883 NewFD->setIsMultiVersion();
11884 Redeclaration = false;
11885 OldDecl = nullptr;
11886 Previous.clear();
11887 return false;
11888}
11889
11890/// Check the validity of a mulitversion function declaration.
11891/// Also sets the multiversion'ness' of the function itself.
11892///
11893/// This sets NewFD->isInvalidDecl() to true if there was an error.
11894///
11895/// Returns true if there was an error, false otherwise.
11896static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11897 bool &Redeclaration, NamedDecl *&OldDecl,
11898 LookupResult &Previous) {
11899 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11900
11901 // Check if FMV is disabled.
11902 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
11903 return false;
11904
11905 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11906 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11907 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11908 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11909 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11910 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11911
11912 // Main isn't allowed to become a multiversion function, however it IS
11913 // permitted to have 'main' be marked with the 'target' optimization hint,
11914 // for 'target_version' only default is allowed.
11915 if (NewFD->isMain()) {
11916 if (MVKind != MultiVersionKind::None &&
11917 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11918 !(MVKind == MultiVersionKind::TargetVersion &&
11919 NewTVA->isDefaultVersion())) {
11920 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11921 NewFD->setInvalidDecl();
11922 return true;
11923 }
11924 return false;
11925 }
11926
11927 // Target attribute on AArch64 is not used for multiversioning
11928 if (NewTA && TI.getTriple().isAArch64())
11929 return false;
11930
11931 // Target attribute on RISCV is not used for multiversioning
11932 if (NewTA && TI.getTriple().isRISCV())
11933 return false;
11934
11935 if (!OldDecl || !OldDecl->getAsFunction() ||
11936 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11937 NewFD->getDeclContext()->getRedeclContext())) {
11938 // If there's no previous declaration, AND this isn't attempting to cause
11939 // multiversioning, this isn't an error condition.
11940 if (MVKind == MultiVersionKind::None)
11941 return false;
11942 return CheckMultiVersionFirstFunction(S, FD: NewFD);
11943 }
11944
11945 FunctionDecl *OldFD = OldDecl->getAsFunction();
11946
11947 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11948 return false;
11949
11950 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11951 // for target_clones and target_version.
11952 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11953 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11954 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11955 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11956 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11957 NewFD->setInvalidDecl();
11958 return true;
11959 }
11960
11961 if (!OldFD->isMultiVersion()) {
11962 switch (MVKind) {
11963 case MultiVersionKind::Target:
11964 case MultiVersionKind::TargetVersion:
11965 return CheckDeclarationCausesMultiVersioning(
11966 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11967 case MultiVersionKind::TargetClones:
11968 if (OldFD->isUsed(false)) {
11969 NewFD->setInvalidDecl();
11970 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11971 }
11972 OldFD->setIsMultiVersion();
11973 break;
11974
11975 case MultiVersionKind::CPUDispatch:
11976 case MultiVersionKind::CPUSpecific:
11977 case MultiVersionKind::None:
11978 break;
11979 }
11980 }
11981
11982 // At this point, we have a multiversion function decl (in OldFD) AND an
11983 // appropriate attribute in the current function decl. Resolve that these are
11984 // still compatible with previous declarations.
11985 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11986 NewCPUSpec, NewClones, Redeclaration,
11987 OldDecl, Previous);
11988}
11989
11990static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
11991 bool IsPure = NewFD->hasAttr<PureAttr>();
11992 bool IsConst = NewFD->hasAttr<ConstAttr>();
11993
11994 // If there are no pure or const attributes, there's nothing to check.
11995 if (!IsPure && !IsConst)
11996 return;
11997
11998 // If the function is marked both pure and const, we retain the const
11999 // attribute because it makes stronger guarantees than the pure attribute, and
12000 // we drop the pure attribute explicitly to prevent later confusion about
12001 // semantics.
12002 if (IsPure && IsConst) {
12003 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12004 NewFD->dropAttrs<PureAttr>();
12005 }
12006
12007 // Constructors and destructors are functions which return void, so are
12008 // handled here as well.
12009 if (NewFD->getReturnType()->isVoidType()) {
12010 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12011 << IsConst;
12012 NewFD->dropAttrs<PureAttr, ConstAttr>();
12013 }
12014}
12015
12016bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12017 LookupResult &Previous,
12018 bool IsMemberSpecialization,
12019 bool DeclIsDefn) {
12020 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12021 "Variably modified return types are not handled here");
12022
12023 // Determine whether the type of this function should be merged with
12024 // a previous visible declaration. This never happens for functions in C++,
12025 // and always happens in C if the previous declaration was visible.
12026 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12027 !Previous.isShadowed();
12028
12029 bool Redeclaration = false;
12030 NamedDecl *OldDecl = nullptr;
12031 bool MayNeedOverloadableChecks = false;
12032
12033 inferLifetimeCaptureByAttribute(FD: NewFD);
12034 // Merge or overload the declaration with an existing declaration of
12035 // the same name, if appropriate.
12036 if (!Previous.empty()) {
12037 // Determine whether NewFD is an overload of PrevDecl or
12038 // a declaration that requires merging. If it's an overload,
12039 // there's no more work to do here; we'll just add the new
12040 // function to the scope.
12041 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12042 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12043 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12044 Redeclaration = true;
12045 OldDecl = Candidate;
12046 }
12047 } else {
12048 MayNeedOverloadableChecks = true;
12049 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12050 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12051 case OverloadKind::Match:
12052 Redeclaration = true;
12053 break;
12054
12055 case OverloadKind::NonFunction:
12056 Redeclaration = true;
12057 break;
12058
12059 case OverloadKind::Overload:
12060 Redeclaration = false;
12061 break;
12062 }
12063 }
12064 }
12065
12066 // Check for a previous extern "C" declaration with this name.
12067 if (!Redeclaration &&
12068 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12069 if (!Previous.empty()) {
12070 // This is an extern "C" declaration with the same name as a previous
12071 // declaration, and thus redeclares that entity...
12072 Redeclaration = true;
12073 OldDecl = Previous.getFoundDecl();
12074 MergeTypeWithPrevious = false;
12075
12076 // ... except in the presence of __attribute__((overloadable)).
12077 if (OldDecl->hasAttr<OverloadableAttr>() ||
12078 NewFD->hasAttr<OverloadableAttr>()) {
12079 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12080 MayNeedOverloadableChecks = true;
12081 Redeclaration = false;
12082 OldDecl = nullptr;
12083 }
12084 }
12085 }
12086 }
12087
12088 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12089 return Redeclaration;
12090
12091 // PPC MMA non-pointer types are not allowed as function return types.
12092 if (Context.getTargetInfo().getTriple().isPPC64() &&
12093 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12094 NewFD->setInvalidDecl();
12095 }
12096
12097 CheckConstPureAttributesUsage(S&: *this, NewFD);
12098
12099 // C++ [dcl.spec.auto.general]p12:
12100 // Return type deduction for a templated function with a placeholder in its
12101 // declared type occurs when the definition is instantiated even if the
12102 // function body contains a return statement with a non-type-dependent
12103 // operand.
12104 //
12105 // C++ [temp.dep.expr]p3:
12106 // An id-expression is type-dependent if it is a template-id that is not a
12107 // concept-id and is dependent; or if its terminal name is:
12108 // - [...]
12109 // - associated by name lookup with one or more declarations of member
12110 // functions of a class that is the current instantiation declared with a
12111 // return type that contains a placeholder type,
12112 // - [...]
12113 //
12114 // If this is a templated function with a placeholder in its return type,
12115 // make the placeholder type dependent since it won't be deduced until the
12116 // definition is instantiated. We do this here because it needs to happen
12117 // for implicitly instantiated member functions/member function templates.
12118 if (getLangOpts().CPlusPlus14 &&
12119 (NewFD->isDependentContext() &&
12120 NewFD->getReturnType()->isUndeducedType())) {
12121 const FunctionProtoType *FPT =
12122 NewFD->getType()->castAs<FunctionProtoType>();
12123 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12124 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12125 EPI: FPT->getExtProtoInfo()));
12126 }
12127
12128 // C++11 [dcl.constexpr]p8:
12129 // A constexpr specifier for a non-static member function that is not
12130 // a constructor declares that member function to be const.
12131 //
12132 // This needs to be delayed until we know whether this is an out-of-line
12133 // definition of a static member function.
12134 //
12135 // This rule is not present in C++1y, so we produce a backwards
12136 // compatibility warning whenever it happens in C++11.
12137 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12138 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12139 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12140 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12141 CXXMethodDecl *OldMD = nullptr;
12142 if (OldDecl)
12143 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12144 if (!OldMD || !OldMD->isStatic()) {
12145 const FunctionProtoType *FPT =
12146 MD->getType()->castAs<FunctionProtoType>();
12147 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12148 EPI.TypeQuals.addConst();
12149 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12150 Args: FPT->getParamTypes(), EPI));
12151
12152 // Warn that we did this, if we're not performing template instantiation.
12153 // In that case, we'll have warned already when the template was defined.
12154 if (!inTemplateInstantiation()) {
12155 SourceLocation AddConstLoc;
12156 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12157 .IgnoreParens().getAs<FunctionTypeLoc>())
12158 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12159
12160 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12161 << FixItHint::CreateInsertion(AddConstLoc, " const");
12162 }
12163 }
12164 }
12165
12166 if (Redeclaration) {
12167 // NewFD and OldDecl represent declarations that need to be
12168 // merged.
12169 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12170 NewDeclIsDefn: DeclIsDefn)) {
12171 NewFD->setInvalidDecl();
12172 return Redeclaration;
12173 }
12174
12175 Previous.clear();
12176 Previous.addDecl(D: OldDecl);
12177
12178 if (FunctionTemplateDecl *OldTemplateDecl =
12179 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12180 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12181 FunctionTemplateDecl *NewTemplateDecl
12182 = NewFD->getDescribedFunctionTemplate();
12183 assert(NewTemplateDecl && "Template/non-template mismatch");
12184
12185 // The call to MergeFunctionDecl above may have created some state in
12186 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12187 // can add it as a redeclaration.
12188 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12189
12190 NewFD->setPreviousDeclaration(OldFD);
12191 if (NewFD->isCXXClassMember()) {
12192 NewFD->setAccess(OldTemplateDecl->getAccess());
12193 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12194 }
12195
12196 // If this is an explicit specialization of a member that is a function
12197 // template, mark it as a member specialization.
12198 if (IsMemberSpecialization &&
12199 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12200 NewTemplateDecl->setMemberSpecialization();
12201 assert(OldTemplateDecl->isMemberSpecialization());
12202 // Explicit specializations of a member template do not inherit deleted
12203 // status from the parent member template that they are specializing.
12204 if (OldFD->isDeleted()) {
12205 // FIXME: This assert will not hold in the presence of modules.
12206 assert(OldFD->getCanonicalDecl() == OldFD);
12207 // FIXME: We need an update record for this AST mutation.
12208 OldFD->setDeletedAsWritten(D: false);
12209 }
12210 }
12211
12212 } else {
12213 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12214 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12215 // This needs to happen first so that 'inline' propagates.
12216 NewFD->setPreviousDeclaration(OldFD);
12217 if (NewFD->isCXXClassMember())
12218 NewFD->setAccess(OldFD->getAccess());
12219 }
12220 }
12221 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12222 !NewFD->getAttr<OverloadableAttr>()) {
12223 assert((Previous.empty() ||
12224 llvm::any_of(Previous,
12225 [](const NamedDecl *ND) {
12226 return ND->hasAttr<OverloadableAttr>();
12227 })) &&
12228 "Non-redecls shouldn't happen without overloadable present");
12229
12230 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12231 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12232 return FD && !FD->hasAttr<OverloadableAttr>();
12233 });
12234
12235 if (OtherUnmarkedIter != Previous.end()) {
12236 Diag(NewFD->getLocation(),
12237 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12238 Diag((*OtherUnmarkedIter)->getLocation(),
12239 diag::note_attribute_overloadable_prev_overload)
12240 << false;
12241
12242 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12243 }
12244 }
12245
12246 if (LangOpts.OpenMP)
12247 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12248
12249 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12250 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12251
12252 // Semantic checking for this function declaration (in isolation).
12253
12254 if (getLangOpts().CPlusPlus) {
12255 // C++-specific checks.
12256 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12257 CheckConstructor(Constructor);
12258 } else if (CXXDestructorDecl *Destructor =
12259 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12260 // We check here for invalid destructor names.
12261 // If we have a friend destructor declaration that is dependent, we can't
12262 // diagnose right away because cases like this are still valid:
12263 // template <class T> struct A { friend T::X::~Y(); };
12264 // struct B { struct Y { ~Y(); }; using X = Y; };
12265 // template struct A<B>;
12266 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12267 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12268 CXXRecordDecl *Record = Destructor->getParent();
12269 QualType ClassType = Context.getTypeDeclType(Record);
12270
12271 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12272 Ty: Context.getCanonicalType(T: ClassType));
12273 if (NewFD->getDeclName() != Name) {
12274 Diag(NewFD->getLocation(), diag::err_destructor_name);
12275 NewFD->setInvalidDecl();
12276 return Redeclaration;
12277 }
12278 }
12279 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12280 if (auto *TD = Guide->getDescribedFunctionTemplate())
12281 CheckDeductionGuideTemplate(TD: TD);
12282
12283 // A deduction guide is not on the list of entities that can be
12284 // explicitly specialized.
12285 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12286 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12287 << /*explicit specialization*/ 1;
12288 }
12289
12290 // Find any virtual functions that this function overrides.
12291 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12292 if (!Method->isFunctionTemplateSpecialization() &&
12293 !Method->getDescribedFunctionTemplate() &&
12294 Method->isCanonicalDecl()) {
12295 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12296 }
12297 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12298 // C++2a [class.virtual]p6
12299 // A virtual method shall not have a requires-clause.
12300 Diag(NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12301 diag::err_constrained_virtual_method);
12302
12303 if (Method->isStatic())
12304 checkThisInStaticMemberFunctionType(Method);
12305 }
12306
12307 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12308 ActOnConversionDeclarator(Conversion);
12309
12310 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12311 if (NewFD->isOverloadedOperator() &&
12312 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12313 NewFD->setInvalidDecl();
12314 return Redeclaration;
12315 }
12316
12317 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12318 if (NewFD->getLiteralIdentifier() &&
12319 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12320 NewFD->setInvalidDecl();
12321 return Redeclaration;
12322 }
12323
12324 // In C++, check default arguments now that we have merged decls. Unless
12325 // the lexical context is the class, because in this case this is done
12326 // during delayed parsing anyway.
12327 if (!CurContext->isRecord())
12328 CheckCXXDefaultArguments(FD: NewFD);
12329
12330 // If this function is declared as being extern "C", then check to see if
12331 // the function returns a UDT (class, struct, or union type) that is not C
12332 // compatible, and if it does, warn the user.
12333 // But, issue any diagnostic on the first declaration only.
12334 if (Previous.empty() && NewFD->isExternC()) {
12335 QualType R = NewFD->getReturnType();
12336 if (R->isIncompleteType() && !R->isVoidType())
12337 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12338 << NewFD << R;
12339 else if (!R.isPODType(Context) && !R->isVoidType() &&
12340 !R->isObjCObjectPointerType())
12341 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12342 }
12343
12344 // C++1z [dcl.fct]p6:
12345 // [...] whether the function has a non-throwing exception-specification
12346 // [is] part of the function type
12347 //
12348 // This results in an ABI break between C++14 and C++17 for functions whose
12349 // declared type includes an exception-specification in a parameter or
12350 // return type. (Exception specifications on the function itself are OK in
12351 // most cases, and exception specifications are not permitted in most other
12352 // contexts where they could make it into a mangling.)
12353 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12354 auto HasNoexcept = [&](QualType T) -> bool {
12355 // Strip off declarator chunks that could be between us and a function
12356 // type. We don't need to look far, exception specifications are very
12357 // restricted prior to C++17.
12358 if (auto *RT = T->getAs<ReferenceType>())
12359 T = RT->getPointeeType();
12360 else if (T->isAnyPointerType())
12361 T = T->getPointeeType();
12362 else if (auto *MPT = T->getAs<MemberPointerType>())
12363 T = MPT->getPointeeType();
12364 if (auto *FPT = T->getAs<FunctionProtoType>())
12365 if (FPT->isNothrow())
12366 return true;
12367 return false;
12368 };
12369
12370 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12371 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12372 for (QualType T : FPT->param_types())
12373 AnyNoexcept |= HasNoexcept(T);
12374 if (AnyNoexcept)
12375 Diag(NewFD->getLocation(),
12376 diag::warn_cxx17_compat_exception_spec_in_signature)
12377 << NewFD;
12378 }
12379
12380 if (!Redeclaration && LangOpts.CUDA) {
12381 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12382 for (auto *Parm : NewFD->parameters()) {
12383 if (!Parm->getType()->isDependentType() &&
12384 Parm->hasAttr<CUDAGridConstantAttr>() &&
12385 !(IsKernel && Parm->getType().isConstQualified()))
12386 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12387 diag::err_cuda_grid_constant_not_allowed);
12388 }
12389 CUDA().checkTargetOverload(NewFD, Previous);
12390 }
12391 }
12392
12393 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12394 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12395
12396 return Redeclaration;
12397}
12398
12399void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12400 // [basic.start.main]p3
12401 // The main function shall not be declared with a linkage-specification.
12402 if (FD->isExternCContext() ||
12403 (FD->isExternCXXContext() &&
12404 FD->getDeclContext()->getRedeclContext()->isTranslationUnit()))
12405 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12406 << FD->getLanguageLinkage();
12407
12408 // C++11 [basic.start.main]p3:
12409 // A program that [...] declares main to be inline, static or
12410 // constexpr is ill-formed.
12411 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12412 // appear in a declaration of main.
12413 // static main is not an error under C99, but we should warn about it.
12414 // We accept _Noreturn main as an extension.
12415 if (FD->getStorageClass() == SC_Static)
12416 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12417 ? diag::err_static_main : diag::warn_static_main)
12418 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12419 if (FD->isInlineSpecified())
12420 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12421 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12422 if (DS.isNoreturnSpecified()) {
12423 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12424 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12425 Diag(NoreturnLoc, diag::ext_noreturn_main);
12426 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12427 << FixItHint::CreateRemoval(NoreturnRange);
12428 }
12429 if (FD->isConstexpr()) {
12430 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12431 << FD->isConsteval()
12432 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12433 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12434 }
12435
12436 if (getLangOpts().OpenCL) {
12437 Diag(FD->getLocation(), diag::err_opencl_no_main)
12438 << FD->hasAttr<DeviceKernelAttr>();
12439 FD->setInvalidDecl();
12440 return;
12441 }
12442
12443 // Functions named main in hlsl are default entries, but don't have specific
12444 // signatures they are required to conform to.
12445 if (getLangOpts().HLSL)
12446 return;
12447
12448 QualType T = FD->getType();
12449 assert(T->isFunctionType() && "function decl is not of function type");
12450 const FunctionType* FT = T->castAs<FunctionType>();
12451
12452 // Set default calling convention for main()
12453 if (FT->getCallConv() != CC_C) {
12454 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12455 FD->setType(QualType(FT, 0));
12456 T = Context.getCanonicalType(FD->getType());
12457 }
12458
12459 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12460 // In C with GNU extensions we allow main() to have non-integer return
12461 // type, but we should warn about the extension, and we disable the
12462 // implicit-return-zero rule.
12463
12464 // GCC in C mode accepts qualified 'int'.
12465 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12466 FD->setHasImplicitReturnZero(true);
12467 else {
12468 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12469 SourceRange RTRange = FD->getReturnTypeSourceRange();
12470 if (RTRange.isValid())
12471 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12472 << FixItHint::CreateReplacement(RTRange, "int");
12473 }
12474 } else {
12475 // In C and C++, main magically returns 0 if you fall off the end;
12476 // set the flag which tells us that.
12477 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12478
12479 // All the standards say that main() should return 'int'.
12480 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12481 FD->setHasImplicitReturnZero(true);
12482 else {
12483 // Otherwise, this is just a flat-out error.
12484 SourceRange RTRange = FD->getReturnTypeSourceRange();
12485 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12486 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12487 : FixItHint());
12488 FD->setInvalidDecl(true);
12489 }
12490 }
12491
12492 // Treat protoless main() as nullary.
12493 if (isa<FunctionNoProtoType>(Val: FT)) return;
12494
12495 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12496 unsigned nparams = FTP->getNumParams();
12497 assert(FD->getNumParams() == nparams);
12498
12499 bool HasExtraParameters = (nparams > 3);
12500
12501 if (FTP->isVariadic()) {
12502 Diag(FD->getLocation(), diag::ext_variadic_main);
12503 // FIXME: if we had information about the location of the ellipsis, we
12504 // could add a FixIt hint to remove it as a parameter.
12505 }
12506
12507 // Darwin passes an undocumented fourth argument of type char**. If
12508 // other platforms start sprouting these, the logic below will start
12509 // getting shifty.
12510 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12511 HasExtraParameters = false;
12512
12513 if (HasExtraParameters) {
12514 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12515 FD->setInvalidDecl(true);
12516 nparams = 3;
12517 }
12518
12519 // FIXME: a lot of the following diagnostics would be improved
12520 // if we had some location information about types.
12521
12522 QualType CharPP =
12523 Context.getPointerType(Context.getPointerType(Context.CharTy));
12524 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12525
12526 for (unsigned i = 0; i < nparams; ++i) {
12527 QualType AT = FTP->getParamType(i);
12528
12529 bool mismatch = true;
12530
12531 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12532 mismatch = false;
12533 else if (Expected[i] == CharPP) {
12534 // As an extension, the following forms are okay:
12535 // char const **
12536 // char const * const *
12537 // char * const *
12538
12539 QualifierCollector qs;
12540 const PointerType* PT;
12541 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12542 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12543 Context.hasSameType(QualType(qs.strip(type: PT->getPointeeType()), 0),
12544 Context.CharTy)) {
12545 qs.removeConst();
12546 mismatch = !qs.empty();
12547 }
12548 }
12549
12550 if (mismatch) {
12551 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12552 // TODO: suggest replacing given type with expected type
12553 FD->setInvalidDecl(true);
12554 }
12555 }
12556
12557 if (nparams == 1 && !FD->isInvalidDecl()) {
12558 Diag(FD->getLocation(), diag::warn_main_one_arg);
12559 }
12560
12561 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12562 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12563 FD->setInvalidDecl();
12564 }
12565}
12566
12567static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12568
12569 // Default calling convention for main and wmain is __cdecl
12570 if (FD->getName() == "main" || FD->getName() == "wmain")
12571 return false;
12572
12573 // Default calling convention for MinGW is __cdecl
12574 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12575 if (T.isWindowsGNUEnvironment())
12576 return false;
12577
12578 // Default calling convention for WinMain, wWinMain and DllMain
12579 // is __stdcall on 32 bit Windows
12580 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12581 return true;
12582
12583 return false;
12584}
12585
12586void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12587 QualType T = FD->getType();
12588 assert(T->isFunctionType() && "function decl is not of function type");
12589 const FunctionType *FT = T->castAs<FunctionType>();
12590
12591 // Set an implicit return of 'zero' if the function can return some integral,
12592 // enumeration, pointer or nullptr type.
12593 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12594 FT->getReturnType()->isAnyPointerType() ||
12595 FT->getReturnType()->isNullPtrType())
12596 // DllMain is exempt because a return value of zero means it failed.
12597 if (FD->getName() != "DllMain")
12598 FD->setHasImplicitReturnZero(true);
12599
12600 // Explicitly specified calling conventions are applied to MSVC entry points
12601 if (!hasExplicitCallingConv(T)) {
12602 if (isDefaultStdCall(FD, S&: *this)) {
12603 if (FT->getCallConv() != CC_X86StdCall) {
12604 FT = Context.adjustFunctionType(
12605 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12606 FD->setType(QualType(FT, 0));
12607 }
12608 } else if (FT->getCallConv() != CC_C) {
12609 FT = Context.adjustFunctionType(Fn: FT,
12610 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12611 FD->setType(QualType(FT, 0));
12612 }
12613 }
12614
12615 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12616 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12617 FD->setInvalidDecl();
12618 }
12619}
12620
12621bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12622 // FIXME: Need strict checking. In C89, we need to check for
12623 // any assignment, increment, decrement, function-calls, or
12624 // commas outside of a sizeof. In C99, it's the same list,
12625 // except that the aforementioned are allowed in unevaluated
12626 // expressions. Everything else falls under the
12627 // "may accept other forms of constant expressions" exception.
12628 //
12629 // Regular C++ code will not end up here (exceptions: language extensions,
12630 // OpenCL C++ etc), so the constant expression rules there don't matter.
12631 if (Init->isValueDependent()) {
12632 assert(Init->containsErrors() &&
12633 "Dependent code should only occur in error-recovery path.");
12634 return true;
12635 }
12636 const Expr *Culprit;
12637 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12638 return false;
12639 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12640 return true;
12641}
12642
12643namespace {
12644 // Visits an initialization expression to see if OrigDecl is evaluated in
12645 // its own initialization and throws a warning if it does.
12646 class SelfReferenceChecker
12647 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12648 Sema &S;
12649 Decl *OrigDecl;
12650 bool isRecordType;
12651 bool isPODType;
12652 bool isReferenceType;
12653 bool isInCXXOperatorCall;
12654
12655 bool isInitList;
12656 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12657
12658 public:
12659 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12660
12661 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12662 S(S), OrigDecl(OrigDecl) {
12663 isPODType = false;
12664 isRecordType = false;
12665 isReferenceType = false;
12666 isInCXXOperatorCall = false;
12667 isInitList = false;
12668 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12669 isPODType = VD->getType().isPODType(Context: S.Context);
12670 isRecordType = VD->getType()->isRecordType();
12671 isReferenceType = VD->getType()->isReferenceType();
12672 }
12673 }
12674
12675 // For most expressions, just call the visitor. For initializer lists,
12676 // track the index of the field being initialized since fields are
12677 // initialized in order allowing use of previously initialized fields.
12678 void CheckExpr(Expr *E) {
12679 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12680 if (!InitList) {
12681 Visit(E);
12682 return;
12683 }
12684
12685 // Track and increment the index here.
12686 isInitList = true;
12687 InitFieldIndex.push_back(Elt: 0);
12688 for (auto *Child : InitList->children()) {
12689 CheckExpr(E: cast<Expr>(Val: Child));
12690 ++InitFieldIndex.back();
12691 }
12692 InitFieldIndex.pop_back();
12693 }
12694
12695 // Returns true if MemberExpr is checked and no further checking is needed.
12696 // Returns false if additional checking is required.
12697 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12698 llvm::SmallVector<FieldDecl*, 4> Fields;
12699 Expr *Base = E;
12700 bool ReferenceField = false;
12701
12702 // Get the field members used.
12703 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12704 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12705 if (!FD)
12706 return false;
12707 Fields.push_back(Elt: FD);
12708 if (FD->getType()->isReferenceType())
12709 ReferenceField = true;
12710 Base = ME->getBase()->IgnoreParenImpCasts();
12711 }
12712
12713 // Keep checking only if the base Decl is the same.
12714 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12715 if (!DRE || DRE->getDecl() != OrigDecl)
12716 return false;
12717
12718 // A reference field can be bound to an unininitialized field.
12719 if (CheckReference && !ReferenceField)
12720 return true;
12721
12722 // Convert FieldDecls to their index number.
12723 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12724 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12725 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12726
12727 // See if a warning is needed by checking the first difference in index
12728 // numbers. If field being used has index less than the field being
12729 // initialized, then the use is safe.
12730 for (auto UsedIter = UsedFieldIndex.begin(),
12731 UsedEnd = UsedFieldIndex.end(),
12732 OrigIter = InitFieldIndex.begin(),
12733 OrigEnd = InitFieldIndex.end();
12734 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12735 if (*UsedIter < *OrigIter)
12736 return true;
12737 if (*UsedIter > *OrigIter)
12738 break;
12739 }
12740
12741 // TODO: Add a different warning which will print the field names.
12742 HandleDeclRefExpr(DRE);
12743 return true;
12744 }
12745
12746 // For most expressions, the cast is directly above the DeclRefExpr.
12747 // For conditional operators, the cast can be outside the conditional
12748 // operator if both expressions are DeclRefExpr's.
12749 void HandleValue(Expr *E) {
12750 E = E->IgnoreParens();
12751 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12752 HandleDeclRefExpr(DRE);
12753 return;
12754 }
12755
12756 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12757 Visit(CO->getCond());
12758 HandleValue(E: CO->getTrueExpr());
12759 HandleValue(E: CO->getFalseExpr());
12760 return;
12761 }
12762
12763 if (BinaryConditionalOperator *BCO =
12764 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12765 Visit(BCO->getCond());
12766 HandleValue(E: BCO->getFalseExpr());
12767 return;
12768 }
12769
12770 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12771 if (Expr *SE = OVE->getSourceExpr())
12772 HandleValue(E: SE);
12773 return;
12774 }
12775
12776 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
12777 if (BO->getOpcode() == BO_Comma) {
12778 Visit(BO->getLHS());
12779 HandleValue(E: BO->getRHS());
12780 return;
12781 }
12782 }
12783
12784 if (isa<MemberExpr>(Val: E)) {
12785 if (isInitList) {
12786 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
12787 CheckReference: false /*CheckReference*/))
12788 return;
12789 }
12790
12791 Expr *Base = E->IgnoreParenImpCasts();
12792 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12793 // Check for static member variables and don't warn on them.
12794 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12795 return;
12796 Base = ME->getBase()->IgnoreParenImpCasts();
12797 }
12798 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
12799 HandleDeclRefExpr(DRE);
12800 return;
12801 }
12802
12803 Visit(E);
12804 }
12805
12806 // Reference types not handled in HandleValue are handled here since all
12807 // uses of references are bad, not just r-value uses.
12808 void VisitDeclRefExpr(DeclRefExpr *E) {
12809 if (isReferenceType)
12810 HandleDeclRefExpr(DRE: E);
12811 }
12812
12813 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12814 if (E->getCastKind() == CK_LValueToRValue) {
12815 HandleValue(E: E->getSubExpr());
12816 return;
12817 }
12818
12819 Inherited::VisitImplicitCastExpr(E);
12820 }
12821
12822 void VisitMemberExpr(MemberExpr *E) {
12823 if (isInitList) {
12824 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
12825 return;
12826 }
12827
12828 // Don't warn on arrays since they can be treated as pointers.
12829 if (E->getType()->canDecayToPointerType()) return;
12830
12831 // Warn when a non-static method call is followed by non-static member
12832 // field accesses, which is followed by a DeclRefExpr.
12833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
12834 bool Warn = (MD && !MD->isStatic());
12835 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12836 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12837 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12838 Warn = false;
12839 Base = ME->getBase()->IgnoreParenImpCasts();
12840 }
12841
12842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
12843 if (Warn)
12844 HandleDeclRefExpr(DRE);
12845 return;
12846 }
12847
12848 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12849 // Visit that expression.
12850 Visit(Base);
12851 }
12852
12853 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12854 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
12855 Expr *Callee = E->getCallee();
12856
12857 if (isa<UnresolvedLookupExpr>(Callee))
12858 return Inherited::VisitCXXOperatorCallExpr(E);
12859
12860 Visit(Callee);
12861 for (auto Arg: E->arguments())
12862 HandleValue(Arg->IgnoreParenImpCasts());
12863 }
12864
12865 void VisitLambdaExpr(LambdaExpr *E) {
12866 if (!isInCXXOperatorCall) {
12867 Inherited::VisitLambdaExpr(LE: E);
12868 return;
12869 }
12870
12871 for (Expr *Init : E->capture_inits())
12872 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
12873 HandleDeclRefExpr(DRE);
12874 else if (Init)
12875 Visit(Init);
12876 }
12877
12878 void VisitUnaryOperator(UnaryOperator *E) {
12879 // For POD record types, addresses of its own members are well-defined.
12880 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12881 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
12882 if (!isPODType)
12883 HandleValue(E: E->getSubExpr());
12884 return;
12885 }
12886
12887 if (E->isIncrementDecrementOp()) {
12888 HandleValue(E: E->getSubExpr());
12889 return;
12890 }
12891
12892 Inherited::VisitUnaryOperator(E);
12893 }
12894
12895 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12896
12897 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12898 if (E->getConstructor()->isCopyConstructor()) {
12899 Expr *ArgExpr = E->getArg(Arg: 0);
12900 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
12901 if (ILE->getNumInits() == 1)
12902 ArgExpr = ILE->getInit(Init: 0);
12903 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
12904 if (ICE->getCastKind() == CK_NoOp)
12905 ArgExpr = ICE->getSubExpr();
12906 HandleValue(E: ArgExpr);
12907 return;
12908 }
12909 Inherited::VisitCXXConstructExpr(E);
12910 }
12911
12912 void VisitCallExpr(CallExpr *E) {
12913 // Treat std::move as a use.
12914 if (E->isCallToStdMove()) {
12915 HandleValue(E: E->getArg(Arg: 0));
12916 return;
12917 }
12918
12919 Inherited::VisitCallExpr(CE: E);
12920 }
12921
12922 void VisitBinaryOperator(BinaryOperator *E) {
12923 if (E->isCompoundAssignmentOp()) {
12924 HandleValue(E: E->getLHS());
12925 Visit(E->getRHS());
12926 return;
12927 }
12928
12929 Inherited::VisitBinaryOperator(E);
12930 }
12931
12932 // A custom visitor for BinaryConditionalOperator is needed because the
12933 // regular visitor would check the condition and true expression separately
12934 // but both point to the same place giving duplicate diagnostics.
12935 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12936 Visit(E->getCond());
12937 Visit(E->getFalseExpr());
12938 }
12939
12940 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12941 Decl* ReferenceDecl = DRE->getDecl();
12942 if (OrigDecl != ReferenceDecl) return;
12943 unsigned diag;
12944 if (isReferenceType) {
12945 diag = diag::warn_uninit_self_reference_in_reference_init;
12946 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
12947 diag = diag::warn_static_self_reference_in_init;
12948 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
12949 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
12950 DRE->getDecl()->getType()->isRecordType()) {
12951 diag = diag::warn_uninit_self_reference_in_init;
12952 } else {
12953 // Local variables will be handled by the CFG analysis.
12954 return;
12955 }
12956
12957 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12958 S.PDiag(diag)
12959 << DRE->getDecl() << OrigDecl->getLocation()
12960 << DRE->getSourceRange());
12961 }
12962 };
12963
12964 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12965 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12966 bool DirectInit) {
12967 // Parameters arguments are occassionially constructed with itself,
12968 // for instance, in recursive functions. Skip them.
12969 if (isa<ParmVarDecl>(Val: OrigDecl))
12970 return;
12971
12972 E = E->IgnoreParens();
12973
12974 // Skip checking T a = a where T is not a record or reference type.
12975 // Doing so is a way to silence uninitialized warnings.
12976 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
12977 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12978 if (ICE->getCastKind() == CK_LValueToRValue)
12979 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12980 if (DRE->getDecl() == OrigDecl)
12981 return;
12982
12983 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12984 }
12985} // end anonymous namespace
12986
12987namespace {
12988 // Simple wrapper to add the name of a variable or (if no variable is
12989 // available) a DeclarationName into a diagnostic.
12990 struct VarDeclOrName {
12991 VarDecl *VDecl;
12992 DeclarationName Name;
12993
12994 friend const Sema::SemaDiagnosticBuilder &
12995 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12996 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12997 }
12998 };
12999} // end anonymous namespace
13000
13001QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13002 DeclarationName Name, QualType Type,
13003 TypeSourceInfo *TSI,
13004 SourceRange Range, bool DirectInit,
13005 Expr *Init) {
13006 bool IsInitCapture = !VDecl;
13007 assert((!VDecl || !VDecl->isInitCapture()) &&
13008 "init captures are expected to be deduced prior to initialization");
13009
13010 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13011
13012 DeducedType *Deduced = Type->getContainedDeducedType();
13013 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13014
13015 // Diagnose auto array declarations in C23, unless it's a supported extension.
13016 if (getLangOpts().C23 && Type->isArrayType() &&
13017 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13018 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13019 << (int)Deduced->getContainedAutoType()->getKeyword()
13020 << /*in array decl*/ 23 << Range;
13021 return QualType();
13022 }
13023
13024 // C++11 [dcl.spec.auto]p3
13025 if (!Init) {
13026 assert(VDecl && "no init for init capture deduction?");
13027
13028 // Except for class argument deduction, and then for an initializing
13029 // declaration only, i.e. no static at class scope or extern.
13030 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13031 VDecl->hasExternalStorage() ||
13032 VDecl->isStaticDataMember()) {
13033 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13034 << VDecl->getDeclName() << Type;
13035 return QualType();
13036 }
13037 }
13038
13039 ArrayRef<Expr*> DeduceInits;
13040 if (Init)
13041 DeduceInits = Init;
13042
13043 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13044 if (DirectInit && PL)
13045 DeduceInits = PL->exprs();
13046
13047 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13048 assert(VDecl && "non-auto type for init capture deduction?");
13049 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13050 InitializationKind Kind = InitializationKind::CreateForInit(
13051 Loc: VDecl->getLocation(), DirectInit, Init);
13052 // FIXME: Initialization should not be taking a mutable list of inits.
13053 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13054 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13055 Init: InitsCopy);
13056 }
13057
13058 if (DirectInit) {
13059 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13060 DeduceInits = IL->inits();
13061 }
13062
13063 // Deduction only works if we have exactly one source expression.
13064 if (DeduceInits.empty()) {
13065 // It isn't possible to write this directly, but it is possible to
13066 // end up in this situation with "auto x(some_pack...);"
13067 Diag(Init->getBeginLoc(), IsInitCapture
13068 ? diag::err_init_capture_no_expression
13069 : diag::err_auto_var_init_no_expression)
13070 << VN << Type << Range;
13071 return QualType();
13072 }
13073
13074 if (DeduceInits.size() > 1) {
13075 Diag(DeduceInits[1]->getBeginLoc(),
13076 IsInitCapture ? diag::err_init_capture_multiple_expressions
13077 : diag::err_auto_var_init_multiple_expressions)
13078 << VN << Type << Range;
13079 return QualType();
13080 }
13081
13082 Expr *DeduceInit = DeduceInits[0];
13083 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13084 Diag(Init->getBeginLoc(), IsInitCapture
13085 ? diag::err_init_capture_paren_braces
13086 : diag::err_auto_var_init_paren_braces)
13087 << isa<InitListExpr>(Init) << VN << Type << Range;
13088 return QualType();
13089 }
13090
13091 // Expressions default to 'id' when we're in a debugger.
13092 bool DefaultedAnyToId = false;
13093 if (getLangOpts().DebuggerCastResultToId &&
13094 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13095 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13096 if (Result.isInvalid()) {
13097 return QualType();
13098 }
13099 Init = Result.get();
13100 DefaultedAnyToId = true;
13101 }
13102
13103 // C++ [dcl.decomp]p1:
13104 // If the assignment-expression [...] has array type A and no ref-qualifier
13105 // is present, e has type cv A
13106 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13107 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13108 DeduceInit->getType()->isConstantArrayType())
13109 return Context.getQualifiedType(T: DeduceInit->getType(),
13110 Qs: Type.getQualifiers());
13111
13112 QualType DeducedType;
13113 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13114 TemplateDeductionResult Result =
13115 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13116 if (Result != TemplateDeductionResult::Success &&
13117 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13118 if (!IsInitCapture)
13119 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13120 else if (isa<InitListExpr>(Init))
13121 Diag(Range.getBegin(),
13122 diag::err_init_capture_deduction_failure_from_init_list)
13123 << VN
13124 << (DeduceInit->getType().isNull() ? TSI->getType()
13125 : DeduceInit->getType())
13126 << DeduceInit->getSourceRange();
13127 else
13128 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13129 << VN << TSI->getType()
13130 << (DeduceInit->getType().isNull() ? TSI->getType()
13131 : DeduceInit->getType())
13132 << DeduceInit->getSourceRange();
13133 }
13134
13135 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13136 // 'id' instead of a specific object type prevents most of our usual
13137 // checks.
13138 // We only want to warn outside of template instantiations, though:
13139 // inside a template, the 'id' could have come from a parameter.
13140 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13141 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13142 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13143 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13144 }
13145
13146 return DeducedType;
13147}
13148
13149bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13150 Expr *Init) {
13151 assert(!Init || !Init->containsErrors());
13152 QualType DeducedType = deduceVarTypeFromInitializer(
13153 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13154 Range: VDecl->getSourceRange(), DirectInit, Init);
13155 if (DeducedType.isNull()) {
13156 VDecl->setInvalidDecl();
13157 return true;
13158 }
13159
13160 VDecl->setType(DeducedType);
13161 assert(VDecl->isLinkageValid());
13162
13163 // In ARC, infer lifetime.
13164 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13165 VDecl->setInvalidDecl();
13166
13167 if (getLangOpts().OpenCL)
13168 deduceOpenCLAddressSpace(VDecl);
13169
13170 if (getLangOpts().HLSL)
13171 HLSL().deduceAddressSpace(Decl: VDecl);
13172
13173 // If this is a redeclaration, check that the type we just deduced matches
13174 // the previously declared type.
13175 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13176 // We never need to merge the type, because we cannot form an incomplete
13177 // array of auto, nor deduce such a type.
13178 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13179 }
13180
13181 // Check the deduced type is valid for a variable declaration.
13182 CheckVariableDeclarationType(NewVD: VDecl);
13183 return VDecl->isInvalidDecl();
13184}
13185
13186void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13187 SourceLocation Loc) {
13188 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13189 Init = EWC->getSubExpr();
13190
13191 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13192 Init = CE->getSubExpr();
13193
13194 QualType InitType = Init->getType();
13195 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13196 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13197 "shouldn't be called if type doesn't have a non-trivial C struct");
13198 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13199 for (auto *I : ILE->inits()) {
13200 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13201 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13202 continue;
13203 SourceLocation SL = I->getExprLoc();
13204 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13205 }
13206 return;
13207 }
13208
13209 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13210 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13211 checkNonTrivialCUnion(QT: InitType, Loc,
13212 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13213 NonTrivialKind: NTCUK_Init);
13214 } else {
13215 // Assume all other explicit initializers involving copying some existing
13216 // object.
13217 // TODO: ignore any explicit initializers where we can guarantee
13218 // copy-elision.
13219 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13220 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13221 NonTrivialKind: NTCUK_Copy);
13222 }
13223}
13224
13225namespace {
13226
13227bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13228 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13229 // in the source code or implicitly by the compiler if it is in a union
13230 // defined in a system header and has non-trivial ObjC ownership
13231 // qualifications. We don't want those fields to participate in determining
13232 // whether the containing union is non-trivial.
13233 return FD->hasAttr<UnavailableAttr>();
13234}
13235
13236struct DiagNonTrivalCUnionDefaultInitializeVisitor
13237 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13238 void> {
13239 using Super =
13240 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13241 void>;
13242
13243 DiagNonTrivalCUnionDefaultInitializeVisitor(
13244 QualType OrigTy, SourceLocation OrigLoc,
13245 NonTrivialCUnionContext UseContext, Sema &S)
13246 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13247
13248 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13249 const FieldDecl *FD, bool InNonTrivialUnion) {
13250 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13251 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13252 InNonTrivialUnion);
13253 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13254 }
13255
13256 void visitARCStrong(QualType QT, const FieldDecl *FD,
13257 bool InNonTrivialUnion) {
13258 if (InNonTrivialUnion)
13259 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13260 << 1 << 0 << QT << FD->getName();
13261 }
13262
13263 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13264 if (InNonTrivialUnion)
13265 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13266 << 1 << 0 << QT << FD->getName();
13267 }
13268
13269 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13270 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13271 if (RD->isUnion()) {
13272 if (OrigLoc.isValid()) {
13273 bool IsUnion = false;
13274 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13275 IsUnion = OrigRD->isUnion();
13276 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13277 << 0 << OrigTy << IsUnion << UseContext;
13278 // Reset OrigLoc so that this diagnostic is emitted only once.
13279 OrigLoc = SourceLocation();
13280 }
13281 InNonTrivialUnion = true;
13282 }
13283
13284 if (InNonTrivialUnion)
13285 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13286 << 0 << 0 << QT.getUnqualifiedType() << "";
13287
13288 for (const FieldDecl *FD : RD->fields())
13289 if (!shouldIgnoreForRecordTriviality(FD))
13290 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13291 }
13292
13293 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13294
13295 // The non-trivial C union type or the struct/union type that contains a
13296 // non-trivial C union.
13297 QualType OrigTy;
13298 SourceLocation OrigLoc;
13299 NonTrivialCUnionContext UseContext;
13300 Sema &S;
13301};
13302
13303struct DiagNonTrivalCUnionDestructedTypeVisitor
13304 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13305 using Super =
13306 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13307
13308 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13309 SourceLocation OrigLoc,
13310 NonTrivialCUnionContext UseContext,
13311 Sema &S)
13312 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13313
13314 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13315 const FieldDecl *FD, bool InNonTrivialUnion) {
13316 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13317 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13318 InNonTrivialUnion);
13319 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13320 }
13321
13322 void visitARCStrong(QualType QT, const FieldDecl *FD,
13323 bool InNonTrivialUnion) {
13324 if (InNonTrivialUnion)
13325 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13326 << 1 << 1 << QT << FD->getName();
13327 }
13328
13329 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13330 if (InNonTrivialUnion)
13331 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13332 << 1 << 1 << QT << FD->getName();
13333 }
13334
13335 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13336 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13337 if (RD->isUnion()) {
13338 if (OrigLoc.isValid()) {
13339 bool IsUnion = false;
13340 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13341 IsUnion = OrigRD->isUnion();
13342 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13343 << 1 << OrigTy << IsUnion << UseContext;
13344 // Reset OrigLoc so that this diagnostic is emitted only once.
13345 OrigLoc = SourceLocation();
13346 }
13347 InNonTrivialUnion = true;
13348 }
13349
13350 if (InNonTrivialUnion)
13351 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13352 << 0 << 1 << QT.getUnqualifiedType() << "";
13353
13354 for (const FieldDecl *FD : RD->fields())
13355 if (!shouldIgnoreForRecordTriviality(FD))
13356 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13357 }
13358
13359 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13360 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13361 bool InNonTrivialUnion) {}
13362
13363 // The non-trivial C union type or the struct/union type that contains a
13364 // non-trivial C union.
13365 QualType OrigTy;
13366 SourceLocation OrigLoc;
13367 NonTrivialCUnionContext UseContext;
13368 Sema &S;
13369};
13370
13371struct DiagNonTrivalCUnionCopyVisitor
13372 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13373 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13374
13375 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13376 NonTrivialCUnionContext UseContext, Sema &S)
13377 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13378
13379 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13380 const FieldDecl *FD, bool InNonTrivialUnion) {
13381 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13382 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13383 InNonTrivialUnion);
13384 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13385 }
13386
13387 void visitARCStrong(QualType QT, const FieldDecl *FD,
13388 bool InNonTrivialUnion) {
13389 if (InNonTrivialUnion)
13390 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13391 << 1 << 2 << QT << FD->getName();
13392 }
13393
13394 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13395 if (InNonTrivialUnion)
13396 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13397 << 1 << 2 << QT << FD->getName();
13398 }
13399
13400 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13401 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13402 if (RD->isUnion()) {
13403 if (OrigLoc.isValid()) {
13404 bool IsUnion = false;
13405 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13406 IsUnion = OrigRD->isUnion();
13407 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13408 << 2 << OrigTy << IsUnion << UseContext;
13409 // Reset OrigLoc so that this diagnostic is emitted only once.
13410 OrigLoc = SourceLocation();
13411 }
13412 InNonTrivialUnion = true;
13413 }
13414
13415 if (InNonTrivialUnion)
13416 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13417 << 0 << 2 << QT.getUnqualifiedType() << "";
13418
13419 for (const FieldDecl *FD : RD->fields())
13420 if (!shouldIgnoreForRecordTriviality(FD))
13421 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13422 }
13423
13424 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13425 if (InNonTrivialUnion)
13426 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13427 << 1 << 2 << QT << FD->getName();
13428 }
13429
13430 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13431 const FieldDecl *FD, bool InNonTrivialUnion) {}
13432 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13433 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13434 bool InNonTrivialUnion) {}
13435
13436 // The non-trivial C union type or the struct/union type that contains a
13437 // non-trivial C union.
13438 QualType OrigTy;
13439 SourceLocation OrigLoc;
13440 NonTrivialCUnionContext UseContext;
13441 Sema &S;
13442};
13443
13444} // namespace
13445
13446void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13447 NonTrivialCUnionContext UseContext,
13448 unsigned NonTrivialKind) {
13449 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13450 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13451 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13452 "shouldn't be called if type doesn't have a non-trivial C union");
13453
13454 if ((NonTrivialKind & NTCUK_Init) &&
13455 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13456 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13457 .visit(QT, nullptr, false);
13458 if ((NonTrivialKind & NTCUK_Destruct) &&
13459 QT.hasNonTrivialToPrimitiveDestructCUnion())
13460 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13461 .visit(QT, nullptr, false);
13462 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13463 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13464 .visit(QT, nullptr, false);
13465}
13466
13467bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13468 const VarDecl *Dcl) {
13469 if (!getLangOpts().CPlusPlus)
13470 return false;
13471
13472 // We only need to warn if the definition is in a header file, so wait to
13473 // diagnose until we've seen the definition.
13474 if (!Dcl->isThisDeclarationADefinition())
13475 return false;
13476
13477 // If an object is defined in a source file, its definition can't get
13478 // duplicated since it will never appear in more than one TU.
13479 if (Dcl->getASTContext().getSourceManager().isInMainFile(Dcl->getLocation()))
13480 return false;
13481
13482 // If the variable we're looking at is a static local, then we actually care
13483 // about the properties of the function containing it.
13484 const ValueDecl *Target = Dcl;
13485 // VarDecls and FunctionDecls have different functions for checking
13486 // inline-ness, and whether they were originally templated, so we have to
13487 // call the appropriate functions manually.
13488 bool TargetIsInline = Dcl->isInline();
13489 bool TargetWasTemplated =
13490 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13491
13492 // Update the Target and TargetIsInline property if necessary
13493 if (Dcl->isStaticLocal()) {
13494 const DeclContext *Ctx = Dcl->getDeclContext();
13495 if (!Ctx)
13496 return false;
13497
13498 const FunctionDecl *FunDcl =
13499 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13500 if (!FunDcl)
13501 return false;
13502
13503 Target = FunDcl;
13504 // IsInlined() checks for the C++ inline property
13505 TargetIsInline = FunDcl->isInlined();
13506 TargetWasTemplated =
13507 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13508 }
13509
13510 // Non-inline functions/variables can only legally appear in one TU
13511 // unless they were part of a template. Unfortunately, making complex
13512 // template instantiations visible is infeasible in practice, since
13513 // everything the template depends on also has to be visible. To avoid
13514 // giving impractical-to-fix warnings, don't warn if we're inside
13515 // something that was templated, even on inline stuff.
13516 if (!TargetIsInline || TargetWasTemplated)
13517 return false;
13518
13519 // If the object isn't hidden, the dynamic linker will prevent duplication.
13520 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13521 if (Lnk.getVisibility() != HiddenVisibility)
13522 return false;
13523
13524 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13525 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13526 return false;
13527
13528 return true;
13529}
13530
13531// Determine whether the object seems mutable for the purpose of diagnosing
13532// possible unique object duplication, i.e. non-const-qualified, and
13533// not an always-constant type like a function.
13534// Not perfect: doesn't account for mutable members, for example, or
13535// elements of container types.
13536// For nested pointers, any individual level being non-const is sufficient.
13537static bool looksMutable(QualType T, const ASTContext &Ctx) {
13538 T = T.getNonReferenceType();
13539 if (T->isFunctionType())
13540 return false;
13541 if (!T.isConstant(Ctx))
13542 return true;
13543 if (T->isPointerType())
13544 return looksMutable(T: T->getPointeeType(), Ctx);
13545 return false;
13546}
13547
13548void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13549 // If this object has external linkage and hidden visibility, it might be
13550 // duplicated when built into a shared library, which causes problems if it's
13551 // mutable (since the copies won't be in sync) or its initialization has side
13552 // effects (since it will run once per copy instead of once globally).
13553 // FIXME: Windows uses dllexport/dllimport instead of visibility, and we don't
13554 // handle that yet. Disable the warning on Windows for now.
13555
13556 // Don't diagnose if we're inside a template, because it's not practical to
13557 // fix the warning in most cases.
13558 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
13559 !VD->isTemplated() &&
13560 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13561
13562 QualType Type = VD->getType();
13563 if (looksMutable(Type, VD->getASTContext())) {
13564 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13565 << VD;
13566 }
13567
13568 // To keep false positives low, only warn if we're certain that the
13569 // initializer has side effects. Don't warn on operator new, since a mutable
13570 // pointer will trigger the previous warning, and an immutable pointer
13571 // getting duplicated just results in a little extra memory usage.
13572 const Expr *Init = VD->getAnyInitializer();
13573 if (Init &&
13574 Init->HasSideEffects(Ctx: VD->getASTContext(),
13575 /*IncludePossibleEffects=*/false) &&
13576 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13577 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13578 << VD;
13579 }
13580 }
13581}
13582
13583void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13584 // If there is no declaration, there was an error parsing it. Just ignore
13585 // the initializer.
13586 if (!RealDecl) {
13587 CorrectDelayedTyposInExpr(E: Init, InitDecl: dyn_cast_or_null<VarDecl>(Val: RealDecl));
13588 return;
13589 }
13590
13591 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13592 if (!Method->isInvalidDecl()) {
13593 // Pure-specifiers are handled in ActOnPureSpecifier.
13594 Diag(Method->getLocation(), diag::err_member_function_initialization)
13595 << Method->getDeclName() << Init->getSourceRange();
13596 Method->setInvalidDecl();
13597 }
13598 return;
13599 }
13600
13601 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13602 if (!VDecl) {
13603 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13604 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13605 RealDecl->setInvalidDecl();
13606 return;
13607 }
13608
13609 if (VDecl->isInvalidDecl()) {
13610 ExprResult Res = CorrectDelayedTyposInExpr(E: Init, InitDecl: VDecl);
13611 SmallVector<Expr *> SubExprs;
13612 if (Res.isUsable())
13613 SubExprs.push_back(Elt: Res.get());
13614 ExprResult Recovery =
13615 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs);
13616 if (Expr *E = Recovery.get())
13617 VDecl->setInit(E);
13618 return;
13619 }
13620
13621 // WebAssembly tables can't be used to initialise a variable.
13622 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13623 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13624 VDecl->setInvalidDecl();
13625 return;
13626 }
13627
13628 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13629 if (VDecl->getType()->isUndeducedType()) {
13630 // Attempt typo correction early so that the type of the init expression can
13631 // be deduced based on the chosen correction if the original init contains a
13632 // TypoExpr.
13633 ExprResult Res = CorrectDelayedTyposInExpr(E: Init, InitDecl: VDecl);
13634 if (!Res.isUsable()) {
13635 // There are unresolved typos in Init, just drop them.
13636 // FIXME: improve the recovery strategy to preserve the Init.
13637 RealDecl->setInvalidDecl();
13638 return;
13639 }
13640 if (Res.get()->containsErrors()) {
13641 // Invalidate the decl as we don't know the type for recovery-expr yet.
13642 RealDecl->setInvalidDecl();
13643 VDecl->setInit(Res.get());
13644 return;
13645 }
13646 Init = Res.get();
13647
13648 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13649 return;
13650 }
13651
13652 // dllimport cannot be used on variable definitions.
13653 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13654 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13655 VDecl->setInvalidDecl();
13656 return;
13657 }
13658
13659 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13660 // the identifier has external or internal linkage, the declaration shall
13661 // have no initializer for the identifier.
13662 // C++14 [dcl.init]p5 is the same restriction for C++.
13663 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13664 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13665 VDecl->setInvalidDecl();
13666 return;
13667 }
13668
13669 if (!VDecl->getType()->isDependentType()) {
13670 // A definition must end up with a complete type, which means it must be
13671 // complete with the restriction that an array type might be completed by
13672 // the initializer; note that later code assumes this restriction.
13673 QualType BaseDeclType = VDecl->getType();
13674 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13675 BaseDeclType = Array->getElementType();
13676 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13677 diag::err_typecheck_decl_incomplete_type)) {
13678 RealDecl->setInvalidDecl();
13679 return;
13680 }
13681
13682 // The variable can not have an abstract class type.
13683 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13684 diag::err_abstract_type_in_decl,
13685 AbstractVariableType))
13686 VDecl->setInvalidDecl();
13687 }
13688
13689 // C++ [module.import/6] external definitions are not permitted in header
13690 // units.
13691 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13692 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13693 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13694 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
13695 !VDecl->getInstantiatedFromStaticDataMember()) {
13696 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13697 VDecl->setInvalidDecl();
13698 }
13699
13700 // If adding the initializer will turn this declaration into a definition,
13701 // and we already have a definition for this variable, diagnose or otherwise
13702 // handle the situation.
13703 if (VarDecl *Def = VDecl->getDefinition())
13704 if (Def != VDecl &&
13705 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13706 !VDecl->isThisDeclarationADemotedDefinition() &&
13707 checkVarDeclRedefinition(Old: Def, New: VDecl))
13708 return;
13709
13710 if (getLangOpts().CPlusPlus) {
13711 // C++ [class.static.data]p4
13712 // If a static data member is of const integral or const
13713 // enumeration type, its declaration in the class definition can
13714 // specify a constant-initializer which shall be an integral
13715 // constant expression (5.19). In that case, the member can appear
13716 // in integral constant expressions. The member shall still be
13717 // defined in a namespace scope if it is used in the program and the
13718 // namespace scope definition shall not contain an initializer.
13719 //
13720 // We already performed a redefinition check above, but for static
13721 // data members we also need to check whether there was an in-class
13722 // declaration with an initializer.
13723 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13724 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13725 << VDecl->getDeclName();
13726 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13727 diag::note_previous_initializer)
13728 << 0;
13729 return;
13730 }
13731
13732 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13733 VDecl->setInvalidDecl();
13734 return;
13735 }
13736 }
13737
13738 // If the variable has an initializer and local storage, check whether
13739 // anything jumps over the initialization.
13740 if (VDecl->hasLocalStorage())
13741 setFunctionHasBranchProtectedScope();
13742
13743 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13744 // a kernel function cannot be initialized."
13745 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13746 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13747 VDecl->setInvalidDecl();
13748 return;
13749 }
13750
13751 // The LoaderUninitialized attribute acts as a definition (of undef).
13752 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13753 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13754 VDecl->setInvalidDecl();
13755 return;
13756 }
13757
13758 // Get the decls type and save a reference for later, since
13759 // CheckInitializerTypes may change it.
13760 QualType DclT = VDecl->getType(), SavT = DclT;
13761
13762 // Expressions default to 'id' when we're in a debugger
13763 // and we are assigning it to a variable of Objective-C pointer type.
13764 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13765 Init->getType() == Context.UnknownAnyTy) {
13766 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13767 if (!Result.isUsable()) {
13768 VDecl->setInvalidDecl();
13769 return;
13770 }
13771 Init = Result.get();
13772 }
13773
13774 // Perform the initialization.
13775 bool InitializedFromParenListExpr = false;
13776 bool IsParenListInit = false;
13777 if (!VDecl->isInvalidDecl()) {
13778 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13779 InitializationKind Kind = InitializationKind::CreateForInit(
13780 Loc: VDecl->getLocation(), DirectInit, Init);
13781
13782 MultiExprArg Args = Init;
13783 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
13784 Args =
13785 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13786 InitializedFromParenListExpr = true;
13787 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
13788 Args = CXXDirectInit->getInitExprs();
13789 InitializedFromParenListExpr = true;
13790 }
13791
13792 // Try to correct any TypoExprs in the initialization arguments.
13793 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13794 ExprResult Res = CorrectDelayedTyposInExpr(
13795 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13796 [this, Entity, Kind](Expr *E) {
13797 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13798 return Init.Failed() ? ExprError() : E;
13799 });
13800 if (!Res.isUsable()) {
13801 VDecl->setInvalidDecl();
13802 } else if (Res.get() != Args[Idx]) {
13803 Args[Idx] = Res.get();
13804 }
13805 }
13806 if (VDecl->isInvalidDecl())
13807 return;
13808
13809 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13810 /*TopLevelOfInitList=*/false,
13811 /*TreatUnavailableAsInvalid=*/false);
13812 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
13813 if (!Result.isUsable()) {
13814 // If the provided initializer fails to initialize the var decl,
13815 // we attach a recovery expr for better recovery.
13816 auto RecoveryExpr =
13817 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
13818 if (RecoveryExpr.get())
13819 VDecl->setInit(RecoveryExpr.get());
13820 // In general, for error recovery purposes, the initializer doesn't play
13821 // part in the valid bit of the declaration. There are a few exceptions:
13822 // 1) if the var decl has a deduced auto type, and the type cannot be
13823 // deduced by an invalid initializer;
13824 // 2) if the var decl is a decomposition decl with a non-deduced type,
13825 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13826 // Case 1) was already handled elsewhere.
13827 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
13828 VDecl->setInvalidDecl();
13829 return;
13830 }
13831
13832 Init = Result.getAs<Expr>();
13833 IsParenListInit = !InitSeq.steps().empty() &&
13834 InitSeq.step_begin()->Kind ==
13835 InitializationSequence::SK_ParenthesizedListInit;
13836 QualType VDeclType = VDecl->getType();
13837 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13838 !VDeclType->isDependentType() &&
13839 Context.getAsIncompleteArrayType(T: VDeclType) &&
13840 Context.getAsIncompleteArrayType(T: Init->getType())) {
13841 // Bail out if it is not possible to deduce array size from the
13842 // initializer.
13843 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13844 << VDeclType;
13845 VDecl->setInvalidDecl();
13846 return;
13847 }
13848 }
13849
13850 // Check for self-references within variable initializers.
13851 // Variables declared within a function/method body (except for references)
13852 // are handled by a dataflow analysis.
13853 // This is undefined behavior in C++, but valid in C.
13854 if (getLangOpts().CPlusPlus)
13855 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13856 VDecl->getType()->isReferenceType())
13857 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
13858
13859 // If the type changed, it means we had an incomplete type that was
13860 // completed by the initializer. For example:
13861 // int ary[] = { 1, 3, 5 };
13862 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13863 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13864 VDecl->setType(DclT);
13865
13866 if (!VDecl->isInvalidDecl()) {
13867 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
13868
13869 if (VDecl->hasAttr<BlocksAttr>())
13870 ObjC().checkRetainCycles(Var: VDecl, Init);
13871
13872 // It is safe to assign a weak reference into a strong variable.
13873 // Although this code can still have problems:
13874 // id x = self.weakProp;
13875 // id y = self.weakProp;
13876 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13877 // paths through the function. This should be revisited if
13878 // -Wrepeated-use-of-weak is made flow-sensitive.
13879 if (FunctionScopeInfo *FSI = getCurFunction())
13880 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13881 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13882 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13883 Init->getBeginLoc()))
13884 FSI->markSafeWeakUse(E: Init);
13885 }
13886
13887 // The initialization is usually a full-expression.
13888 //
13889 // FIXME: If this is a braced initialization of an aggregate, it is not
13890 // an expression, and each individual field initializer is a separate
13891 // full-expression. For instance, in:
13892 //
13893 // struct Temp { ~Temp(); };
13894 // struct S { S(Temp); };
13895 // struct T { S a, b; } t = { Temp(), Temp() }
13896 //
13897 // we should destroy the first Temp before constructing the second.
13898 ExprResult Result =
13899 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13900 /*DiscardedValue*/ false, VDecl->isConstexpr());
13901 if (!Result.isUsable()) {
13902 VDecl->setInvalidDecl();
13903 return;
13904 }
13905 Init = Result.get();
13906
13907 // Attach the initializer to the decl.
13908 VDecl->setInit(Init);
13909
13910 if (VDecl->isLocalVarDecl()) {
13911 // Don't check the initializer if the declaration is malformed.
13912 if (VDecl->isInvalidDecl()) {
13913 // do nothing
13914
13915 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13916 // This is true even in C++ for OpenCL.
13917 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13918 CheckForConstantInitializer(Init);
13919
13920 // Otherwise, C++ does not restrict the initializer.
13921 } else if (getLangOpts().CPlusPlus) {
13922 // do nothing
13923
13924 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13925 // static storage duration shall be constant expressions or string literals.
13926 } else if (VDecl->getStorageClass() == SC_Static) {
13927 CheckForConstantInitializer(Init);
13928
13929 // C89 is stricter than C99 for aggregate initializers.
13930 // C89 6.5.7p3: All the expressions [...] in an initializer list
13931 // for an object that has aggregate or union type shall be
13932 // constant expressions.
13933 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13934 isa<InitListExpr>(Val: Init)) {
13935 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13936 }
13937
13938 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
13939 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13940 if (VDecl->hasLocalStorage())
13941 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13942 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13943 VDecl->getLexicalDeclContext()->isRecord()) {
13944 // This is an in-class initialization for a static data member, e.g.,
13945 //
13946 // struct S {
13947 // static const int value = 17;
13948 // };
13949
13950 // C++ [class.mem]p4:
13951 // A member-declarator can contain a constant-initializer only
13952 // if it declares a static member (9.4) of const integral or
13953 // const enumeration type, see 9.4.2.
13954 //
13955 // C++11 [class.static.data]p3:
13956 // If a non-volatile non-inline const static data member is of integral
13957 // or enumeration type, its declaration in the class definition can
13958 // specify a brace-or-equal-initializer in which every initializer-clause
13959 // that is an assignment-expression is a constant expression. A static
13960 // data member of literal type can be declared in the class definition
13961 // with the constexpr specifier; if so, its declaration shall specify a
13962 // brace-or-equal-initializer in which every initializer-clause that is
13963 // an assignment-expression is a constant expression.
13964
13965 // Do nothing on dependent types.
13966 if (DclT->isDependentType()) {
13967
13968 // Allow any 'static constexpr' members, whether or not they are of literal
13969 // type. We separately check that every constexpr variable is of literal
13970 // type.
13971 } else if (VDecl->isConstexpr()) {
13972
13973 // Require constness.
13974 } else if (!DclT.isConstQualified()) {
13975 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13976 << Init->getSourceRange();
13977 VDecl->setInvalidDecl();
13978
13979 // We allow integer constant expressions in all cases.
13980 } else if (DclT->isIntegralOrEnumerationType()) {
13981 // Check whether the expression is a constant expression.
13982 SourceLocation Loc;
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(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13987 else if (Init->isValueDependent())
13988 ; // Nothing to check.
13989 else if (Init->isIntegerConstantExpr(Ctx: Context, Loc: &Loc))
13990 ; // Ok, it's an ICE!
13991 else if (Init->getType()->isScopedEnumeralType() &&
13992 Init->isCXX11ConstantExpr(Ctx: Context))
13993 ; // Ok, it is a scoped-enum constant expression.
13994 else if (Init->isEvaluatable(Ctx: Context)) {
13995 // If we can constant fold the initializer through heroics, accept it,
13996 // but report this as a use of an extension for -pedantic.
13997 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13998 << Init->getSourceRange();
13999 } else {
14000 // Otherwise, this is some crazy unknown case. Report the issue at the
14001 // location provided by the isIntegerConstantExpr failed check.
14002 Diag(Loc, diag::err_in_class_initializer_non_constant)
14003 << Init->getSourceRange();
14004 VDecl->setInvalidDecl();
14005 }
14006
14007 // We allow foldable floating-point constants as an extension.
14008 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14009 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14010 // it anyway and provide a fixit to add the 'constexpr'.
14011 if (getLangOpts().CPlusPlus11) {
14012 Diag(VDecl->getLocation(),
14013 diag::ext_in_class_initializer_float_type_cxx11)
14014 << DclT << Init->getSourceRange();
14015 Diag(VDecl->getBeginLoc(),
14016 diag::note_in_class_initializer_float_type_cxx11)
14017 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14018 } else {
14019 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14020 << DclT << Init->getSourceRange();
14021
14022 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14023 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14024 << Init->getSourceRange();
14025 VDecl->setInvalidDecl();
14026 }
14027 }
14028
14029 // Suggest adding 'constexpr' in C++11 for literal types.
14030 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14031 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14032 << DclT << Init->getSourceRange()
14033 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14034 VDecl->setConstexpr(true);
14035
14036 } else {
14037 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14038 << DclT << Init->getSourceRange();
14039 VDecl->setInvalidDecl();
14040 }
14041 } else if (VDecl->isFileVarDecl()) {
14042 // In C, extern is typically used to avoid tentative definitions when
14043 // declaring variables in headers, but adding an initializer makes it a
14044 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14045 // In C++, extern is often used to give implicitly static const variables
14046 // external linkage, so don't warn in that case. If selectany is present,
14047 // this might be header code intended for C and C++ inclusion, so apply the
14048 // C++ rules.
14049 if (VDecl->getStorageClass() == SC_Extern &&
14050 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14051 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14052 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14053 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
14054 Diag(VDecl->getLocation(), diag::warn_extern_init);
14055
14056 // In Microsoft C++ mode, a const variable defined in namespace scope has
14057 // external linkage by default if the variable is declared with
14058 // __declspec(dllexport).
14059 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14060 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14061 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14062 VDecl->setStorageClass(SC_Extern);
14063
14064 // C99 6.7.8p4. All file scoped initializers need to be constant.
14065 // Avoid duplicate diagnostics for constexpr variables.
14066 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14067 !VDecl->isConstexpr())
14068 CheckForConstantInitializer(Init);
14069 }
14070
14071 QualType InitType = Init->getType();
14072 if (!InitType.isNull() &&
14073 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14074 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14075 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14076
14077 // We will represent direct-initialization similarly to copy-initialization:
14078 // int x(1); -as-> int x = 1;
14079 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14080 //
14081 // Clients that want to distinguish between the two forms, can check for
14082 // direct initializer using VarDecl::getInitStyle().
14083 // A major benefit is that clients that don't particularly care about which
14084 // exactly form was it (like the CodeGen) can handle both cases without
14085 // special case code.
14086
14087 // C++ 8.5p11:
14088 // The form of initialization (using parentheses or '=') matters
14089 // when the entity being initialized has class type.
14090 if (InitializedFromParenListExpr) {
14091 assert(DirectInit && "Call-style initializer must be direct init.");
14092 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14093 : VarDecl::CallInit);
14094 } else if (DirectInit) {
14095 // This must be list-initialization. No other way is direct-initialization.
14096 VDecl->setInitStyle(VarDecl::ListInit);
14097 }
14098
14099 if (LangOpts.OpenMP &&
14100 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14101 VDecl->isFileVarDecl())
14102 DeclsToCheckForDeferredDiags.insert(VDecl);
14103 CheckCompleteVariableDeclaration(VD: VDecl);
14104
14105 if (LangOpts.OpenACC && !InitType.isNull())
14106 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14107}
14108
14109void Sema::ActOnInitializerError(Decl *D) {
14110 // Our main concern here is re-establishing invariants like "a
14111 // variable's type is either dependent or complete".
14112 if (!D || D->isInvalidDecl()) return;
14113
14114 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14115 if (!VD) return;
14116
14117 // Bindings are not usable if we can't make sense of the initializer.
14118 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14119 for (auto *BD : DD->bindings())
14120 BD->setInvalidDecl();
14121
14122 // Auto types are meaningless if we can't make sense of the initializer.
14123 if (VD->getType()->isUndeducedType()) {
14124 D->setInvalidDecl();
14125 return;
14126 }
14127
14128 QualType Ty = VD->getType();
14129 if (Ty->isDependentType()) return;
14130
14131 // Require a complete type.
14132 if (RequireCompleteType(VD->getLocation(),
14133 Context.getBaseElementType(Ty),
14134 diag::err_typecheck_decl_incomplete_type)) {
14135 VD->setInvalidDecl();
14136 return;
14137 }
14138
14139 // Require a non-abstract type.
14140 if (RequireNonAbstractType(VD->getLocation(), Ty,
14141 diag::err_abstract_type_in_decl,
14142 AbstractVariableType)) {
14143 VD->setInvalidDecl();
14144 return;
14145 }
14146
14147 // Don't bother complaining about constructors or destructors,
14148 // though.
14149}
14150
14151void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14152 // If there is no declaration, there was an error parsing it. Just ignore it.
14153 if (!RealDecl)
14154 return;
14155
14156 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14157 QualType Type = Var->getType();
14158
14159 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14160 if (isa<DecompositionDecl>(Val: RealDecl)) {
14161 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14162 Var->setInvalidDecl();
14163 return;
14164 }
14165
14166 if (Type->isUndeducedType() &&
14167 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14168 return;
14169
14170 // C++11 [class.static.data]p3: A static data member can be declared with
14171 // the constexpr specifier; if so, its declaration shall specify
14172 // a brace-or-equal-initializer.
14173 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14174 // the definition of a variable [...] or the declaration of a static data
14175 // member.
14176 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14177 !Var->isThisDeclarationADemotedDefinition()) {
14178 if (Var->isStaticDataMember()) {
14179 // C++1z removes the relevant rule; the in-class declaration is always
14180 // a definition there.
14181 if (!getLangOpts().CPlusPlus17 &&
14182 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14183 Diag(Var->getLocation(),
14184 diag::err_constexpr_static_mem_var_requires_init)
14185 << Var;
14186 Var->setInvalidDecl();
14187 return;
14188 }
14189 } else {
14190 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14191 Var->setInvalidDecl();
14192 return;
14193 }
14194 }
14195
14196 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14197 // be initialized.
14198 if (!Var->isInvalidDecl() &&
14199 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14200 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14201 bool HasConstExprDefaultConstructor = false;
14202 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14203 for (auto *Ctor : RD->ctors()) {
14204 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14205 Ctor->getMethodQualifiers().getAddressSpace() ==
14206 LangAS::opencl_constant) {
14207 HasConstExprDefaultConstructor = true;
14208 }
14209 }
14210 }
14211 if (!HasConstExprDefaultConstructor) {
14212 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14213 Var->setInvalidDecl();
14214 return;
14215 }
14216 }
14217
14218 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14219 if (Var->getStorageClass() == SC_Extern) {
14220 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14221 << Var;
14222 Var->setInvalidDecl();
14223 return;
14224 }
14225 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14226 diag::err_typecheck_decl_incomplete_type)) {
14227 Var->setInvalidDecl();
14228 return;
14229 }
14230 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14231 if (!RD->hasTrivialDefaultConstructor()) {
14232 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14233 Var->setInvalidDecl();
14234 return;
14235 }
14236 }
14237 // The declaration is uninitialized, no need for further checks.
14238 return;
14239 }
14240
14241 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14242 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14243 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14244 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14245 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14246 NonTrivialKind: NTCUK_Init);
14247
14248 switch (DefKind) {
14249 case VarDecl::Definition:
14250 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14251 break;
14252
14253 // We have an out-of-line definition of a static data member
14254 // that has an in-class initializer, so we type-check this like
14255 // a declaration.
14256 //
14257 [[fallthrough]];
14258
14259 case VarDecl::DeclarationOnly:
14260 // It's only a declaration.
14261
14262 // Block scope. C99 6.7p7: If an identifier for an object is
14263 // declared with no linkage (C99 6.2.2p6), the type for the
14264 // object shall be complete.
14265 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14266 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14267 RequireCompleteType(Var->getLocation(), Type,
14268 diag::err_typecheck_decl_incomplete_type))
14269 Var->setInvalidDecl();
14270
14271 // Make sure that the type is not abstract.
14272 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14273 RequireNonAbstractType(Var->getLocation(), Type,
14274 diag::err_abstract_type_in_decl,
14275 AbstractVariableType))
14276 Var->setInvalidDecl();
14277 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14278 Var->getStorageClass() == SC_PrivateExtern) {
14279 Diag(Var->getLocation(), diag::warn_private_extern);
14280 Diag(Var->getLocation(), diag::note_private_extern);
14281 }
14282
14283 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14284 !Var->isInvalidDecl())
14285 ExternalDeclarations.push_back(Var);
14286
14287 return;
14288
14289 case VarDecl::TentativeDefinition:
14290 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14291 // object that has file scope without an initializer, and without a
14292 // storage-class specifier or with the storage-class specifier "static",
14293 // constitutes a tentative definition. Note: A tentative definition with
14294 // external linkage is valid (C99 6.2.2p5).
14295 if (!Var->isInvalidDecl()) {
14296 if (const IncompleteArrayType *ArrayT
14297 = Context.getAsIncompleteArrayType(T: Type)) {
14298 if (RequireCompleteSizedType(
14299 Var->getLocation(), ArrayT->getElementType(),
14300 diag::err_array_incomplete_or_sizeless_type))
14301 Var->setInvalidDecl();
14302 }
14303 if (Var->getStorageClass() == SC_Static) {
14304 // C99 6.9.2p3: If the declaration of an identifier for an object is
14305 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14306 // declared type shall not be an incomplete type.
14307 // NOTE: code such as the following
14308 // static struct s;
14309 // struct s { int a; };
14310 // is accepted by gcc. Hence here we issue a warning instead of
14311 // an error and we do not invalidate the static declaration.
14312 // NOTE: to avoid multiple warnings, only check the first declaration.
14313 if (Var->isFirstDecl())
14314 RequireCompleteType(Var->getLocation(), Type,
14315 diag::ext_typecheck_decl_incomplete_type,
14316 Type->isArrayType());
14317 }
14318 }
14319
14320 // Record the tentative definition; we're done.
14321 if (!Var->isInvalidDecl())
14322 TentativeDefinitions.push_back(LocalValue: Var);
14323 return;
14324 }
14325
14326 // Provide a specific diagnostic for uninitialized variable
14327 // definitions with incomplete array type.
14328 if (Type->isIncompleteArrayType()) {
14329 if (Var->isConstexpr())
14330 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14331 << Var;
14332 else
14333 Diag(Var->getLocation(),
14334 diag::err_typecheck_incomplete_array_needs_initializer);
14335 Var->setInvalidDecl();
14336 return;
14337 }
14338
14339 // Provide a specific diagnostic for uninitialized variable
14340 // definitions with reference type.
14341 if (Type->isReferenceType()) {
14342 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14343 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14344 return;
14345 }
14346
14347 // Do not attempt to type-check the default initializer for a
14348 // variable with dependent type.
14349 if (Type->isDependentType())
14350 return;
14351
14352 if (Var->isInvalidDecl())
14353 return;
14354
14355 if (!Var->hasAttr<AliasAttr>()) {
14356 if (RequireCompleteType(Var->getLocation(),
14357 Context.getBaseElementType(Type),
14358 diag::err_typecheck_decl_incomplete_type)) {
14359 Var->setInvalidDecl();
14360 return;
14361 }
14362 } else {
14363 return;
14364 }
14365
14366 // The variable can not have an abstract class type.
14367 if (RequireNonAbstractType(Var->getLocation(), Type,
14368 diag::err_abstract_type_in_decl,
14369 AbstractVariableType)) {
14370 Var->setInvalidDecl();
14371 return;
14372 }
14373
14374 // In C, if the definition is const-qualified and has no initializer, it
14375 // is left uninitialized unless it has static or thread storage duration.
14376 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14377 unsigned DiagID = diag::warn_default_init_const_unsafe;
14378 if (Var->getStorageDuration() == SD_Static ||
14379 Var->getStorageDuration() == SD_Thread)
14380 DiagID = diag::warn_default_init_const;
14381
14382 bool EmitCppCompat = !Diags.isIgnored(
14383 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14384 Var->getLocation());
14385
14386 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14387 }
14388
14389 // Check for jumps past the implicit initializer. C++0x
14390 // clarifies that this applies to a "variable with automatic
14391 // storage duration", not a "local variable".
14392 // C++11 [stmt.dcl]p3
14393 // A program that jumps from a point where a variable with automatic
14394 // storage duration is not in scope to a point where it is in scope is
14395 // ill-formed unless the variable has scalar type, class type with a
14396 // trivial default constructor and a trivial destructor, a cv-qualified
14397 // version of one of these types, or an array of one of the preceding
14398 // types and is declared without an initializer.
14399 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14400 if (const RecordType *Record
14401 = Context.getBaseElementType(QT: Type)->getAs<RecordType>()) {
14402 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record->getDecl());
14403 // Mark the function (if we're in one) for further checking even if the
14404 // looser rules of C++11 do not require such checks, so that we can
14405 // diagnose incompatibilities with C++98.
14406 if (!CXXRecord->isPOD())
14407 setFunctionHasBranchProtectedScope();
14408 }
14409 }
14410 // In OpenCL, we can't initialize objects in the __local address space,
14411 // even implicitly, so don't synthesize an implicit initializer.
14412 if (getLangOpts().OpenCL &&
14413 Var->getType().getAddressSpace() == LangAS::opencl_local)
14414 return;
14415
14416 // Handle HLSL uninitialized decls
14417 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14418 return;
14419
14420 // HLSL input variables are expected to be externally initialized, even
14421 // when marked `static`.
14422 if (getLangOpts().HLSL &&
14423 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14424 return;
14425
14426 // C++03 [dcl.init]p9:
14427 // If no initializer is specified for an object, and the
14428 // object is of (possibly cv-qualified) non-POD class type (or
14429 // array thereof), the object shall be default-initialized; if
14430 // the object is of const-qualified type, the underlying class
14431 // type shall have a user-declared default
14432 // constructor. Otherwise, if no initializer is specified for
14433 // a non- static object, the object and its subobjects, if
14434 // any, have an indeterminate initial value); if the object
14435 // or any of its subobjects are of const-qualified type, the
14436 // program is ill-formed.
14437 // C++0x [dcl.init]p11:
14438 // If no initializer is specified for an object, the object is
14439 // default-initialized; [...].
14440 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14441 InitializationKind Kind
14442 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14443
14444 InitializationSequence InitSeq(*this, Entity, Kind, {});
14445 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14446
14447 if (Init.get()) {
14448 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14449 // This is important for template substitution.
14450 Var->setInitStyle(VarDecl::CallInit);
14451 } else if (Init.isInvalid()) {
14452 // If default-init fails, attach a recovery-expr initializer to track
14453 // that initialization was attempted and failed.
14454 auto RecoveryExpr =
14455 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14456 if (RecoveryExpr.get())
14457 Var->setInit(RecoveryExpr.get());
14458 }
14459
14460 CheckCompleteVariableDeclaration(VD: Var);
14461 }
14462}
14463
14464void Sema::ActOnCXXForRangeDecl(Decl *D) {
14465 // If there is no declaration, there was an error parsing it. Ignore it.
14466 if (!D)
14467 return;
14468
14469 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14470 if (!VD) {
14471 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14472 D->setInvalidDecl();
14473 return;
14474 }
14475
14476 VD->setCXXForRangeDecl(true);
14477
14478 // for-range-declaration cannot be given a storage class specifier.
14479 int Error = -1;
14480 switch (VD->getStorageClass()) {
14481 case SC_None:
14482 break;
14483 case SC_Extern:
14484 Error = 0;
14485 break;
14486 case SC_Static:
14487 Error = 1;
14488 break;
14489 case SC_PrivateExtern:
14490 Error = 2;
14491 break;
14492 case SC_Auto:
14493 Error = 3;
14494 break;
14495 case SC_Register:
14496 Error = 4;
14497 break;
14498 }
14499
14500 // for-range-declaration cannot be given a storage class specifier con't.
14501 switch (VD->getTSCSpec()) {
14502 case TSCS_thread_local:
14503 Error = 6;
14504 break;
14505 case TSCS___thread:
14506 case TSCS__Thread_local:
14507 case TSCS_unspecified:
14508 break;
14509 }
14510
14511 if (Error != -1) {
14512 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14513 << VD << Error;
14514 D->setInvalidDecl();
14515 }
14516}
14517
14518StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14519 IdentifierInfo *Ident,
14520 ParsedAttributes &Attrs) {
14521 // C++1y [stmt.iter]p1:
14522 // A range-based for statement of the form
14523 // for ( for-range-identifier : for-range-initializer ) statement
14524 // is equivalent to
14525 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14526 DeclSpec DS(Attrs.getPool().getFactory());
14527
14528 const char *PrevSpec;
14529 unsigned DiagID;
14530 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14531 Policy: getPrintingPolicy());
14532
14533 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14534 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14535 D.takeAttributes(attrs&: Attrs);
14536
14537 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14538 EndLoc: IdentLoc);
14539 Decl *Var = ActOnDeclarator(S, D);
14540 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14541 FinalizeDeclaration(D: Var);
14542 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14543 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14544 : IdentLoc);
14545}
14546
14547void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14548 if (var->isInvalidDecl()) return;
14549
14550 CUDA().MaybeAddConstantAttr(VD: var);
14551
14552 if (getLangOpts().OpenCL) {
14553 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14554 // initialiser
14555 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14556 !var->hasInit()) {
14557 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14558 << 1 /*Init*/;
14559 var->setInvalidDecl();
14560 return;
14561 }
14562 }
14563
14564 // In Objective-C, don't allow jumps past the implicit initialization of a
14565 // local retaining variable.
14566 if (getLangOpts().ObjC &&
14567 var->hasLocalStorage()) {
14568 switch (var->getType().getObjCLifetime()) {
14569 case Qualifiers::OCL_None:
14570 case Qualifiers::OCL_ExplicitNone:
14571 case Qualifiers::OCL_Autoreleasing:
14572 break;
14573
14574 case Qualifiers::OCL_Weak:
14575 case Qualifiers::OCL_Strong:
14576 setFunctionHasBranchProtectedScope();
14577 break;
14578 }
14579 }
14580
14581 if (var->hasLocalStorage() &&
14582 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14583 setFunctionHasBranchProtectedScope();
14584
14585 // Warn about externally-visible variables being defined without a
14586 // prior declaration. We only want to do this for global
14587 // declarations, but we also specifically need to avoid doing it for
14588 // class members because the linkage of an anonymous class can
14589 // change if it's later given a typedef name.
14590 if (var->isThisDeclarationADefinition() &&
14591 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14592 var->isExternallyVisible() && var->hasLinkage() &&
14593 !var->isInline() && !var->getDescribedVarTemplate() &&
14594 var->getStorageClass() != SC_Register &&
14595 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14596 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14597 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14598 var->getLocation())) {
14599 // Find a previous declaration that's not a definition.
14600 VarDecl *prev = var->getPreviousDecl();
14601 while (prev && prev->isThisDeclarationADefinition())
14602 prev = prev->getPreviousDecl();
14603
14604 if (!prev) {
14605 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14606 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14607 << /* variable */ 0;
14608 }
14609 }
14610
14611 // Cache the result of checking for constant initialization.
14612 std::optional<bool> CacheHasConstInit;
14613 const Expr *CacheCulprit = nullptr;
14614 auto checkConstInit = [&]() mutable {
14615 const Expr *Init = var->getInit();
14616 if (Init->isInstantiationDependent())
14617 return true;
14618
14619 if (!CacheHasConstInit)
14620 CacheHasConstInit = var->getInit()->isConstantInitializer(
14621 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14622 return *CacheHasConstInit;
14623 };
14624
14625 if (var->getTLSKind() == VarDecl::TLS_Static) {
14626 if (var->getType().isDestructedType()) {
14627 // GNU C++98 edits for __thread, [basic.start.term]p3:
14628 // The type of an object with thread storage duration shall not
14629 // have a non-trivial destructor.
14630 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14631 if (getLangOpts().CPlusPlus11)
14632 Diag(var->getLocation(), diag::note_use_thread_local);
14633 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14634 if (!checkConstInit()) {
14635 // GNU C++98 edits for __thread, [basic.start.init]p4:
14636 // An object of thread storage duration shall not require dynamic
14637 // initialization.
14638 // FIXME: Need strict checking here.
14639 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14640 << CacheCulprit->getSourceRange();
14641 if (getLangOpts().CPlusPlus11)
14642 Diag(var->getLocation(), diag::note_use_thread_local);
14643 }
14644 }
14645 }
14646
14647
14648 if (!var->getType()->isStructureType() && var->hasInit() &&
14649 isa<InitListExpr>(Val: var->getInit())) {
14650 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14651 unsigned NumInits = ILE->getNumInits();
14652 if (NumInits > 2)
14653 for (unsigned I = 0; I < NumInits; ++I) {
14654 const auto *Init = ILE->getInit(Init: I);
14655 if (!Init)
14656 break;
14657 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14658 if (!SL)
14659 break;
14660
14661 unsigned NumConcat = SL->getNumConcatenated();
14662 // Diagnose missing comma in string array initialization.
14663 // Do not warn when all the elements in the initializer are concatenated
14664 // together. Do not warn for macros too.
14665 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14666 bool OnlyOneMissingComma = true;
14667 for (unsigned J = I + 1; J < NumInits; ++J) {
14668 const auto *Init = ILE->getInit(Init: J);
14669 if (!Init)
14670 break;
14671 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14672 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14673 OnlyOneMissingComma = false;
14674 break;
14675 }
14676 }
14677
14678 if (OnlyOneMissingComma) {
14679 SmallVector<FixItHint, 1> Hints;
14680 for (unsigned i = 0; i < NumConcat - 1; ++i)
14681 Hints.push_back(Elt: FixItHint::CreateInsertion(
14682 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14683
14684 Diag(SL->getStrTokenLoc(1),
14685 diag::warn_concatenated_literal_array_init)
14686 << Hints;
14687 Diag(SL->getBeginLoc(),
14688 diag::note_concatenated_string_literal_silence);
14689 }
14690 // In any case, stop now.
14691 break;
14692 }
14693 }
14694 }
14695
14696
14697 QualType type = var->getType();
14698
14699 if (var->hasAttr<BlocksAttr>())
14700 getCurFunction()->addByrefBlockVar(VD: var);
14701
14702 Expr *Init = var->getInit();
14703 bool GlobalStorage = var->hasGlobalStorage();
14704 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14705 QualType baseType = Context.getBaseElementType(QT: type);
14706 bool HasConstInit = true;
14707
14708 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14709 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14710 << var;
14711
14712 // Check whether the initializer is sufficiently constant.
14713 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14714 !type->isDependentType() && Init && !Init->isValueDependent() &&
14715 (GlobalStorage || var->isConstexpr() ||
14716 var->mightBeUsableInConstantExpressions(C: Context))) {
14717 // If this variable might have a constant initializer or might be usable in
14718 // constant expressions, check whether or not it actually is now. We can't
14719 // do this lazily, because the result might depend on things that change
14720 // later, such as which constexpr functions happen to be defined.
14721 SmallVector<PartialDiagnosticAt, 8> Notes;
14722 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14723 // Prior to C++11, in contexts where a constant initializer is required,
14724 // the set of valid constant initializers is described by syntactic rules
14725 // in [expr.const]p2-6.
14726 // FIXME: Stricter checking for these rules would be useful for constinit /
14727 // -Wglobal-constructors.
14728 HasConstInit = checkConstInit();
14729
14730 // Compute and cache the constant value, and remember that we have a
14731 // constant initializer.
14732 if (HasConstInit) {
14733 (void)var->checkForConstantInitialization(Notes);
14734 Notes.clear();
14735 } else if (CacheCulprit) {
14736 Notes.emplace_back(CacheCulprit->getExprLoc(),
14737 PDiag(diag::note_invalid_subexpr_in_const_expr));
14738 Notes.back().second << CacheCulprit->getSourceRange();
14739 }
14740 } else {
14741 // Evaluate the initializer to see if it's a constant initializer.
14742 HasConstInit = var->checkForConstantInitialization(Notes);
14743 }
14744
14745 if (HasConstInit) {
14746 // FIXME: Consider replacing the initializer with a ConstantExpr.
14747 } else if (var->isConstexpr()) {
14748 SourceLocation DiagLoc = var->getLocation();
14749 // If the note doesn't add any useful information other than a source
14750 // location, fold it into the primary diagnostic.
14751 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14752 diag::note_invalid_subexpr_in_const_expr) {
14753 DiagLoc = Notes[0].first;
14754 Notes.clear();
14755 }
14756 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14757 << var << Init->getSourceRange();
14758 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14759 Diag(Notes[I].first, Notes[I].second);
14760 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14761 auto *Attr = var->getAttr<ConstInitAttr>();
14762 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14763 << Init->getSourceRange();
14764 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14765 << Attr->getRange() << Attr->isConstinit();
14766 for (auto &it : Notes)
14767 Diag(it.first, it.second);
14768 } else if (IsGlobal &&
14769 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14770 var->getLocation())) {
14771 // Warn about globals which don't have a constant initializer. Don't
14772 // warn about globals with a non-trivial destructor because we already
14773 // warned about them.
14774 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14775 if (!(RD && !RD->hasTrivialDestructor())) {
14776 // checkConstInit() here permits trivial default initialization even in
14777 // C++11 onwards, where such an initializer is not a constant initializer
14778 // but nonetheless doesn't require a global constructor.
14779 if (!checkConstInit())
14780 Diag(var->getLocation(), diag::warn_global_constructor)
14781 << Init->getSourceRange();
14782 }
14783 }
14784 }
14785
14786 // Apply section attributes and pragmas to global variables.
14787 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14788 !inTemplateInstantiation()) {
14789 PragmaStack<StringLiteral *> *Stack = nullptr;
14790 int SectionFlags = ASTContext::PSF_Read;
14791 bool MSVCEnv =
14792 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14793 std::optional<QualType::NonConstantStorageReason> Reason;
14794 if (HasConstInit &&
14795 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14796 Stack = &ConstSegStack;
14797 } else {
14798 SectionFlags |= ASTContext::PSF_Write;
14799 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14800 }
14801 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14802 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14803 SectionFlags |= ASTContext::PSF_Implicit;
14804 UnifySection(SA->getName(), SectionFlags, var);
14805 } else if (Stack->CurrentValue) {
14806 if (Stack != &ConstSegStack && MSVCEnv &&
14807 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14808 var->getType().isConstQualified()) {
14809 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14810 NonConstNonReferenceType) &&
14811 "This case should've already been handled elsewhere");
14812 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14813 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14814 ? QualType::NonConstantStorageReason::NonTrivialCtor
14815 : *Reason);
14816 }
14817 SectionFlags |= ASTContext::PSF_Implicit;
14818 auto SectionName = Stack->CurrentValue->getString();
14819 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14820 Stack->CurrentPragmaLocation,
14821 SectionAttr::Declspec_allocate));
14822 if (UnifySection(SectionName, SectionFlags, var))
14823 var->dropAttr<SectionAttr>();
14824 }
14825
14826 // Apply the init_seg attribute if this has an initializer. If the
14827 // initializer turns out to not be dynamic, we'll end up ignoring this
14828 // attribute.
14829 if (CurInitSeg && var->getInit())
14830 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14831 CurInitSegLoc));
14832 }
14833
14834 // All the following checks are C++ only.
14835 if (!getLangOpts().CPlusPlus) {
14836 // If this variable must be emitted, add it as an initializer for the
14837 // current module.
14838 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14839 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14840 return;
14841 }
14842
14843 DiagnoseUniqueObjectDuplication(VD: var);
14844
14845 // Require the destructor.
14846 if (!type->isDependentType())
14847 if (const RecordType *recordType = baseType->getAs<RecordType>())
14848 FinalizeVarWithDestructor(VD: var, DeclInitType: recordType);
14849
14850 // If this variable must be emitted, add it as an initializer for the current
14851 // module.
14852 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14853 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14854
14855 // Build the bindings if this is a structured binding declaration.
14856 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
14857 CheckCompleteDecompositionDeclaration(DD);
14858}
14859
14860void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14861 assert(VD->isStaticLocal());
14862
14863 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14864
14865 // Find outermost function when VD is in lambda function.
14866 while (FD && !getDLLAttr(FD) &&
14867 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14868 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14869 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14870 }
14871
14872 if (!FD)
14873 return;
14874
14875 // Static locals inherit dll attributes from their function.
14876 if (Attr *A = getDLLAttr(FD)) {
14877 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
14878 NewAttr->setInherited(true);
14879 VD->addAttr(A: NewAttr);
14880 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14881 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14882 NewAttr->setInherited(true);
14883 VD->addAttr(A: NewAttr);
14884
14885 // Export this function to enforce exporting this static variable even
14886 // if it is not used in this compilation unit.
14887 if (!FD->hasAttr<DLLExportAttr>())
14888 FD->addAttr(NewAttr);
14889
14890 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14891 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14892 NewAttr->setInherited(true);
14893 VD->addAttr(A: NewAttr);
14894 }
14895}
14896
14897void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14898 assert(VD->getTLSKind());
14899
14900 // Perform TLS alignment check here after attributes attached to the variable
14901 // which may affect the alignment have been processed. Only perform the check
14902 // if the target has a maximum TLS alignment (zero means no constraints).
14903 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14904 // Protect the check so that it's not performed on dependent types and
14905 // dependent alignments (we can't determine the alignment in that case).
14906 if (!VD->hasDependentAlignment()) {
14907 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
14908 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14909 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14910 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14911 << (unsigned)MaxAlignChars.getQuantity();
14912 }
14913 }
14914 }
14915}
14916
14917void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14918 // Note that we are no longer parsing the initializer for this declaration.
14919 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
14920
14921 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
14922 if (!VD)
14923 return;
14924
14925 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14926 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14927 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14928 if (PragmaClangBSSSection.Valid)
14929 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14930 Context, PragmaClangBSSSection.SectionName,
14931 PragmaClangBSSSection.PragmaLocation));
14932 if (PragmaClangDataSection.Valid)
14933 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14934 Context, PragmaClangDataSection.SectionName,
14935 PragmaClangDataSection.PragmaLocation));
14936 if (PragmaClangRodataSection.Valid)
14937 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14938 Context, PragmaClangRodataSection.SectionName,
14939 PragmaClangRodataSection.PragmaLocation));
14940 if (PragmaClangRelroSection.Valid)
14941 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14942 Context, PragmaClangRelroSection.SectionName,
14943 PragmaClangRelroSection.PragmaLocation));
14944 }
14945
14946 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
14947 for (auto *BD : DD->bindings()) {
14948 FinalizeDeclaration(BD);
14949 }
14950 }
14951
14952 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
14953 K: BuiltinCountedByRefKind::Initializer);
14954
14955 checkAttributesAfterMerging(*this, *VD);
14956
14957 if (VD->isStaticLocal())
14958 CheckStaticLocalForDllExport(VD);
14959
14960 if (VD->getTLSKind())
14961 CheckThreadLocalForLargeAlignment(VD);
14962
14963 // Perform check for initializers of device-side global variables.
14964 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14965 // 7.5). We must also apply the same checks to all __shared__
14966 // variables whether they are local or not. CUDA also allows
14967 // constant initializers for __constant__ and __device__ variables.
14968 if (getLangOpts().CUDA)
14969 CUDA().checkAllowedInitializer(VD);
14970
14971 // Grab the dllimport or dllexport attribute off of the VarDecl.
14972 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14973
14974 // Imported static data members cannot be defined out-of-line.
14975 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14976 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14977 VD->isThisDeclarationADefinition()) {
14978 // We allow definitions of dllimport class template static data members
14979 // with a warning.
14980 CXXRecordDecl *Context =
14981 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14982 bool IsClassTemplateMember =
14983 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
14984 Context->getDescribedClassTemplate();
14985
14986 Diag(VD->getLocation(),
14987 IsClassTemplateMember
14988 ? diag::warn_attribute_dllimport_static_field_definition
14989 : diag::err_attribute_dllimport_static_field_definition);
14990 Diag(IA->getLocation(), diag::note_attribute);
14991 if (!IsClassTemplateMember)
14992 VD->setInvalidDecl();
14993 }
14994 }
14995
14996 // dllimport/dllexport variables cannot be thread local, their TLS index
14997 // isn't exported with the variable.
14998 if (DLLAttr && VD->getTLSKind()) {
14999 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15000 if (F && getDLLAttr(F)) {
15001 assert(VD->isStaticLocal());
15002 // But if this is a static local in a dlimport/dllexport function, the
15003 // function will never be inlined, which means the var would never be
15004 // imported, so having it marked import/export is safe.
15005 } else {
15006 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15007 << DLLAttr;
15008 VD->setInvalidDecl();
15009 }
15010 }
15011
15012 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15013 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15014 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15015 << Attr;
15016 VD->dropAttr<UsedAttr>();
15017 }
15018 }
15019 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15020 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15021 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15022 << Attr;
15023 VD->dropAttr<RetainAttr>();
15024 }
15025 }
15026
15027 const DeclContext *DC = VD->getDeclContext();
15028 // If there's a #pragma GCC visibility in scope, and this isn't a class
15029 // member, set the visibility of this variable.
15030 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15031 AddPushedVisibilityAttribute(VD);
15032
15033 // FIXME: Warn on unused var template partial specializations.
15034 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15035 MarkUnusedFileScopedDecl(VD);
15036
15037 // Now we have parsed the initializer and can update the table of magic
15038 // tag values.
15039 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15040 !VD->getType()->isIntegralOrEnumerationType())
15041 return;
15042
15043 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15044 const Expr *MagicValueExpr = VD->getInit();
15045 if (!MagicValueExpr) {
15046 continue;
15047 }
15048 std::optional<llvm::APSInt> MagicValueInt;
15049 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15050 Diag(I->getRange().getBegin(),
15051 diag::err_type_tag_for_datatype_not_ice)
15052 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15053 continue;
15054 }
15055 if (MagicValueInt->getActiveBits() > 64) {
15056 Diag(I->getRange().getBegin(),
15057 diag::err_type_tag_for_datatype_too_large)
15058 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15059 continue;
15060 }
15061 uint64_t MagicValue = MagicValueInt->getZExtValue();
15062 RegisterTypeTagForDatatype(I->getArgumentKind(),
15063 MagicValue,
15064 I->getMatchingCType(),
15065 I->getLayoutCompatible(),
15066 I->getMustBeNull());
15067 }
15068}
15069
15070static bool hasDeducedAuto(DeclaratorDecl *DD) {
15071 auto *VD = dyn_cast<VarDecl>(Val: DD);
15072 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15073}
15074
15075Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15076 ArrayRef<Decl *> Group) {
15077 SmallVector<Decl*, 8> Decls;
15078
15079 if (DS.isTypeSpecOwned())
15080 Decls.push_back(Elt: DS.getRepAsDecl());
15081
15082 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15083 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15084 bool DiagnosedMultipleDecomps = false;
15085 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15086 bool DiagnosedNonDeducedAuto = false;
15087
15088 for (Decl *D : Group) {
15089 if (!D)
15090 continue;
15091 // Check if the Decl has been declared in '#pragma omp declare target'
15092 // directive and has static storage duration.
15093 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15094 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15095 VD->hasGlobalStorage())
15096 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15097 // For declarators, there are some additional syntactic-ish checks we need
15098 // to perform.
15099 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15100 if (!FirstDeclaratorInGroup)
15101 FirstDeclaratorInGroup = DD;
15102 if (!FirstDecompDeclaratorInGroup)
15103 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15104 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15105 !hasDeducedAuto(DD))
15106 FirstNonDeducedAutoInGroup = DD;
15107
15108 if (FirstDeclaratorInGroup != DD) {
15109 // A decomposition declaration cannot be combined with any other
15110 // declaration in the same group.
15111 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15112 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15113 diag::err_decomp_decl_not_alone)
15114 << FirstDeclaratorInGroup->getSourceRange()
15115 << DD->getSourceRange();
15116 DiagnosedMultipleDecomps = true;
15117 }
15118
15119 // A declarator that uses 'auto' in any way other than to declare a
15120 // variable with a deduced type cannot be combined with any other
15121 // declarator in the same group.
15122 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15123 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15124 diag::err_auto_non_deduced_not_alone)
15125 << FirstNonDeducedAutoInGroup->getType()
15126 ->hasAutoForTrailingReturnType()
15127 << FirstDeclaratorInGroup->getSourceRange()
15128 << DD->getSourceRange();
15129 DiagnosedNonDeducedAuto = true;
15130 }
15131 }
15132 }
15133
15134 Decls.push_back(Elt: D);
15135 }
15136
15137 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15138 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15139 handleTagNumbering(Tag, TagScope: S);
15140 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15141 getLangOpts().CPlusPlus)
15142 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15143 }
15144 }
15145
15146 return BuildDeclaratorGroup(Group: Decls);
15147}
15148
15149Sema::DeclGroupPtrTy
15150Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15151 // C++14 [dcl.spec.auto]p7: (DR1347)
15152 // If the type that replaces the placeholder type is not the same in each
15153 // deduction, the program is ill-formed.
15154 if (Group.size() > 1) {
15155 QualType Deduced;
15156 VarDecl *DeducedDecl = nullptr;
15157 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15158 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15159 if (!D || D->isInvalidDecl())
15160 break;
15161 DeducedType *DT = D->getType()->getContainedDeducedType();
15162 if (!DT || DT->getDeducedType().isNull())
15163 continue;
15164 if (Deduced.isNull()) {
15165 Deduced = DT->getDeducedType();
15166 DeducedDecl = D;
15167 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15168 auto *AT = dyn_cast<AutoType>(Val: DT);
15169 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15170 diag::err_auto_different_deductions)
15171 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15172 << DeducedDecl->getDeclName() << DT->getDeducedType()
15173 << D->getDeclName();
15174 if (DeducedDecl->hasInit())
15175 Dia << DeducedDecl->getInit()->getSourceRange();
15176 if (D->getInit())
15177 Dia << D->getInit()->getSourceRange();
15178 D->setInvalidDecl();
15179 break;
15180 }
15181 }
15182 }
15183
15184 ActOnDocumentableDecls(Group);
15185
15186 return DeclGroupPtrTy::make(
15187 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15188}
15189
15190void Sema::ActOnDocumentableDecl(Decl *D) {
15191 ActOnDocumentableDecls(Group: D);
15192}
15193
15194void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15195 // Don't parse the comment if Doxygen diagnostics are ignored.
15196 if (Group.empty() || !Group[0])
15197 return;
15198
15199 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15200 Group[0]->getLocation()) &&
15201 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15202 Group[0]->getLocation()))
15203 return;
15204
15205 if (Group.size() >= 2) {
15206 // This is a decl group. Normally it will contain only declarations
15207 // produced from declarator list. But in case we have any definitions or
15208 // additional declaration references:
15209 // 'typedef struct S {} S;'
15210 // 'typedef struct S *S;'
15211 // 'struct S *pS;'
15212 // FinalizeDeclaratorGroup adds these as separate declarations.
15213 Decl *MaybeTagDecl = Group[0];
15214 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15215 Group = Group.slice(N: 1);
15216 }
15217 }
15218
15219 // FIMXE: We assume every Decl in the group is in the same file.
15220 // This is false when preprocessor constructs the group from decls in
15221 // different files (e. g. macros or #include).
15222 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15223}
15224
15225void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15226 // Check that there are no default arguments inside the type of this
15227 // parameter.
15228 if (getLangOpts().CPlusPlus)
15229 CheckExtraCXXDefaultArguments(D);
15230
15231 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15232 if (D.getCXXScopeSpec().isSet()) {
15233 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15234 << D.getCXXScopeSpec().getRange();
15235 }
15236
15237 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15238 // simple identifier except [...irrelevant cases...].
15239 switch (D.getName().getKind()) {
15240 case UnqualifiedIdKind::IK_Identifier:
15241 break;
15242
15243 case UnqualifiedIdKind::IK_OperatorFunctionId:
15244 case UnqualifiedIdKind::IK_ConversionFunctionId:
15245 case UnqualifiedIdKind::IK_LiteralOperatorId:
15246 case UnqualifiedIdKind::IK_ConstructorName:
15247 case UnqualifiedIdKind::IK_DestructorName:
15248 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15249 case UnqualifiedIdKind::IK_DeductionGuideName:
15250 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15251 << GetNameForDeclarator(D).getName();
15252 break;
15253
15254 case UnqualifiedIdKind::IK_TemplateId:
15255 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15256 // GetNameForDeclarator would not produce a useful name in this case.
15257 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15258 break;
15259 }
15260}
15261
15262void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15263 // This only matters in C.
15264 if (getLangOpts().CPlusPlus)
15265 return;
15266
15267 // This only matters if the declaration has a type.
15268 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15269 if (!VD)
15270 return;
15271
15272 // Get the type, this only matters for tag types.
15273 QualType QT = VD->getType();
15274 const auto *TD = QT->getAsTagDecl();
15275 if (!TD)
15276 return;
15277
15278 // Check if the tag declaration is lexically declared somewhere different
15279 // from the lexical declaration of the given object, then it will be hidden
15280 // in C++ and we should warn on it.
15281 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15282 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15283 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15284 Diag(TD->getLocation(), diag::note_declared_at);
15285 }
15286}
15287
15288static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15289 SourceLocation ExplicitThisLoc) {
15290 if (!ExplicitThisLoc.isValid())
15291 return;
15292 assert(S.getLangOpts().CPlusPlus &&
15293 "explicit parameter in non-cplusplus mode");
15294 if (!S.getLangOpts().CPlusPlus23)
15295 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15296 << P->getSourceRange();
15297
15298 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15299 // parameter pack.
15300 if (P->isParameterPack()) {
15301 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15302 << P->getSourceRange();
15303 return;
15304 }
15305 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15306 if (LambdaScopeInfo *LSI = S.getCurLambda())
15307 LSI->ExplicitObjectParameter = P;
15308}
15309
15310Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15311 SourceLocation ExplicitThisLoc) {
15312 const DeclSpec &DS = D.getDeclSpec();
15313
15314 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15315 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15316 // except for the special case of a single unnamed parameter of type void
15317 // with no storage class specifier, no type qualifier, and no following
15318 // ellipsis terminator.
15319 // Clang applies the C2y rules for 'register void' in all C language modes,
15320 // same as GCC, because it's questionable what that could possibly mean.
15321
15322 // C++03 [dcl.stc]p2 also permits 'auto'.
15323 StorageClass SC = SC_None;
15324 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15325 SC = SC_Register;
15326 // In C++11, the 'register' storage class specifier is deprecated.
15327 // In C++17, it is not allowed, but we tolerate it as an extension.
15328 if (getLangOpts().CPlusPlus11) {
15329 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus17
15330 ? diag::ext_register_storage_class
15331 : diag::warn_deprecated_register)
15332 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15333 } else if (!getLangOpts().CPlusPlus &&
15334 DS.getTypeSpecType() == DeclSpec::TST_void &&
15335 D.getNumTypeObjects() == 0) {
15336 Diag(DS.getStorageClassSpecLoc(),
15337 diag::err_invalid_storage_class_in_func_decl)
15338 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15339 D.getMutableDeclSpec().ClearStorageClassSpecs();
15340 }
15341 } else if (getLangOpts().CPlusPlus &&
15342 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15343 SC = SC_Auto;
15344 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15345 Diag(DS.getStorageClassSpecLoc(),
15346 diag::err_invalid_storage_class_in_func_decl);
15347 D.getMutableDeclSpec().ClearStorageClassSpecs();
15348 }
15349
15350 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15351 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15352 << DeclSpec::getSpecifierName(TSCS);
15353 if (DS.isInlineSpecified())
15354 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15355 << getLangOpts().CPlusPlus17;
15356 if (DS.hasConstexprSpecifier())
15357 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15358 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15359
15360 DiagnoseFunctionSpecifiers(DS);
15361
15362 CheckFunctionOrTemplateParamDeclarator(S, D);
15363
15364 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15365 QualType parmDeclType = TInfo->getType();
15366
15367 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15368 const IdentifierInfo *II = D.getIdentifier();
15369 if (II) {
15370 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15371 RedeclarationKind::ForVisibleRedeclaration);
15372 LookupName(R, S);
15373 if (!R.empty()) {
15374 NamedDecl *PrevDecl = *R.begin();
15375 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15376 // Maybe we will complain about the shadowed template parameter.
15377 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15378 // Just pretend that we didn't see the previous declaration.
15379 PrevDecl = nullptr;
15380 }
15381 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15382 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15383 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15384 // Recover by removing the name
15385 II = nullptr;
15386 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15387 D.setInvalidType(true);
15388 }
15389 }
15390 }
15391
15392 // Temporarily put parameter variables in the translation unit, not
15393 // the enclosing context. This prevents them from accidentally
15394 // looking like class members in C++.
15395 ParmVarDecl *New =
15396 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15397 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15398
15399 if (D.isInvalidType())
15400 New->setInvalidDecl();
15401
15402 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15403
15404 assert(S->isFunctionPrototypeScope());
15405 assert(S->getFunctionPrototypeDepth() >= 1);
15406 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15407 parameterIndex: S->getNextFunctionPrototypeIndex());
15408
15409 warnOnCTypeHiddenInCPlusPlus(New);
15410
15411 // Add the parameter declaration into this scope.
15412 S->AddDecl(New);
15413 if (II)
15414 IdResolver.AddDecl(New);
15415
15416 ProcessDeclAttributes(S, New, D);
15417
15418 if (D.getDeclSpec().isModulePrivateSpecified())
15419 Diag(New->getLocation(), diag::err_module_private_local)
15420 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15421 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15422
15423 if (New->hasAttr<BlocksAttr>()) {
15424 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15425 }
15426
15427 if (getLangOpts().OpenCL)
15428 deduceOpenCLAddressSpace(New);
15429
15430 return New;
15431}
15432
15433ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15434 SourceLocation Loc,
15435 QualType T) {
15436 /* FIXME: setting StartLoc == Loc.
15437 Would it be worth to modify callers so as to provide proper source
15438 location for the unnamed parameters, embedding the parameter's type? */
15439 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15440 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15441 S: SC_None, DefArg: nullptr);
15442 Param->setImplicit();
15443 return Param;
15444}
15445
15446void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15447 // Don't diagnose unused-parameter errors in template instantiations; we
15448 // will already have done so in the template itself.
15449 if (inTemplateInstantiation())
15450 return;
15451
15452 for (const ParmVarDecl *Parameter : Parameters) {
15453 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15454 !Parameter->hasAttr<UnusedAttr>() &&
15455 !Parameter->getIdentifier()->isPlaceholder()) {
15456 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15457 << Parameter->getDeclName();
15458 }
15459 }
15460}
15461
15462void Sema::DiagnoseSizeOfParametersAndReturnValue(
15463 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15464 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15465 return;
15466
15467 // Warn if the return value is pass-by-value and larger than the specified
15468 // threshold.
15469 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15470 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15471 if (Size > LangOpts.NumLargeByValueCopy)
15472 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15473 }
15474
15475 // Warn if any parameter is pass-by-value and larger than the specified
15476 // threshold.
15477 for (const ParmVarDecl *Parameter : Parameters) {
15478 QualType T = Parameter->getType();
15479 if (T->isDependentType() || !T.isPODType(Context))
15480 continue;
15481 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15482 if (Size > LangOpts.NumLargeByValueCopy)
15483 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15484 << Parameter << Size;
15485 }
15486}
15487
15488ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15489 SourceLocation NameLoc,
15490 const IdentifierInfo *Name, QualType T,
15491 TypeSourceInfo *TSInfo, StorageClass SC) {
15492 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15493 if (getLangOpts().ObjCAutoRefCount &&
15494 T.getObjCLifetime() == Qualifiers::OCL_None &&
15495 T->isObjCLifetimeType()) {
15496
15497 Qualifiers::ObjCLifetime lifetime;
15498
15499 // Special cases for arrays:
15500 // - if it's const, use __unsafe_unretained
15501 // - otherwise, it's an error
15502 if (T->isArrayType()) {
15503 if (!T.isConstQualified()) {
15504 if (DelayedDiagnostics.shouldDelayDiagnostics())
15505 DelayedDiagnostics.add(
15506 sema::DelayedDiagnostic::makeForbiddenType(
15507 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15508 else
15509 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15510 << TSInfo->getTypeLoc().getSourceRange();
15511 }
15512 lifetime = Qualifiers::OCL_ExplicitNone;
15513 } else {
15514 lifetime = T->getObjCARCImplicitLifetime();
15515 }
15516 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15517 }
15518
15519 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15520 T: Context.getAdjustedParameterType(T),
15521 TInfo: TSInfo, S: SC, DefArg: nullptr);
15522
15523 // Make a note if we created a new pack in the scope of a lambda, so that
15524 // we know that references to that pack must also be expanded within the
15525 // lambda scope.
15526 if (New->isParameterPack())
15527 if (auto *CSI = getEnclosingLambdaOrBlock())
15528 CSI->LocalPacks.push_back(New);
15529
15530 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15531 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15532 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15533 UseContext: NonTrivialCUnionContext::FunctionParam,
15534 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15535
15536 // Parameter declarators cannot be interface types. All ObjC objects are
15537 // passed by reference.
15538 if (T->isObjCObjectType()) {
15539 SourceLocation TypeEndLoc =
15540 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15541 Diag(NameLoc,
15542 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15543 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15544 T = Context.getObjCObjectPointerType(OIT: T);
15545 New->setType(T);
15546 }
15547
15548 // __ptrauth is forbidden on parameters.
15549 if (T.getPointerAuth()) {
15550 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15551 New->setInvalidDecl();
15552 }
15553
15554 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15555 // duration shall not be qualified by an address-space qualifier."
15556 // Since all parameters have automatic store duration, they can not have
15557 // an address space.
15558 if (T.getAddressSpace() != LangAS::Default &&
15559 // OpenCL allows function arguments declared to be an array of a type
15560 // to be qualified with an address space.
15561 !(getLangOpts().OpenCL &&
15562 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15563 // WebAssembly allows reference types as parameters. Funcref in particular
15564 // lives in a different address space.
15565 !(T->isFunctionPointerType() &&
15566 T.getAddressSpace() == LangAS::wasm_funcref)) {
15567 Diag(NameLoc, diag::err_arg_with_address_space);
15568 New->setInvalidDecl();
15569 }
15570
15571 // PPC MMA non-pointer types are not allowed as function argument types.
15572 if (Context.getTargetInfo().getTriple().isPPC64() &&
15573 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15574 New->setInvalidDecl();
15575 }
15576
15577 return New;
15578}
15579
15580void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15581 SourceLocation LocAfterDecls) {
15582 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15583
15584 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15585 // in the declaration list shall have at least one declarator, those
15586 // declarators shall only declare identifiers from the identifier list, and
15587 // every identifier in the identifier list shall be declared.
15588 //
15589 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15590 // identifiers it names shall be declared in the declaration list."
15591 //
15592 // This is why we only diagnose in C99 and later. Note, the other conditions
15593 // listed are checked elsewhere.
15594 if (!FTI.hasPrototype) {
15595 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15596 --i;
15597 if (FTI.Params[i].Param == nullptr) {
15598 if (getLangOpts().C99) {
15599 SmallString<256> Code;
15600 llvm::raw_svector_ostream(Code)
15601 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15602 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15603 << FTI.Params[i].Ident
15604 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15605 }
15606
15607 // Implicitly declare the argument as type 'int' for lack of a better
15608 // type.
15609 AttributeFactory attrs;
15610 DeclSpec DS(attrs);
15611 const char* PrevSpec; // unused
15612 unsigned DiagID; // unused
15613 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15614 DiagID, Policy: Context.getPrintingPolicy());
15615 // Use the identifier location for the type source range.
15616 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15617 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15618 Declarator ParamD(DS, ParsedAttributesView::none(),
15619 DeclaratorContext::KNRTypeList);
15620 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15621 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15622 }
15623 }
15624 }
15625}
15626
15627Decl *
15628Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15629 MultiTemplateParamsArg TemplateParameterLists,
15630 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15631 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15632 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15633 Scope *ParentScope = FnBodyScope->getParent();
15634
15635 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15636 // we define a non-templated function definition, we will create a declaration
15637 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15638 // The base function declaration will have the equivalent of an `omp declare
15639 // variant` annotation which specifies the mangled definition as a
15640 // specialization function under the OpenMP context defined as part of the
15641 // `omp begin declare variant`.
15642 SmallVector<FunctionDecl *, 4> Bases;
15643 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15644 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15645 S: ParentScope, D, TemplateParameterLists, Bases);
15646
15647 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15648 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15649 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15650
15651 if (!Bases.empty())
15652 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15653 Bases);
15654
15655 return Dcl;
15656}
15657
15658void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15659 Consumer.HandleInlineFunctionDefinition(D);
15660}
15661
15662static bool FindPossiblePrototype(const FunctionDecl *FD,
15663 const FunctionDecl *&PossiblePrototype) {
15664 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15665 Prev = Prev->getPreviousDecl()) {
15666 // Ignore any declarations that occur in function or method
15667 // scope, because they aren't visible from the header.
15668 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15669 continue;
15670
15671 PossiblePrototype = Prev;
15672 return Prev->getType()->isFunctionProtoType();
15673 }
15674 return false;
15675}
15676
15677static bool
15678ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15679 const FunctionDecl *&PossiblePrototype) {
15680 // Don't warn about invalid declarations.
15681 if (FD->isInvalidDecl())
15682 return false;
15683
15684 // Or declarations that aren't global.
15685 if (!FD->isGlobal())
15686 return false;
15687
15688 // Don't warn about C++ member functions.
15689 if (isa<CXXMethodDecl>(Val: FD))
15690 return false;
15691
15692 // Don't warn about 'main'.
15693 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15694 if (IdentifierInfo *II = FD->getIdentifier())
15695 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15696 return false;
15697
15698 if (FD->isMSVCRTEntryPoint())
15699 return false;
15700
15701 // Don't warn about inline functions.
15702 if (FD->isInlined())
15703 return false;
15704
15705 // Don't warn about function templates.
15706 if (FD->getDescribedFunctionTemplate())
15707 return false;
15708
15709 // Don't warn about function template specializations.
15710 if (FD->isFunctionTemplateSpecialization())
15711 return false;
15712
15713 // Don't warn for OpenCL kernels.
15714 if (FD->hasAttr<DeviceKernelAttr>())
15715 return false;
15716
15717 // Don't warn on explicitly deleted functions.
15718 if (FD->isDeleted())
15719 return false;
15720
15721 // Don't warn on implicitly local functions (such as having local-typed
15722 // parameters).
15723 if (!FD->isExternallyVisible())
15724 return false;
15725
15726 // If we were able to find a potential prototype, don't warn.
15727 if (FindPossiblePrototype(FD, PossiblePrototype))
15728 return false;
15729
15730 return true;
15731}
15732
15733void
15734Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15735 const FunctionDecl *EffectiveDefinition,
15736 SkipBodyInfo *SkipBody) {
15737 const FunctionDecl *Definition = EffectiveDefinition;
15738 if (!Definition &&
15739 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15740 return;
15741
15742 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15743 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15744 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15745 // A merged copy of the same function, instantiated as a member of
15746 // the same class, is OK.
15747 if (declaresSameEntity(OrigFD, OrigDef) &&
15748 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15749 cast<Decl>(FD->getLexicalDeclContext())))
15750 return;
15751 }
15752 }
15753 }
15754
15755 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
15756 return;
15757
15758 // Don't emit an error when this is redefinition of a typo-corrected
15759 // definition.
15760 if (TypoCorrectedFunctionDefinitions.count(Definition))
15761 return;
15762
15763 // If we don't have a visible definition of the function, and it's inline or
15764 // a template, skip the new definition.
15765 if (SkipBody && !hasVisibleDefinition(Definition) &&
15766 (Definition->getFormalLinkage() == Linkage::Internal ||
15767 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15768 Definition->getNumTemplateParameterLists())) {
15769 SkipBody->ShouldSkip = true;
15770 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15771 if (auto *TD = Definition->getDescribedFunctionTemplate())
15772 makeMergedDefinitionVisible(TD);
15773 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15774 return;
15775 }
15776
15777 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15778 Definition->getStorageClass() == SC_Extern)
15779 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15780 << FD << getLangOpts().CPlusPlus;
15781 else
15782 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15783
15784 Diag(Definition->getLocation(), diag::note_previous_definition);
15785 FD->setInvalidDecl();
15786}
15787
15788LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15789 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15790
15791 LambdaScopeInfo *LSI = PushLambdaScope();
15792 LSI->CallOperator = CallOperator;
15793 LSI->Lambda = LambdaClass;
15794 LSI->ReturnType = CallOperator->getReturnType();
15795 // When this function is called in situation where the context of the call
15796 // operator is not entered, we set AfterParameterList to false, so that
15797 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15798 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15799 // where we would set the CurContext to the lambda operator before
15800 // substituting into it. In this case the flag needs to be true such that
15801 // tryCaptureVariable can correctly handle potential captures thereof.
15802 LSI->AfterParameterList = CurContext == CallOperator;
15803
15804 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15805 // used at the point of dealing with potential captures.
15806 //
15807 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15808 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15809 // associated. (Technically, we could recover that list from their
15810 // instantiation patterns, but for now, the GLTemplateParameterList seems
15811 // unnecessary in these cases.)
15812 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15813 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15814 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15815
15816 if (LCD == LCD_None)
15817 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15818 else if (LCD == LCD_ByCopy)
15819 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15820 else if (LCD == LCD_ByRef)
15821 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15822 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15823
15824 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15825 LSI->Mutable = !CallOperator->isConst();
15826 if (CallOperator->isExplicitObjectMemberFunction())
15827 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15828
15829 // Add the captures to the LSI so they can be noted as already
15830 // captured within tryCaptureVar.
15831 auto I = LambdaClass->field_begin();
15832 for (const auto &C : LambdaClass->captures()) {
15833 if (C.capturesVariable()) {
15834 ValueDecl *VD = C.getCapturedVar();
15835 if (VD->isInitCapture())
15836 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15837 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15838 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
15839 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
15840 /*EllipsisLoc*/C.isPackExpansion()
15841 ? C.getEllipsisLoc() : SourceLocation(),
15842 CaptureType: I->getType(), /*Invalid*/false);
15843
15844 } else if (C.capturesThis()) {
15845 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
15846 ByCopy: C.getCaptureKind() == LCK_StarThis);
15847 } else {
15848 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
15849 CaptureType: I->getType());
15850 }
15851 ++I;
15852 }
15853 return LSI;
15854}
15855
15856Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15857 SkipBodyInfo *SkipBody,
15858 FnBodyKind BodyKind) {
15859 if (!D) {
15860 // Parsing the function declaration failed in some way. Push on a fake scope
15861 // anyway so we can try to parse the function body.
15862 PushFunctionScope();
15863 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
15864 return D;
15865 }
15866
15867 FunctionDecl *FD = nullptr;
15868
15869 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
15870 FD = FunTmpl->getTemplatedDecl();
15871 else
15872 FD = cast<FunctionDecl>(Val: D);
15873
15874 // Do not push if it is a lambda because one is already pushed when building
15875 // the lambda in ActOnStartOfLambdaDefinition().
15876 if (!isLambdaCallOperator(FD))
15877 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
15878 FD);
15879
15880 // Check for defining attributes before the check for redefinition.
15881 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15882 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15883 FD->dropAttr<AliasAttr>();
15884 FD->setInvalidDecl();
15885 }
15886 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15887 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15888 FD->dropAttr<IFuncAttr>();
15889 FD->setInvalidDecl();
15890 }
15891 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15892 if (Context.getTargetInfo().getTriple().isAArch64() &&
15893 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
15894 !Attr->isDefaultVersion()) {
15895 // If function multi versioning disabled skip parsing function body
15896 // defined with non-default target_version attribute
15897 if (SkipBody)
15898 SkipBody->ShouldSkip = true;
15899 return nullptr;
15900 }
15901 }
15902
15903 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
15904 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15905 Ctor->isDefaultConstructor() &&
15906 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15907 // If this is an MS ABI dllexport default constructor, instantiate any
15908 // default arguments.
15909 InstantiateDefaultCtorDefaultArgs(Ctor);
15910 }
15911 }
15912
15913 // See if this is a redefinition. If 'will have body' (or similar) is already
15914 // set, then these checks were already performed when it was set.
15915 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15916 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15917 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
15918
15919 // If we're skipping the body, we're done. Don't enter the scope.
15920 if (SkipBody && SkipBody->ShouldSkip)
15921 return D;
15922 }
15923
15924 // Mark this function as "will have a body eventually". This lets users to
15925 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15926 // this function.
15927 FD->setWillHaveBody();
15928
15929 // If we are instantiating a generic lambda call operator, push
15930 // a LambdaScopeInfo onto the function stack. But use the information
15931 // that's already been calculated (ActOnLambdaExpr) to prime the current
15932 // LambdaScopeInfo.
15933 // When the template operator is being specialized, the LambdaScopeInfo,
15934 // has to be properly restored so that tryCaptureVariable doesn't try
15935 // and capture any new variables. In addition when calculating potential
15936 // captures during transformation of nested lambdas, it is necessary to
15937 // have the LSI properly restored.
15938 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15939 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15940 // instantiated, explicitly specialized.
15941 if (FD->getTemplateSpecializationInfo()
15942 ->isExplicitInstantiationOrSpecialization()) {
15943 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15944 FD->setInvalidDecl();
15945 PushFunctionScope();
15946 } else {
15947 assert(inTemplateInstantiation() &&
15948 "There should be an active template instantiation on the stack "
15949 "when instantiating a generic lambda!");
15950 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
15951 }
15952 } else {
15953 // Enter a new function scope
15954 PushFunctionScope();
15955 }
15956
15957 // Builtin functions cannot be defined.
15958 if (unsigned BuiltinID = FD->getBuiltinID()) {
15959 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
15960 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
15961 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15962 FD->setInvalidDecl();
15963 }
15964 }
15965
15966 // The return type of a function definition must be complete (C99 6.9.1p3).
15967 // C++23 [dcl.fct.def.general]/p2
15968 // The type of [...] the return for a function definition
15969 // shall not be a (possibly cv-qualified) class type that is incomplete
15970 // or abstract within the function body unless the function is deleted.
15971 QualType ResultType = FD->getReturnType();
15972 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15973 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15974 (RequireCompleteType(FD->getLocation(), ResultType,
15975 diag::err_func_def_incomplete_result) ||
15976 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15977 diag::err_abstract_type_in_decl,
15978 AbstractReturnType)))
15979 FD->setInvalidDecl();
15980
15981 if (FnBodyScope)
15982 PushDeclContext(FnBodyScope, FD);
15983
15984 // Check the validity of our function parameters
15985 if (BodyKind != FnBodyKind::Delete)
15986 CheckParmsForFunctionDef(Parameters: FD->parameters(),
15987 /*CheckParameterNames=*/true);
15988
15989 // Add non-parameter declarations already in the function to the current
15990 // scope.
15991 if (FnBodyScope) {
15992 for (Decl *NPD : FD->decls()) {
15993 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15994 if (!NonParmDecl)
15995 continue;
15996 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15997 "parameters should not be in newly created FD yet");
15998
15999 // If the decl has a name, make it accessible in the current scope.
16000 if (NonParmDecl->getDeclName())
16001 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16002
16003 // Similarly, dive into enums and fish their constants out, making them
16004 // accessible in this scope.
16005 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16006 for (auto *EI : ED->enumerators())
16007 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16008 }
16009 }
16010 }
16011
16012 // Introduce our parameters into the function scope
16013 for (auto *Param : FD->parameters()) {
16014 Param->setOwningFunction(FD);
16015
16016 // If this has an identifier, add it to the scope stack.
16017 if (Param->getIdentifier() && FnBodyScope) {
16018 CheckShadow(FnBodyScope, Param);
16019
16020 PushOnScopeChains(Param, FnBodyScope);
16021 }
16022 }
16023
16024 // C++ [module.import/6] external definitions are not permitted in header
16025 // units. Deleted and Defaulted functions are implicitly inline (but the
16026 // inline state is not set at this point, so check the BodyKind explicitly).
16027 // FIXME: Consider an alternate location for the test where the inlined()
16028 // state is complete.
16029 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16030 !FD->isInvalidDecl() && !FD->isInlined() &&
16031 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16032 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16033 !FD->isTemplateInstantiation()) {
16034 assert(FD->isThisDeclarationADefinition());
16035 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16036 FD->setInvalidDecl();
16037 }
16038
16039 // Ensure that the function's exception specification is instantiated.
16040 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16041 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16042
16043 // dllimport cannot be applied to non-inline function definitions.
16044 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16045 !FD->isTemplateInstantiation()) {
16046 assert(!FD->hasAttr<DLLExportAttr>());
16047 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16048 FD->setInvalidDecl();
16049 return D;
16050 }
16051
16052 // Some function attributes (like OptimizeNoneAttr) need actions before
16053 // parsing body started.
16054 applyFunctionAttributesBeforeParsingBody(FD: D);
16055
16056 // We want to attach documentation to original Decl (which might be
16057 // a function template).
16058 ActOnDocumentableDecl(D);
16059 if (getCurLexicalContext()->isObjCContainer() &&
16060 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16061 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16062 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16063
16064 maybeAddDeclWithEffects(D: FD);
16065
16066 return D;
16067}
16068
16069void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16070 if (!FD || FD->isInvalidDecl())
16071 return;
16072 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16073 FD = TD->getTemplatedDecl();
16074 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16075 FPOptionsOverride FPO;
16076 FPO.setDisallowOptimizations();
16077 CurFPFeatures.applyChanges(FPO);
16078 FpPragmaStack.CurrentValue =
16079 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16080 }
16081}
16082
16083void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16084 ReturnStmt **Returns = Scope->Returns.data();
16085
16086 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16087 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16088 if (!NRVOCandidate->isNRVOVariable()) {
16089 Diag(Returns[I]->getRetValue()->getExprLoc(),
16090 diag::warn_not_eliding_copy_on_return);
16091 Returns[I]->setNRVOCandidate(nullptr);
16092 }
16093 }
16094 }
16095}
16096
16097bool Sema::canDelayFunctionBody(const Declarator &D) {
16098 // We can't delay parsing the body of a constexpr function template (yet).
16099 if (D.getDeclSpec().hasConstexprSpecifier())
16100 return false;
16101
16102 // We can't delay parsing the body of a function template with a deduced
16103 // return type (yet).
16104 if (D.getDeclSpec().hasAutoTypeSpec()) {
16105 // If the placeholder introduces a non-deduced trailing return type,
16106 // we can still delay parsing it.
16107 if (D.getNumTypeObjects()) {
16108 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16109 if (Outer.Kind == DeclaratorChunk::Function &&
16110 Outer.Fun.hasTrailingReturnType()) {
16111 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16112 return Ty.isNull() || !Ty->isUndeducedType();
16113 }
16114 }
16115 return false;
16116 }
16117
16118 return true;
16119}
16120
16121bool Sema::canSkipFunctionBody(Decl *D) {
16122 // We cannot skip the body of a function (or function template) which is
16123 // constexpr, since we may need to evaluate its body in order to parse the
16124 // rest of the file.
16125 // We cannot skip the body of a function with an undeduced return type,
16126 // because any callers of that function need to know the type.
16127 if (const FunctionDecl *FD = D->getAsFunction()) {
16128 if (FD->isConstexpr())
16129 return false;
16130 // We can't simply call Type::isUndeducedType here, because inside template
16131 // auto can be deduced to a dependent type, which is not considered
16132 // "undeduced".
16133 if (FD->getReturnType()->getContainedDeducedType())
16134 return false;
16135 }
16136 return Consumer.shouldSkipFunctionBody(D);
16137}
16138
16139Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16140 if (!Decl)
16141 return nullptr;
16142 if (FunctionDecl *FD = Decl->getAsFunction())
16143 FD->setHasSkippedBody();
16144 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16145 MD->setHasSkippedBody();
16146 return Decl;
16147}
16148
16149Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
16150 return ActOnFinishFunctionBody(Decl: D, Body: BodyArg, /*IsInstantiation=*/false);
16151}
16152
16153/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16154/// body.
16155class ExitFunctionBodyRAII {
16156public:
16157 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16158 ~ExitFunctionBodyRAII() {
16159 if (!IsLambda)
16160 S.PopExpressionEvaluationContext();
16161 }
16162
16163private:
16164 Sema &S;
16165 bool IsLambda = false;
16166};
16167
16168static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16169 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16170
16171 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16172 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16173 if (!Inserted)
16174 return It->second;
16175
16176 bool R = false;
16177 const BlockDecl *CurBD = BD;
16178
16179 do {
16180 R = !CurBD->doesNotEscape();
16181 if (R)
16182 break;
16183 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16184 } while (CurBD);
16185
16186 return It->second = R;
16187 };
16188
16189 // If the location where 'self' is implicitly retained is inside a escaping
16190 // block, emit a diagnostic.
16191 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16192 S.ImplicitlyRetainedSelfLocs)
16193 if (IsOrNestedInEscapingBlock(P.second))
16194 S.Diag(P.first, diag::warn_implicitly_retains_self)
16195 << FixItHint::CreateInsertion(P.first, "self->");
16196}
16197
16198static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16199 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16200 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16201}
16202
16203bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16204 return methodHasName(FD, Name: "get_return_object");
16205}
16206
16207bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16208 return FD->isStatic() &&
16209 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16210}
16211
16212void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16213 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16214 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16215 return;
16216 // Allow some_promise_type::get_return_object().
16217 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16218 return;
16219 if (!FD->hasAttr<CoroWrapperAttr>())
16220 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16221}
16222
16223Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
16224 bool IsInstantiation) {
16225 FunctionScopeInfo *FSI = getCurFunction();
16226 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16227
16228 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16229 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16230
16231 SourceLocation AnalysisLoc;
16232 if (Body)
16233 AnalysisLoc = Body->getEndLoc();
16234 else if (FD)
16235 AnalysisLoc = FD->getEndLoc();
16236 sema::AnalysisBasedWarnings::Policy WP =
16237 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16238 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16239
16240 // If we skip function body, we can't tell if a function is a coroutine.
16241 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16242 if (FSI->isCoroutine())
16243 CheckCompletedCoroutineBody(FD, Body);
16244 else
16245 CheckCoroutineWrapper(FD);
16246 }
16247
16248 // Diagnose invalid SYCL kernel entry point function declarations
16249 // and build SYCLKernelCallStmts for valid ones.
16250 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16251 SYCLKernelEntryPointAttr *SKEPAttr =
16252 FD->getAttr<SYCLKernelEntryPointAttr>();
16253 if (FD->isDefaulted()) {
16254 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16255 << /*defaulted function*/ 3;
16256 SKEPAttr->setInvalidAttr();
16257 } else if (FD->isDeleted()) {
16258 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16259 << /*deleted function*/ 2;
16260 SKEPAttr->setInvalidAttr();
16261 } else if (FSI->isCoroutine()) {
16262 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16263 << /*coroutine*/ 7;
16264 SKEPAttr->setInvalidAttr();
16265 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16266 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16267 << /*function defined with a function try block*/ 8;
16268 SKEPAttr->setInvalidAttr();
16269 }
16270
16271 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16272 StmtResult SR =
16273 SYCL().BuildSYCLKernelCallStmt(FD, Body: cast<CompoundStmt>(Val: Body));
16274 if (SR.isInvalid())
16275 return nullptr;
16276 Body = SR.get();
16277 }
16278 }
16279
16280 {
16281 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16282 // one is already popped when finishing the lambda in BuildLambdaExpr().
16283 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16284 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16285 if (FD) {
16286 // The function body and the DefaultedOrDeletedInfo, if present, use
16287 // the same storage; don't overwrite the latter if the former is null
16288 // (the body is initialised to null anyway, so even if the latter isn't
16289 // present, this would still be a no-op).
16290 if (Body)
16291 FD->setBody(Body);
16292 FD->setWillHaveBody(false);
16293
16294 if (getLangOpts().CPlusPlus14) {
16295 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16296 FD->getReturnType()->isUndeducedType()) {
16297 // For a function with a deduced result type to return void,
16298 // the result type as written must be 'auto' or 'decltype(auto)',
16299 // possibly cv-qualified or constrained, but not ref-qualified.
16300 if (!FD->getReturnType()->getAs<AutoType>()) {
16301 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16302 << FD->getReturnType();
16303 FD->setInvalidDecl();
16304 } else {
16305 // Falling off the end of the function is the same as 'return;'.
16306 Expr *Dummy = nullptr;
16307 if (DeduceFunctionTypeFromReturnExpr(
16308 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16309 AT: FD->getReturnType()->getAs<AutoType>()))
16310 FD->setInvalidDecl();
16311 }
16312 }
16313 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16314 // In C++11, we don't use 'auto' deduction rules for lambda call
16315 // operators because we don't support return type deduction.
16316 auto *LSI = getCurLambda();
16317 if (LSI->HasImplicitReturnType) {
16318 deduceClosureReturnType(*LSI);
16319
16320 // C++11 [expr.prim.lambda]p4:
16321 // [...] if there are no return statements in the compound-statement
16322 // [the deduced type is] the type void
16323 QualType RetType =
16324 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16325
16326 // Update the return type to the deduced type.
16327 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16328 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16329 EPI: Proto->getExtProtoInfo()));
16330 }
16331 }
16332
16333 // If the function implicitly returns zero (like 'main') or is naked,
16334 // don't complain about missing return statements.
16335 // Clang implicitly returns 0 in C89 mode, but that's considered an
16336 // extension. The check is necessary to ensure the expected extension
16337 // warning is emitted in C89 mode.
16338 if ((FD->hasImplicitReturnZero() &&
16339 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16340 FD->hasAttr<NakedAttr>())
16341 WP.disableCheckFallThrough();
16342
16343 // MSVC permits the use of pure specifier (=0) on function definition,
16344 // defined at class scope, warn about this non-standard construct.
16345 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16346 !FD->isOutOfLine())
16347 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16348
16349 if (!FD->isInvalidDecl()) {
16350 // Don't diagnose unused parameters of defaulted, deleted or naked
16351 // functions.
16352 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16353 !FD->hasAttr<NakedAttr>())
16354 DiagnoseUnusedParameters(Parameters: FD->parameters());
16355 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
16356 FD->getReturnType(), FD);
16357
16358 // If this is a structor, we need a vtable.
16359 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16360 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16361 else if (CXXDestructorDecl *Destructor =
16362 dyn_cast<CXXDestructorDecl>(Val: FD))
16363 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16364
16365 // Try to apply the named return value optimization. We have to check
16366 // if we can do this here because lambdas keep return statements around
16367 // to deduce an implicit return type.
16368 if (FD->getReturnType()->isRecordType() &&
16369 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16370 computeNRVO(Body, Scope: FSI);
16371 }
16372
16373 // GNU warning -Wmissing-prototypes:
16374 // Warn if a global function is defined without a previous
16375 // prototype declaration. This warning is issued even if the
16376 // definition itself provides a prototype. The aim is to detect
16377 // global functions that fail to be declared in header files.
16378 const FunctionDecl *PossiblePrototype = nullptr;
16379 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16380 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16381
16382 if (PossiblePrototype) {
16383 // We found a declaration that is not a prototype,
16384 // but that could be a zero-parameter prototype
16385 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16386 TypeLoc TL = TI->getTypeLoc();
16387 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16388 Diag(PossiblePrototype->getLocation(),
16389 diag::note_declaration_not_a_prototype)
16390 << (FD->getNumParams() != 0)
16391 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16392 FTL.getRParenLoc(), "void")
16393 : FixItHint{});
16394 }
16395 } else {
16396 // Returns true if the token beginning at this Loc is `const`.
16397 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16398 const LangOptions &LangOpts) {
16399 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16400 if (LocInfo.first.isInvalid())
16401 return false;
16402
16403 bool Invalid = false;
16404 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16405 if (Invalid)
16406 return false;
16407
16408 if (LocInfo.second > Buffer.size())
16409 return false;
16410
16411 const char *LexStart = Buffer.data() + LocInfo.second;
16412 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16413
16414 return StartTok.consume_front(Prefix: "const") &&
16415 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16416 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16417 };
16418
16419 auto findBeginLoc = [&]() {
16420 // If the return type has `const` qualifier, we want to insert
16421 // `static` before `const` (and not before the typename).
16422 if ((FD->getReturnType()->isAnyPointerType() &&
16423 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16424 FD->getReturnType().isConstQualified()) {
16425 // But only do this if we can determine where the `const` is.
16426
16427 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16428 getLangOpts()))
16429
16430 return FD->getBeginLoc();
16431 }
16432 return FD->getTypeSpecStartLoc();
16433 };
16434 Diag(FD->getTypeSpecStartLoc(),
16435 diag::note_static_for_internal_linkage)
16436 << /* function */ 1
16437 << (FD->getStorageClass() == SC_None
16438 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16439 : FixItHint{});
16440 }
16441 }
16442
16443 // We might not have found a prototype because we didn't wish to warn on
16444 // the lack of a missing prototype. Try again without the checks for
16445 // whether we want to warn on the missing prototype.
16446 if (!PossiblePrototype)
16447 (void)FindPossiblePrototype(FD, PossiblePrototype);
16448
16449 // If the function being defined does not have a prototype, then we may
16450 // need to diagnose it as changing behavior in C23 because we now know
16451 // whether the function accepts arguments or not. This only handles the
16452 // case where the definition has no prototype but does have parameters
16453 // and either there is no previous potential prototype, or the previous
16454 // potential prototype also has no actual prototype. This handles cases
16455 // like:
16456 // void f(); void f(a) int a; {}
16457 // void g(a) int a; {}
16458 // See MergeFunctionDecl() for other cases of the behavior change
16459 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16460 // type without a prototype.
16461 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16462 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16463 !PossiblePrototype->isImplicit()))) {
16464 // The function definition has parameters, so this will change behavior
16465 // in C23. If there is a possible prototype, it comes before the
16466 // function definition.
16467 // FIXME: The declaration may have already been diagnosed as being
16468 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16469 // there's no way to test for the "changes behavior" condition in
16470 // SemaType.cpp when forming the declaration's function type. So, we do
16471 // this awkward dance instead.
16472 //
16473 // If we have a possible prototype and it declares a function with a
16474 // prototype, we don't want to diagnose it; if we have a possible
16475 // prototype and it has no prototype, it may have already been
16476 // diagnosed in SemaType.cpp as deprecated depending on whether
16477 // -Wstrict-prototypes is enabled. If we already warned about it being
16478 // deprecated, add a note that it also changes behavior. If we didn't
16479 // warn about it being deprecated (because the diagnostic is not
16480 // enabled), warn now that it is deprecated and changes behavior.
16481
16482 // This K&R C function definition definitely changes behavior in C23,
16483 // so diagnose it.
16484 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16485 << /*definition*/ 1 << /* not supported in C23 */ 0;
16486
16487 // If we have a possible prototype for the function which is a user-
16488 // visible declaration, we already tested that it has no prototype.
16489 // This will change behavior in C23. This gets a warning rather than a
16490 // note because it's the same behavior-changing problem as with the
16491 // definition.
16492 if (PossiblePrototype)
16493 Diag(PossiblePrototype->getLocation(),
16494 diag::warn_non_prototype_changes_behavior)
16495 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16496 << /*definition*/ 1;
16497 }
16498
16499 // Warn on CPUDispatch with an actual body.
16500 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16501 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16502 if (!CmpndBody->body_empty())
16503 Diag(CmpndBody->body_front()->getBeginLoc(),
16504 diag::warn_dispatch_body_ignored);
16505
16506 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16507 const CXXMethodDecl *KeyFunction;
16508 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16509 MD->isVirtual() &&
16510 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16511 MD == KeyFunction->getCanonicalDecl()) {
16512 // Update the key-function state if necessary for this ABI.
16513 if (FD->isInlined() &&
16514 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16515 Context.setNonKeyFunction(MD);
16516
16517 // If the newly-chosen key function is already defined, then we
16518 // need to mark the vtable as used retroactively.
16519 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16520 const FunctionDecl *Definition;
16521 if (KeyFunction && KeyFunction->isDefined(Definition))
16522 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16523 } else {
16524 // We just defined they key function; mark the vtable as used.
16525 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16526 }
16527 }
16528 }
16529
16530 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16531 "Function parsing confused");
16532 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16533 assert(MD == getCurMethodDecl() && "Method parsing confused");
16534 MD->setBody(Body);
16535 if (!MD->isInvalidDecl()) {
16536 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16537 MD->getReturnType(), MD);
16538
16539 if (Body)
16540 computeNRVO(Body, Scope: FSI);
16541 }
16542 if (FSI->ObjCShouldCallSuper) {
16543 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16544 << MD->getSelector().getAsString();
16545 FSI->ObjCShouldCallSuper = false;
16546 }
16547 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16548 const ObjCMethodDecl *InitMethod = nullptr;
16549 bool isDesignated =
16550 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16551 assert(isDesignated && InitMethod);
16552 (void)isDesignated;
16553
16554 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16555 auto IFace = MD->getClassInterface();
16556 if (!IFace)
16557 return false;
16558 auto SuperD = IFace->getSuperClass();
16559 if (!SuperD)
16560 return false;
16561 return SuperD->getIdentifier() ==
16562 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16563 };
16564 // Don't issue this warning for unavailable inits or direct subclasses
16565 // of NSObject.
16566 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16567 Diag(MD->getLocation(),
16568 diag::warn_objc_designated_init_missing_super_call);
16569 Diag(InitMethod->getLocation(),
16570 diag::note_objc_designated_init_marked_here);
16571 }
16572 FSI->ObjCWarnForNoDesignatedInitChain = false;
16573 }
16574 if (FSI->ObjCWarnForNoInitDelegation) {
16575 // Don't issue this warning for unavailable inits.
16576 if (!MD->isUnavailable())
16577 Diag(MD->getLocation(),
16578 diag::warn_objc_secondary_init_missing_init_call);
16579 FSI->ObjCWarnForNoInitDelegation = false;
16580 }
16581
16582 diagnoseImplicitlyRetainedSelf(S&: *this);
16583 } else {
16584 // Parsing the function declaration failed in some way. Pop the fake scope
16585 // we pushed on.
16586 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16587 return nullptr;
16588 }
16589
16590 if (Body && FSI->HasPotentialAvailabilityViolations)
16591 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16592
16593 assert(!FSI->ObjCShouldCallSuper &&
16594 "This should only be set for ObjC methods, which should have been "
16595 "handled in the block above.");
16596
16597 // Verify and clean out per-function state.
16598 if (Body && (!FD || !FD->isDefaulted())) {
16599 // C++ constructors that have function-try-blocks can't have return
16600 // statements in the handlers of that block. (C++ [except.handle]p14)
16601 // Verify this.
16602 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16603 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16604
16605 // Verify that gotos and switch cases don't jump into scopes illegally.
16606 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16607 DiagnoseInvalidJumps(Body);
16608
16609 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16610 if (!Destructor->getParent()->isDependentType())
16611 CheckDestructor(Destructor);
16612
16613 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16614 Record: Destructor->getParent());
16615 }
16616
16617 // If any errors have occurred, clear out any temporaries that may have
16618 // been leftover. This ensures that these temporaries won't be picked up
16619 // for deletion in some later function.
16620 if (hasUncompilableErrorOccurred() ||
16621 hasAnyUnrecoverableErrorsInThisFunction() ||
16622 getDiagnostics().getSuppressAllDiagnostics()) {
16623 DiscardCleanupsInEvaluationContext();
16624 }
16625 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16626 // Since the body is valid, issue any analysis-based warnings that are
16627 // enabled.
16628 ActivePolicy = &WP;
16629 }
16630
16631 if (!IsInstantiation && FD &&
16632 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16633 !FD->isInvalidDecl() &&
16634 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16635 FD->setInvalidDecl();
16636
16637 if (FD && FD->hasAttr<NakedAttr>()) {
16638 for (const Stmt *S : Body->children()) {
16639 // Allow local register variables without initializer as they don't
16640 // require prologue.
16641 bool RegisterVariables = false;
16642 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16643 for (const auto *Decl : DS->decls()) {
16644 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16645 RegisterVariables =
16646 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16647 if (!RegisterVariables)
16648 break;
16649 }
16650 }
16651 }
16652 if (RegisterVariables)
16653 continue;
16654 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16655 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16656 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16657 FD->setInvalidDecl();
16658 break;
16659 }
16660 }
16661 }
16662
16663 assert(ExprCleanupObjects.size() ==
16664 ExprEvalContexts.back().NumCleanupObjects &&
16665 "Leftover temporaries in function");
16666 assert(!Cleanup.exprNeedsCleanups() &&
16667 "Unaccounted cleanups in function");
16668 assert(MaybeODRUseExprs.empty() &&
16669 "Leftover expressions for odr-use checking");
16670 }
16671 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16672 // the declaration context below. Otherwise, we're unable to transform
16673 // 'this' expressions when transforming immediate context functions.
16674
16675 if (FD)
16676 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
16677
16678 if (!IsInstantiation)
16679 PopDeclContext();
16680
16681 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16682 // If any errors have occurred, clear out any temporaries that may have
16683 // been leftover. This ensures that these temporaries won't be picked up for
16684 // deletion in some later function.
16685 if (hasUncompilableErrorOccurred()) {
16686 DiscardCleanupsInEvaluationContext();
16687 }
16688
16689 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16690 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16691 auto ES = getEmissionStatus(Decl: FD);
16692 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16693 ES == Sema::FunctionEmissionStatus::Unknown)
16694 DeclsToCheckForDeferredDiags.insert(FD);
16695 }
16696
16697 if (FD && !FD->isDeleted())
16698 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16699
16700 return dcl;
16701}
16702
16703/// When we finish delayed parsing of an attribute, we must attach it to the
16704/// relevant Decl.
16705void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16706 ParsedAttributes &Attrs) {
16707 // Always attach attributes to the underlying decl.
16708 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
16709 D = TD->getTemplatedDecl();
16710 ProcessDeclAttributeList(S, D, AttrList: Attrs);
16711 ProcessAPINotes(D);
16712
16713 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
16714 if (Method->isStatic())
16715 checkThisInStaticMemberFunctionAttributes(Method);
16716}
16717
16718NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16719 IdentifierInfo &II, Scope *S) {
16720 // It is not valid to implicitly define a function in C23.
16721 assert(LangOpts.implicitFunctionsAllowed() &&
16722 "Implicit function declarations aren't allowed in this language mode");
16723
16724 // Find the scope in which the identifier is injected and the corresponding
16725 // DeclContext.
16726 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16727 // In that case, we inject the declaration into the translation unit scope
16728 // instead.
16729 Scope *BlockScope = S;
16730 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16731 BlockScope = BlockScope->getParent();
16732
16733 // Loop until we find a DeclContext that is either a function/method or the
16734 // translation unit, which are the only two valid places to implicitly define
16735 // a function. This avoids accidentally defining the function within a tag
16736 // declaration, for example.
16737 Scope *ContextScope = BlockScope;
16738 while (!ContextScope->getEntity() ||
16739 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16740 !ContextScope->getEntity()->isTranslationUnit()))
16741 ContextScope = ContextScope->getParent();
16742 ContextRAII SavedContext(*this, ContextScope->getEntity());
16743
16744 // Before we produce a declaration for an implicitly defined
16745 // function, see whether there was a locally-scoped declaration of
16746 // this name as a function or variable. If so, use that
16747 // (non-visible) declaration, and complain about it.
16748 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
16749 if (ExternCPrev) {
16750 // We still need to inject the function into the enclosing block scope so
16751 // that later (non-call) uses can see it.
16752 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
16753
16754 // C89 footnote 38:
16755 // If in fact it is not defined as having type "function returning int",
16756 // the behavior is undefined.
16757 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
16758 !Context.typesAreCompatible(
16759 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
16760 T2: Context.getFunctionNoProtoType(Context.IntTy))) {
16761 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16762 << ExternCPrev << !getLangOpts().C99;
16763 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16764 return ExternCPrev;
16765 }
16766 }
16767
16768 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16769 unsigned diag_id;
16770 if (II.getName().starts_with("__builtin_"))
16771 diag_id = diag::warn_builtin_unknown;
16772 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16773 else if (getLangOpts().C99)
16774 diag_id = diag::ext_implicit_function_decl_c99;
16775 else
16776 diag_id = diag::warn_implicit_function_decl;
16777
16778 TypoCorrection Corrected;
16779 // Because typo correction is expensive, only do it if the implicit
16780 // function declaration is going to be treated as an error.
16781 //
16782 // Perform the correction before issuing the main diagnostic, as some
16783 // consumers use typo-correction callbacks to enhance the main diagnostic.
16784 if (S && !ExternCPrev &&
16785 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
16786 DeclFilterCCC<FunctionDecl> CCC{};
16787 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
16788 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
16789 }
16790
16791 Diag(Loc, diag_id) << &II;
16792 if (Corrected) {
16793 // If the correction is going to suggest an implicitly defined function,
16794 // skip the correction as not being a particularly good idea.
16795 bool Diagnose = true;
16796 if (const auto *D = Corrected.getCorrectionDecl())
16797 Diagnose = !D->isImplicit();
16798 if (Diagnose)
16799 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16800 /*ErrorRecovery*/ false);
16801 }
16802
16803 // If we found a prior declaration of this function, don't bother building
16804 // another one. We've already pushed that one into scope, so there's nothing
16805 // more to do.
16806 if (ExternCPrev)
16807 return ExternCPrev;
16808
16809 // Set a Declarator for the implicit definition: int foo();
16810 const char *Dummy;
16811 AttributeFactory attrFactory;
16812 DeclSpec DS(attrFactory);
16813 unsigned DiagID;
16814 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
16815 Policy: Context.getPrintingPolicy());
16816 (void)Error; // Silence warning.
16817 assert(!Error && "Error setting up implicit decl!");
16818 SourceLocation NoLoc;
16819 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16820 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
16821 /*IsAmbiguous=*/false,
16822 /*LParenLoc=*/NoLoc,
16823 /*Params=*/nullptr,
16824 /*NumParams=*/0,
16825 /*EllipsisLoc=*/NoLoc,
16826 /*RParenLoc=*/NoLoc,
16827 /*RefQualifierIsLvalueRef=*/true,
16828 /*RefQualifierLoc=*/NoLoc,
16829 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
16830 /*ESpecRange=*/SourceRange(),
16831 /*Exceptions=*/nullptr,
16832 /*ExceptionRanges=*/nullptr,
16833 /*NumExceptions=*/0,
16834 /*NoexceptExpr=*/nullptr,
16835 /*ExceptionSpecTokens=*/nullptr,
16836 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
16837 TheDeclarator&: D),
16838 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
16839 D.SetIdentifier(Id: &II, IdLoc: Loc);
16840
16841 // Insert this function into the enclosing block scope.
16842 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
16843 FD->setImplicit();
16844
16845 AddKnownFunctionAttributes(FD);
16846
16847 return FD;
16848}
16849
16850void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16851 FunctionDecl *FD) {
16852 if (FD->isInvalidDecl())
16853 return;
16854
16855 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16856 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16857 return;
16858
16859 UnsignedOrNone AlignmentParam = std::nullopt;
16860 bool IsNothrow = false;
16861 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
16862 return;
16863
16864 // C++2a [basic.stc.dynamic.allocation]p4:
16865 // An allocation function that has a non-throwing exception specification
16866 // indicates failure by returning a null pointer value. Any other allocation
16867 // function never returns a null pointer value and indicates failure only by
16868 // throwing an exception [...]
16869 //
16870 // However, -fcheck-new invalidates this possible assumption, so don't add
16871 // NonNull when that is enabled.
16872 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16873 !getLangOpts().CheckNew)
16874 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16875
16876 // C++2a [basic.stc.dynamic.allocation]p2:
16877 // An allocation function attempts to allocate the requested amount of
16878 // storage. [...] If the request succeeds, the value returned by a
16879 // replaceable allocation function is a [...] pointer value p0 different
16880 // from any previously returned value p1 [...]
16881 //
16882 // However, this particular information is being added in codegen,
16883 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16884
16885 // C++2a [basic.stc.dynamic.allocation]p2:
16886 // An allocation function attempts to allocate the requested amount of
16887 // storage. If it is successful, it returns the address of the start of a
16888 // block of storage whose length in bytes is at least as large as the
16889 // requested size.
16890 if (!FD->hasAttr<AllocSizeAttr>()) {
16891 FD->addAttr(AllocSizeAttr::CreateImplicit(
16892 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16893 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16894 }
16895
16896 // C++2a [basic.stc.dynamic.allocation]p3:
16897 // For an allocation function [...], the pointer returned on a successful
16898 // call shall represent the address of storage that is aligned as follows:
16899 // (3.1) If the allocation function takes an argument of type
16900 // std​::​align_­val_­t, the storage will have the alignment
16901 // specified by the value of this argument.
16902 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16903 FD->addAttr(AllocAlignAttr::CreateImplicit(
16904 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16905 }
16906
16907 // FIXME:
16908 // C++2a [basic.stc.dynamic.allocation]p3:
16909 // For an allocation function [...], the pointer returned on a successful
16910 // call shall represent the address of storage that is aligned as follows:
16911 // (3.2) Otherwise, if the allocation function is named operator new[],
16912 // the storage is aligned for any object that does not have
16913 // new-extended alignment ([basic.align]) and is no larger than the
16914 // requested size.
16915 // (3.3) Otherwise, the storage is aligned for any object that does not
16916 // have new-extended alignment and is of the requested size.
16917}
16918
16919void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16920 if (FD->isInvalidDecl())
16921 return;
16922
16923 // If this is a built-in function, map its builtin attributes to
16924 // actual attributes.
16925 if (unsigned BuiltinID = FD->getBuiltinID()) {
16926 // Handle printf-formatting attributes.
16927 unsigned FormatIdx;
16928 bool HasVAListArg;
16929 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
16930 if (!FD->hasAttr<FormatAttr>()) {
16931 const char *fmt = "printf";
16932 unsigned int NumParams = FD->getNumParams();
16933 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16934 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
16935 fmt = "NSString";
16936 FD->addAttr(FormatAttr::CreateImplicit(Context,
16937 &Context.Idents.get(fmt),
16938 FormatIdx+1,
16939 HasVAListArg ? 0 : FormatIdx+2,
16940 FD->getLocation()));
16941 }
16942 }
16943 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
16944 HasVAListArg)) {
16945 if (!FD->hasAttr<FormatAttr>())
16946 FD->addAttr(FormatAttr::CreateImplicit(Context,
16947 &Context.Idents.get("scanf"),
16948 FormatIdx+1,
16949 HasVAListArg ? 0 : FormatIdx+2,
16950 FD->getLocation()));
16951 }
16952
16953 // Handle automatically recognized callbacks.
16954 SmallVector<int, 4> Encoding;
16955 if (!FD->hasAttr<CallbackAttr>() &&
16956 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16957 FD->addAttr(CallbackAttr::CreateImplicit(
16958 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16959
16960 // Mark const if we don't care about errno and/or floating point exceptions
16961 // that are the only thing preventing the function from being const. This
16962 // allows IRgen to use LLVM intrinsics for such functions.
16963 bool NoExceptions =
16964 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16965 bool ConstWithoutErrnoAndExceptions =
16966 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
16967 bool ConstWithoutExceptions =
16968 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
16969 if (!FD->hasAttr<ConstAttr>() &&
16970 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16971 (!ConstWithoutErrnoAndExceptions ||
16972 (!getLangOpts().MathErrno && NoExceptions)) &&
16973 (!ConstWithoutExceptions || NoExceptions))
16974 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16975
16976 // We make "fma" on GNU or Windows const because we know it does not set
16977 // errno in those environments even though it could set errno based on the
16978 // C standard.
16979 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16980 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16981 !FD->hasAttr<ConstAttr>()) {
16982 switch (BuiltinID) {
16983 case Builtin::BI__builtin_fma:
16984 case Builtin::BI__builtin_fmaf:
16985 case Builtin::BI__builtin_fmal:
16986 case Builtin::BIfma:
16987 case Builtin::BIfmaf:
16988 case Builtin::BIfmal:
16989 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16990 break;
16991 default:
16992 break;
16993 }
16994 }
16995
16996 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16997 !FD->hasAttr<ReturnsTwiceAttr>())
16998 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16999 FD->getLocation()));
17000 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17001 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17002 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17003 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17004 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17005 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17006 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17007 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17008 // Add the appropriate attribute, depending on the CUDA compilation mode
17009 // and which target the builtin belongs to. For example, during host
17010 // compilation, aux builtins are __device__, while the rest are __host__.
17011 if (getLangOpts().CUDAIsDevice !=
17012 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17013 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17014 else
17015 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17016 }
17017
17018 // Add known guaranteed alignment for allocation functions.
17019 switch (BuiltinID) {
17020 case Builtin::BImemalign:
17021 case Builtin::BIaligned_alloc:
17022 if (!FD->hasAttr<AllocAlignAttr>())
17023 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17024 FD->getLocation()));
17025 break;
17026 default:
17027 break;
17028 }
17029
17030 // Add allocsize attribute for allocation functions.
17031 switch (BuiltinID) {
17032 case Builtin::BIcalloc:
17033 FD->addAttr(AllocSizeAttr::CreateImplicit(
17034 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17035 break;
17036 case Builtin::BImemalign:
17037 case Builtin::BIaligned_alloc:
17038 case Builtin::BIrealloc:
17039 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17040 ParamIdx(), FD->getLocation()));
17041 break;
17042 case Builtin::BImalloc:
17043 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17044 ParamIdx(), FD->getLocation()));
17045 break;
17046 default:
17047 break;
17048 }
17049 }
17050
17051 LazyProcessLifetimeCaptureByParams(FD);
17052 inferLifetimeBoundAttribute(FD);
17053 inferLifetimeCaptureByAttribute(FD);
17054 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17055
17056 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17057 // throw, add an implicit nothrow attribute to any extern "C" function we come
17058 // across.
17059 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17060 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17061 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17062 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17063 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17064 }
17065
17066 IdentifierInfo *Name = FD->getIdentifier();
17067 if (!Name)
17068 return;
17069 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17070 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
17071 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17072 LinkageSpecLanguageIDs::C)) {
17073 // Okay: this could be a libc/libm/Objective-C function we know
17074 // about.
17075 } else
17076 return;
17077
17078 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17079 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17080 // target-specific builtins, perhaps?
17081 if (!FD->hasAttr<FormatAttr>())
17082 FD->addAttr(FormatAttr::CreateImplicit(Context,
17083 &Context.Idents.get("printf"), 2,
17084 Name->isStr("vasprintf") ? 0 : 3,
17085 FD->getLocation()));
17086 }
17087
17088 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17089 // We already have a __builtin___CFStringMakeConstantString,
17090 // but builds that use -fno-constant-cfstrings don't go through that.
17091 if (!FD->hasAttr<FormatArgAttr>())
17092 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17093 FD->getLocation()));
17094 }
17095}
17096
17097TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17098 TypeSourceInfo *TInfo) {
17099 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17100 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17101
17102 if (!TInfo) {
17103 assert(D.isInvalidType() && "no declarator info for valid type");
17104 TInfo = Context.getTrivialTypeSourceInfo(T);
17105 }
17106
17107 // Scope manipulation handled by caller.
17108 TypedefDecl *NewTD =
17109 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17110 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17111
17112 // Bail out immediately if we have an invalid declaration.
17113 if (D.isInvalidType()) {
17114 NewTD->setInvalidDecl();
17115 return NewTD;
17116 }
17117
17118 if (D.getDeclSpec().isModulePrivateSpecified()) {
17119 if (CurContext->isFunctionOrMethod())
17120 Diag(NewTD->getLocation(), diag::err_module_private_local)
17121 << 2 << NewTD
17122 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17123 << FixItHint::CreateRemoval(
17124 D.getDeclSpec().getModulePrivateSpecLoc());
17125 else
17126 NewTD->setModulePrivate();
17127 }
17128
17129 // C++ [dcl.typedef]p8:
17130 // If the typedef declaration defines an unnamed class (or
17131 // enum), the first typedef-name declared by the declaration
17132 // to be that class type (or enum type) is used to denote the
17133 // class type (or enum type) for linkage purposes only.
17134 // We need to check whether the type was declared in the declaration.
17135 switch (D.getDeclSpec().getTypeSpecType()) {
17136 case TST_enum:
17137 case TST_struct:
17138 case TST_interface:
17139 case TST_union:
17140 case TST_class: {
17141 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17142 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17143 break;
17144 }
17145
17146 default:
17147 break;
17148 }
17149
17150 return NewTD;
17151}
17152
17153bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17154 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17155 QualType T = TI->getType();
17156
17157 if (T->isDependentType())
17158 return false;
17159
17160 // This doesn't use 'isIntegralType' despite the error message mentioning
17161 // integral type because isIntegralType would also allow enum types in C.
17162 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17163 if (BT->isInteger())
17164 return false;
17165
17166 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17167 << T << T->isBitIntType();
17168}
17169
17170bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17171 QualType EnumUnderlyingTy, bool IsFixed,
17172 const EnumDecl *Prev) {
17173 if (IsScoped != Prev->isScoped()) {
17174 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17175 << Prev->isScoped();
17176 Diag(Prev->getLocation(), diag::note_previous_declaration);
17177 return true;
17178 }
17179
17180 if (IsFixed && Prev->isFixed()) {
17181 if (!EnumUnderlyingTy->isDependentType() &&
17182 !Prev->getIntegerType()->isDependentType() &&
17183 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17184 T2: Prev->getIntegerType())) {
17185 // TODO: Highlight the underlying type of the redeclaration.
17186 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17187 << EnumUnderlyingTy << Prev->getIntegerType();
17188 Diag(Prev->getLocation(), diag::note_previous_declaration)
17189 << Prev->getIntegerTypeRange();
17190 return true;
17191 }
17192 } else if (IsFixed != Prev->isFixed()) {
17193 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17194 << Prev->isFixed();
17195 Diag(Prev->getLocation(), diag::note_previous_declaration);
17196 return true;
17197 }
17198
17199 return false;
17200}
17201
17202/// Get diagnostic %select index for tag kind for
17203/// redeclaration diagnostic message.
17204/// WARNING: Indexes apply to particular diagnostics only!
17205///
17206/// \returns diagnostic %select index.
17207static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17208 switch (Tag) {
17209 case TagTypeKind::Struct:
17210 return 0;
17211 case TagTypeKind::Interface:
17212 return 1;
17213 case TagTypeKind::Class:
17214 return 2;
17215 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17216 }
17217}
17218
17219/// Determine if tag kind is a class-key compatible with
17220/// class for redeclaration (class, struct, or __interface).
17221///
17222/// \returns true iff the tag kind is compatible.
17223static bool isClassCompatTagKind(TagTypeKind Tag)
17224{
17225 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17226 Tag == TagTypeKind::Interface;
17227}
17228
17229NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17230 if (isa<TypedefDecl>(Val: PrevDecl))
17231 return NonTagKind::Typedef;
17232 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17233 return NonTagKind::TypeAlias;
17234 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17235 return NonTagKind::Template;
17236 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17237 return NonTagKind::TypeAliasTemplate;
17238 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17239 return NonTagKind::TemplateTemplateArgument;
17240 switch (TTK) {
17241 case TagTypeKind::Struct:
17242 case TagTypeKind::Interface:
17243 case TagTypeKind::Class:
17244 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17245 : NonTagKind::NonStruct;
17246 case TagTypeKind::Union:
17247 return NonTagKind::NonUnion;
17248 case TagTypeKind::Enum:
17249 return NonTagKind::NonEnum;
17250 }
17251 llvm_unreachable("invalid TTK");
17252}
17253
17254bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17255 TagTypeKind NewTag, bool isDefinition,
17256 SourceLocation NewTagLoc,
17257 const IdentifierInfo *Name) {
17258 // C++ [dcl.type.elab]p3:
17259 // The class-key or enum keyword present in the
17260 // elaborated-type-specifier shall agree in kind with the
17261 // declaration to which the name in the elaborated-type-specifier
17262 // refers. This rule also applies to the form of
17263 // elaborated-type-specifier that declares a class-name or
17264 // friend class since it can be construed as referring to the
17265 // definition of the class. Thus, in any
17266 // elaborated-type-specifier, the enum keyword shall be used to
17267 // refer to an enumeration (7.2), the union class-key shall be
17268 // used to refer to a union (clause 9), and either the class or
17269 // struct class-key shall be used to refer to a class (clause 9)
17270 // declared using the class or struct class-key.
17271 TagTypeKind OldTag = Previous->getTagKind();
17272 if (OldTag != NewTag &&
17273 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17274 return false;
17275
17276 // Tags are compatible, but we might still want to warn on mismatched tags.
17277 // Non-class tags can't be mismatched at this point.
17278 if (!isClassCompatTagKind(Tag: NewTag))
17279 return true;
17280
17281 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17282 // by our warning analysis. We don't want to warn about mismatches with (eg)
17283 // declarations in system headers that are designed to be specialized, but if
17284 // a user asks us to warn, we should warn if their code contains mismatched
17285 // declarations.
17286 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17287 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17288 Loc);
17289 };
17290 if (IsIgnoredLoc(NewTagLoc))
17291 return true;
17292
17293 auto IsIgnored = [&](const TagDecl *Tag) {
17294 return IsIgnoredLoc(Tag->getLocation());
17295 };
17296 while (IsIgnored(Previous)) {
17297 Previous = Previous->getPreviousDecl();
17298 if (!Previous)
17299 return true;
17300 OldTag = Previous->getTagKind();
17301 }
17302
17303 bool isTemplate = false;
17304 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17305 isTemplate = Record->getDescribedClassTemplate();
17306
17307 if (inTemplateInstantiation()) {
17308 if (OldTag != NewTag) {
17309 // In a template instantiation, do not offer fix-its for tag mismatches
17310 // since they usually mess up the template instead of fixing the problem.
17311 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17312 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17313 << getRedeclDiagFromTagKind(OldTag);
17314 // FIXME: Note previous location?
17315 }
17316 return true;
17317 }
17318
17319 if (isDefinition) {
17320 // On definitions, check all previous tags and issue a fix-it for each
17321 // one that doesn't match the current tag.
17322 if (Previous->getDefinition()) {
17323 // Don't suggest fix-its for redefinitions.
17324 return true;
17325 }
17326
17327 bool previousMismatch = false;
17328 for (const TagDecl *I : Previous->redecls()) {
17329 if (I->getTagKind() != NewTag) {
17330 // Ignore previous declarations for which the warning was disabled.
17331 if (IsIgnored(I))
17332 continue;
17333
17334 if (!previousMismatch) {
17335 previousMismatch = true;
17336 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17337 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17338 << getRedeclDiagFromTagKind(I->getTagKind());
17339 }
17340 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17341 << getRedeclDiagFromTagKind(NewTag)
17342 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17343 TypeWithKeyword::getTagTypeKindName(NewTag));
17344 }
17345 }
17346 return true;
17347 }
17348
17349 // Identify the prevailing tag kind: this is the kind of the definition (if
17350 // there is a non-ignored definition), or otherwise the kind of the prior
17351 // (non-ignored) declaration.
17352 const TagDecl *PrevDef = Previous->getDefinition();
17353 if (PrevDef && IsIgnored(PrevDef))
17354 PrevDef = nullptr;
17355 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17356 if (Redecl->getTagKind() != NewTag) {
17357 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17358 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17359 << getRedeclDiagFromTagKind(OldTag);
17360 Diag(Redecl->getLocation(), diag::note_previous_use);
17361
17362 // If there is a previous definition, suggest a fix-it.
17363 if (PrevDef) {
17364 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17365 << getRedeclDiagFromTagKind(Redecl->getTagKind())
17366 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
17367 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
17368 }
17369 }
17370
17371 return true;
17372}
17373
17374/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17375/// from an outer enclosing namespace or file scope inside a friend declaration.
17376/// This should provide the commented out code in the following snippet:
17377/// namespace N {
17378/// struct X;
17379/// namespace M {
17380/// struct Y { friend struct /*N::*/ X; };
17381/// }
17382/// }
17383static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17384 SourceLocation NameLoc) {
17385 // While the decl is in a namespace, do repeated lookup of that name and see
17386 // if we get the same namespace back. If we do not, continue until
17387 // translation unit scope, at which point we have a fully qualified NNS.
17388 SmallVector<IdentifierInfo *, 4> Namespaces;
17389 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17390 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17391 // This tag should be declared in a namespace, which can only be enclosed by
17392 // other namespaces. Bail if there's an anonymous namespace in the chain.
17393 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17394 if (!Namespace || Namespace->isAnonymousNamespace())
17395 return FixItHint();
17396 IdentifierInfo *II = Namespace->getIdentifier();
17397 Namespaces.push_back(Elt: II);
17398 NamedDecl *Lookup = SemaRef.LookupSingleName(
17399 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17400 if (Lookup == Namespace)
17401 break;
17402 }
17403
17404 // Once we have all the namespaces, reverse them to go outermost first, and
17405 // build an NNS.
17406 SmallString<64> Insertion;
17407 llvm::raw_svector_ostream OS(Insertion);
17408 if (DC->isTranslationUnit())
17409 OS << "::";
17410 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17411 for (auto *II : Namespaces)
17412 OS << II->getName() << "::";
17413 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17414}
17415
17416/// Determine whether a tag originally declared in context \p OldDC can
17417/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17418/// found a declaration in \p OldDC as a previous decl, perhaps through a
17419/// using-declaration).
17420static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17421 DeclContext *NewDC) {
17422 OldDC = OldDC->getRedeclContext();
17423 NewDC = NewDC->getRedeclContext();
17424
17425 if (OldDC->Equals(DC: NewDC))
17426 return true;
17427
17428 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17429 // encloses the other).
17430 if (S.getLangOpts().MSVCCompat &&
17431 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17432 return true;
17433
17434 return false;
17435}
17436
17437DeclResult
17438Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17439 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17440 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17441 SourceLocation ModulePrivateLoc,
17442 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17443 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17444 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17445 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17446 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17447 // If this is not a definition, it must have a name.
17448 IdentifierInfo *OrigName = Name;
17449 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17450 "Nameless record must be a definition!");
17451 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17452
17453 OwnedDecl = false;
17454 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17455 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17456
17457 // FIXME: Check member specializations more carefully.
17458 bool isMemberSpecialization = false;
17459 bool Invalid = false;
17460
17461 // We only need to do this matching if we have template parameters
17462 // or a scope specifier, which also conveniently avoids this work
17463 // for non-C++ cases.
17464 if (TemplateParameterLists.size() > 0 ||
17465 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17466 TemplateParameterList *TemplateParams =
17467 MatchTemplateParametersToScopeSpecifier(
17468 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17469 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17470
17471 // C++23 [dcl.type.elab] p2:
17472 // If an elaborated-type-specifier is the sole constituent of a
17473 // declaration, the declaration is ill-formed unless it is an explicit
17474 // specialization, an explicit instantiation or it has one of the
17475 // following forms: [...]
17476 // C++23 [dcl.enum] p1:
17477 // If the enum-head-name of an opaque-enum-declaration contains a
17478 // nested-name-specifier, the declaration shall be an explicit
17479 // specialization.
17480 //
17481 // FIXME: Class template partial specializations can be forward declared
17482 // per CWG2213, but the resolution failed to allow qualified forward
17483 // declarations. This is almost certainly unintentional, so we allow them.
17484 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17485 !isMemberSpecialization)
17486 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17487 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17488
17489 if (TemplateParams) {
17490 if (Kind == TagTypeKind::Enum) {
17491 Diag(KWLoc, diag::err_enum_template);
17492 return true;
17493 }
17494
17495 if (TemplateParams->size() > 0) {
17496 // This is a declaration or definition of a class template (which may
17497 // be a member of another template).
17498
17499 if (Invalid)
17500 return true;
17501
17502 OwnedDecl = false;
17503 DeclResult Result = CheckClassTemplate(
17504 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17505 AS, ModulePrivateLoc,
17506 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17507 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17508 return Result.get();
17509 } else {
17510 // The "template<>" header is extraneous.
17511 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17512 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17513 isMemberSpecialization = true;
17514 }
17515 }
17516
17517 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17518 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17519 return true;
17520 }
17521
17522 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17523 // C++23 [dcl.type.elab]p4:
17524 // If an elaborated-type-specifier appears with the friend specifier as
17525 // an entire member-declaration, the member-declaration shall have one
17526 // of the following forms:
17527 // friend class-key nested-name-specifier(opt) identifier ;
17528 // friend class-key simple-template-id ;
17529 // friend class-key nested-name-specifier template(opt)
17530 // simple-template-id ;
17531 //
17532 // Since enum is not a class-key, so declarations like "friend enum E;"
17533 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17534 // invalid, most implementations accept so we issue a pedantic warning.
17535 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17536 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17537 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17538 Diag(KWLoc, diag::note_enum_friend)
17539 << (ScopedEnum + ScopedEnumUsesClassTag);
17540 }
17541
17542 // Figure out the underlying type if this a enum declaration. We need to do
17543 // this early, because it's needed to detect if this is an incompatible
17544 // redeclaration.
17545 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17546 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17547
17548 if (Kind == TagTypeKind::Enum) {
17549 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17550 // No underlying type explicitly specified, or we failed to parse the
17551 // type, default to int.
17552 EnumUnderlying = Context.IntTy.getTypePtr();
17553 } else if (UnderlyingType.get()) {
17554 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17555 // integral type; any cv-qualification is ignored.
17556 TypeSourceInfo *TI = nullptr;
17557 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17558 EnumUnderlying = TI;
17559
17560 if (CheckEnumUnderlyingType(TI))
17561 // Recover by falling back to int.
17562 EnumUnderlying = Context.IntTy.getTypePtr();
17563
17564 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17565 UPPC: UPPC_FixedUnderlyingType))
17566 EnumUnderlying = Context.IntTy.getTypePtr();
17567
17568 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17569 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17570 // of 'int'. However, if this is an unfixed forward declaration, don't set
17571 // the underlying type unless the user enables -fms-compatibility. This
17572 // makes unfixed forward declared enums incomplete and is more conforming.
17573 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17574 EnumUnderlying = Context.IntTy.getTypePtr();
17575 }
17576 }
17577
17578 DeclContext *SearchDC = CurContext;
17579 DeclContext *DC = CurContext;
17580 bool isStdBadAlloc = false;
17581 bool isStdAlignValT = false;
17582
17583 RedeclarationKind Redecl = forRedeclarationInCurContext();
17584 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17585 Redecl = RedeclarationKind::NotForRedeclaration;
17586
17587 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17588 /// implemented asks for structural equivalence checking, the returned decl
17589 /// here is passed back to the parser, allowing the tag body to be parsed.
17590 auto createTagFromNewDecl = [&]() -> TagDecl * {
17591 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17592 // If there is an identifier, use the location of the identifier as the
17593 // location of the decl, otherwise use the location of the struct/union
17594 // keyword.
17595 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17596 TagDecl *New = nullptr;
17597
17598 if (Kind == TagTypeKind::Enum) {
17599 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17600 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17601 // If this is an undefined enum, bail.
17602 if (TUK != TagUseKind::Definition && !Invalid)
17603 return nullptr;
17604 if (EnumUnderlying) {
17605 EnumDecl *ED = cast<EnumDecl>(Val: New);
17606 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
17607 ED->setIntegerTypeSourceInfo(TI);
17608 else
17609 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
17610 QualType EnumTy = ED->getIntegerType();
17611 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17612 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17613 : EnumTy);
17614 }
17615 } else { // struct/union
17616 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17617 PrevDecl: nullptr);
17618 }
17619
17620 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17621 // Add alignment attributes if necessary; these attributes are checked
17622 // when the ASTContext lays out the structure.
17623 //
17624 // It is important for implementing the correct semantics that this
17625 // happen here (in ActOnTag). The #pragma pack stack is
17626 // maintained as a result of parser callbacks which can occur at
17627 // many points during the parsing of a struct declaration (because
17628 // the #pragma tokens are effectively skipped over during the
17629 // parsing of the struct).
17630 if (TUK == TagUseKind::Definition &&
17631 (!SkipBody || !SkipBody->ShouldSkip)) {
17632 if (LangOpts.HLSL)
17633 RD->addAttr(PackedAttr::CreateImplicit(Context));
17634 AddAlignmentAttributesForRecord(RD);
17635 AddMsStructLayoutForRecord(RD);
17636 }
17637 }
17638 New->setLexicalDeclContext(CurContext);
17639 return New;
17640 };
17641
17642 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17643 if (Name && SS.isNotEmpty()) {
17644 // We have a nested-name tag ('struct foo::bar').
17645
17646 // Check for invalid 'foo::'.
17647 if (SS.isInvalid()) {
17648 Name = nullptr;
17649 goto CreateNewDecl;
17650 }
17651
17652 // If this is a friend or a reference to a class in a dependent
17653 // context, don't try to make a decl for it.
17654 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17655 DC = computeDeclContext(SS, EnteringContext: false);
17656 if (!DC) {
17657 IsDependent = true;
17658 return true;
17659 }
17660 } else {
17661 DC = computeDeclContext(SS, EnteringContext: true);
17662 if (!DC) {
17663 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17664 << SS.getRange();
17665 return true;
17666 }
17667 }
17668
17669 if (RequireCompleteDeclContext(SS, DC))
17670 return true;
17671
17672 SearchDC = DC;
17673 // Look-up name inside 'foo::'.
17674 LookupQualifiedName(R&: Previous, LookupCtx: DC);
17675
17676 if (Previous.isAmbiguous())
17677 return true;
17678
17679 if (Previous.empty()) {
17680 // Name lookup did not find anything. However, if the
17681 // nested-name-specifier refers to the current instantiation,
17682 // and that current instantiation has any dependent base
17683 // classes, we might find something at instantiation time: treat
17684 // this as a dependent elaborated-type-specifier.
17685 // But this only makes any sense for reference-like lookups.
17686 if (Previous.wasNotFoundInCurrentInstantiation() &&
17687 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17688 IsDependent = true;
17689 return true;
17690 }
17691
17692 // A tag 'foo::bar' must already exist.
17693 Diag(NameLoc, diag::err_not_tag_in_scope)
17694 << Kind << Name << DC << SS.getRange();
17695 Name = nullptr;
17696 Invalid = true;
17697 goto CreateNewDecl;
17698 }
17699 } else if (Name) {
17700 // C++14 [class.mem]p14:
17701 // If T is the name of a class, then each of the following shall have a
17702 // name different from T:
17703 // -- every member of class T that is itself a type
17704 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17705 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
17706 return true;
17707
17708 // If this is a named struct, check to see if there was a previous forward
17709 // declaration or definition.
17710 // FIXME: We're looking into outer scopes here, even when we
17711 // shouldn't be. Doing so can result in ambiguities that we
17712 // shouldn't be diagnosing.
17713 LookupName(R&: Previous, S);
17714
17715 // When declaring or defining a tag, ignore ambiguities introduced
17716 // by types using'ed into this scope.
17717 if (Previous.isAmbiguous() &&
17718 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
17719 LookupResult::Filter F = Previous.makeFilter();
17720 while (F.hasNext()) {
17721 NamedDecl *ND = F.next();
17722 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17723 SearchDC->getRedeclContext()))
17724 F.erase();
17725 }
17726 F.done();
17727 }
17728
17729 // C++11 [namespace.memdef]p3:
17730 // If the name in a friend declaration is neither qualified nor
17731 // a template-id and the declaration is a function or an
17732 // elaborated-type-specifier, the lookup to determine whether
17733 // the entity has been previously declared shall not consider
17734 // any scopes outside the innermost enclosing namespace.
17735 //
17736 // MSVC doesn't implement the above rule for types, so a friend tag
17737 // declaration may be a redeclaration of a type declared in an enclosing
17738 // scope. They do implement this rule for friend functions.
17739 //
17740 // Does it matter that this should be by scope instead of by
17741 // semantic context?
17742 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17743 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17744 LookupResult::Filter F = Previous.makeFilter();
17745 bool FriendSawTagOutsideEnclosingNamespace = false;
17746 while (F.hasNext()) {
17747 NamedDecl *ND = F.next();
17748 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17749 if (DC->isFileContext() &&
17750 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
17751 if (getLangOpts().MSVCCompat)
17752 FriendSawTagOutsideEnclosingNamespace = true;
17753 else
17754 F.erase();
17755 }
17756 }
17757 F.done();
17758
17759 // Diagnose this MSVC extension in the easy case where lookup would have
17760 // unambiguously found something outside the enclosing namespace.
17761 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17762 NamedDecl *ND = Previous.getFoundDecl();
17763 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17764 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17765 }
17766 }
17767
17768 // Note: there used to be some attempt at recovery here.
17769 if (Previous.isAmbiguous())
17770 return true;
17771
17772 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17773 // FIXME: This makes sure that we ignore the contexts associated
17774 // with C structs, unions, and enums when looking for a matching
17775 // tag declaration or definition. See the similar lookup tweak
17776 // in Sema::LookupName; is there a better way to deal with this?
17777 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
17778 SearchDC = SearchDC->getParent();
17779 } else if (getLangOpts().CPlusPlus) {
17780 // Inside ObjCContainer want to keep it as a lexical decl context but go
17781 // past it (most often to TranslationUnit) to find the semantic decl
17782 // context.
17783 while (isa<ObjCContainerDecl>(Val: SearchDC))
17784 SearchDC = SearchDC->getParent();
17785 }
17786 } else if (getLangOpts().CPlusPlus) {
17787 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17788 // TagDecl the same way as we skip it for named TagDecl.
17789 while (isa<ObjCContainerDecl>(Val: SearchDC))
17790 SearchDC = SearchDC->getParent();
17791 }
17792
17793 if (Previous.isSingleResult() &&
17794 Previous.getFoundDecl()->isTemplateParameter()) {
17795 // Maybe we will complain about the shadowed template parameter.
17796 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17797 // Just pretend that we didn't see the previous declaration.
17798 Previous.clear();
17799 }
17800
17801 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17802 DC->Equals(getStdNamespace())) {
17803 if (Name->isStr(Str: "bad_alloc")) {
17804 // This is a declaration of or a reference to "std::bad_alloc".
17805 isStdBadAlloc = true;
17806
17807 // If std::bad_alloc has been implicitly declared (but made invisible to
17808 // name lookup), fill in this implicit declaration as the previous
17809 // declaration, so that the declarations get chained appropriately.
17810 if (Previous.empty() && StdBadAlloc)
17811 Previous.addDecl(getStdBadAlloc());
17812 } else if (Name->isStr(Str: "align_val_t")) {
17813 isStdAlignValT = true;
17814 if (Previous.empty() && StdAlignValT)
17815 Previous.addDecl(getStdAlignValT());
17816 }
17817 }
17818
17819 // If we didn't find a previous declaration, and this is a reference
17820 // (or friend reference), move to the correct scope. In C++, we
17821 // also need to do a redeclaration lookup there, just in case
17822 // there's a shadow friend decl.
17823 if (Name && Previous.empty() &&
17824 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17825 IsTemplateParamOrArg)) {
17826 if (Invalid) goto CreateNewDecl;
17827 assert(SS.isEmpty());
17828
17829 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17830 // C++ [basic.scope.pdecl]p5:
17831 // -- for an elaborated-type-specifier of the form
17832 //
17833 // class-key identifier
17834 //
17835 // if the elaborated-type-specifier is used in the
17836 // decl-specifier-seq or parameter-declaration-clause of a
17837 // function defined in namespace scope, the identifier is
17838 // declared as a class-name in the namespace that contains
17839 // the declaration; otherwise, except as a friend
17840 // declaration, the identifier is declared in the smallest
17841 // non-class, non-function-prototype scope that contains the
17842 // declaration.
17843 //
17844 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17845 // C structs and unions.
17846 //
17847 // It is an error in C++ to declare (rather than define) an enum
17848 // type, including via an elaborated type specifier. We'll
17849 // diagnose that later; for now, declare the enum in the same
17850 // scope as we would have picked for any other tag type.
17851 //
17852 // GNU C also supports this behavior as part of its incomplete
17853 // enum types extension, while GNU C++ does not.
17854 //
17855 // Find the context where we'll be declaring the tag.
17856 // FIXME: We would like to maintain the current DeclContext as the
17857 // lexical context,
17858 SearchDC = getTagInjectionContext(DC: SearchDC);
17859
17860 // Find the scope where we'll be declaring the tag.
17861 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17862 } else {
17863 assert(TUK == TagUseKind::Friend);
17864 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
17865
17866 // C++ [namespace.memdef]p3:
17867 // If a friend declaration in a non-local class first declares a
17868 // class or function, the friend class or function is a member of
17869 // the innermost enclosing namespace.
17870 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17871 : SearchDC->getEnclosingNamespaceContext();
17872 }
17873
17874 // In C++, we need to do a redeclaration lookup to properly
17875 // diagnose some problems.
17876 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17877 // hidden declaration so that we don't get ambiguity errors when using a
17878 // type declared by an elaborated-type-specifier. In C that is not correct
17879 // and we should instead merge compatible types found by lookup.
17880 if (getLangOpts().CPlusPlus) {
17881 // FIXME: This can perform qualified lookups into function contexts,
17882 // which are meaningless.
17883 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17884 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
17885 } else {
17886 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17887 LookupName(R&: Previous, S);
17888 }
17889 }
17890
17891 // If we have a known previous declaration to use, then use it.
17892 if (Previous.empty() && SkipBody && SkipBody->Previous)
17893 Previous.addDecl(D: SkipBody->Previous);
17894
17895 if (!Previous.empty()) {
17896 NamedDecl *PrevDecl = Previous.getFoundDecl();
17897 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17898
17899 // It's okay to have a tag decl in the same scope as a typedef
17900 // which hides a tag decl in the same scope. Finding this
17901 // with a redeclaration lookup can only actually happen in C++.
17902 //
17903 // This is also okay for elaborated-type-specifiers, which is
17904 // technically forbidden by the current standard but which is
17905 // okay according to the likely resolution of an open issue;
17906 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17907 if (getLangOpts().CPlusPlus) {
17908 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
17909 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17910 TagDecl *Tag = TT->getDecl();
17911 if (Tag->getDeclName() == Name &&
17912 Tag->getDeclContext()->getRedeclContext()
17913 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17914 PrevDecl = Tag;
17915 Previous.clear();
17916 Previous.addDecl(Tag);
17917 Previous.resolveKind();
17918 }
17919 }
17920 }
17921 }
17922
17923 // If this is a redeclaration of a using shadow declaration, it must
17924 // declare a tag in the same context. In MSVC mode, we allow a
17925 // redefinition if either context is within the other.
17926 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
17927 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
17928 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17929 TUK != TagUseKind::Friend &&
17930 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17931 !(OldTag && isAcceptableTagRedeclContext(
17932 *this, OldTag->getDeclContext(), SearchDC))) {
17933 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17934 Diag(Shadow->getTargetDecl()->getLocation(),
17935 diag::note_using_decl_target);
17936 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17937 << 0;
17938 // Recover by ignoring the old declaration.
17939 Previous.clear();
17940 goto CreateNewDecl;
17941 }
17942 }
17943
17944 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
17945 // If this is a use of a previous tag, or if the tag is already declared
17946 // in the same scope (so that the definition/declaration completes or
17947 // rementions the tag), reuse the decl.
17948 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17949 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
17950 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
17951 // Make sure that this wasn't declared as an enum and now used as a
17952 // struct or something similar.
17953 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
17954 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
17955 Name)) {
17956 bool SafeToContinue =
17957 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17958 Kind != TagTypeKind::Enum);
17959 if (SafeToContinue)
17960 Diag(KWLoc, diag::err_use_with_wrong_tag)
17961 << Name
17962 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17963 PrevTagDecl->getKindName());
17964 else
17965 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17966 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17967
17968 if (SafeToContinue)
17969 Kind = PrevTagDecl->getTagKind();
17970 else {
17971 // Recover by making this an anonymous redefinition.
17972 Name = nullptr;
17973 Previous.clear();
17974 Invalid = true;
17975 }
17976 }
17977
17978 if (Kind == TagTypeKind::Enum &&
17979 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17980 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
17981 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17982 return PrevTagDecl;
17983
17984 QualType EnumUnderlyingTy;
17985 if (TypeSourceInfo *TI =
17986 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
17987 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17988 else if (const Type *T =
17989 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
17990 EnumUnderlyingTy = QualType(T, 0);
17991
17992 // All conflicts with previous declarations are recovered by
17993 // returning the previous declaration, unless this is a definition,
17994 // in which case we want the caller to bail out.
17995 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
17996 IsScoped: ScopedEnum, EnumUnderlyingTy,
17997 IsFixed, Prev: PrevEnum))
17998 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17999 }
18000
18001 // C++11 [class.mem]p1:
18002 // A member shall not be declared twice in the member-specification,
18003 // except that a nested class or member class template can be declared
18004 // and then later defined.
18005 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18006 S->isDeclScope(PrevDecl)) {
18007 Diag(NameLoc, diag::ext_member_redeclared);
18008 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18009 }
18010
18011 if (!Invalid) {
18012 // If this is a use, just return the declaration we found, unless
18013 // we have attributes.
18014 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18015 if (!Attrs.empty()) {
18016 // FIXME: Diagnose these attributes. For now, we create a new
18017 // declaration to hold them.
18018 } else if (TUK == TagUseKind::Reference &&
18019 (PrevTagDecl->getFriendObjectKind() ==
18020 Decl::FOK_Undeclared ||
18021 PrevDecl->getOwningModule() != getCurrentModule()) &&
18022 SS.isEmpty()) {
18023 // This declaration is a reference to an existing entity, but
18024 // has different visibility from that entity: it either makes
18025 // a friend visible or it makes a type visible in a new module.
18026 // In either case, create a new declaration. We only do this if
18027 // the declaration would have meant the same thing if no prior
18028 // declaration were found, that is, if it was found in the same
18029 // scope where we would have injected a declaration.
18030 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18031 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18032 return PrevTagDecl;
18033 // This is in the injected scope, create a new declaration in
18034 // that scope.
18035 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18036 } else {
18037 return PrevTagDecl;
18038 }
18039 }
18040
18041 // Diagnose attempts to redefine a tag.
18042 if (TUK == TagUseKind::Definition) {
18043 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
18044 // If we're defining a specialization and the previous definition
18045 // is from an implicit instantiation, don't emit an error
18046 // here; we'll catch this in the general case below.
18047 bool IsExplicitSpecializationAfterInstantiation = false;
18048 if (isMemberSpecialization) {
18049 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18050 IsExplicitSpecializationAfterInstantiation =
18051 RD->getTemplateSpecializationKind() !=
18052 TSK_ExplicitSpecialization;
18053 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18054 IsExplicitSpecializationAfterInstantiation =
18055 ED->getTemplateSpecializationKind() !=
18056 TSK_ExplicitSpecialization;
18057 }
18058
18059 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
18060 // not keep more that one definition around (merge them). However,
18061 // ensure the decl passes the structural compatibility check in
18062 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18063 NamedDecl *Hidden = nullptr;
18064 if (SkipBody &&
18065 (!hasVisibleDefinition(D: Def, Suggested: &Hidden) || getLangOpts().C23)) {
18066 // There is a definition of this tag, but it is not visible. We
18067 // explicitly make use of C++'s one definition rule here, and
18068 // assume that this definition is identical to the hidden one
18069 // we already have. Make the existing definition visible and
18070 // use it in place of this one.
18071 if (!getLangOpts().CPlusPlus) {
18072 // Postpone making the old definition visible until after we
18073 // complete parsing the new one and do the structural
18074 // comparison.
18075 SkipBody->CheckSameAsPrevious = true;
18076 SkipBody->New = createTagFromNewDecl();
18077 SkipBody->Previous = Def;
18078
18079 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18080 return Def;
18081 } else {
18082 SkipBody->ShouldSkip = true;
18083 SkipBody->Previous = Def;
18084 makeMergedDefinitionVisible(ND: Hidden);
18085 // Carry on and handle it like a normal definition. We'll
18086 // skip starting the definition later.
18087 }
18088 } else if (!IsExplicitSpecializationAfterInstantiation) {
18089 // A redeclaration in function prototype scope in C isn't
18090 // visible elsewhere, so merely issue a warning.
18091 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
18092 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
18093 else
18094 Diag(NameLoc, diag::err_redefinition) << Name;
18095 notePreviousDefinition(Old: Def,
18096 New: NameLoc.isValid() ? NameLoc : KWLoc);
18097 // If this is a redefinition, recover by making this
18098 // struct be anonymous, which will make any later
18099 // references get the previous definition.
18100 Name = nullptr;
18101 Previous.clear();
18102 Invalid = true;
18103 }
18104 } else {
18105 // If the type is currently being defined, complain
18106 // about a nested redefinition.
18107 auto *TD = Context.getTagDeclType(Decl: PrevTagDecl)->getAsTagDecl();
18108 if (TD->isBeingDefined()) {
18109 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18110 Diag(PrevTagDecl->getLocation(),
18111 diag::note_previous_definition);
18112 Name = nullptr;
18113 Previous.clear();
18114 Invalid = true;
18115 }
18116 }
18117
18118 // Okay, this is definition of a previously declared or referenced
18119 // tag. We're going to create a new Decl for it.
18120 }
18121
18122 // Okay, we're going to make a redeclaration. If this is some kind
18123 // of reference, make sure we build the redeclaration in the same DC
18124 // as the original, and ignore the current access specifier.
18125 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18126 SearchDC = PrevTagDecl->getDeclContext();
18127 AS = AS_none;
18128 }
18129 }
18130 // If we get here we have (another) forward declaration or we
18131 // have a definition. Just create a new decl.
18132
18133 } else {
18134 // If we get here, this is a definition of a new tag type in a nested
18135 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18136 // new decl/type. We set PrevDecl to NULL so that the entities
18137 // have distinct types.
18138 Previous.clear();
18139 }
18140 // If we get here, we're going to create a new Decl. If PrevDecl
18141 // is non-NULL, it's a definition of the tag declared by
18142 // PrevDecl. If it's NULL, we have a new definition.
18143
18144 // Otherwise, PrevDecl is not a tag, but was found with tag
18145 // lookup. This is only actually possible in C++, where a few
18146 // things like templates still live in the tag namespace.
18147 } else {
18148 // Use a better diagnostic if an elaborated-type-specifier
18149 // found the wrong kind of type on the first
18150 // (non-redeclaration) lookup.
18151 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18152 !Previous.isForRedeclaration()) {
18153 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18154 Diag(NameLoc, diag::err_tag_reference_non_tag)
18155 << PrevDecl << NTK << Kind;
18156 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18157 Invalid = true;
18158
18159 // Otherwise, only diagnose if the declaration is in scope.
18160 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18161 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18162 // do nothing
18163
18164 // Diagnose implicit declarations introduced by elaborated types.
18165 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18166 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18167 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18168 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18169 Invalid = true;
18170
18171 // Otherwise it's a declaration. Call out a particularly common
18172 // case here.
18173 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18174 unsigned Kind = 0;
18175 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18176 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18177 << Name << Kind << TND->getUnderlyingType();
18178 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18179 Invalid = true;
18180
18181 // Otherwise, diagnose.
18182 } else {
18183 // The tag name clashes with something else in the target scope,
18184 // issue an error and recover by making this tag be anonymous.
18185 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18186 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18187 Name = nullptr;
18188 Invalid = true;
18189 }
18190
18191 // The existing declaration isn't relevant to us; we're in a
18192 // new scope, so clear out the previous declaration.
18193 Previous.clear();
18194 }
18195 }
18196
18197CreateNewDecl:
18198
18199 TagDecl *PrevDecl = nullptr;
18200 if (Previous.isSingleResult())
18201 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18202
18203 // If there is an identifier, use the location of the identifier as the
18204 // location of the decl, otherwise use the location of the struct/union
18205 // keyword.
18206 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18207
18208 // Otherwise, create a new declaration. If there is a previous
18209 // declaration of the same entity, the two will be linked via
18210 // PrevDecl.
18211 TagDecl *New;
18212
18213 if (Kind == TagTypeKind::Enum) {
18214 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18215 // enum X { A, B, C } D; D should chain to X.
18216 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18217 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18218 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18219
18220 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18221 StdAlignValT = cast<EnumDecl>(Val: New);
18222
18223 // If this is an undefined enum, warn.
18224 if (TUK != TagUseKind::Definition && !Invalid) {
18225 TagDecl *Def;
18226 if (IsFixed && cast<EnumDecl>(Val: New)->isFixed()) {
18227 // C++0x: 7.2p2: opaque-enum-declaration.
18228 // Conflicts are diagnosed above. Do nothing.
18229 }
18230 else if (PrevDecl && (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18231 Diag(Loc, diag::ext_forward_ref_enum_def)
18232 << New;
18233 Diag(Def->getLocation(), diag::note_previous_definition);
18234 } else {
18235 unsigned DiagID = diag::ext_forward_ref_enum;
18236 if (getLangOpts().MSVCCompat)
18237 DiagID = diag::ext_ms_forward_ref_enum;
18238 else if (getLangOpts().CPlusPlus)
18239 DiagID = diag::err_forward_ref_enum;
18240 Diag(Loc, DiagID);
18241 }
18242 }
18243
18244 if (EnumUnderlying) {
18245 EnumDecl *ED = cast<EnumDecl>(Val: New);
18246 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18247 ED->setIntegerTypeSourceInfo(TI);
18248 else
18249 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18250 QualType EnumTy = ED->getIntegerType();
18251 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18252 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18253 : EnumTy);
18254 assert(ED->isComplete() && "enum with type should be complete");
18255 }
18256 } else {
18257 // struct/union/class
18258
18259 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18260 // struct X { int A; } D; D should chain to X.
18261 if (getLangOpts().CPlusPlus) {
18262 // FIXME: Look for a way to use RecordDecl for simple structs.
18263 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18264 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18265
18266 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18267 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18268 } else
18269 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18270 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18271 }
18272
18273 // Only C23 and later allow defining new types in 'offsetof()'.
18274 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18275 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18276 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18277 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18278
18279 // C++11 [dcl.type]p3:
18280 // A type-specifier-seq shall not define a class or enumeration [...].
18281 if (!Invalid && getLangOpts().CPlusPlus &&
18282 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18283 TUK == TagUseKind::Definition) {
18284 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18285 << Context.getTagDeclType(New);
18286 Invalid = true;
18287 }
18288
18289 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18290 DC->getDeclKind() == Decl::Enum) {
18291 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18292 << Context.getTagDeclType(New);
18293 Invalid = true;
18294 }
18295
18296 // Maybe add qualifier info.
18297 if (SS.isNotEmpty()) {
18298 if (SS.isSet()) {
18299 // If this is either a declaration or a definition, check the
18300 // nested-name-specifier against the current context.
18301 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18302 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18303 /*TemplateId=*/nullptr,
18304 IsMemberSpecialization: isMemberSpecialization))
18305 Invalid = true;
18306
18307 New->setQualifierInfo(SS.getWithLocInContext(Context));
18308 if (TemplateParameterLists.size() > 0) {
18309 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18310 }
18311 }
18312 else
18313 Invalid = true;
18314 }
18315
18316 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18317 // Add alignment attributes if necessary; these attributes are checked when
18318 // the ASTContext lays out the structure.
18319 //
18320 // It is important for implementing the correct semantics that this
18321 // happen here (in ActOnTag). The #pragma pack stack is
18322 // maintained as a result of parser callbacks which can occur at
18323 // many points during the parsing of a struct declaration (because
18324 // the #pragma tokens are effectively skipped over during the
18325 // parsing of the struct).
18326 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18327 if (LangOpts.HLSL)
18328 RD->addAttr(PackedAttr::CreateImplicit(Context));
18329 AddAlignmentAttributesForRecord(RD);
18330 AddMsStructLayoutForRecord(RD);
18331 }
18332 }
18333
18334 if (ModulePrivateLoc.isValid()) {
18335 if (isMemberSpecialization)
18336 Diag(New->getLocation(), diag::err_module_private_specialization)
18337 << 2
18338 << FixItHint::CreateRemoval(ModulePrivateLoc);
18339 // __module_private__ does not apply to local classes. However, we only
18340 // diagnose this as an error when the declaration specifiers are
18341 // freestanding. Here, we just ignore the __module_private__.
18342 else if (!SearchDC->isFunctionOrMethod())
18343 New->setModulePrivate();
18344 }
18345
18346 // If this is a specialization of a member class (of a class template),
18347 // check the specialization.
18348 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18349 Invalid = true;
18350
18351 // If we're declaring or defining a tag in function prototype scope in C,
18352 // note that this type can only be used within the function and add it to
18353 // the list of decls to inject into the function definition scope. However,
18354 // in C23 and later, while the type is only visible within the function, the
18355 // function can be called with a compatible type defined in the same TU, so
18356 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18357 if ((Name || Kind == TagTypeKind::Enum) &&
18358 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18359 if (getLangOpts().CPlusPlus) {
18360 // C++ [dcl.fct]p6:
18361 // Types shall not be defined in return or parameter types.
18362 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18363 Diag(Loc, diag::err_type_defined_in_param_type)
18364 << Name;
18365 Invalid = true;
18366 }
18367 if (TUK == TagUseKind::Declaration)
18368 Invalid = true;
18369 } else if (!PrevDecl) {
18370 // In C23 mode, if the declaration is complete, we do not want to
18371 // diagnose.
18372 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18373 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18374 }
18375 }
18376
18377 if (Invalid)
18378 New->setInvalidDecl();
18379
18380 // Set the lexical context. If the tag has a C++ scope specifier, the
18381 // lexical context will be different from the semantic context.
18382 New->setLexicalDeclContext(CurContext);
18383
18384 // Mark this as a friend decl if applicable.
18385 // In Microsoft mode, a friend declaration also acts as a forward
18386 // declaration so we always pass true to setObjectOfFriendDecl to make
18387 // the tag name visible.
18388 if (TUK == TagUseKind::Friend)
18389 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18390
18391 // Set the access specifier.
18392 if (!Invalid && SearchDC->isRecord())
18393 SetMemberAccessSpecifier(New, PrevDecl, AS);
18394
18395 if (PrevDecl)
18396 CheckRedeclarationInModule(New, PrevDecl);
18397
18398 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18399 New->startDefinition();
18400
18401 ProcessDeclAttributeList(S, New, Attrs);
18402 AddPragmaAttributes(S, New);
18403
18404 // If this has an identifier, add it to the scope stack.
18405 if (TUK == TagUseKind::Friend) {
18406 // We might be replacing an existing declaration in the lookup tables;
18407 // if so, borrow its access specifier.
18408 if (PrevDecl)
18409 New->setAccess(PrevDecl->getAccess());
18410
18411 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18412 DC->makeDeclVisibleInContext(New);
18413 if (Name) // can be null along some error paths
18414 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18415 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18416 } else if (Name) {
18417 S = getNonFieldDeclScope(S);
18418 PushOnScopeChains(New, S, true);
18419 } else {
18420 CurContext->addDecl(New);
18421 }
18422
18423 // If this is the C FILE type, notify the AST context.
18424 if (IdentifierInfo *II = New->getIdentifier())
18425 if (!New->isInvalidDecl() &&
18426 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18427 II->isStr(Str: "FILE"))
18428 Context.setFILEDecl(New);
18429
18430 if (PrevDecl)
18431 mergeDeclAttributes(New, PrevDecl);
18432
18433 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18434 inferGslOwnerPointerAttribute(Record: CXXRD);
18435 inferNullableClassAttribute(CRD: CXXRD);
18436 }
18437
18438 // If there's a #pragma GCC visibility in scope, set the visibility of this
18439 // record.
18440 AddPushedVisibilityAttribute(New);
18441
18442 if (isMemberSpecialization && !New->isInvalidDecl())
18443 CompleteMemberSpecialization(New, Previous);
18444
18445 OwnedDecl = true;
18446 // In C++, don't return an invalid declaration. We can't recover well from
18447 // the cases where we make the type anonymous.
18448 if (Invalid && getLangOpts().CPlusPlus) {
18449 if (New->isBeingDefined())
18450 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18451 RD->completeDefinition();
18452 return true;
18453 } else if (SkipBody && SkipBody->ShouldSkip) {
18454 return SkipBody->Previous;
18455 } else {
18456 return New;
18457 }
18458}
18459
18460void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18461 AdjustDeclIfTemplate(Decl&: TagD);
18462 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18463
18464 // Enter the tag context.
18465 PushDeclContext(S, Tag);
18466
18467 ActOnDocumentableDecl(D: TagD);
18468
18469 // If there's a #pragma GCC visibility in scope, set the visibility of this
18470 // record.
18471 AddPushedVisibilityAttribute(Tag);
18472}
18473
18474bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18475 SkipBodyInfo &SkipBody) {
18476 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18477 return false;
18478
18479 // Make the previous decl visible.
18480 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18481 CleanupMergedEnum(S, SkipBody.New);
18482 return true;
18483}
18484
18485void Sema::ActOnStartCXXMemberDeclarations(
18486 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18487 bool IsAbstract, SourceLocation TriviallyRelocatable,
18488 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18489 AdjustDeclIfTemplate(Decl&: TagD);
18490 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18491
18492 FieldCollector->StartClass();
18493
18494 if (!Record->getIdentifier())
18495 return;
18496
18497 if (IsAbstract)
18498 Record->markAbstract();
18499
18500 if (FinalLoc.isValid()) {
18501 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18502 IsFinalSpelledSealed
18503 ? FinalAttr::Keyword_sealed
18504 : FinalAttr::Keyword_final));
18505 }
18506
18507 if (TriviallyRelocatable.isValid())
18508 Record->addAttr(
18509 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
18510
18511 if (Replaceable.isValid())
18512 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));
18513
18514 // C++ [class]p2:
18515 // [...] The class-name is also inserted into the scope of the
18516 // class itself; this is known as the injected-class-name. For
18517 // purposes of access checking, the injected-class-name is treated
18518 // as if it were a public member name.
18519 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18520 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18521 IdLoc: Record->getLocation(), Id: Record->getIdentifier(),
18522 /*PrevDecl=*/nullptr,
18523 /*DelayTypeCreation=*/true);
18524 Context.getTypeDeclType(InjectedClassName, Record);
18525 InjectedClassName->setImplicit();
18526 InjectedClassName->setAccess(AS_public);
18527 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18528 InjectedClassName->setDescribedClassTemplate(Template);
18529 PushOnScopeChains(InjectedClassName, S);
18530 assert(InjectedClassName->isInjectedClassName() &&
18531 "Broken injected-class-name");
18532}
18533
18534void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18535 SourceRange BraceRange) {
18536 AdjustDeclIfTemplate(Decl&: TagD);
18537 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18538 Tag->setBraceRange(BraceRange);
18539
18540 // Make sure we "complete" the definition even it is invalid.
18541 if (Tag->isBeingDefined()) {
18542 assert(Tag->isInvalidDecl() && "We should already have completed it");
18543 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18544 RD->completeDefinition();
18545 }
18546
18547 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18548 FieldCollector->FinishClass();
18549 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18550 auto *Def = RD->getDefinition();
18551 assert(Def && "The record is expected to have a completed definition");
18552 unsigned NumInitMethods = 0;
18553 for (auto *Method : Def->methods()) {
18554 if (!Method->getIdentifier())
18555 continue;
18556 if (Method->getName() == "__init")
18557 NumInitMethods++;
18558 }
18559 if (NumInitMethods > 1 || !Def->hasInitMethod())
18560 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18561 }
18562
18563 // If we're defining a dynamic class in a module interface unit, we always
18564 // need to produce the vtable for it, even if the vtable is not used in the
18565 // current TU.
18566 //
18567 // The case where the current class is not dynamic is handled in
18568 // MarkVTableUsed.
18569 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18570 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
18571 }
18572
18573 // Exit this scope of this tag's definition.
18574 PopDeclContext();
18575
18576 if (getCurLexicalContext()->isObjCContainer() &&
18577 Tag->getDeclContext()->isFileContext())
18578 Tag->setTopLevelDeclInObjCContainer();
18579
18580 // Notify the consumer that we've defined a tag.
18581 if (!Tag->isInvalidDecl())
18582 Consumer.HandleTagDeclDefinition(D: Tag);
18583
18584 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18585 // from XLs and instead matches the XL #pragma pack(1) behavior.
18586 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18587 AlignPackStack.hasValue()) {
18588 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18589 // Only diagnose #pragma align(packed).
18590 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18591 return;
18592 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18593 if (!RD)
18594 return;
18595 // Only warn if there is at least 1 bitfield member.
18596 if (llvm::any_of(RD->fields(),
18597 [](const FieldDecl *FD) { return FD->isBitField(); }))
18598 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18599 }
18600}
18601
18602void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18603 AdjustDeclIfTemplate(Decl&: TagD);
18604 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18605 Tag->setInvalidDecl();
18606
18607 // Make sure we "complete" the definition even it is invalid.
18608 if (Tag->isBeingDefined()) {
18609 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18610 RD->completeDefinition();
18611 }
18612
18613 // We're undoing ActOnTagStartDefinition here, not
18614 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18615 // the FieldCollector.
18616
18617 PopDeclContext();
18618}
18619
18620// Note that FieldName may be null for anonymous bitfields.
18621ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18622 const IdentifierInfo *FieldName,
18623 QualType FieldTy, bool IsMsStruct,
18624 Expr *BitWidth) {
18625 assert(BitWidth);
18626 if (BitWidth->containsErrors())
18627 return ExprError();
18628
18629 // C99 6.7.2.1p4 - verify the field type.
18630 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18631 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18632 // Handle incomplete and sizeless types with a specific error.
18633 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18634 diag::err_field_incomplete_or_sizeless))
18635 return ExprError();
18636 if (FieldName)
18637 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18638 << FieldName << FieldTy << BitWidth->getSourceRange();
18639 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18640 << FieldTy << BitWidth->getSourceRange();
18641 } else if (DiagnoseUnexpandedParameterPack(E: const_cast<Expr *>(BitWidth),
18642 UPPC: UPPC_BitFieldWidth))
18643 return ExprError();
18644
18645 // If the bit-width is type- or value-dependent, don't try to check
18646 // it now.
18647 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18648 return BitWidth;
18649
18650 llvm::APSInt Value;
18651 ExprResult ICE =
18652 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
18653 if (ICE.isInvalid())
18654 return ICE;
18655 BitWidth = ICE.get();
18656
18657 // Zero-width bitfield is ok for anonymous field.
18658 if (Value == 0 && FieldName)
18659 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18660 << FieldName << BitWidth->getSourceRange();
18661
18662 if (Value.isSigned() && Value.isNegative()) {
18663 if (FieldName)
18664 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18665 << FieldName << toString(Value, 10);
18666 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18667 << toString(Value, 10);
18668 }
18669
18670 // The size of the bit-field must not exceed our maximum permitted object
18671 // size.
18672 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18673 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18674 << !FieldName << FieldName << toString(Value, 10);
18675 }
18676
18677 if (!FieldTy->isDependentType()) {
18678 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
18679 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
18680 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
18681
18682 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18683 // ABI.
18684 bool CStdConstraintViolation =
18685 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18686 bool MSBitfieldViolation =
18687 Value.ugt(RHS: TypeStorageSize) &&
18688 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18689 if (CStdConstraintViolation || MSBitfieldViolation) {
18690 unsigned DiagWidth =
18691 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18692 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18693 << (bool)FieldName << FieldName << toString(Value, 10)
18694 << !CStdConstraintViolation << DiagWidth;
18695 }
18696
18697 // Warn on types where the user might conceivably expect to get all
18698 // specified bits as value bits: that's all integral types other than
18699 // 'bool'.
18700 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18701 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18702 << FieldName << toString(Value, 10)
18703 << (unsigned)TypeWidth;
18704 }
18705 }
18706
18707 if (isa<ConstantExpr>(Val: BitWidth))
18708 return BitWidth;
18709 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
18710}
18711
18712Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18713 Declarator &D, Expr *BitfieldWidth) {
18714 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
18715 D, BitfieldWidth,
18716 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
18717 return Res;
18718}
18719
18720FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18721 SourceLocation DeclStart,
18722 Declarator &D, Expr *BitWidth,
18723 InClassInitStyle InitStyle,
18724 AccessSpecifier AS) {
18725 if (D.isDecompositionDeclarator()) {
18726 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18727 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18728 << Decomp.getSourceRange();
18729 return nullptr;
18730 }
18731
18732 const IdentifierInfo *II = D.getIdentifier();
18733 SourceLocation Loc = DeclStart;
18734 if (II) Loc = D.getIdentifierLoc();
18735
18736 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18737 QualType T = TInfo->getType();
18738 if (getLangOpts().CPlusPlus) {
18739 CheckExtraCXXDefaultArguments(D);
18740
18741 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
18742 UPPC: UPPC_DataMemberType)) {
18743 D.setInvalidType();
18744 T = Context.IntTy;
18745 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18746 }
18747 }
18748
18749 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
18750
18751 if (D.getDeclSpec().isInlineSpecified())
18752 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18753 << getLangOpts().CPlusPlus17;
18754 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18755 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18756 diag::err_invalid_thread)
18757 << DeclSpec::getSpecifierName(TSCS);
18758
18759 // Check to see if this name was declared as a member previously
18760 NamedDecl *PrevDecl = nullptr;
18761 LookupResult Previous(*this, II, Loc, LookupMemberName,
18762 RedeclarationKind::ForVisibleRedeclaration);
18763 LookupName(R&: Previous, S);
18764 switch (Previous.getResultKind()) {
18765 case LookupResultKind::Found:
18766 case LookupResultKind::FoundUnresolvedValue:
18767 PrevDecl = Previous.getAsSingle<NamedDecl>();
18768 break;
18769
18770 case LookupResultKind::FoundOverloaded:
18771 PrevDecl = Previous.getRepresentativeDecl();
18772 break;
18773
18774 case LookupResultKind::NotFound:
18775 case LookupResultKind::NotFoundInCurrentInstantiation:
18776 case LookupResultKind::Ambiguous:
18777 break;
18778 }
18779 Previous.suppressDiagnostics();
18780
18781 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18782 // Maybe we will complain about the shadowed template parameter.
18783 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18784 // Just pretend that we didn't see the previous declaration.
18785 PrevDecl = nullptr;
18786 }
18787
18788 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18789 PrevDecl = nullptr;
18790
18791 bool Mutable
18792 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18793 SourceLocation TSSL = D.getBeginLoc();
18794 FieldDecl *NewFD
18795 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
18796 TSSL, AS, PrevDecl, D: &D);
18797
18798 if (NewFD->isInvalidDecl())
18799 Record->setInvalidDecl();
18800
18801 if (D.getDeclSpec().isModulePrivateSpecified())
18802 NewFD->setModulePrivate();
18803
18804 if (NewFD->isInvalidDecl() && PrevDecl) {
18805 // Don't introduce NewFD into scope; there's already something
18806 // with the same name in the same scope.
18807 } else if (II) {
18808 PushOnScopeChains(NewFD, S);
18809 } else
18810 Record->addDecl(NewFD);
18811
18812 return NewFD;
18813}
18814
18815FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18816 TypeSourceInfo *TInfo,
18817 RecordDecl *Record, SourceLocation Loc,
18818 bool Mutable, Expr *BitWidth,
18819 InClassInitStyle InitStyle,
18820 SourceLocation TSSL,
18821 AccessSpecifier AS, NamedDecl *PrevDecl,
18822 Declarator *D) {
18823 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18824 bool InvalidDecl = false;
18825 if (D) InvalidDecl = D->isInvalidType();
18826
18827 // If we receive a broken type, recover by assuming 'int' and
18828 // marking this declaration as invalid.
18829 if (T.isNull() || T->containsErrors()) {
18830 InvalidDecl = true;
18831 T = Context.IntTy;
18832 }
18833
18834 QualType EltTy = Context.getBaseElementType(QT: T);
18835 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18836 bool isIncomplete =
18837 LangOpts.HLSL // HLSL allows sizeless builtin types
18838 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18839 : RequireCompleteSizedType(Loc, EltTy,
18840 diag::err_field_incomplete_or_sizeless);
18841 if (isIncomplete) {
18842 // Fields of incomplete type force their record to be invalid.
18843 Record->setInvalidDecl();
18844 InvalidDecl = true;
18845 } else {
18846 NamedDecl *Def;
18847 EltTy->isIncompleteType(Def: &Def);
18848 if (Def && Def->isInvalidDecl()) {
18849 Record->setInvalidDecl();
18850 InvalidDecl = true;
18851 }
18852 }
18853 }
18854
18855 // TR 18037 does not allow fields to be declared with address space
18856 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18857 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18858 Diag(Loc, diag::err_field_with_address_space);
18859 Record->setInvalidDecl();
18860 InvalidDecl = true;
18861 }
18862
18863 if (LangOpts.OpenCL) {
18864 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18865 // used as structure or union field: image, sampler, event or block types.
18866 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18867 T->isBlockPointerType()) {
18868 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18869 Record->setInvalidDecl();
18870 InvalidDecl = true;
18871 }
18872 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18873 // is enabled.
18874 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18875 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
18876 Diag(Loc, diag::err_opencl_bitfields);
18877 InvalidDecl = true;
18878 }
18879 }
18880
18881 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18882 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18883 T.hasQualifiers()) {
18884 InvalidDecl = true;
18885 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18886 }
18887
18888 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18889 // than a variably modified type.
18890 if (!InvalidDecl && T->isVariablyModifiedType()) {
18891 if (!tryToFixVariablyModifiedVarType(
18892 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18893 InvalidDecl = true;
18894 }
18895
18896 // Fields can not have abstract class types
18897 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18898 diag::err_abstract_type_in_decl,
18899 AbstractFieldType))
18900 InvalidDecl = true;
18901
18902 if (InvalidDecl)
18903 BitWidth = nullptr;
18904 // If this is declared as a bit-field, check the bit-field.
18905 if (BitWidth) {
18906 BitWidth =
18907 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
18908 if (!BitWidth) {
18909 InvalidDecl = true;
18910 BitWidth = nullptr;
18911 }
18912 }
18913
18914 // Check that 'mutable' is consistent with the type of the declaration.
18915 if (!InvalidDecl && Mutable) {
18916 unsigned DiagID = 0;
18917 if (T->isReferenceType())
18918 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18919 : diag::err_mutable_reference;
18920 else if (T.isConstQualified())
18921 DiagID = diag::err_mutable_const;
18922
18923 if (DiagID) {
18924 SourceLocation ErrLoc = Loc;
18925 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18926 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18927 Diag(ErrLoc, DiagID);
18928 if (DiagID != diag::ext_mutable_reference) {
18929 Mutable = false;
18930 InvalidDecl = true;
18931 }
18932 }
18933 }
18934
18935 // C++11 [class.union]p8 (DR1460):
18936 // At most one variant member of a union may have a
18937 // brace-or-equal-initializer.
18938 if (InitStyle != ICIS_NoInit)
18939 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
18940
18941 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18942 BitWidth, Mutable, InitStyle);
18943 if (InvalidDecl)
18944 NewFD->setInvalidDecl();
18945
18946 if (!InvalidDecl)
18947 warnOnCTypeHiddenInCPlusPlus(NewFD);
18948
18949 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
18950 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
18951 Diag(Loc, diag::err_duplicate_member) << II;
18952 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18953 NewFD->setInvalidDecl();
18954 }
18955
18956 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18957 if (Record->isUnion()) {
18958 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18959 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
18960 if (RDecl->getDefinition()) {
18961 // C++ [class.union]p1: An object of a class with a non-trivial
18962 // constructor, a non-trivial copy constructor, a non-trivial
18963 // destructor, or a non-trivial copy assignment operator
18964 // cannot be a member of a union, nor can an array of such
18965 // objects.
18966 if (CheckNontrivialField(FD: NewFD))
18967 NewFD->setInvalidDecl();
18968 }
18969 }
18970
18971 // C++ [class.union]p1: If a union contains a member of reference type,
18972 // the program is ill-formed, except when compiling with MSVC extensions
18973 // enabled.
18974 if (EltTy->isReferenceType()) {
18975 const bool HaveMSExt =
18976 getLangOpts().MicrosoftExt &&
18977 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
18978
18979 Diag(NewFD->getLocation(),
18980 HaveMSExt ? diag::ext_union_member_of_reference_type
18981 : diag::err_union_member_of_reference_type)
18982 << NewFD->getDeclName() << EltTy;
18983 if (!HaveMSExt)
18984 NewFD->setInvalidDecl();
18985 }
18986 }
18987 }
18988
18989 // FIXME: We need to pass in the attributes given an AST
18990 // representation, not a parser representation.
18991 if (D) {
18992 // FIXME: The current scope is almost... but not entirely... correct here.
18993 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18994
18995 if (NewFD->hasAttrs())
18996 CheckAlignasUnderalignment(NewFD);
18997 }
18998
18999 // In auto-retain/release, infer strong retension for fields of
19000 // retainable type.
19001 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19002 NewFD->setInvalidDecl();
19003
19004 if (T.isObjCGCWeak())
19005 Diag(Loc, diag::warn_attribute_weak_on_field);
19006
19007 // PPC MMA non-pointer types are not allowed as field types.
19008 if (Context.getTargetInfo().getTriple().isPPC64() &&
19009 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19010 NewFD->setInvalidDecl();
19011
19012 NewFD->setAccess(AS);
19013 return NewFD;
19014}
19015
19016bool Sema::CheckNontrivialField(FieldDecl *FD) {
19017 assert(FD);
19018 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19019
19020 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19021 return false;
19022
19023 QualType EltTy = Context.getBaseElementType(FD->getType());
19024 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
19025 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
19026 if (RDecl->getDefinition()) {
19027 // We check for copy constructors before constructors
19028 // because otherwise we'll never get complaints about
19029 // copy constructors.
19030
19031 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19032 // We're required to check for any non-trivial constructors. Since the
19033 // implicit default constructor is suppressed if there are any
19034 // user-declared constructors, we just need to check that there is a
19035 // trivial default constructor and a trivial copy constructor. (We don't
19036 // worry about move constructors here, since this is a C++98 check.)
19037 if (RDecl->hasNonTrivialCopyConstructor())
19038 member = CXXSpecialMemberKind::CopyConstructor;
19039 else if (!RDecl->hasTrivialDefaultConstructor())
19040 member = CXXSpecialMemberKind::DefaultConstructor;
19041 else if (RDecl->hasNonTrivialCopyAssignment())
19042 member = CXXSpecialMemberKind::CopyAssignment;
19043 else if (RDecl->hasNonTrivialDestructor())
19044 member = CXXSpecialMemberKind::Destructor;
19045
19046 if (member != CXXSpecialMemberKind::Invalid) {
19047 if (!getLangOpts().CPlusPlus11 &&
19048 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
19049 // Objective-C++ ARC: it is an error to have a non-trivial field of
19050 // a union. However, system headers in Objective-C programs
19051 // occasionally have Objective-C lifetime objects within unions,
19052 // and rather than cause the program to fail, we make those
19053 // members unavailable.
19054 SourceLocation Loc = FD->getLocation();
19055 if (getSourceManager().isInSystemHeader(Loc)) {
19056 if (!FD->hasAttr<UnavailableAttr>())
19057 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
19058 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19059 return false;
19060 }
19061 }
19062
19063 Diag(
19064 FD->getLocation(),
19065 getLangOpts().CPlusPlus11
19066 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19067 : diag::err_illegal_union_or_anon_struct_member)
19068 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19069 DiagnoseNontrivial(Record: RDecl, CSM: member);
19070 return !getLangOpts().CPlusPlus11;
19071 }
19072 }
19073 }
19074
19075 return false;
19076}
19077
19078void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19079 SmallVectorImpl<Decl *> &AllIvarDecls) {
19080 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19081 return;
19082
19083 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19084 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19085
19086 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19087 return;
19088 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19089 if (!ID) {
19090 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19091 if (!CD->IsClassExtension())
19092 return;
19093 }
19094 // No need to add this to end of @implementation.
19095 else
19096 return;
19097 }
19098 // All conditions are met. Add a new bitfield to the tail end of ivars.
19099 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19100 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19101 Expr *BitWidth =
19102 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19103
19104 Ivar = ObjCIvarDecl::Create(
19105 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19106 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19107 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19108 AllIvarDecls.push_back(Ivar);
19109}
19110
19111/// [class.dtor]p4:
19112/// At the end of the definition of a class, overload resolution is
19113/// performed among the prospective destructors declared in that class with
19114/// an empty argument list to select the destructor for the class, also
19115/// known as the selected destructor.
19116///
19117/// We do the overload resolution here, then mark the selected constructor in the AST.
19118/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19119static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19120 if (!Record->hasUserDeclaredDestructor()) {
19121 return;
19122 }
19123
19124 SourceLocation Loc = Record->getLocation();
19125 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19126
19127 for (auto *Decl : Record->decls()) {
19128 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19129 if (DD->isInvalidDecl())
19130 continue;
19131 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19132 OCS);
19133 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19134 }
19135 }
19136
19137 if (OCS.empty()) {
19138 return;
19139 }
19140 OverloadCandidateSet::iterator Best;
19141 unsigned Msg = 0;
19142 OverloadCandidateDisplayKind DisplayKind;
19143
19144 switch (OCS.BestViableFunction(S, Loc, Best)) {
19145 case OR_Success:
19146 case OR_Deleted:
19147 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19148 break;
19149
19150 case OR_Ambiguous:
19151 Msg = diag::err_ambiguous_destructor;
19152 DisplayKind = OCD_AmbiguousCandidates;
19153 break;
19154
19155 case OR_No_Viable_Function:
19156 Msg = diag::err_no_viable_destructor;
19157 DisplayKind = OCD_AllCandidates;
19158 break;
19159 }
19160
19161 if (Msg) {
19162 // OpenCL have got their own thing going with destructors. It's slightly broken,
19163 // but we allow it.
19164 if (!S.LangOpts.OpenCL) {
19165 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19166 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19167 Record->setInvalidDecl();
19168 }
19169 // It's a bit hacky: At this point we've raised an error but we want the
19170 // rest of the compiler to continue somehow working. However almost
19171 // everything we'll try to do with the class will depend on there being a
19172 // destructor. So let's pretend the first one is selected and hope for the
19173 // best.
19174 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19175 }
19176}
19177
19178/// [class.mem.special]p5
19179/// Two special member functions are of the same kind if:
19180/// - they are both default constructors,
19181/// - they are both copy or move constructors with the same first parameter
19182/// type, or
19183/// - they are both copy or move assignment operators with the same first
19184/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19185static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19186 CXXMethodDecl *M1,
19187 CXXMethodDecl *M2,
19188 CXXSpecialMemberKind CSM) {
19189 // We don't want to compare templates to non-templates: See
19190 // https://github.com/llvm/llvm-project/issues/59206
19191 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19192 return bool(M1->getDescribedFunctionTemplate()) ==
19193 bool(M2->getDescribedFunctionTemplate());
19194 // FIXME: better resolve CWG
19195 // https://cplusplus.github.io/CWG/issues/2787.html
19196 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19197 M2->getNonObjectParameter(0)->getType()))
19198 return false;
19199 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19200 T2: M2->getFunctionObjectParameterReferenceType()))
19201 return false;
19202
19203 return true;
19204}
19205
19206/// [class.mem.special]p6:
19207/// An eligible special member function is a special member function for which:
19208/// - the function is not deleted,
19209/// - the associated constraints, if any, are satisfied, and
19210/// - no special member function of the same kind whose associated constraints
19211/// [CWG2595], if any, are satisfied is more constrained.
19212static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19213 ArrayRef<CXXMethodDecl *> Methods,
19214 CXXSpecialMemberKind CSM) {
19215 SmallVector<bool, 4> SatisfactionStatus;
19216
19217 for (CXXMethodDecl *Method : Methods) {
19218 if (!Method->getTrailingRequiresClause())
19219 SatisfactionStatus.push_back(Elt: true);
19220 else {
19221 ConstraintSatisfaction Satisfaction;
19222 if (S.CheckFunctionConstraints(Method, Satisfaction))
19223 SatisfactionStatus.push_back(Elt: false);
19224 else
19225 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19226 }
19227 }
19228
19229 for (size_t i = 0; i < Methods.size(); i++) {
19230 if (!SatisfactionStatus[i])
19231 continue;
19232 CXXMethodDecl *Method = Methods[i];
19233 CXXMethodDecl *OrigMethod = Method;
19234 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19235 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19236
19237 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19238 bool AnotherMethodIsMoreConstrained = false;
19239 for (size_t j = 0; j < Methods.size(); j++) {
19240 if (i == j || !SatisfactionStatus[j])
19241 continue;
19242 CXXMethodDecl *OtherMethod = Methods[j];
19243 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19244 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19245
19246 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19247 CSM))
19248 continue;
19249
19250 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19251 if (!Other)
19252 continue;
19253 if (!Orig) {
19254 AnotherMethodIsMoreConstrained = true;
19255 break;
19256 }
19257 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19258 AnotherMethodIsMoreConstrained)) {
19259 // There was an error with the constraints comparison. Exit the loop
19260 // and don't consider this function eligible.
19261 AnotherMethodIsMoreConstrained = true;
19262 }
19263 if (AnotherMethodIsMoreConstrained)
19264 break;
19265 }
19266 // FIXME: Do not consider deleted methods as eligible after implementing
19267 // DR1734 and DR1496.
19268 if (!AnotherMethodIsMoreConstrained) {
19269 Method->setIneligibleOrNotSelected(false);
19270 Record->addedEligibleSpecialMemberFunction(MD: Method,
19271 SMKind: 1 << llvm::to_underlying(E: CSM));
19272 }
19273 }
19274}
19275
19276static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19277 CXXRecordDecl *Record) {
19278 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19279 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19280 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19281 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19282 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19283
19284 for (auto *Decl : Record->decls()) {
19285 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19286 if (!MD) {
19287 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19288 if (FTD)
19289 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19290 }
19291 if (!MD)
19292 continue;
19293 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19294 if (CD->isInvalidDecl())
19295 continue;
19296 if (CD->isDefaultConstructor())
19297 DefaultConstructors.push_back(MD);
19298 else if (CD->isCopyConstructor())
19299 CopyConstructors.push_back(MD);
19300 else if (CD->isMoveConstructor())
19301 MoveConstructors.push_back(MD);
19302 } else if (MD->isCopyAssignmentOperator()) {
19303 CopyAssignmentOperators.push_back(MD);
19304 } else if (MD->isMoveAssignmentOperator()) {
19305 MoveAssignmentOperators.push_back(MD);
19306 }
19307 }
19308
19309 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19310 CSM: CXXSpecialMemberKind::DefaultConstructor);
19311 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19312 CSM: CXXSpecialMemberKind::CopyConstructor);
19313 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19314 CSM: CXXSpecialMemberKind::MoveConstructor);
19315 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19316 CSM: CXXSpecialMemberKind::CopyAssignment);
19317 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19318 CSM: CXXSpecialMemberKind::MoveAssignment);
19319}
19320
19321bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19322 // Check to see if a FieldDecl is a pointer to a function.
19323 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19324 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19325 if (!FD) {
19326 // Check whether this is a forward declaration that was inserted by
19327 // Clang. This happens when a non-forward declared / defined type is
19328 // used, e.g.:
19329 //
19330 // struct foo {
19331 // struct bar *(*f)();
19332 // struct bar *(*g)();
19333 // };
19334 //
19335 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19336 // incomplete definition.
19337 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19338 return !TD->isCompleteDefinition();
19339 return false;
19340 }
19341 QualType FieldType = FD->getType().getDesugaredType(Context);
19342 if (isa<PointerType>(Val: FieldType)) {
19343 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19344 return PointeeType.getDesugaredType(Context)->isFunctionType();
19345 }
19346 // If a member is a struct entirely of function pointers, that counts too.
19347 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
19348 const RecordDecl *Record = RT->getDecl();
19349 if (Record->isStruct() && EntirelyFunctionPointers(Record))
19350 return true;
19351 }
19352 return false;
19353 };
19354
19355 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19356}
19357
19358void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19359 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19360 SourceLocation RBrac,
19361 const ParsedAttributesView &Attrs) {
19362 assert(EnclosingDecl && "missing record or interface decl");
19363
19364 // If this is an Objective-C @implementation or category and we have
19365 // new fields here we should reset the layout of the interface since
19366 // it will now change.
19367 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19368 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19369 switch (DC->getKind()) {
19370 default: break;
19371 case Decl::ObjCCategory:
19372 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19373 break;
19374 case Decl::ObjCImplementation:
19375 Context.
19376 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19377 break;
19378 }
19379 }
19380
19381 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19382 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19383
19384 // Start counting up the number of named members; make sure to include
19385 // members of anonymous structs and unions in the total.
19386 unsigned NumNamedMembers = 0;
19387 if (Record) {
19388 for (const auto *I : Record->decls()) {
19389 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19390 if (IFD->getDeclName())
19391 ++NumNamedMembers;
19392 }
19393 }
19394
19395 // Verify that all the fields are okay.
19396 SmallVector<FieldDecl*, 32> RecFields;
19397 const FieldDecl *PreviousField = nullptr;
19398 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19399 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19400 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19401
19402 // Get the type for the field.
19403 const Type *FDTy = FD->getType().getTypePtr();
19404
19405 if (!FD->isAnonymousStructOrUnion()) {
19406 // Remember all fields written by the user.
19407 RecFields.push_back(Elt: FD);
19408 }
19409
19410 // If the field is already invalid for some reason, don't emit more
19411 // diagnostics about it.
19412 if (FD->isInvalidDecl()) {
19413 EnclosingDecl->setInvalidDecl();
19414 continue;
19415 }
19416
19417 // C99 6.7.2.1p2:
19418 // A structure or union shall not contain a member with
19419 // incomplete or function type (hence, a structure shall not
19420 // contain an instance of itself, but may contain a pointer to
19421 // an instance of itself), except that the last member of a
19422 // structure with more than one named member may have incomplete
19423 // array type; such a structure (and any union containing,
19424 // possibly recursively, a member that is such a structure)
19425 // shall not be a member of a structure or an element of an
19426 // array.
19427 bool IsLastField = (i + 1 == Fields.end());
19428 if (FDTy->isFunctionType()) {
19429 // Field declared as a function.
19430 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19431 << FD->getDeclName();
19432 FD->setInvalidDecl();
19433 EnclosingDecl->setInvalidDecl();
19434 continue;
19435 } else if (FDTy->isIncompleteArrayType() &&
19436 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19437 if (Record) {
19438 // Flexible array member.
19439 // Microsoft and g++ is more permissive regarding flexible array.
19440 // It will accept flexible array in union and also
19441 // as the sole element of a struct/class.
19442 unsigned DiagID = 0;
19443 if (!Record->isUnion() && !IsLastField) {
19444 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19445 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19446 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19447 FD->setInvalidDecl();
19448 EnclosingDecl->setInvalidDecl();
19449 continue;
19450 } else if (Record->isUnion())
19451 DiagID = getLangOpts().MicrosoftExt
19452 ? diag::ext_flexible_array_union_ms
19453 : diag::ext_flexible_array_union_gnu;
19454 else if (NumNamedMembers < 1)
19455 DiagID = getLangOpts().MicrosoftExt
19456 ? diag::ext_flexible_array_empty_aggregate_ms
19457 : diag::ext_flexible_array_empty_aggregate_gnu;
19458
19459 if (DiagID)
19460 Diag(FD->getLocation(), DiagID)
19461 << FD->getDeclName() << Record->getTagKind();
19462 // While the layout of types that contain virtual bases is not specified
19463 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19464 // virtual bases after the derived members. This would make a flexible
19465 // array member declared at the end of an object not adjacent to the end
19466 // of the type.
19467 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19468 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19469 << FD->getDeclName() << Record->getTagKind();
19470 if (!getLangOpts().C99)
19471 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19472 << FD->getDeclName() << Record->getTagKind();
19473
19474 // If the element type has a non-trivial destructor, we would not
19475 // implicitly destroy the elements, so disallow it for now.
19476 //
19477 // FIXME: GCC allows this. We should probably either implicitly delete
19478 // the destructor of the containing class, or just allow this.
19479 QualType BaseElem = Context.getBaseElementType(FD->getType());
19480 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19481 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19482 << FD->getDeclName() << FD->getType();
19483 FD->setInvalidDecl();
19484 EnclosingDecl->setInvalidDecl();
19485 continue;
19486 }
19487 // Okay, we have a legal flexible array member at the end of the struct.
19488 Record->setHasFlexibleArrayMember(true);
19489 } else {
19490 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19491 // unless they are followed by another ivar. That check is done
19492 // elsewhere, after synthesized ivars are known.
19493 }
19494 } else if (!FDTy->isDependentType() &&
19495 (LangOpts.HLSL // HLSL allows sizeless builtin types
19496 ? RequireCompleteType(FD->getLocation(), FD->getType(),
19497 diag::err_incomplete_type)
19498 : RequireCompleteSizedType(
19499 FD->getLocation(), FD->getType(),
19500 diag::err_field_incomplete_or_sizeless))) {
19501 // Incomplete type
19502 FD->setInvalidDecl();
19503 EnclosingDecl->setInvalidDecl();
19504 continue;
19505 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19506 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19507 // A type which contains a flexible array member is considered to be a
19508 // flexible array member.
19509 Record->setHasFlexibleArrayMember(true);
19510 if (!Record->isUnion()) {
19511 // If this is a struct/class and this is not the last element, reject
19512 // it. Note that GCC supports variable sized arrays in the middle of
19513 // structures.
19514 if (!IsLastField)
19515 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19516 << FD->getDeclName() << FD->getType();
19517 else {
19518 // We support flexible arrays at the end of structs in
19519 // other structs as an extension.
19520 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19521 << FD->getDeclName();
19522 }
19523 }
19524 }
19525 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19526 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19527 diag::err_abstract_type_in_decl,
19528 AbstractIvarType)) {
19529 // Ivars can not have abstract class types
19530 FD->setInvalidDecl();
19531 }
19532 if (Record && FDTTy->getDecl()->hasObjectMember())
19533 Record->setHasObjectMember(true);
19534 if (Record && FDTTy->getDecl()->hasVolatileMember())
19535 Record->setHasVolatileMember(true);
19536 } else if (FDTy->isObjCObjectType()) {
19537 /// A field cannot be an Objective-c object
19538 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19539 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19540 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19541 FD->setType(T);
19542 } else if (Record && Record->isUnion() &&
19543 FD->getType().hasNonTrivialObjCLifetime() &&
19544 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19545 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19546 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19547 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19548 // For backward compatibility, fields of C unions declared in system
19549 // headers that have non-trivial ObjC ownership qualifications are marked
19550 // as unavailable unless the qualifier is explicit and __strong. This can
19551 // break ABI compatibility between programs compiled with ARC and MRR, but
19552 // is a better option than rejecting programs using those unions under
19553 // ARC.
19554 FD->addAttr(UnavailableAttr::CreateImplicit(
19555 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19556 FD->getLocation()));
19557 } else if (getLangOpts().ObjC &&
19558 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19559 !Record->hasObjectMember()) {
19560 if (FD->getType()->isObjCObjectPointerType() ||
19561 FD->getType().isObjCGCStrong())
19562 Record->setHasObjectMember(true);
19563 else if (Context.getAsArrayType(T: FD->getType())) {
19564 QualType BaseType = Context.getBaseElementType(FD->getType());
19565 if (BaseType->isRecordType() &&
19566 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19567 Record->setHasObjectMember(true);
19568 else if (BaseType->isObjCObjectPointerType() ||
19569 BaseType.isObjCGCStrong())
19570 Record->setHasObjectMember(true);
19571 }
19572 }
19573
19574 if (Record && !getLangOpts().CPlusPlus &&
19575 !shouldIgnoreForRecordTriviality(FD)) {
19576 QualType FT = FD->getType();
19577 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19578 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19579 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19580 Record->isUnion())
19581 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19582 }
19583 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19584 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19585 Record->setNonTrivialToPrimitiveCopy(true);
19586 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19587 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19588 }
19589 if (FD->hasAttr<ExplicitInitAttr>())
19590 Record->setHasUninitializedExplicitInitFields(true);
19591 if (FT.isDestructedType()) {
19592 Record->setNonTrivialToPrimitiveDestroy(true);
19593 Record->setParamDestroyedInCallee(true);
19594 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19595 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19596 }
19597
19598 if (const auto *RT = FT->getAs<RecordType>()) {
19599 if (RT->getDecl()->getArgPassingRestrictions() ==
19600 RecordArgPassingKind::CanNeverPassInRegs)
19601 Record->setArgPassingRestrictions(
19602 RecordArgPassingKind::CanNeverPassInRegs);
19603 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19604 Record->setArgPassingRestrictions(
19605 RecordArgPassingKind::CanNeverPassInRegs);
19606 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19607 Q && Q.isAddressDiscriminated()) {
19608 Record->setArgPassingRestrictions(
19609 RecordArgPassingKind::CanNeverPassInRegs);
19610 }
19611 }
19612
19613 if (Record && FD->getType().isVolatileQualified())
19614 Record->setHasVolatileMember(true);
19615 bool ReportMSBitfieldStoragePacking =
19616 Record && PreviousField &&
19617 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19618 Record->getLocation());
19619 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19620 return FD->isBitField() && !FD->getType()->isDependentType();
19621 };
19622
19623 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19624 IsNonDependentBitField(PreviousField)) {
19625 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19626 CharUnits PreviousFieldStorageSize =
19627 Context.getTypeSizeInChars(PreviousField->getType());
19628 if (FDStorageSize != PreviousFieldStorageSize) {
19629 Diag(FD->getLocation(),
19630 diag::warn_ms_bitfield_mismatched_storage_packing)
19631 << FD << FD->getType() << FDStorageSize.getQuantity()
19632 << PreviousFieldStorageSize.getQuantity();
19633 Diag(PreviousField->getLocation(),
19634 diag::note_ms_bitfield_mismatched_storage_size_previous)
19635 << PreviousField << PreviousField->getType();
19636 }
19637 }
19638 // Keep track of the number of named members.
19639 if (FD->getIdentifier())
19640 ++NumNamedMembers;
19641 }
19642
19643 // Okay, we successfully defined 'Record'.
19644 if (Record) {
19645 bool Completed = false;
19646 if (S) {
19647 Scope *Parent = S->getParent();
19648 if (Parent && Parent->isTypeAliasScope() &&
19649 Parent->isTemplateParamScope())
19650 Record->setInvalidDecl();
19651 }
19652
19653 if (CXXRecord) {
19654 if (!CXXRecord->isInvalidDecl()) {
19655 // Set access bits correctly on the directly-declared conversions.
19656 for (CXXRecordDecl::conversion_iterator
19657 I = CXXRecord->conversion_begin(),
19658 E = CXXRecord->conversion_end(); I != E; ++I)
19659 I.setAccess((*I)->getAccess());
19660 }
19661
19662 // Add any implicitly-declared members to this class.
19663 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
19664
19665 if (!CXXRecord->isDependentType()) {
19666 if (!CXXRecord->isInvalidDecl()) {
19667 // If we have virtual base classes, we may end up finding multiple
19668 // final overriders for a given virtual function. Check for this
19669 // problem now.
19670 if (CXXRecord->getNumVBases()) {
19671 CXXFinalOverriderMap FinalOverriders;
19672 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
19673
19674 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19675 MEnd = FinalOverriders.end();
19676 M != MEnd; ++M) {
19677 for (OverridingMethods::iterator SO = M->second.begin(),
19678 SOEnd = M->second.end();
19679 SO != SOEnd; ++SO) {
19680 assert(SO->second.size() > 0 &&
19681 "Virtual function without overriding functions?");
19682 if (SO->second.size() == 1)
19683 continue;
19684
19685 // C++ [class.virtual]p2:
19686 // In a derived class, if a virtual member function of a base
19687 // class subobject has more than one final overrider the
19688 // program is ill-formed.
19689 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19690 << (const NamedDecl *)M->first << Record;
19691 Diag(M->first->getLocation(),
19692 diag::note_overridden_virtual_function);
19693 for (OverridingMethods::overriding_iterator
19694 OM = SO->second.begin(),
19695 OMEnd = SO->second.end();
19696 OM != OMEnd; ++OM)
19697 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19698 << (const NamedDecl *)M->first << OM->Method->getParent();
19699
19700 Record->setInvalidDecl();
19701 }
19702 }
19703 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
19704 Completed = true;
19705 }
19706 }
19707 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
19708 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
19709 }
19710 }
19711
19712 if (!Completed)
19713 Record->completeDefinition();
19714
19715 // Handle attributes before checking the layout.
19716 ProcessDeclAttributeList(S, Record, Attrs);
19717
19718 // Maybe randomize the record's decls. We automatically randomize a record
19719 // of function pointers, unless it has the "no_randomize_layout" attribute.
19720 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19721 !Record->isRandomized() && !Record->isUnion() &&
19722 (Record->hasAttr<RandomizeLayoutAttr>() ||
19723 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19724 EntirelyFunctionPointers(Record)))) {
19725 SmallVector<Decl *, 32> NewDeclOrdering;
19726 if (randstruct::randomizeStructureLayout(Context, RD: Record,
19727 FinalOrdering&: NewDeclOrdering))
19728 Record->reorderDecls(Decls: NewDeclOrdering);
19729 }
19730
19731 // We may have deferred checking for a deleted destructor. Check now.
19732 if (CXXRecord) {
19733 auto *Dtor = CXXRecord->getDestructor();
19734 if (Dtor && Dtor->isImplicit() &&
19735 ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {
19736 CXXRecord->setImplicitDestructorIsDeleted();
19737 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
19738 }
19739 }
19740
19741 if (Record->hasAttrs()) {
19742 CheckAlignasUnderalignment(Record);
19743
19744 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19745 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
19746 Range: IA->getRange(), BestCase: IA->getBestCase(),
19747 SemanticSpelling: IA->getInheritanceModel());
19748 }
19749
19750 // Check if the structure/union declaration is a type that can have zero
19751 // size in C. For C this is a language extension, for C++ it may cause
19752 // compatibility problems.
19753 bool CheckForZeroSize;
19754 if (!getLangOpts().CPlusPlus) {
19755 CheckForZeroSize = true;
19756 } else {
19757 // For C++ filter out types that cannot be referenced in C code.
19758 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
19759 CheckForZeroSize =
19760 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19761 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19762 CXXRecord->isCLike();
19763 }
19764 if (CheckForZeroSize) {
19765 bool ZeroSize = true;
19766 bool IsEmpty = true;
19767 unsigned NonBitFields = 0;
19768 for (RecordDecl::field_iterator I = Record->field_begin(),
19769 E = Record->field_end();
19770 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19771 IsEmpty = false;
19772 if (I->isUnnamedBitField()) {
19773 if (!I->isZeroLengthBitField())
19774 ZeroSize = false;
19775 } else {
19776 ++NonBitFields;
19777 QualType FieldType = I->getType();
19778 if (FieldType->isIncompleteType() ||
19779 !Context.getTypeSizeInChars(T: FieldType).isZero())
19780 ZeroSize = false;
19781 }
19782 }
19783
19784 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19785 // allowed in C++, but warn if its declaration is inside
19786 // extern "C" block.
19787 if (ZeroSize) {
19788 Diag(RecLoc, getLangOpts().CPlusPlus ?
19789 diag::warn_zero_size_struct_union_in_extern_c :
19790 diag::warn_zero_size_struct_union_compat)
19791 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19792 }
19793
19794 // Structs without named members are extension in C (C99 6.7.2.1p7),
19795 // but are accepted by GCC. In C2y, this became implementation-defined
19796 // (C2y 6.7.3.2p10).
19797 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19798 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19799 : diag::ext_no_named_members_in_struct_union)
19800 << Record->isUnion();
19801 }
19802 }
19803 } else {
19804 ObjCIvarDecl **ClsFields =
19805 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19806 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
19807 ID->setEndOfDefinitionLoc(RBrac);
19808 // Add ivar's to class's DeclContext.
19809 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19810 ClsFields[i]->setLexicalDeclContext(ID);
19811 ID->addDecl(ClsFields[i]);
19812 }
19813 // Must enforce the rule that ivars in the base classes may not be
19814 // duplicates.
19815 if (ID->getSuperClass())
19816 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
19817 } else if (ObjCImplementationDecl *IMPDecl =
19818 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
19819 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19820 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19821 // Ivar declared in @implementation never belongs to the implementation.
19822 // Only it is in implementation's lexical context.
19823 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19824 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
19825 Loc: RBrac);
19826 IMPDecl->setIvarLBraceLoc(LBrac);
19827 IMPDecl->setIvarRBraceLoc(RBrac);
19828 } else if (ObjCCategoryDecl *CDecl =
19829 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
19830 // case of ivars in class extension; all other cases have been
19831 // reported as errors elsewhere.
19832 // FIXME. Class extension does not have a LocEnd field.
19833 // CDecl->setLocEnd(RBrac);
19834 // Add ivar's to class extension's DeclContext.
19835 // Diagnose redeclaration of private ivars.
19836 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19837 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19838 if (IDecl) {
19839 if (const ObjCIvarDecl *ClsIvar =
19840 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19841 Diag(ClsFields[i]->getLocation(),
19842 diag::err_duplicate_ivar_declaration);
19843 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19844 continue;
19845 }
19846 for (const auto *Ext : IDecl->known_extensions()) {
19847 if (const ObjCIvarDecl *ClsExtIvar
19848 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19849 Diag(ClsFields[i]->getLocation(),
19850 diag::err_duplicate_ivar_declaration);
19851 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19852 continue;
19853 }
19854 }
19855 }
19856 ClsFields[i]->setLexicalDeclContext(CDecl);
19857 CDecl->addDecl(ClsFields[i]);
19858 }
19859 CDecl->setIvarLBraceLoc(LBrac);
19860 CDecl->setIvarRBraceLoc(RBrac);
19861 }
19862 }
19863 ProcessAPINotes(Record);
19864}
19865
19866// Given an integral type, return the next larger integral type
19867// (or a NULL type of no such type exists).
19868static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19869 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19870 // enum checking below.
19871 assert((T->isIntegralType(Context) ||
19872 T->isEnumeralType()) && "Integral type required!");
19873 const unsigned NumTypes = 4;
19874 QualType SignedIntegralTypes[NumTypes] = {
19875 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19876 };
19877 QualType UnsignedIntegralTypes[NumTypes] = {
19878 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19879 Context.UnsignedLongLongTy
19880 };
19881
19882 unsigned BitWidth = Context.getTypeSize(T);
19883 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19884 : UnsignedIntegralTypes;
19885 for (unsigned I = 0; I != NumTypes; ++I)
19886 if (Context.getTypeSize(T: Types[I]) > BitWidth)
19887 return Types[I];
19888
19889 return QualType();
19890}
19891
19892EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19893 EnumConstantDecl *LastEnumConst,
19894 SourceLocation IdLoc,
19895 IdentifierInfo *Id,
19896 Expr *Val) {
19897 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19898 llvm::APSInt EnumVal(IntWidth);
19899 QualType EltTy;
19900
19901 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
19902 Val = nullptr;
19903
19904 if (Val)
19905 Val = DefaultLvalueConversion(E: Val).get();
19906
19907 if (Val) {
19908 if (Enum->isDependentType() || Val->isTypeDependent() ||
19909 Val->containsErrors())
19910 EltTy = Context.DependentTy;
19911 else {
19912 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19913 // underlying type, but do allow it in all other contexts.
19914 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19915 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19916 // constant-expression in the enumerator-definition shall be a converted
19917 // constant expression of the underlying type.
19918 EltTy = Enum->getIntegerType();
19919 ExprResult Converted = CheckConvertedConstantExpression(
19920 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
19921 if (Converted.isInvalid())
19922 Val = nullptr;
19923 else
19924 Val = Converted.get();
19925 } else if (!Val->isValueDependent() &&
19926 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
19927 CanFold: AllowFoldKind::Allow)
19928 .get())) {
19929 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19930 } else {
19931 if (Enum->isComplete()) {
19932 EltTy = Enum->getIntegerType();
19933
19934 // In Obj-C and Microsoft mode, require the enumeration value to be
19935 // representable in the underlying type of the enumeration. In C++11,
19936 // we perform a non-narrowing conversion as part of converted constant
19937 // expression checking.
19938 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
19939 if (Context.getTargetInfo()
19940 .getTriple()
19941 .isWindowsMSVCEnvironment()) {
19942 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19943 } else {
19944 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19945 }
19946 }
19947
19948 // Cast to the underlying type.
19949 Val = ImpCastExprToType(E: Val, Type: EltTy,
19950 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
19951 : CK_IntegralCast)
19952 .get();
19953 } else if (getLangOpts().CPlusPlus) {
19954 // C++11 [dcl.enum]p5:
19955 // If the underlying type is not fixed, the type of each enumerator
19956 // is the type of its initializing value:
19957 // - If an initializer is specified for an enumerator, the
19958 // initializing value has the same type as the expression.
19959 EltTy = Val->getType();
19960 } else {
19961 // C99 6.7.2.2p2:
19962 // The expression that defines the value of an enumeration constant
19963 // shall be an integer constant expression that has a value
19964 // representable as an int.
19965
19966 // Complain if the value is not representable in an int.
19967 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
19968 Diag(IdLoc, getLangOpts().C23
19969 ? diag::warn_c17_compat_enum_value_not_int
19970 : diag::ext_c23_enum_value_not_int)
19971 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
19972 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19973 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19974 // Force the type of the expression to 'int'.
19975 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
19976 }
19977 EltTy = Val->getType();
19978 }
19979 }
19980 }
19981 }
19982
19983 if (!Val) {
19984 if (Enum->isDependentType())
19985 EltTy = Context.DependentTy;
19986 else if (!LastEnumConst) {
19987 // C++0x [dcl.enum]p5:
19988 // If the underlying type is not fixed, the type of each enumerator
19989 // is the type of its initializing value:
19990 // - If no initializer is specified for the first enumerator, the
19991 // initializing value has an unspecified integral type.
19992 //
19993 // GCC uses 'int' for its unspecified integral type, as does
19994 // C99 6.7.2.2p3.
19995 if (Enum->isFixed()) {
19996 EltTy = Enum->getIntegerType();
19997 }
19998 else {
19999 EltTy = Context.IntTy;
20000 }
20001 } else {
20002 // Assign the last value + 1.
20003 EnumVal = LastEnumConst->getInitVal();
20004 ++EnumVal;
20005 EltTy = LastEnumConst->getType();
20006
20007 // Check for overflow on increment.
20008 if (EnumVal < LastEnumConst->getInitVal()) {
20009 // C++0x [dcl.enum]p5:
20010 // If the underlying type is not fixed, the type of each enumerator
20011 // is the type of its initializing value:
20012 //
20013 // - Otherwise the type of the initializing value is the same as
20014 // the type of the initializing value of the preceding enumerator
20015 // unless the incremented value is not representable in that type,
20016 // in which case the type is an unspecified integral type
20017 // sufficient to contain the incremented value. If no such type
20018 // exists, the program is ill-formed.
20019 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20020 if (T.isNull() || Enum->isFixed()) {
20021 // There is no integral type larger enough to represent this
20022 // value. Complain, then allow the value to wrap around.
20023 EnumVal = LastEnumConst->getInitVal();
20024 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20025 ++EnumVal;
20026 if (Enum->isFixed())
20027 // When the underlying type is fixed, this is ill-formed.
20028 Diag(IdLoc, diag::err_enumerator_wrapped)
20029 << toString(EnumVal, 10)
20030 << EltTy;
20031 else
20032 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20033 << toString(EnumVal, 10);
20034 } else {
20035 EltTy = T;
20036 }
20037
20038 // Retrieve the last enumerator's value, extent that type to the
20039 // type that is supposed to be large enough to represent the incremented
20040 // value, then increment.
20041 EnumVal = LastEnumConst->getInitVal();
20042 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20043 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20044 ++EnumVal;
20045
20046 // If we're not in C++, diagnose the overflow of enumerator values,
20047 // which in C99 means that the enumerator value is not representable in
20048 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20049 // are representable in some larger integral type and we allow it in
20050 // older language modes as an extension.
20051 // Exclude fixed enumerators since they are diagnosed with an error for
20052 // this case.
20053 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20054 Diag(IdLoc, getLangOpts().C23
20055 ? diag::warn_c17_compat_enum_value_not_int
20056 : diag::ext_c23_enum_value_not_int)
20057 << 1 << toString(EnumVal, 10) << 1;
20058 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20059 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20060 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20061 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20062 : diag::ext_c23_enum_value_not_int)
20063 << 1 << toString(EnumVal, 10) << 1;
20064 }
20065 }
20066 }
20067
20068 if (!EltTy->isDependentType()) {
20069 // Make the enumerator value match the signedness and size of the
20070 // enumerator's type.
20071 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20072 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20073 }
20074
20075 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20076 E: Val, V: EnumVal);
20077}
20078
20079SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20080 SourceLocation IILoc) {
20081 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20082 !getLangOpts().CPlusPlus)
20083 return SkipBodyInfo();
20084
20085 // We have an anonymous enum definition. Look up the first enumerator to
20086 // determine if we should merge the definition with an existing one and
20087 // skip the body.
20088 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20089 Redecl: forRedeclarationInCurContext());
20090 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20091 if (!PrevECD)
20092 return SkipBodyInfo();
20093
20094 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20095 NamedDecl *Hidden;
20096 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20097 SkipBodyInfo Skip;
20098 Skip.Previous = Hidden;
20099 return Skip;
20100 }
20101
20102 return SkipBodyInfo();
20103}
20104
20105Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20106 SourceLocation IdLoc, IdentifierInfo *Id,
20107 const ParsedAttributesView &Attrs,
20108 SourceLocation EqualLoc, Expr *Val,
20109 SkipBodyInfo *SkipBody) {
20110 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20111 EnumConstantDecl *LastEnumConst =
20112 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20113
20114 // The scope passed in may not be a decl scope. Zip up the scope tree until
20115 // we find one that is.
20116 S = getNonFieldDeclScope(S);
20117
20118 // Verify that there isn't already something declared with this name in this
20119 // scope.
20120 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20121 RedeclarationKind::ForVisibleRedeclaration);
20122 LookupName(R, S);
20123 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20124
20125 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20126 // Maybe we will complain about the shadowed template parameter.
20127 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20128 // Just pretend that we didn't see the previous declaration.
20129 PrevDecl = nullptr;
20130 }
20131
20132 // C++ [class.mem]p15:
20133 // If T is the name of a class, then each of the following shall have a name
20134 // different from T:
20135 // - every enumerator of every member of class T that is an unscoped
20136 // enumerated type
20137 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20138 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20139 NameInfo: DeclarationNameInfo(Id, IdLoc));
20140
20141 EnumConstantDecl *New =
20142 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20143 if (!New)
20144 return nullptr;
20145
20146 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20147 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20148 // Check for other kinds of shadowing not already handled.
20149 CheckShadow(New, PrevDecl, R);
20150 }
20151
20152 // When in C++, we may get a TagDecl with the same name; in this case the
20153 // enum constant will 'hide' the tag.
20154 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20155 "Received TagDecl when not in C++!");
20156 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20157 if (isa<EnumConstantDecl>(PrevDecl))
20158 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20159 else
20160 Diag(IdLoc, diag::err_redefinition) << Id;
20161 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20162 return nullptr;
20163 }
20164 }
20165
20166 // Process attributes.
20167 ProcessDeclAttributeList(S, New, Attrs);
20168 AddPragmaAttributes(S, New);
20169 ProcessAPINotes(New);
20170
20171 // Register this decl in the current scope stack.
20172 New->setAccess(TheEnumDecl->getAccess());
20173 PushOnScopeChains(New, S);
20174
20175 ActOnDocumentableDecl(New);
20176
20177 return New;
20178}
20179
20180// Returns true when the enum initial expression does not trigger the
20181// duplicate enum warning. A few common cases are exempted as follows:
20182// Element2 = Element1
20183// Element2 = Element1 + 1
20184// Element2 = Element1 - 1
20185// Where Element2 and Element1 are from the same enum.
20186static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20187 Expr *InitExpr = ECD->getInitExpr();
20188 if (!InitExpr)
20189 return true;
20190 InitExpr = InitExpr->IgnoreImpCasts();
20191
20192 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20193 if (!BO->isAdditiveOp())
20194 return true;
20195 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20196 if (!IL)
20197 return true;
20198 if (IL->getValue() != 1)
20199 return true;
20200
20201 InitExpr = BO->getLHS();
20202 }
20203
20204 // This checks if the elements are from the same enum.
20205 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20206 if (!DRE)
20207 return true;
20208
20209 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20210 if (!EnumConstant)
20211 return true;
20212
20213 if (cast<EnumDecl>(TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20214 Enum)
20215 return true;
20216
20217 return false;
20218}
20219
20220// Emits a warning when an element is implicitly set a value that
20221// a previous element has already been set to.
20222static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20223 EnumDecl *Enum, QualType EnumType) {
20224 // Avoid anonymous enums
20225 if (!Enum->getIdentifier())
20226 return;
20227
20228 // Only check for small enums.
20229 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20230 return;
20231
20232 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20233 return;
20234
20235 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20236 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20237
20238 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20239
20240 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20241 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20242
20243 // Use int64_t as a key to avoid needing special handling for map keys.
20244 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20245 llvm::APSInt Val = D->getInitVal();
20246 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20247 };
20248
20249 DuplicatesVector DupVector;
20250 ValueToVectorMap EnumMap;
20251
20252 // Populate the EnumMap with all values represented by enum constants without
20253 // an initializer.
20254 for (auto *Element : Elements) {
20255 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20256
20257 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20258 // this constant. Skip this enum since it may be ill-formed.
20259 if (!ECD) {
20260 return;
20261 }
20262
20263 // Constants with initializers are handled in the next loop.
20264 if (ECD->getInitExpr())
20265 continue;
20266
20267 // Duplicate values are handled in the next loop.
20268 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20269 }
20270
20271 if (EnumMap.size() == 0)
20272 return;
20273
20274 // Create vectors for any values that has duplicates.
20275 for (auto *Element : Elements) {
20276 // The last loop returned if any constant was null.
20277 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20278 if (!ValidDuplicateEnum(ECD, Enum))
20279 continue;
20280
20281 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20282 if (Iter == EnumMap.end())
20283 continue;
20284
20285 DeclOrVector& Entry = Iter->second;
20286 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20287 // Ensure constants are different.
20288 if (D == ECD)
20289 continue;
20290
20291 // Create new vector and push values onto it.
20292 auto Vec = std::make_unique<ECDVector>();
20293 Vec->push_back(Elt: D);
20294 Vec->push_back(Elt: ECD);
20295
20296 // Update entry to point to the duplicates vector.
20297 Entry = Vec.get();
20298
20299 // Store the vector somewhere we can consult later for quick emission of
20300 // diagnostics.
20301 DupVector.emplace_back(Args: std::move(Vec));
20302 continue;
20303 }
20304
20305 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20306 // Make sure constants are not added more than once.
20307 if (*Vec->begin() == ECD)
20308 continue;
20309
20310 Vec->push_back(Elt: ECD);
20311 }
20312
20313 // Emit diagnostics.
20314 for (const auto &Vec : DupVector) {
20315 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20316
20317 // Emit warning for one enum constant.
20318 auto *FirstECD = Vec->front();
20319 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20320 << FirstECD << toString(FirstECD->getInitVal(), 10)
20321 << FirstECD->getSourceRange();
20322
20323 // Emit one note for each of the remaining enum constants with
20324 // the same value.
20325 for (auto *ECD : llvm::drop_begin(*Vec))
20326 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20327 << ECD << toString(ECD->getInitVal(), 10)
20328 << ECD->getSourceRange();
20329 }
20330}
20331
20332bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20333 bool AllowMask) const {
20334 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20335 assert(ED->isCompleteDefinition() && "expected enum definition");
20336
20337 auto R = FlagBitsCache.try_emplace(Key: ED);
20338 llvm::APInt &FlagBits = R.first->second;
20339
20340 if (R.second) {
20341 for (auto *E : ED->enumerators()) {
20342 const auto &EVal = E->getInitVal();
20343 // Only single-bit enumerators introduce new flag values.
20344 if (EVal.isPowerOf2())
20345 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20346 }
20347 }
20348
20349 // A value is in a flag enum if either its bits are a subset of the enum's
20350 // flag bits (the first condition) or we are allowing masks and the same is
20351 // true of its complement (the second condition). When masks are allowed, we
20352 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20353 //
20354 // While it's true that any value could be used as a mask, the assumption is
20355 // that a mask will have all of the insignificant bits set. Anything else is
20356 // likely a logic error.
20357 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20358 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20359}
20360
20361void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20362 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20363 const ParsedAttributesView &Attrs) {
20364 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20365 QualType EnumType = Context.getTypeDeclType(Enum);
20366
20367 ProcessDeclAttributeList(S, Enum, Attrs);
20368 ProcessAPINotes(Enum);
20369
20370 if (Enum->isDependentType()) {
20371 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20372 EnumConstantDecl *ECD =
20373 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20374 if (!ECD) continue;
20375
20376 ECD->setType(EnumType);
20377 }
20378
20379 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20380 return;
20381 }
20382
20383 // Verify that all the values are okay, compute the size of the values, and
20384 // reverse the list.
20385 unsigned NumNegativeBits = 0;
20386 unsigned NumPositiveBits = 0;
20387 bool MembersRepresentableByInt =
20388 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20389
20390 // Figure out the type that should be used for this enum.
20391 QualType BestType;
20392 unsigned BestWidth;
20393
20394 // C++0x N3000 [conv.prom]p3:
20395 // An rvalue of an unscoped enumeration type whose underlying
20396 // type is not fixed can be converted to an rvalue of the first
20397 // of the following types that can represent all the values of
20398 // the enumeration: int, unsigned int, long int, unsigned long
20399 // int, long long int, or unsigned long long int.
20400 // C99 6.4.4.3p2:
20401 // An identifier declared as an enumeration constant has type int.
20402 // The C99 rule is modified by C23.
20403 QualType BestPromotionType;
20404
20405 bool Packed = Enum->hasAttr<PackedAttr>();
20406 // -fshort-enums is the equivalent to specifying the packed attribute on all
20407 // enum definitions.
20408 if (LangOpts.ShortEnums)
20409 Packed = true;
20410
20411 // If the enum already has a type because it is fixed or dictated by the
20412 // target, promote that type instead of analyzing the enumerators.
20413 if (Enum->isComplete()) {
20414 BestType = Enum->getIntegerType();
20415 if (Context.isPromotableIntegerType(T: BestType))
20416 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20417 else
20418 BestPromotionType = BestType;
20419
20420 BestWidth = Context.getIntWidth(T: BestType);
20421 } else {
20422 bool EnumTooLarge = Context.computeBestEnumTypes(
20423 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20424 BestWidth = Context.getIntWidth(T: BestType);
20425 if (EnumTooLarge)
20426 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20427 }
20428
20429 // Loop over all of the enumerator constants, changing their types to match
20430 // the type of the enum if needed.
20431 for (auto *D : Elements) {
20432 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20433 if (!ECD) continue; // Already issued a diagnostic.
20434
20435 // C99 says the enumerators have int type, but we allow, as an
20436 // extension, the enumerators to be larger than int size. If each
20437 // enumerator value fits in an int, type it as an int, otherwise type it the
20438 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20439 // that X has type 'int', not 'unsigned'.
20440
20441 // Determine whether the value fits into an int.
20442 llvm::APSInt InitVal = ECD->getInitVal();
20443
20444 // If it fits into an integer type, force it. Otherwise force it to match
20445 // the enum decl type.
20446 QualType NewTy;
20447 unsigned NewWidth;
20448 bool NewSign;
20449 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20450 MembersRepresentableByInt) {
20451 // C23 6.7.3.3.3p15:
20452 // The enumeration member type for an enumerated type without fixed
20453 // underlying type upon completion is:
20454 // - int if all the values of the enumeration are representable as an
20455 // int; or,
20456 // - the enumerated type
20457 NewTy = Context.IntTy;
20458 NewWidth = Context.getTargetInfo().getIntWidth();
20459 NewSign = true;
20460 } else if (ECD->getType() == BestType) {
20461 // Already the right type!
20462 if (getLangOpts().CPlusPlus)
20463 // C++ [dcl.enum]p4: Following the closing brace of an
20464 // enum-specifier, each enumerator has the type of its
20465 // enumeration.
20466 ECD->setType(EnumType);
20467 continue;
20468 } else {
20469 NewTy = BestType;
20470 NewWidth = BestWidth;
20471 NewSign = BestType->isSignedIntegerOrEnumerationType();
20472 }
20473
20474 // Adjust the APSInt value.
20475 InitVal = InitVal.extOrTrunc(width: NewWidth);
20476 InitVal.setIsSigned(NewSign);
20477 ECD->setInitVal(C: Context, V: InitVal);
20478
20479 // Adjust the Expr initializer and type.
20480 if (ECD->getInitExpr() &&
20481 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20482 ECD->setInitExpr(ImplicitCastExpr::Create(
20483 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20484 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20485 if (getLangOpts().CPlusPlus)
20486 // C++ [dcl.enum]p4: Following the closing brace of an
20487 // enum-specifier, each enumerator has the type of its
20488 // enumeration.
20489 ECD->setType(EnumType);
20490 else
20491 ECD->setType(NewTy);
20492 }
20493
20494 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20495 NumPositiveBits, NumNegativeBits);
20496
20497 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20498
20499 if (Enum->isClosedFlag()) {
20500 for (Decl *D : Elements) {
20501 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20502 if (!ECD) continue; // Already issued a diagnostic.
20503
20504 llvm::APSInt InitVal = ECD->getInitVal();
20505 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20506 !IsValueInFlagEnum(Enum, InitVal, true))
20507 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20508 << ECD << Enum;
20509 }
20510 }
20511
20512 // Now that the enum type is defined, ensure it's not been underaligned.
20513 if (Enum->hasAttrs())
20514 CheckAlignasUnderalignment(Enum);
20515}
20516
20517Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
20518 SourceLocation EndLoc) {
20519
20520 FileScopeAsmDecl *New =
20521 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
20522 CurContext->addDecl(New);
20523 return New;
20524}
20525
20526TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20527 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
20528 CurContext->addDecl(New);
20529 PushDeclContext(S, New);
20530 PushFunctionScope();
20531 PushCompoundScope(IsStmtExpr: false);
20532 return New;
20533}
20534
20535void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20536 D->setStmt(Statement);
20537 PopCompoundScope();
20538 PopFunctionScopeInfo();
20539 PopDeclContext();
20540}
20541
20542void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20543 IdentifierInfo* AliasName,
20544 SourceLocation PragmaLoc,
20545 SourceLocation NameLoc,
20546 SourceLocation AliasNameLoc) {
20547 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20548 NameKind: LookupOrdinaryName);
20549 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20550 AttributeCommonInfo::Form::Pragma());
20551 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20552 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20553
20554 // If a declaration that:
20555 // 1) declares a function or a variable
20556 // 2) has external linkage
20557 // already exists, add a label attribute to it.
20558 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20559 if (isDeclExternC(PrevDecl))
20560 PrevDecl->addAttr(A: Attr);
20561 else
20562 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20563 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20564 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20565 } else
20566 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20567}
20568
20569void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20570 SourceLocation PragmaLoc,
20571 SourceLocation NameLoc) {
20572 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
20573
20574 if (PrevDecl) {
20575 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20576 } else {
20577 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
20578 }
20579}
20580
20581void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20582 IdentifierInfo* AliasName,
20583 SourceLocation PragmaLoc,
20584 SourceLocation NameLoc,
20585 SourceLocation AliasNameLoc) {
20586 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
20587 NameKind: LookupOrdinaryName);
20588 WeakInfo W = WeakInfo(Name, NameLoc);
20589
20590 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20591 if (!PrevDecl->hasAttr<AliasAttr>())
20592 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
20593 DeclApplyPragmaWeak(S: TUScope, ND, W);
20594 } else {
20595 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
20596 }
20597}
20598
20599Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20600 bool Final) {
20601 assert(FD && "Expected non-null FunctionDecl");
20602
20603 // SYCL functions can be template, so we check if they have appropriate
20604 // attribute prior to checking if it is a template.
20605 if (LangOpts.SYCLIsDevice && FD->hasAttr<DeviceKernelAttr>())
20606 return FunctionEmissionStatus::Emitted;
20607
20608 // Templates are emitted when they're instantiated.
20609 if (FD->isDependentContext())
20610 return FunctionEmissionStatus::TemplateDiscarded;
20611
20612 // Check whether this function is an externally visible definition.
20613 auto IsEmittedForExternalSymbol = [this, FD]() {
20614 // We have to check the GVA linkage of the function's *definition* -- if we
20615 // only have a declaration, we don't know whether or not the function will
20616 // be emitted, because (say) the definition could include "inline".
20617 const FunctionDecl *Def = FD->getDefinition();
20618
20619 // We can't compute linkage when we skip function bodies.
20620 return Def && !Def->hasSkippedBody() &&
20621 !isDiscardableGVALinkage(
20622 L: getASTContext().GetGVALinkageForFunction(FD: Def));
20623 };
20624
20625 if (LangOpts.OpenMPIsTargetDevice) {
20626 // In OpenMP device mode we will not emit host only functions, or functions
20627 // we don't need due to their linkage.
20628 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20629 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20630 // DevTy may be changed later by
20631 // #pragma omp declare target to(*) device_type(*).
20632 // Therefore DevTy having no value does not imply host. The emission status
20633 // will be checked again at the end of compilation unit with Final = true.
20634 if (DevTy)
20635 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20636 return FunctionEmissionStatus::OMPDiscarded;
20637 // If we have an explicit value for the device type, or we are in a target
20638 // declare context, we need to emit all extern and used symbols.
20639 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20640 if (IsEmittedForExternalSymbol())
20641 return FunctionEmissionStatus::Emitted;
20642 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20643 // we'll omit it.
20644 if (Final)
20645 return FunctionEmissionStatus::OMPDiscarded;
20646 } else if (LangOpts.OpenMP > 45) {
20647 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20648 // function. In 5.0, no_host was introduced which might cause a function to
20649 // be omitted.
20650 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20651 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20652 if (DevTy)
20653 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20654 return FunctionEmissionStatus::OMPDiscarded;
20655 }
20656
20657 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20658 return FunctionEmissionStatus::Emitted;
20659
20660 if (LangOpts.CUDA) {
20661 // When compiling for device, host functions are never emitted. Similarly,
20662 // when compiling for host, device and global functions are never emitted.
20663 // (Technically, we do emit a host-side stub for global functions, but this
20664 // doesn't count for our purposes here.)
20665 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
20666 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20667 return FunctionEmissionStatus::CUDADiscarded;
20668 if (!LangOpts.CUDAIsDevice &&
20669 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
20670 return FunctionEmissionStatus::CUDADiscarded;
20671
20672 if (IsEmittedForExternalSymbol())
20673 return FunctionEmissionStatus::Emitted;
20674
20675 // If FD is a virtual destructor of an explicit instantiation
20676 // of a template class, return Emitted.
20677 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
20678 if (Destructor->isVirtual()) {
20679 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
20680 Destructor->getParent())) {
20681 TemplateSpecializationKind TSK =
20682 Spec->getTemplateSpecializationKind();
20683 if (TSK == TSK_ExplicitInstantiationDeclaration ||
20684 TSK == TSK_ExplicitInstantiationDefinition)
20685 return FunctionEmissionStatus::Emitted;
20686 }
20687 }
20688 }
20689 }
20690
20691 // Otherwise, the function is known-emitted if it's in our set of
20692 // known-emitted functions.
20693 return FunctionEmissionStatus::Unknown;
20694}
20695
20696bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20697 // Host-side references to a __global__ function refer to the stub, so the
20698 // function itself is never emitted and therefore should not be marked.
20699 // If we have host fn calls kernel fn calls host+device, the HD function
20700 // does not get instantiated on the host. We model this by omitting at the
20701 // call to the kernel from the callgraph. This ensures that, when compiling
20702 // for host, only HD functions actually called from the host get marked as
20703 // known-emitted.
20704 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20705 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
20706}
20707

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

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