1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NonTrivialTypeVisitor.h"
29#include "clang/AST/Randstruct.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/HLSLRuntime.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/CXXFieldCollector.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/DelayedDiagnostic.h"
44#include "clang/Sema/Initialization.h"
45#include "clang/Sema/Lookup.h"
46#include "clang/Sema/ParsedTemplate.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/SemaAMDGPU.h"
50#include "clang/Sema/SemaARM.h"
51#include "clang/Sema/SemaBPF.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaHexagon.h"
55#include "clang/Sema/SemaInternal.h"
56#include "clang/Sema/SemaObjC.h"
57#include "clang/Sema/SemaOpenACC.h"
58#include "clang/Sema/SemaOpenMP.h"
59#include "clang/Sema/SemaPPC.h"
60#include "clang/Sema/SemaProxy.h"
61#include "clang/Sema/SemaRISCV.h"
62#include "clang/Sema/SemaSYCL.h"
63#include "clang/Sema/SemaSwift.h"
64#include "clang/Sema/SemaWasm.h"
65#include "clang/Sema/Template.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/STLForwardCompat.h"
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/SmallPtrSet.h"
70#include "llvm/ADT/SmallString.h"
71#include "llvm/ADT/StringExtras.h"
72#include "llvm/ADT/StringRef.h"
73#include "llvm/Support/SaveAndRestore.h"
74#include "llvm/TargetParser/Triple.h"
75#include <algorithm>
76#include <cstring>
77#include <optional>
78#include <unordered_map>
79
80using namespace clang;
81using namespace sema;
82
83Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
84 if (OwnedType) {
85 Decl *Group[2] = { OwnedType, Ptr };
86 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
87 }
88
89 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
90}
91
92namespace {
93
94class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
95 public:
96 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
97 bool AllowTemplates = false,
98 bool AllowNonTemplates = true)
99 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
100 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
101 WantExpressionKeywords = false;
102 WantCXXNamedCasts = false;
103 WantRemainingKeywords = false;
104 }
105
106 bool ValidateCandidate(const TypoCorrection &candidate) override {
107 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
108 if (!AllowInvalidDecl && ND->isInvalidDecl())
109 return false;
110
111 if (getAsTypeTemplateDecl(D: ND))
112 return AllowTemplates;
113
114 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
115 if (!IsType)
116 return false;
117
118 if (AllowNonTemplates)
119 return true;
120
121 // An injected-class-name of a class template (specialization) is valid
122 // as a template or as a non-template.
123 if (AllowTemplates) {
124 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
125 if (!RD || !RD->isInjectedClassName())
126 return false;
127 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
128 return RD->getDescribedClassTemplate() ||
129 isa<ClassTemplateSpecializationDecl>(Val: RD);
130 }
131
132 return false;
133 }
134
135 return !WantClassName && candidate.isKeyword();
136 }
137
138 std::unique_ptr<CorrectionCandidateCallback> clone() override {
139 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
140 }
141
142 private:
143 bool AllowInvalidDecl;
144 bool WantClassName;
145 bool AllowTemplates;
146 bool AllowNonTemplates;
147};
148
149} // end anonymous namespace
150
151void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
152 TypeDecl *TD, SourceLocation NameLoc) {
153 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
154 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
155 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
156 FoundRD->isInjectedClassName() &&
157 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
158 Diag(Loc: NameLoc,
159 DiagID: DCK == DiagCtorKind::Typename
160 ? diag::ext_out_of_line_qualified_id_type_names_constructor
161 : diag::err_out_of_line_qualified_id_type_names_constructor)
162 << TD->getIdentifier() << /*Type=*/1
163 << 0 /*if any keyword was present, it was 'typename'*/;
164 }
165
166 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
167 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
168}
169
170namespace {
171enum class UnqualifiedTypeNameLookupResult {
172 NotFound,
173 FoundNonType,
174 FoundType
175};
176} // end anonymous namespace
177
178/// Tries to perform unqualified lookup of the type decls in bases for
179/// dependent class.
180/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
181/// type decl, \a FoundType if only type decls are found.
182static UnqualifiedTypeNameLookupResult
183lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
184 SourceLocation NameLoc,
185 const CXXRecordDecl *RD) {
186 if (!RD->hasDefinition())
187 return UnqualifiedTypeNameLookupResult::NotFound;
188 // Look for type decls in base classes.
189 UnqualifiedTypeNameLookupResult FoundTypeDecl =
190 UnqualifiedTypeNameLookupResult::NotFound;
191 for (const auto &Base : RD->bases()) {
192 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
193 if (BaseRD) {
194 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
195 Val: Base.getType().getCanonicalType())) {
196 // Look for type decls in dependent base classes that have known primary
197 // templates.
198 if (!TST->isDependentType())
199 continue;
200 auto *TD = TST->getTemplateName().getAsTemplateDecl();
201 if (!TD)
202 continue;
203 if (auto *BasePrimaryTemplate =
204 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
205 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
206 BaseRD = BasePrimaryTemplate;
207 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
208 if (const ClassTemplatePartialSpecializationDecl *PS =
209 CTD->findPartialSpecialization(T: Base.getType()))
210 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
211 BaseRD = PS;
212 }
213 }
214 }
215 if (BaseRD) {
216 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
217 if (!isa<TypeDecl>(Val: ND))
218 return UnqualifiedTypeNameLookupResult::FoundNonType;
219 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220 }
221 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
223 case UnqualifiedTypeNameLookupResult::FoundNonType:
224 return UnqualifiedTypeNameLookupResult::FoundNonType;
225 case UnqualifiedTypeNameLookupResult::FoundType:
226 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227 break;
228 case UnqualifiedTypeNameLookupResult::NotFound:
229 break;
230 }
231 }
232 }
233 }
234
235 return FoundTypeDecl;
236}
237
238static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
239 const IdentifierInfo &II,
240 SourceLocation NameLoc) {
241 // Lookup in the parent class template context, if any.
242 const CXXRecordDecl *RD = nullptr;
243 UnqualifiedTypeNameLookupResult FoundTypeDecl =
244 UnqualifiedTypeNameLookupResult::NotFound;
245 for (DeclContext *DC = S.CurContext;
246 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
247 DC = DC->getParent()) {
248 // Look for type decls in dependent base classes that have known primary
249 // templates.
250 RD = dyn_cast<CXXRecordDecl>(Val: DC);
251 if (RD && RD->getDescribedClassTemplate())
252 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
253 }
254 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
255 return nullptr;
256
257 // We found some types in dependent base classes. Recover as if the user
258 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
259 // allowed. We'll fully resolve the lookup during template instantiation.
260 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
261
262 ASTContext &Context = S.Context;
263 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
264 QualType T =
265 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
266
267 CXXScopeSpec SS;
268 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
269
270 TypeLocBuilder Builder;
271 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
272 DepTL.setNameLoc(NameLoc);
273 DepTL.setElaboratedKeywordLoc(SourceLocation());
274 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
275 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
276}
277
278ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
279 Scope *S, CXXScopeSpec *SS, bool isClassName,
280 bool HasTrailingDot, ParsedType ObjectTypePtr,
281 bool IsCtorOrDtorName,
282 bool WantNontrivialTypeSourceInfo,
283 bool IsClassTemplateDeductionContext,
284 ImplicitTypenameContext AllowImplicitTypename,
285 IdentifierInfo **CorrectedII) {
286 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
287 // FIXME: Consider allowing this outside C++1z mode as an extension.
288 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
289 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
290 !HasTrailingDot;
291
292 // Determine where we will perform name lookup.
293 DeclContext *LookupCtx = nullptr;
294 if (ObjectTypePtr) {
295 QualType ObjectType = ObjectTypePtr.get();
296 if (ObjectType->isRecordType())
297 LookupCtx = computeDeclContext(T: ObjectType);
298 } else if (SS && SS->isNotEmpty()) {
299 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
300
301 if (!LookupCtx) {
302 if (isDependentScopeSpecifier(SS: *SS)) {
303 // C++ [temp.res]p3:
304 // A qualified-id that refers to a type and in which the
305 // nested-name-specifier depends on a template-parameter (14.6.2)
306 // shall be prefixed by the keyword typename to indicate that the
307 // qualified-id denotes a type, forming an
308 // elaborated-type-specifier (7.1.5.3).
309 //
310 // We therefore do not perform any name lookup if the result would
311 // refer to a member of an unknown specialization.
312 // In C++2a, in several contexts a 'typename' is not required. Also
313 // allow this as an extension.
314 if (IsImplicitTypename) {
315 if (AllowImplicitTypename == ImplicitTypenameContext::No)
316 return nullptr;
317 SourceLocation QualifiedLoc = SS->getRange().getBegin();
318 // FIXME: Defer the diagnostic after we build the type and use it.
319 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
320 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
321 NNS: SS->getScopeRep(), Name: &II);
322 if (!getLangOpts().CPlusPlus20)
323 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
324 }
325
326 // We know from the grammar that this name refers to a type,
327 // so build a dependent node to describe the type.
328 if (WantNontrivialTypeSourceInfo)
329 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
330 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
331 .get();
332
333 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
334 QualType T = CheckTypenameType(
335 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
336 : ElaboratedTypeKeyword::None,
337 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
338 return ParsedType::make(P: T);
339 }
340
341 return nullptr;
342 }
343
344 if (!LookupCtx->isDependentContext() &&
345 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
346 return nullptr;
347 }
348
349 // In the case where we know that the identifier is a class name, we know that
350 // it is a type declaration (struct, class, union or enum) so we can use tag
351 // name lookup.
352 //
353 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
354 // the component name of the type-name or simple-template-id is type-only.
355 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
356 LookupResult Result(*this, &II, NameLoc, Kind);
357 if (LookupCtx) {
358 // Perform "qualified" name lookup into the declaration context we
359 // computed, which is either the type of the base of a member access
360 // expression or the declaration context associated with a prior
361 // nested-name-specifier.
362 LookupQualifiedName(R&: Result, LookupCtx);
363
364 if (ObjectTypePtr && Result.empty()) {
365 // C++ [basic.lookup.classref]p3:
366 // If the unqualified-id is ~type-name, the type-name is looked up
367 // in the context of the entire postfix-expression. If the type T of
368 // the object expression is of a class type C, the type-name is also
369 // looked up in the scope of class C. At least one of the lookups shall
370 // find a name that refers to (possibly cv-qualified) T.
371 LookupName(R&: Result, S);
372 }
373 } else {
374 // Perform unqualified name lookup.
375 LookupName(R&: Result, S);
376
377 // For unqualified lookup in a class template in MSVC mode, look into
378 // dependent base classes where the primary class template is known.
379 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
380 if (ParsedType TypeInBase =
381 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
382 return TypeInBase;
383 }
384 }
385
386 NamedDecl *IIDecl = nullptr;
387 UsingShadowDecl *FoundUsingShadow = nullptr;
388 switch (Result.getResultKind()) {
389 case LookupResultKind::NotFound:
390 if (CorrectedII) {
391 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
392 AllowDeducedTemplate);
393 TypoCorrection Correction =
394 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
395 Mode: CorrectTypoKind::ErrorRecovery);
396 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
397 TemplateTy Template;
398 bool MemberOfUnknownSpecialization;
399 UnqualifiedId TemplateName;
400 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
401 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
402 CXXScopeSpec NewSS, *NewSSPtr = SS;
403 if (SS && NNS) {
404 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
405 NewSSPtr = &NewSS;
406 }
407 if (Correction && (NNS || NewII != &II) &&
408 // Ignore a correction to a template type as the to-be-corrected
409 // identifier is not a template (typo correction for template names
410 // is handled elsewhere).
411 !(getLangOpts().CPlusPlus && NewSSPtr &&
412 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
413 Template, MemberOfUnknownSpecialization))) {
414 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
415 isClassName, HasTrailingDot, ObjectTypePtr,
416 IsCtorOrDtorName,
417 WantNontrivialTypeSourceInfo,
418 IsClassTemplateDeductionContext);
419 if (Ty) {
420 diagnoseTypo(Correction,
421 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
422 << Result.getLookupName() << isClassName);
423 if (SS && NNS)
424 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
425 *CorrectedII = NewII;
426 return Ty;
427 }
428 }
429 }
430 Result.suppressDiagnostics();
431 return nullptr;
432 case LookupResultKind::NotFoundInCurrentInstantiation:
433 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
434 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
435 NNS: SS->getScopeRep(), Name: &II);
436 TypeLocBuilder TLB;
437 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
438 TL.setElaboratedKeywordLoc(SourceLocation());
439 TL.setQualifierLoc(SS->getWithLocInContext(Context));
440 TL.setNameLoc(NameLoc);
441 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
442 }
443 [[fallthrough]];
444 case LookupResultKind::FoundOverloaded:
445 case LookupResultKind::FoundUnresolvedValue:
446 Result.suppressDiagnostics();
447 return nullptr;
448
449 case LookupResultKind::Ambiguous:
450 // Recover from type-hiding ambiguities by hiding the type. We'll
451 // do the lookup again when looking for an object, and we can
452 // diagnose the error then. If we don't do this, then the error
453 // about hiding the type will be immediately followed by an error
454 // that only makes sense if the identifier was treated like a type.
455 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
456 Result.suppressDiagnostics();
457 return nullptr;
458 }
459
460 // Look to see if we have a type anywhere in the list of results.
461 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
462 Res != ResEnd; ++Res) {
463 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
464 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
465 Val: RealRes) ||
466 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
467 if (!IIDecl ||
468 // Make the selection of the recovery decl deterministic.
469 RealRes->getLocation() < IIDecl->getLocation()) {
470 IIDecl = RealRes;
471 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
472 }
473 }
474 }
475
476 if (!IIDecl) {
477 // None of the entities we found is a type, so there is no way
478 // to even assume that the result is a type. In this case, don't
479 // complain about the ambiguity. The parser will either try to
480 // perform this lookup again (e.g., as an object name), which
481 // will produce the ambiguity, or will complain that it expected
482 // a type name.
483 Result.suppressDiagnostics();
484 return nullptr;
485 }
486
487 // We found a type within the ambiguous lookup; diagnose the
488 // ambiguity and then return that type. This might be the right
489 // answer, or it might not be, but it suppresses any attempt to
490 // perform the name lookup again.
491 break;
492
493 case LookupResultKind::Found:
494 IIDecl = Result.getFoundDecl();
495 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
496 break;
497 }
498
499 assert(IIDecl && "Didn't find decl");
500
501 TypeLocBuilder TLB;
502 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
503 checkTypeDeclType(LookupCtx,
504 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
505 : DiagCtorKind::None,
506 TD, NameLoc);
507 QualType T;
508 if (FoundUsingShadow) {
509 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
510 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
511 D: FoundUsingShadow);
512 if (!WantNontrivialTypeSourceInfo)
513 return ParsedType::make(P: T);
514 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
515 QualifierLoc: SS ? SS->getWithLocInContext(Context)
516 : NestedNameSpecifierLoc(),
517 NameLoc);
518 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
519 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
520 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
521 /*OwnsTag=*/false);
522 if (!WantNontrivialTypeSourceInfo)
523 return ParsedType::make(P: T);
524 auto TL = TLB.push<TagTypeLoc>(T);
525 TL.setElaboratedKeywordLoc(SourceLocation());
526 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
527 : NestedNameSpecifierLoc());
528 TL.setNameLoc(NameLoc);
529 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
530 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
531 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
532 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
533 if (!WantNontrivialTypeSourceInfo)
534 return ParsedType::make(P: T);
535 TLB.push<TypedefTypeLoc>(T).set(
536 /*ElaboratedKeywordLoc=*/SourceLocation(),
537 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
538 NameLoc);
539 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
540 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
541 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
542 D: UD);
543 if (!WantNontrivialTypeSourceInfo)
544 return ParsedType::make(P: T);
545 TLB.push<UnresolvedUsingTypeLoc>(T).set(
546 /*ElaboratedKeywordLoc=*/SourceLocation(),
547 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
548 NameLoc);
549 } else {
550 T = Context.getTypeDeclType(Decl: TD);
551 if (!WantNontrivialTypeSourceInfo)
552 return ParsedType::make(P: T);
553 if (isa<ObjCTypeParamType>(Val: T))
554 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
555 else
556 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
557 }
558 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
559 }
560
561 if (getLangOpts().HLSL) {
562 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
563 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
564 /*AllowDependent=*/false))) {
565 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
566 if (!ShorthandTy.isNull())
567 return ParsedType::make(P: ShorthandTy);
568 }
569 }
570
571 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
572 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
573 if (!HasTrailingDot) {
574 // FIXME: Support UsingType for this case.
575 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
576 if (!WantNontrivialTypeSourceInfo)
577 return ParsedType::make(P: T);
578 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
579 TL.setNameLoc(NameLoc);
580 // FIXME: Pass in this source location.
581 TL.setNameEndLoc(NameLoc);
582 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
583 }
584 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
585 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
586 // Recover with 'int'
587 return ParsedType::make(P: Context.IntTy);
588 } else if (AllowDeducedTemplate) {
589 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
590 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
591 // FIXME: Support UsingType here.
592 TemplateName Template = Context.getQualifiedTemplateName(
593 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
594 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
595 QualType T = Context.getDeducedTemplateSpecializationType(
596 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
597 Template);
598 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
599 TL.setElaboratedKeywordLoc(SourceLocation());
600 TL.setNameLoc(NameLoc);
601 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
602 : NestedNameSpecifierLoc());
603 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
604 }
605 }
606
607 // As it's not plausibly a type, suppress diagnostics.
608 Result.suppressDiagnostics();
609 return nullptr;
610}
611
612// Builds a fake NNS for the given decl context.
613static NestedNameSpecifier
614synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
615 for (;; DC = DC->getLookupParent()) {
616 DC = DC->getPrimaryContext();
617 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
618 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
619 return NestedNameSpecifier(Context, ND, std::nullopt);
620 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
621 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
622 if (isa<TranslationUnitDecl>(Val: DC))
623 return NestedNameSpecifier::getGlobal();
624 }
625 llvm_unreachable("something isn't in TU scope?");
626}
627
628/// Find the parent class with dependent bases of the innermost enclosing method
629/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
630/// up allowing unqualified dependent type names at class-level, which MSVC
631/// correctly rejects.
632static const CXXRecordDecl *
633findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
634 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
635 DC = DC->getPrimaryContext();
636 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
637 if (MD->getParent()->hasAnyDependentBases())
638 return MD->getParent();
639 }
640 return nullptr;
641}
642
643ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
644 SourceLocation NameLoc,
645 bool IsTemplateTypeArg) {
646 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
647
648 NestedNameSpecifier NNS = std::nullopt;
649 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
650 // If we weren't able to parse a default template argument, delay lookup
651 // until instantiation time by making a non-dependent DependentTypeName. We
652 // pretend we saw a NestedNameSpecifier referring to the current scope, and
653 // lookup is retried.
654 // FIXME: This hurts our diagnostic quality, since we get errors like "no
655 // type named 'Foo' in 'current_namespace'" when the user didn't write any
656 // name specifiers.
657 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
658 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
659 } else if (const CXXRecordDecl *RD =
660 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
661 // Build a DependentNameType that will perform lookup into RD at
662 // instantiation time.
663 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
664
665 // Diagnose that this identifier was undeclared, and retry the lookup during
666 // template instantiation.
667 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
668 << RD;
669 } else {
670 // This is not a situation that we should recover from.
671 return ParsedType();
672 }
673
674 QualType T =
675 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
676
677 // Build type location information. We synthesized the qualifier, so we have
678 // to build a fake NestedNameSpecifierLoc.
679 NestedNameSpecifierLocBuilder NNSLocBuilder;
680 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
681 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
682
683 TypeLocBuilder Builder;
684 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
685 DepTL.setNameLoc(NameLoc);
686 DepTL.setElaboratedKeywordLoc(SourceLocation());
687 DepTL.setQualifierLoc(QualifierLoc);
688 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
689}
690
691DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
692 // Do a tag name lookup in this scope.
693 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
694 LookupName(R, S, AllowBuiltinCreation: false);
695 R.suppressDiagnostics();
696 if (R.getResultKind() == LookupResultKind::Found)
697 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
698 switch (TD->getTagKind()) {
699 case TagTypeKind::Struct:
700 return DeclSpec::TST_struct;
701 case TagTypeKind::Interface:
702 return DeclSpec::TST_interface;
703 case TagTypeKind::Union:
704 return DeclSpec::TST_union;
705 case TagTypeKind::Class:
706 return DeclSpec::TST_class;
707 case TagTypeKind::Enum:
708 return DeclSpec::TST_enum;
709 }
710 }
711
712 return DeclSpec::TST_unspecified;
713}
714
715bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
716 if (!CurContext->isRecord())
717 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
718
719 switch (SS->getScopeRep().getKind()) {
720 case NestedNameSpecifier::Kind::MicrosoftSuper:
721 return true;
722 case NestedNameSpecifier::Kind::Type: {
723 QualType T(SS->getScopeRep().getAsType(), 0);
724 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
725 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
726 return true;
727 [[fallthrough]];
728 }
729 default:
730 return S->isFunctionPrototypeScope();
731 }
732}
733
734void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
735 SourceLocation IILoc,
736 Scope *S,
737 CXXScopeSpec *SS,
738 ParsedType &SuggestedType,
739 bool IsTemplateName) {
740 // Don't report typename errors for editor placeholders.
741 if (II->isEditorPlaceholder())
742 return;
743 // We don't have anything to suggest (yet).
744 SuggestedType = nullptr;
745
746 // There may have been a typo in the name of the type. Look up typo
747 // results, in case we have something that we can suggest.
748 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
749 /*AllowTemplates=*/IsTemplateName,
750 /*AllowNonTemplates=*/!IsTemplateName);
751 if (TypoCorrection Corrected =
752 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
753 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
754 // FIXME: Support error recovery for the template-name case.
755 bool CanRecover = !IsTemplateName;
756 if (Corrected.isKeyword()) {
757 // We corrected to a keyword.
758 diagnoseTypo(Correction: Corrected,
759 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
760 : diag::err_unknown_typename_suggest)
761 << II);
762 II = Corrected.getCorrectionAsIdentifierInfo();
763 } else {
764 // We found a similarly-named type or interface; suggest that.
765 if (!SS || !SS->isSet()) {
766 diagnoseTypo(Correction: Corrected,
767 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
768 : diag::err_unknown_typename_suggest)
769 << II, ErrorRecovery: CanRecover);
770 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
771 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
772 bool DroppedSpecifier =
773 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
774 diagnoseTypo(Correction: Corrected,
775 TypoDiag: PDiag(DiagID: IsTemplateName
776 ? diag::err_no_member_template_suggest
777 : diag::err_unknown_nested_typename_suggest)
778 << II << DC << DroppedSpecifier << SS->getRange(),
779 ErrorRecovery: CanRecover);
780 } else {
781 llvm_unreachable("could not have corrected a typo here");
782 }
783
784 if (!CanRecover)
785 return;
786
787 CXXScopeSpec tmpSS;
788 if (Corrected.getCorrectionSpecifier())
789 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
790 R: SourceRange(IILoc));
791 // FIXME: Support class template argument deduction here.
792 SuggestedType =
793 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
794 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
795 /*IsCtorOrDtorName=*/false,
796 /*WantNontrivialTypeSourceInfo=*/true);
797 }
798 return;
799 }
800
801 if (getLangOpts().CPlusPlus && !IsTemplateName) {
802 // See if II is a class template that the user forgot to pass arguments to.
803 UnqualifiedId Name;
804 Name.setIdentifier(Id: II, IdLoc: IILoc);
805 CXXScopeSpec EmptySS;
806 TemplateTy TemplateResult;
807 bool MemberOfUnknownSpecialization;
808 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
809 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
810 MemberOfUnknownSpecialization) == TNK_Type_template) {
811 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
812 return;
813 }
814 }
815
816 // FIXME: Should we move the logic that tries to recover from a missing tag
817 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
818
819 if (!SS || (!SS->isSet() && !SS->isInvalid()))
820 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
821 : diag::err_unknown_typename)
822 << II;
823 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
824 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
825 : diag::err_typename_nested_not_found)
826 << II << DC << SS->getRange();
827 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
828 SuggestedType =
829 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
830 } else if (isDependentScopeSpecifier(SS: *SS)) {
831 unsigned DiagID = diag::err_typename_missing;
832 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
833 DiagID = diag::ext_typename_missing;
834
835 SuggestedType =
836 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
837
838 Diag(Loc: SS->getRange().getBegin(), DiagID)
839 << GetTypeFromParser(Ty: SuggestedType)
840 << SourceRange(SS->getRange().getBegin(), IILoc)
841 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
842 } else {
843 assert(SS && SS->isInvalid() &&
844 "Invalid scope specifier has already been diagnosed");
845 }
846}
847
848/// Determine whether the given result set contains either a type name
849/// or
850static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
851 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
852 NextToken.is(K: tok::less);
853
854 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
855 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
856 return true;
857
858 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
859 return true;
860 }
861
862 return false;
863}
864
865static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
866 Scope *S, CXXScopeSpec &SS,
867 IdentifierInfo *&Name,
868 SourceLocation NameLoc) {
869 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
870 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
871 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
872 StringRef FixItTagName;
873 switch (Tag->getTagKind()) {
874 case TagTypeKind::Class:
875 FixItTagName = "class ";
876 break;
877
878 case TagTypeKind::Enum:
879 FixItTagName = "enum ";
880 break;
881
882 case TagTypeKind::Struct:
883 FixItTagName = "struct ";
884 break;
885
886 case TagTypeKind::Interface:
887 FixItTagName = "__interface ";
888 break;
889
890 case TagTypeKind::Union:
891 FixItTagName = "union ";
892 break;
893 }
894
895 StringRef TagName = FixItTagName.drop_back();
896 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
897 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
898 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
899
900 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
901 I != IEnd; ++I)
902 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
903 << Name << TagName;
904
905 // Replace lookup results with just the tag decl.
906 Result.clear(Kind: Sema::LookupTagName);
907 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
908 return true;
909 }
910
911 return false;
912}
913
914Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
915 IdentifierInfo *&Name,
916 SourceLocation NameLoc,
917 const Token &NextToken,
918 CorrectionCandidateCallback *CCC) {
919 DeclarationNameInfo NameInfo(Name, NameLoc);
920 ObjCMethodDecl *CurMethod = getCurMethodDecl();
921
922 assert(NextToken.isNot(tok::coloncolon) &&
923 "parse nested name specifiers before calling ClassifyName");
924 if (getLangOpts().CPlusPlus && SS.isSet() &&
925 isCurrentClassName(II: *Name, S, SS: &SS)) {
926 // Per [class.qual]p2, this names the constructors of SS, not the
927 // injected-class-name. We don't have a classification for that.
928 // There's not much point caching this result, since the parser
929 // will reject it later.
930 return NameClassification::Unknown();
931 }
932
933 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
934 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
935 /*AllowBuiltinCreation=*/!CurMethod);
936
937 if (SS.isInvalid())
938 return NameClassification::Error();
939
940 // For unqualified lookup in a class template in MSVC mode, look into
941 // dependent base classes where the primary class template is known.
942 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
943 if (ParsedType TypeInBase =
944 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
945 return TypeInBase;
946 }
947
948 // Perform lookup for Objective-C instance variables (including automatically
949 // synthesized instance variables), if we're in an Objective-C method.
950 // FIXME: This lookup really, really needs to be folded in to the normal
951 // unqualified lookup mechanism.
952 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
953 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
954 if (Ivar.isInvalid())
955 return NameClassification::Error();
956 if (Ivar.isUsable())
957 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
958
959 // We defer builtin creation until after ivar lookup inside ObjC methods.
960 if (Result.empty())
961 LookupBuiltin(R&: Result);
962 }
963
964 bool SecondTry = false;
965 bool IsFilteredTemplateName = false;
966
967Corrected:
968 switch (Result.getResultKind()) {
969 case LookupResultKind::NotFound:
970 // If an unqualified-id is followed by '(' or '<<<', then we have a
971 // function call or kernel launch.
972 if (SS.isEmpty() && NextToken.isOneOf(Ks: tok::l_paren, Ks: tok::lesslessless)) {
973 // In C++, this is an ADL-only call.
974 // FIXME: Reference?
975 if (getLangOpts().CPlusPlus)
976 return NameClassification::UndeclaredNonType();
977
978 // C90 6.3.2.2:
979 // If the expression that precedes the parenthesized argument list in a
980 // function call consists solely of an identifier, and if no
981 // declaration is visible for this identifier, the identifier is
982 // implicitly declared exactly as if, in the innermost block containing
983 // the function call, the declaration
984 //
985 // extern int identifier ();
986 //
987 // appeared.
988 //
989 // We also allow this in C99 as an extension. However, this is not
990 // allowed in all language modes as functions without prototypes may not
991 // be supported.
992 if (getLangOpts().implicitFunctionsAllowed()) {
993 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
994 return NameClassification::NonType(D);
995 }
996 }
997
998 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
999 // In C++20 onwards, this could be an ADL-only call to a function
1000 // template, and we're required to assume that this is a template name.
1001 //
1002 // FIXME: Find a way to still do typo correction in this case.
1003 TemplateName Template =
1004 Context.getAssumedTemplateName(Name: NameInfo.getName());
1005 return NameClassification::UndeclaredTemplate(Name: Template);
1006 }
1007
1008 // In C, we first see whether there is a tag type by the same name, in
1009 // which case it's likely that the user just forgot to write "enum",
1010 // "struct", or "union".
1011 if (!getLangOpts().CPlusPlus && !SecondTry &&
1012 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1013 break;
1014 }
1015
1016 // Perform typo correction to determine if there is another name that is
1017 // close to this name.
1018 if (!SecondTry && CCC) {
1019 SecondTry = true;
1020 if (TypoCorrection Corrected =
1021 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1022 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1023 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1024 unsigned QualifiedDiag = diag::err_no_member_suggest;
1025
1026 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1027 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1028 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1029 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1030 UnqualifiedDiag = diag::err_no_template_suggest;
1031 QualifiedDiag = diag::err_no_member_template_suggest;
1032 } else if (UnderlyingFirstDecl &&
1033 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1034 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1035 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1036 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1037 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1038 }
1039
1040 if (SS.isEmpty()) {
1041 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1042 } else {// FIXME: is this even reachable? Test it.
1043 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1044 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1045 Name->getName() == CorrectedStr;
1046 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1047 << Name << computeDeclContext(SS, EnteringContext: false)
1048 << DroppedSpecifier << SS.getRange());
1049 }
1050
1051 // Update the name, so that the caller has the new name.
1052 Name = Corrected.getCorrectionAsIdentifierInfo();
1053
1054 // Typo correction corrected to a keyword.
1055 if (Corrected.isKeyword())
1056 return Name;
1057
1058 // Also update the LookupResult...
1059 // FIXME: This should probably go away at some point
1060 Result.clear();
1061 Result.setLookupName(Corrected.getCorrection());
1062 if (FirstDecl)
1063 Result.addDecl(D: FirstDecl);
1064
1065 // If we found an Objective-C instance variable, let
1066 // LookupInObjCMethod build the appropriate expression to
1067 // reference the ivar.
1068 // FIXME: This is a gross hack.
1069 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1070 DeclResult R =
1071 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1072 if (R.isInvalid())
1073 return NameClassification::Error();
1074 if (R.isUsable())
1075 return NameClassification::NonType(D: Ivar);
1076 }
1077
1078 goto Corrected;
1079 }
1080 }
1081
1082 // We failed to correct; just fall through and let the parser deal with it.
1083 Result.suppressDiagnostics();
1084 return NameClassification::Unknown();
1085
1086 case LookupResultKind::NotFoundInCurrentInstantiation: {
1087 // We performed name lookup into the current instantiation, and there were
1088 // dependent bases, so we treat this result the same way as any other
1089 // dependent nested-name-specifier.
1090
1091 // C++ [temp.res]p2:
1092 // A name used in a template declaration or definition and that is
1093 // dependent on a template-parameter is assumed not to name a type
1094 // unless the applicable name lookup finds a type name or the name is
1095 // qualified by the keyword typename.
1096 //
1097 // FIXME: If the next token is '<', we might want to ask the parser to
1098 // perform some heroics to see if we actually have a
1099 // template-argument-list, which would indicate a missing 'template'
1100 // keyword here.
1101 return NameClassification::DependentNonType();
1102 }
1103
1104 case LookupResultKind::Found:
1105 case LookupResultKind::FoundOverloaded:
1106 case LookupResultKind::FoundUnresolvedValue:
1107 break;
1108
1109 case LookupResultKind::Ambiguous:
1110 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1111 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1112 /*AllowDependent=*/false)) {
1113 // C++ [temp.local]p3:
1114 // A lookup that finds an injected-class-name (10.2) can result in an
1115 // ambiguity in certain cases (for example, if it is found in more than
1116 // one base class). If all of the injected-class-names that are found
1117 // refer to specializations of the same class template, and if the name
1118 // is followed by a template-argument-list, the reference refers to the
1119 // class template itself and not a specialization thereof, and is not
1120 // ambiguous.
1121 //
1122 // This filtering can make an ambiguous result into an unambiguous one,
1123 // so try again after filtering out template names.
1124 FilterAcceptableTemplateNames(R&: Result);
1125 if (!Result.isAmbiguous()) {
1126 IsFilteredTemplateName = true;
1127 break;
1128 }
1129 }
1130
1131 // Diagnose the ambiguity and return an error.
1132 return NameClassification::Error();
1133 }
1134
1135 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1136 (IsFilteredTemplateName ||
1137 hasAnyAcceptableTemplateNames(
1138 R&: Result, /*AllowFunctionTemplates=*/true,
1139 /*AllowDependent=*/false,
1140 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1141 getLangOpts().CPlusPlus20))) {
1142 // C++ [temp.names]p3:
1143 // After name lookup (3.4) finds that a name is a template-name or that
1144 // an operator-function-id or a literal- operator-id refers to a set of
1145 // overloaded functions any member of which is a function template if
1146 // this is followed by a <, the < is always taken as the delimiter of a
1147 // template-argument-list and never as the less-than operator.
1148 // C++2a [temp.names]p2:
1149 // A name is also considered to refer to a template if it is an
1150 // unqualified-id followed by a < and name lookup finds either one
1151 // or more functions or finds nothing.
1152 if (!IsFilteredTemplateName)
1153 FilterAcceptableTemplateNames(R&: Result);
1154
1155 bool IsFunctionTemplate;
1156 bool IsVarTemplate;
1157 TemplateName Template;
1158 if (Result.end() - Result.begin() > 1) {
1159 IsFunctionTemplate = true;
1160 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1161 End: Result.end());
1162 } else if (!Result.empty()) {
1163 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1164 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1165 /*AllowDependent=*/false));
1166 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1167 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1168
1169 UsingShadowDecl *FoundUsingShadow =
1170 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1171 assert(!FoundUsingShadow ||
1172 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1173 Template = Context.getQualifiedTemplateName(
1174 Qualifier: SS.getScopeRep(),
1175 /*TemplateKeyword=*/false,
1176 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1177 } else {
1178 // All results were non-template functions. This is a function template
1179 // name.
1180 IsFunctionTemplate = true;
1181 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1182 }
1183
1184 if (IsFunctionTemplate) {
1185 // Function templates always go through overload resolution, at which
1186 // point we'll perform the various checks (e.g., accessibility) we need
1187 // to based on which function we selected.
1188 Result.suppressDiagnostics();
1189
1190 return NameClassification::FunctionTemplate(Name: Template);
1191 }
1192
1193 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1194 : NameClassification::TypeTemplate(Name: Template);
1195 }
1196
1197 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1198 QualType T;
1199 TypeLocBuilder TLB;
1200 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1201 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1202 D: USD);
1203 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1204 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1205 } else {
1206 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1207 Decl: Type);
1208 if (isa<TagType>(Val: T)) {
1209 auto TTL = TLB.push<TagTypeLoc>(T);
1210 TTL.setElaboratedKeywordLoc(SourceLocation());
1211 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1212 TTL.setNameLoc(NameLoc);
1213 } else if (isa<TypedefType>(Val: T)) {
1214 TLB.push<TypedefTypeLoc>(T).set(
1215 /*ElaboratedKeywordLoc=*/SourceLocation(),
1216 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1217 } else if (isa<UnresolvedUsingType>(Val: T)) {
1218 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1219 /*ElaboratedKeywordLoc=*/SourceLocation(),
1220 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1221 } else {
1222 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1223 }
1224 }
1225 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1226 };
1227
1228 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1229 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1230 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1231 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1232 return BuildTypeFor(Type, *Result.begin());
1233 }
1234
1235 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1236 if (!Class) {
1237 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1238 if (ObjCCompatibleAliasDecl *Alias =
1239 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1240 Class = Alias->getClassInterface();
1241 }
1242
1243 if (Class) {
1244 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1245
1246 if (NextToken.is(K: tok::period)) {
1247 // Interface. <something> is parsed as a property reference expression.
1248 // Just return "unknown" as a fall-through for now.
1249 Result.suppressDiagnostics();
1250 return NameClassification::Unknown();
1251 }
1252
1253 QualType T = Context.getObjCInterfaceType(Decl: Class);
1254 return ParsedType::make(P: T);
1255 }
1256
1257 if (isa<ConceptDecl>(Val: FirstDecl)) {
1258 // We want to preserve the UsingShadowDecl for concepts.
1259 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1260 return NameClassification::Concept(Name: TemplateName(USD));
1261 return NameClassification::Concept(
1262 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1263 }
1264
1265 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1266 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1267 return NameClassification::Error();
1268 }
1269
1270 // We can have a type template here if we're classifying a template argument.
1271 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1272 !isa<VarTemplateDecl>(Val: FirstDecl))
1273 return NameClassification::TypeTemplate(
1274 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1275
1276 // Check for a tag type hidden by a non-type decl in a few cases where it
1277 // seems likely a type is wanted instead of the non-type that was found.
1278 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1279 if ((NextToken.is(K: tok::identifier) ||
1280 (NextIsOp &&
1281 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1282 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1283 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1284 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1285 return BuildTypeFor(Type, *Result.begin());
1286 }
1287
1288 // If we already know which single declaration is referenced, just annotate
1289 // that declaration directly. Defer resolving even non-overloaded class
1290 // member accesses, as we need to defer certain access checks until we know
1291 // the context.
1292 bool ADL = UseArgumentDependentLookup(
1293 SS, R: Result, IsCall: NextToken.isOneOf(Ks: tok::l_paren, Ks: tok::lesslessless));
1294 if (Result.isSingleResult() && !ADL &&
1295 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1296 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1297
1298 // Otherwise, this is an overload set that we will need to resolve later.
1299 Result.suppressDiagnostics();
1300 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1301 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1302 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1303 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1304}
1305
1306ExprResult
1307Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1308 SourceLocation NameLoc) {
1309 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1310 CXXScopeSpec SS;
1311 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1312 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1313}
1314
1315ExprResult
1316Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1317 IdentifierInfo *Name,
1318 SourceLocation NameLoc,
1319 bool IsAddressOfOperand) {
1320 DeclarationNameInfo NameInfo(Name, NameLoc);
1321 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1322 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1323 /*TemplateArgs=*/nullptr);
1324}
1325
1326ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1327 NamedDecl *Found,
1328 SourceLocation NameLoc,
1329 const Token &NextToken) {
1330 if (getCurMethodDecl() && SS.isEmpty())
1331 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1332 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1333
1334 // Reconstruct the lookup result.
1335 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1336 Result.addDecl(D: Found);
1337 Result.resolveKind();
1338
1339 bool ADL = UseArgumentDependentLookup(
1340 SS, R: Result, IsCall: NextToken.isOneOf(Ks: tok::l_paren, Ks: tok::lesslessless));
1341 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1342}
1343
1344ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1345 // For an implicit class member access, transform the result into a member
1346 // access expression if necessary.
1347 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1348 if ((*ULE->decls_begin())->isCXXClassMember()) {
1349 CXXScopeSpec SS;
1350 SS.Adopt(Other: ULE->getQualifierLoc());
1351
1352 // Reconstruct the lookup result.
1353 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1354 LookupOrdinaryName);
1355 Result.setNamingClass(ULE->getNamingClass());
1356 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1357 Result.addDecl(D: *I, AS: I.getAccess());
1358 Result.resolveKind();
1359 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1360 TemplateArgs: nullptr, S);
1361 }
1362
1363 // Otherwise, this is already in the form we needed, and no further checks
1364 // are necessary.
1365 return ULE;
1366}
1367
1368Sema::TemplateNameKindForDiagnostics
1369Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1370 auto *TD = Name.getAsTemplateDecl();
1371 if (!TD)
1372 return TemplateNameKindForDiagnostics::DependentTemplate;
1373 if (isa<ClassTemplateDecl>(Val: TD))
1374 return TemplateNameKindForDiagnostics::ClassTemplate;
1375 if (isa<FunctionTemplateDecl>(Val: TD))
1376 return TemplateNameKindForDiagnostics::FunctionTemplate;
1377 if (isa<VarTemplateDecl>(Val: TD))
1378 return TemplateNameKindForDiagnostics::VarTemplate;
1379 if (isa<TypeAliasTemplateDecl>(Val: TD))
1380 return TemplateNameKindForDiagnostics::AliasTemplate;
1381 if (isa<TemplateTemplateParmDecl>(Val: TD))
1382 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1383 if (isa<ConceptDecl>(Val: TD))
1384 return TemplateNameKindForDiagnostics::Concept;
1385 return TemplateNameKindForDiagnostics::DependentTemplate;
1386}
1387
1388void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1389 assert(DC->getLexicalParent() == CurContext &&
1390 "The next DeclContext should be lexically contained in the current one.");
1391 CurContext = DC;
1392 if (S)
1393 S->setEntity(DC);
1394}
1395
1396void Sema::PopDeclContext() {
1397 assert(CurContext && "DeclContext imbalance!");
1398
1399 CurContext = CurContext->getLexicalParent();
1400 assert(CurContext && "Popped translation unit!");
1401}
1402
1403Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1404 Decl *D) {
1405 // Unlike PushDeclContext, the context to which we return is not necessarily
1406 // the containing DC of TD, because the new context will be some pre-existing
1407 // TagDecl definition instead of a fresh one.
1408 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1409 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1410 assert(CurContext && "skipping definition of undefined tag");
1411 // Start lookups from the parent of the current context; we don't want to look
1412 // into the pre-existing complete definition.
1413 S->setEntity(CurContext->getLookupParent());
1414 return Result;
1415}
1416
1417void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1418 CurContext = static_cast<decltype(CurContext)>(Context);
1419}
1420
1421void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1422 // C++0x [basic.lookup.unqual]p13:
1423 // A name used in the definition of a static data member of class
1424 // X (after the qualified-id of the static member) is looked up as
1425 // if the name was used in a member function of X.
1426 // C++0x [basic.lookup.unqual]p14:
1427 // If a variable member of a namespace is defined outside of the
1428 // scope of its namespace then any name used in the definition of
1429 // the variable member (after the declarator-id) is looked up as
1430 // if the definition of the variable member occurred in its
1431 // namespace.
1432 // Both of these imply that we should push a scope whose context
1433 // is the semantic context of the declaration. We can't use
1434 // PushDeclContext here because that context is not necessarily
1435 // lexically contained in the current context. Fortunately,
1436 // the containing scope should have the appropriate information.
1437
1438 assert(!S->getEntity() && "scope already has entity");
1439
1440#ifndef NDEBUG
1441 Scope *Ancestor = S->getParent();
1442 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1443 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1444#endif
1445
1446 CurContext = DC;
1447 S->setEntity(DC);
1448
1449 if (S->getParent()->isTemplateParamScope()) {
1450 // Also set the corresponding entities for all immediately-enclosing
1451 // template parameter scopes.
1452 EnterTemplatedContext(S: S->getParent(), DC);
1453 }
1454}
1455
1456void Sema::ExitDeclaratorContext(Scope *S) {
1457 assert(S->getEntity() == CurContext && "Context imbalance!");
1458
1459 // Switch back to the lexical context. The safety of this is
1460 // enforced by an assert in EnterDeclaratorContext.
1461 Scope *Ancestor = S->getParent();
1462 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1463 CurContext = Ancestor->getEntity();
1464
1465 // We don't need to do anything with the scope, which is going to
1466 // disappear.
1467}
1468
1469void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1470 assert(S->isTemplateParamScope() &&
1471 "expected to be initializing a template parameter scope");
1472
1473 // C++20 [temp.local]p7:
1474 // In the definition of a member of a class template that appears outside
1475 // of the class template definition, the name of a member of the class
1476 // template hides the name of a template-parameter of any enclosing class
1477 // templates (but not a template-parameter of the member if the member is a
1478 // class or function template).
1479 // C++20 [temp.local]p9:
1480 // In the definition of a class template or in the definition of a member
1481 // of such a template that appears outside of the template definition, for
1482 // each non-dependent base class (13.8.2.1), if the name of the base class
1483 // or the name of a member of the base class is the same as the name of a
1484 // template-parameter, the base class name or member name hides the
1485 // template-parameter name (6.4.10).
1486 //
1487 // This means that a template parameter scope should be searched immediately
1488 // after searching the DeclContext for which it is a template parameter
1489 // scope. For example, for
1490 // template<typename T> template<typename U> template<typename V>
1491 // void N::A<T>::B<U>::f(...)
1492 // we search V then B<U> (and base classes) then U then A<T> (and base
1493 // classes) then T then N then ::.
1494 unsigned ScopeDepth = getTemplateDepth(S);
1495 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1496 DeclContext *SearchDCAfterScope = DC;
1497 for (; DC; DC = DC->getLookupParent()) {
1498 if (const TemplateParameterList *TPL =
1499 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1500 unsigned DCDepth = TPL->getDepth() + 1;
1501 if (DCDepth > ScopeDepth)
1502 continue;
1503 if (ScopeDepth == DCDepth)
1504 SearchDCAfterScope = DC = DC->getLookupParent();
1505 break;
1506 }
1507 }
1508 S->setLookupEntity(SearchDCAfterScope);
1509 }
1510}
1511
1512void Sema::ActOnReenterFunctionPrototypeParams(Scope *S,
1513 ArrayRef<ParmVarDecl *> Params) {
1514 for (ParmVarDecl *Param : Params)
1515 if (Param->getIdentifier()) {
1516 S->AddDecl(D: Param);
1517 IdResolver.AddDecl(D: Param);
1518 }
1519}
1520
1521void Sema::ActOnExitFunctionPrototypeParams(Scope *S,
1522 ArrayRef<ParmVarDecl *> Params) {
1523 // Remove in reverse so each name is the most recent one when it is removed.
1524 for (ParmVarDecl *Param : llvm::reverse(C&: Params))
1525 if (Param->getIdentifier()) {
1526 IdResolver.RemoveDecl(D: Param);
1527 S->RemoveDecl(D: Param);
1528 }
1529}
1530
1531void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1532 // We assume that the caller has already called
1533 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1534 FunctionDecl *FD = D->getAsFunction();
1535 if (!FD)
1536 return;
1537
1538 // Same implementation as PushDeclContext, but enters the context
1539 // from the lexical parent, rather than the top-level class.
1540 assert(CurContext == FD->getLexicalParent() &&
1541 "The next DeclContext should be lexically contained in the current one.");
1542 CurContext = FD;
1543 S->setEntity(CurContext);
1544
1545 ActOnReenterFunctionPrototypeParams(S, Params: FD->parameters());
1546}
1547
1548void Sema::ActOnExitFunctionContext() {
1549 // Same implementation as PopDeclContext, but returns to the lexical parent,
1550 // rather than the top-level class.
1551 assert(CurContext && "DeclContext imbalance!");
1552 CurContext = CurContext->getLexicalParent();
1553 assert(CurContext && "Popped translation unit!");
1554}
1555
1556/// Determine whether overloading is allowed for a new function
1557/// declaration considering prior declarations of the same name.
1558///
1559/// This routine determines whether overloading is possible, not
1560/// whether a new declaration actually overloads a previous one.
1561/// It will return true in C++ (where overloads are always permitted)
1562/// or, as a C extension, when either the new declaration or a
1563/// previous one is declared with the 'overloadable' attribute.
1564static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1565 ASTContext &Context,
1566 const FunctionDecl *New) {
1567 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1568 return true;
1569
1570 // Multiversion function declarations are not overloads in the
1571 // usual sense of that term, but lookup will report that an
1572 // overload set was found if more than one multiversion function
1573 // declaration is present for the same name. It is therefore
1574 // inadequate to assume that some prior declaration(s) had
1575 // the overloadable attribute; checking is required. Since one
1576 // declaration is permitted to omit the attribute, it is necessary
1577 // to check at least two; hence the 'any_of' check below. Note that
1578 // the overloadable attribute is implicitly added to declarations
1579 // that were required to have it but did not.
1580 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1581 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1582 return ND->hasAttr<OverloadableAttr>();
1583 });
1584 } else if (Previous.getResultKind() == LookupResultKind::Found)
1585 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1586
1587 return false;
1588}
1589
1590void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1591 // Move up the scope chain until we find the nearest enclosing
1592 // non-transparent context. The declaration will be introduced into this
1593 // scope.
1594 while (S->getEntity() && S->getEntity()->isTransparentContext())
1595 S = S->getParent();
1596
1597 // Add scoped declarations into their context, so that they can be
1598 // found later. Declarations without a context won't be inserted
1599 // into any context.
1600 if (AddToContext)
1601 CurContext->addDecl(D);
1602
1603 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1604 // are function-local declarations.
1605 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1606 if (!S->getFnParent())
1607 return;
1608
1609 // Even inside a function, an out-of-line definition of a type that is
1610 // nested inside a local class must not be pushed into the enclosing
1611 // function scope. For example:
1612 //
1613 // class A { public: class B; };
1614 // class A::B {}; // out-of-line definition inside the function
1615 // B b; // must fail - only A::B is valid
1616 // Wrapper{B{}} // must also fail
1617 //
1618 // Per C++ scoping rules only the qualified form A::B is accessible.
1619 // Without this guard, PushOnScopeChains would add B to the function's
1620 // local scope, making it findable via unqualified lookup, which is
1621 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1622 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1623 // of a local class being defined out-of-line.
1624 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1625 return;
1626 }
1627
1628 // Template instantiations should also not be pushed into scope.
1629 if (isa<FunctionDecl>(Val: D) &&
1630 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1631 return;
1632
1633 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1634 S->AddDecl(D);
1635 return;
1636 }
1637 // If this replaces anything in the current scope,
1638 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1639 IEnd = IdResolver.end();
1640 for (; I != IEnd; ++I) {
1641 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1642 S->RemoveDecl(D: *I);
1643 IdResolver.RemoveDecl(D: *I);
1644
1645 // Should only need to replace one decl.
1646 break;
1647 }
1648 }
1649
1650 S->AddDecl(D);
1651
1652 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1653 // Implicitly-generated labels may end up getting generated in an order that
1654 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1655 // the label at the appropriate place in the identifier chain.
1656 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1657 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1658 if (IDC == CurContext) {
1659 if (!S->isDeclScope(D: *I))
1660 continue;
1661 } else if (IDC->Encloses(DC: CurContext))
1662 break;
1663 }
1664
1665 IdResolver.InsertDeclAfter(Pos: I, D);
1666 } else {
1667 IdResolver.AddDecl(D);
1668 }
1669 warnOnReservedIdentifier(D);
1670}
1671
1672bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1673 bool AllowInlineNamespace) const {
1674 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1675}
1676
1677bool Sema::isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1678 bool AllowInlineNamespace) const {
1679 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1680 return true;
1681
1682 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: D))
1683 return isDeclInScope(D: Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1684
1685 return false;
1686}
1687
1688Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1689 DeclContext *TargetDC = DC->getPrimaryContext();
1690 do {
1691 if (DeclContext *ScopeDC = S->getEntity())
1692 if (ScopeDC->getPrimaryContext() == TargetDC)
1693 return S;
1694 } while ((S = S->getParent()));
1695
1696 return nullptr;
1697}
1698
1699static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1700 DeclContext*,
1701 ASTContext&);
1702
1703void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1704 bool ConsiderLinkage,
1705 bool AllowInlineNamespace) {
1706 LookupResult::Filter F = R.makeFilter();
1707 while (F.hasNext()) {
1708 NamedDecl *D = F.next();
1709
1710 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1711 continue;
1712
1713 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1714 continue;
1715
1716 F.erase();
1717 }
1718
1719 F.done();
1720}
1721
1722static bool isImplicitInstantiation(NamedDecl *D) {
1723 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1724 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1725 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1726 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1727 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1728 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1729
1730 return false;
1731}
1732
1733bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1734 // [module.interface]p7:
1735 // A declaration is attached to a module as follows:
1736 // - If the declaration is a non-dependent friend declaration that nominates a
1737 // function with a declarator-id that is a qualified-id or template-id or that
1738 // nominates a class other than with an elaborated-type-specifier with neither
1739 // a nested-name-specifier nor a simple-template-id, it is attached to the
1740 // module to which the friend is attached ([basic.link]).
1741 if (New->getFriendObjectKind() &&
1742 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1743 New->setLocalOwningModule(Old->getOwningModule());
1744 makeMergedDefinitionVisible(ND: New);
1745 return false;
1746 }
1747
1748 // Although we have questions for the module ownership of implicit
1749 // instantiations, it should be sure that we shouldn't diagnose the
1750 // redeclaration of incorrect module ownership for different implicit
1751 // instantiations in different modules. We will diagnose the redeclaration of
1752 // incorrect module ownership for the template itself.
1753 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1754 return false;
1755
1756 Module *NewM = New->getOwningModule();
1757 Module *OldM = Old->getOwningModule();
1758
1759 if (NewM && NewM->isPrivateModule())
1760 NewM = NewM->Parent;
1761 if (OldM && OldM->isPrivateModule())
1762 OldM = OldM->Parent;
1763
1764 if (NewM == OldM)
1765 return false;
1766
1767 if (NewM && OldM) {
1768 // A module implementation unit has visibility of the decls in its
1769 // implicitly imported interface.
1770 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1771 return false;
1772
1773 // Partitions are part of the module, but a partition could import another
1774 // module, so verify that the PMIs agree.
1775 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1776 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1777 return false;
1778 }
1779
1780 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1781 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1782 if (NewIsModuleInterface || OldIsModuleInterface) {
1783 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1784 // if a declaration of D [...] appears in the purview of a module, all
1785 // other such declarations shall appear in the purview of the same module
1786 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1787 << New
1788 << NewIsModuleInterface
1789 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1790 << OldIsModuleInterface
1791 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1792 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1793 New->setInvalidDecl();
1794 return true;
1795 }
1796
1797 return false;
1798}
1799
1800bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1801 // [module.interface]p1:
1802 // An export-declaration shall inhabit a namespace scope.
1803 //
1804 // So it is meaningless to talk about redeclaration which is not at namespace
1805 // scope.
1806 if (!New->getLexicalDeclContext()
1807 ->getNonTransparentContext()
1808 ->isFileContext() ||
1809 !Old->getLexicalDeclContext()
1810 ->getNonTransparentContext()
1811 ->isFileContext())
1812 return false;
1813
1814 bool IsNewExported = New->isInExportDeclContext();
1815 bool IsOldExported = Old->isInExportDeclContext();
1816
1817 // It should be irrevelant if both of them are not exported.
1818 if (!IsNewExported && !IsOldExported)
1819 return false;
1820
1821 if (IsOldExported)
1822 return false;
1823
1824 // If the Old declaration are not attached to named modules
1825 // and the New declaration are attached to global module.
1826 // It should be fine to allow the export since it doesn't change
1827 // the linkage of declarations. See
1828 // https://github.com/llvm/llvm-project/issues/98583 for details.
1829 if (!Old->isInNamedModule() && New->getOwningModule() &&
1830 New->getOwningModule()->isImplicitGlobalModule())
1831 return false;
1832
1833 assert(IsNewExported);
1834
1835 auto Lk = Old->getFormalLinkage();
1836 int S = 0;
1837 if (Lk == Linkage::Internal)
1838 S = 1;
1839 else if (Lk == Linkage::Module)
1840 S = 2;
1841 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1842 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1843 return true;
1844}
1845
1846bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1847 if (CheckRedeclarationModuleOwnership(New, Old))
1848 return true;
1849
1850 if (CheckRedeclarationExported(New, Old))
1851 return true;
1852
1853 return false;
1854}
1855
1856bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1857 const NamedDecl *Old) const {
1858 assert(getASTContext().isSameEntity(New, Old) &&
1859 "New and Old are not the same definition, we should diagnostic it "
1860 "immediately instead of checking it.");
1861 assert(const_cast<Sema *>(this)->isReachable(New) &&
1862 const_cast<Sema *>(this)->isReachable(Old) &&
1863 "We shouldn't see unreachable definitions here.");
1864
1865 Module *NewM = New->getOwningModule();
1866 Module *OldM = Old->getOwningModule();
1867
1868 // We only checks for named modules here. The header like modules is skipped.
1869 // FIXME: This is not right if we import the header like modules in the module
1870 // purview.
1871 //
1872 // For example, assuming "header.h" provides definition for `D`.
1873 // ```C++
1874 // //--- M.cppm
1875 // export module M;
1876 // import "header.h"; // or #include "header.h" but import it by clang modules
1877 // actually.
1878 //
1879 // //--- Use.cpp
1880 // import M;
1881 // import "header.h"; // or uses clang modules.
1882 // ```
1883 //
1884 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1885 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1886 // reject it. But the current implementation couldn't detect the case since we
1887 // don't record the information about the importee modules.
1888 //
1889 // But this might not be painful in practice. Since the design of C++20 Named
1890 // Modules suggests us to use headers in global module fragment instead of
1891 // module purview.
1892 if (NewM && NewM->isHeaderLikeModule())
1893 NewM = nullptr;
1894 if (OldM && OldM->isHeaderLikeModule())
1895 OldM = nullptr;
1896
1897 if (!NewM && !OldM)
1898 return true;
1899
1900 // [basic.def.odr]p14.3
1901 // Each such definition shall not be attached to a named module
1902 // ([module.unit]).
1903 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1904 return true;
1905
1906 // Then New and Old lives in the same TU if their share one same module unit.
1907 if (NewM)
1908 NewM = NewM->getTopLevelModule();
1909 if (OldM)
1910 OldM = OldM->getTopLevelModule();
1911 return OldM == NewM;
1912}
1913
1914static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1915 if (D->getDeclContext()->isFileContext())
1916 return false;
1917
1918 return isa<UsingShadowDecl>(Val: D) ||
1919 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1920 isa<UnresolvedUsingValueDecl>(Val: D);
1921}
1922
1923/// Removes using shadow declarations not at class scope from the lookup
1924/// results.
1925static void RemoveUsingDecls(LookupResult &R) {
1926 LookupResult::Filter F = R.makeFilter();
1927 while (F.hasNext())
1928 if (isUsingDeclNotAtClassScope(D: F.next()))
1929 F.erase();
1930
1931 F.done();
1932}
1933
1934/// Check for this common pattern:
1935/// @code
1936/// class S {
1937/// S(const S&); // DO NOT IMPLEMENT
1938/// void operator=(const S&); // DO NOT IMPLEMENT
1939/// };
1940/// @endcode
1941static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1942 // FIXME: Should check for private access too but access is set after we get
1943 // the decl here.
1944 if (D->doesThisDeclarationHaveABody())
1945 return false;
1946
1947 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1948 return CD->isCopyConstructor();
1949 return D->isCopyAssignmentOperator();
1950}
1951
1952bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1953 const DeclContext *DC = D->getDeclContext();
1954 while (!DC->isTranslationUnit()) {
1955 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1956 if (!RD->hasNameForLinkage())
1957 return true;
1958 }
1959 DC = DC->getParent();
1960 }
1961
1962 return !D->isExternallyVisible();
1963}
1964
1965bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1966 assert(D);
1967
1968 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1969 return false;
1970
1971 // Ignore all entities declared within templates, and out-of-line definitions
1972 // of members of class templates.
1973 if (D->getDeclContext()->isDependentContext() ||
1974 D->getLexicalDeclContext()->isDependentContext())
1975 return false;
1976
1977 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1978 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1979 return false;
1980 // A non-out-of-line declaration of a member specialization was implicitly
1981 // instantiated; it's the out-of-line declaration that we're interested in.
1982 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1983 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1984 return false;
1985
1986 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1987 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1988 return false;
1989 } else {
1990 // 'static inline' functions are defined in headers; don't warn.
1991 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1992 return false;
1993 }
1994
1995 if (FD->doesThisDeclarationHaveABody() &&
1996 Context.DeclMustBeEmitted(D: FD))
1997 return false;
1998 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1999 // Constants and utility variables are defined in headers with internal
2000 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
2001 // like "inline".)
2002 if (!isMainFileLoc(Loc: VD->getLocation()))
2003 return false;
2004
2005 if (Context.DeclMustBeEmitted(D: VD))
2006 return false;
2007
2008 if (VD->isStaticDataMember() &&
2009 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2010 return false;
2011 if (VD->isStaticDataMember() &&
2012 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2013 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
2014 return false;
2015
2016 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
2017 return false;
2018 } else {
2019 return false;
2020 }
2021
2022 // Only warn for unused decls internal to the translation unit.
2023 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2024 // for inline functions defined in the main source file, for instance.
2025 return mightHaveNonExternalLinkage(D);
2026}
2027
2028void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2029 if (!D)
2030 return;
2031
2032 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2033 const FunctionDecl *First = FD->getFirstDecl();
2034 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2035 return; // First should already be in the vector.
2036 }
2037
2038 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2039 const VarDecl *First = VD->getFirstDecl();
2040 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2041 return; // First should already be in the vector.
2042 }
2043
2044 if (ShouldWarnIfUnusedFileScopedDecl(D))
2045 UnusedFileScopedDecls.push_back(LocalValue: D);
2046}
2047
2048static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2049 const NamedDecl *D) {
2050 if (D->isInvalidDecl())
2051 return false;
2052
2053 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2054 // For a decomposition declaration, warn if none of the bindings are
2055 // referenced, instead of if the variable itself is referenced (which
2056 // it is, by the bindings' expressions).
2057 bool IsAllIgnored = true;
2058 for (const auto *BD : DD->bindings()) {
2059 if (BD->isReferenced())
2060 return false;
2061 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2062 BD->hasAttr<UnusedAttr>());
2063 }
2064 if (IsAllIgnored)
2065 return false;
2066 } else if (!D->getDeclName()) {
2067 return false;
2068 } else if (D->isReferenced() || D->isUsed()) {
2069 return false;
2070 }
2071
2072 if (D->isPlaceholderVar(LangOpts))
2073 return false;
2074
2075 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2076 D->hasAttr<CleanupAttr>())
2077 return false;
2078
2079 if (isa<LabelDecl>(Val: D))
2080 return true;
2081
2082 // Except for labels, we only care about unused decls that are local to
2083 // functions.
2084 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2085 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2086 // For dependent types, the diagnostic is deferred.
2087 WithinFunction =
2088 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2089 if (!WithinFunction)
2090 return false;
2091
2092 if (isa<TypedefNameDecl>(Val: D))
2093 return true;
2094
2095 // White-list anything that isn't a local variable.
2096 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2097 return false;
2098
2099 // Types of valid local variables should be complete, so this should succeed.
2100 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2101
2102 const Expr *Init = VD->getInit();
2103 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2104 Init = Cleanups->getSubExpr();
2105
2106 const auto *Ty = VD->getType().getTypePtr();
2107
2108 // Only look at the outermost level of typedef.
2109 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2110 // Allow anything marked with __attribute__((unused)).
2111 if (TT->getDecl()->hasAttr<UnusedAttr>())
2112 return false;
2113 }
2114
2115 // Warn for reference variables whose initializtion performs lifetime
2116 // extension.
2117 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2118 MTE && MTE->getExtendingDecl()) {
2119 Ty = VD->getType().getNonReferenceType().getTypePtr();
2120 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2121 }
2122
2123 // If we failed to complete the type for some reason, or if the type is
2124 // dependent, don't diagnose the variable.
2125 if (Ty->isIncompleteType() || Ty->isDependentType())
2126 return false;
2127
2128 // Look at the element type to ensure that the warning behaviour is
2129 // consistent for both scalars and arrays.
2130 Ty = Ty->getBaseElementTypeUnsafe();
2131
2132 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2133 if (Tag->hasAttr<UnusedAttr>())
2134 return false;
2135
2136 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2137 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2138 return false;
2139
2140 if (Init) {
2141 const auto *Construct =
2142 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2143 if (Construct && !Construct->isElidable()) {
2144 const CXXConstructorDecl *CD = Construct->getConstructor();
2145 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2146 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2147 return false;
2148 }
2149
2150 // Suppress the warning if we don't know how this is constructed, and
2151 // it could possibly be non-trivial constructor.
2152 if (Init->isTypeDependent()) {
2153 for (const CXXConstructorDecl *Ctor : RD->ctors())
2154 if (!Ctor->isTrivial())
2155 return false;
2156 }
2157
2158 // Suppress the warning if the constructor is unresolved because
2159 // its arguments are dependent.
2160 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2161 return false;
2162 }
2163 }
2164 }
2165
2166 // TODO: __attribute__((unused)) templates?
2167 }
2168
2169 return true;
2170}
2171
2172static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2173 FixItHint &Hint) {
2174 if (isa<LabelDecl>(Val: D)) {
2175 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2176 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2177 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2178 if (AfterColon.isInvalid())
2179 return;
2180 Hint = FixItHint::CreateRemoval(
2181 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2182 }
2183}
2184
2185void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2186 DiagnoseUnusedNestedTypedefs(
2187 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2188}
2189
2190void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2191 DiagReceiverTy DiagReceiver) {
2192 if (D->isDependentType())
2193 return;
2194
2195 for (auto *TmpD : D->decls()) {
2196 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2197 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2198 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2199 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2200 }
2201}
2202
2203void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2204 DiagnoseUnusedDecl(
2205 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2206}
2207
2208void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2209 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2210 return;
2211
2212 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2213 // typedefs can be referenced later on, so the diagnostics are emitted
2214 // at end-of-translation-unit.
2215 UnusedLocalTypedefNameCandidates.insert(Ptr: TD);
2216 return;
2217 }
2218
2219 FixItHint Hint;
2220 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2221
2222 unsigned DiagID;
2223 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2224 DiagID = diag::warn_unused_exception_param;
2225 else if (isa<LabelDecl>(Val: D))
2226 DiagID = diag::warn_unused_label;
2227 else
2228 DiagID = diag::warn_unused_variable;
2229
2230 SourceLocation DiagLoc = D->getLocation();
2231 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2232}
2233
2234void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2235 DiagReceiverTy DiagReceiver) {
2236 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2237 // it's not really unused.
2238 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2239 return;
2240
2241 // In C++, `_` variables behave as if they were maybe_unused
2242 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2243 return;
2244
2245 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2246
2247 if (Ty->isReferenceType() || Ty->isDependentType())
2248 return;
2249
2250 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2251 if (Tag->hasAttr<UnusedAttr>())
2252 return;
2253 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2254 // mimic gcc's behavior.
2255 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2256 RD && !RD->hasAttr<WarnUnusedAttr>())
2257 return;
2258 }
2259
2260 // Don't warn on volatile file-scope variables. They are visible beyond their
2261 // declaring function and writes to them could be observable side effects.
2262 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2263 return;
2264
2265 // Don't warn about __block Objective-C pointer variables, as they might
2266 // be assigned in the block but not used elsewhere for the purpose of lifetime
2267 // extension.
2268 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2269 return;
2270
2271 // Don't warn about Objective-C pointer variables with precise lifetime
2272 // semantics; they can be used to ensure ARC releases the object at a known
2273 // time, which may mean assignment but no other references.
2274 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2275 return;
2276
2277 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2278 if (iter == RefsMinusAssignments.end())
2279 return;
2280
2281 assert(iter->getSecond() >= 0 &&
2282 "Found a negative number of references to a VarDecl");
2283 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2284 // Assume the given VarDecl is "used" if its ref count stored in
2285 // `RefMinusAssignments` is positive, with one exception.
2286 //
2287 // For a C++ variable whose decl (with initializer) entirely consist the
2288 // condition expression of a if/while/for construct,
2289 // Clang creates a DeclRefExpr for the condition expression rather than a
2290 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2291 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2292 // used in the body of the if/while/for construct.
2293 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2294 if (!UnusedCXXCondDecl)
2295 return;
2296 }
2297
2298 unsigned DiagID;
2299 if (isa<ParmVarDecl>(Val: VD))
2300 DiagID = diag::warn_unused_but_set_parameter;
2301 else if (VD->isFileVarDecl())
2302 DiagID = diag::warn_unused_but_set_global;
2303 else
2304 DiagID = diag::warn_unused_but_set_variable;
2305 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2306}
2307
2308static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2309 Sema::DiagReceiverTy DiagReceiver) {
2310 // Verify that we have no forward references left. If so, there was a goto
2311 // or address of a label taken, but no definition of it. Label fwd
2312 // definitions are indicated with a null substmt which is also not a resolved
2313 // MS inline assembly label name.
2314 bool Diagnose = false;
2315 if (L->isMSAsmLabel())
2316 Diagnose = !L->isResolvedMSAsmLabel();
2317 else
2318 Diagnose = L->getStmt() == nullptr;
2319 if (Diagnose)
2320 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2321 << L);
2322}
2323
2324void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2325 S->applyNRVO();
2326
2327 if (S->decl_empty()) return;
2328 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2329 "Scope shouldn't contain decls!");
2330
2331 /// We visit the decls in non-deterministic order, but we want diagnostics
2332 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2333 /// and sort the diagnostics before emitting them, after we visited all decls.
2334 struct LocAndDiag {
2335 SourceLocation Loc;
2336 std::optional<SourceLocation> PreviousDeclLoc;
2337 PartialDiagnostic PD;
2338 };
2339 SmallVector<LocAndDiag, 16> DeclDiags;
2340 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2341 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2342 };
2343 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2344 SourceLocation PreviousDeclLoc,
2345 PartialDiagnostic PD) {
2346 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2347 };
2348
2349 for (auto *TmpD : S->decls()) {
2350 assert(TmpD && "This decl didn't get pushed??");
2351
2352 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2353 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2354
2355 // Diagnose unused variables in this scope.
2356 if (!S->hasUnrecoverableErrorOccurred()) {
2357 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2358 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2359 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2360 // Wait until end of TU to diagnose internal linkage file vars.
2361 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2362 VD && !VD->isInternalLinkageFileVar()) {
2363 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2364 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2365 }
2366 }
2367
2368 if (!D->getDeclName()) continue;
2369
2370 // If this was a forward reference to a label, verify it was defined.
2371 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2372 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2373
2374 // Partial translation units that are created in incremental processing must
2375 // not clean up the IdResolver because PTUs should take into account the
2376 // declarations that came from previous PTUs.
2377 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2378 getLangOpts().CPlusPlus)
2379 IdResolver.RemoveDecl(D);
2380
2381 // Warn on it if we are shadowing a declaration.
2382 auto ShadowI = ShadowingDecls.find(Val: D);
2383 if (ShadowI != ShadowingDecls.end()) {
2384 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2385 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2386 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2387 << D << FD << FD->getParent());
2388 }
2389 ShadowingDecls.erase(I: ShadowI);
2390 }
2391 }
2392
2393 llvm::sort(C&: DeclDiags,
2394 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2395 // The particular order for diagnostics is not important, as long
2396 // as the order is deterministic. Using the raw location is going
2397 // to generally be in source order unless there are macro
2398 // expansions involved.
2399 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2400 });
2401 for (const LocAndDiag &D : DeclDiags) {
2402 Diag(Loc: D.Loc, PD: D.PD);
2403 if (D.PreviousDeclLoc)
2404 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2405 }
2406}
2407
2408Scope *Sema::getNonFieldDeclScope(Scope *S) {
2409 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2410 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2411 (S->isClassScope() && !getLangOpts().CPlusPlus))
2412 S = S->getParent();
2413 return S;
2414}
2415
2416static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2417 ASTContext::GetBuiltinTypeError Error) {
2418 switch (Error) {
2419 case ASTContext::GE_None:
2420 return "";
2421 case ASTContext::GE_Missing_type:
2422 return BuiltinInfo.getHeaderName(ID);
2423 case ASTContext::GE_Missing_stdio:
2424 return "stdio.h";
2425 case ASTContext::GE_Missing_setjmp:
2426 return "setjmp.h";
2427 case ASTContext::GE_Missing_ucontext:
2428 return "ucontext.h";
2429 }
2430 llvm_unreachable("unhandled error kind");
2431}
2432
2433FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2434 unsigned ID, SourceLocation Loc) {
2435 DeclContext *Parent = Context.getTranslationUnitDecl();
2436
2437 if (getLangOpts().CPlusPlus) {
2438 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2439 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2440 CLinkageDecl->setImplicit();
2441 Parent->addDecl(D: CLinkageDecl);
2442 Parent = CLinkageDecl;
2443 }
2444
2445 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2446 if (Context.BuiltinInfo.isImmediate(ID)) {
2447 assert(getLangOpts().CPlusPlus20 &&
2448 "consteval builtins should only be available in C++20 mode");
2449 ConstexprKind = ConstexprSpecKind::Consteval;
2450 }
2451
2452 FunctionDecl *New = FunctionDecl::Create(
2453 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2454 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2455 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2456 New->setImplicit();
2457 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2458
2459 // Create Decl objects for each parameter, adding them to the
2460 // FunctionDecl.
2461 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2462 SmallVector<ParmVarDecl *, 16> Params;
2463 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2464 ParmVarDecl *parm = ParmVarDecl::Create(
2465 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2466 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2467 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2468 Params.push_back(Elt: parm);
2469 }
2470 New->setParams(Params);
2471 }
2472
2473 AddKnownFunctionAttributes(FD: New);
2474 return New;
2475}
2476
2477NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2478 Scope *S, bool ForRedeclaration,
2479 SourceLocation Loc) {
2480 LookupNecessaryTypesForBuiltin(S, ID);
2481
2482 ASTContext::GetBuiltinTypeError Error;
2483 QualType R = Context.GetBuiltinType(ID, Error);
2484 if (Error) {
2485 if (!ForRedeclaration)
2486 return nullptr;
2487
2488 // If we have a builtin without an associated type we should not emit a
2489 // warning when we were not able to find a type for it.
2490 if (Error == ASTContext::GE_Missing_type ||
2491 Context.BuiltinInfo.allowTypeMismatch(ID))
2492 return nullptr;
2493
2494 // If we could not find a type for setjmp it is because the jmp_buf type was
2495 // not defined prior to the setjmp declaration.
2496 if (Error == ASTContext::GE_Missing_setjmp) {
2497 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2498 << Context.BuiltinInfo.getName(ID);
2499 return nullptr;
2500 }
2501
2502 // Generally, we emit a warning that the declaration requires the
2503 // appropriate header.
2504 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2505 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2506 << Context.BuiltinInfo.getName(ID);
2507 return nullptr;
2508 }
2509
2510 if (!ForRedeclaration &&
2511 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2512 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2513 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2514 : diag::ext_implicit_lib_function_decl)
2515 << Context.BuiltinInfo.getName(ID) << R;
2516 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2517 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2518 << Header << Context.BuiltinInfo.getName(ID);
2519 }
2520
2521 if (R.isNull())
2522 return nullptr;
2523
2524 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2525 RegisterLocallyScopedExternCDecl(ND: New, S);
2526
2527 // TUScope is the translation-unit scope to insert this function into.
2528 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2529 // relate Scopes to DeclContexts, and probably eliminate CurContext
2530 // entirely, but we're not there yet.
2531 DeclContext *SavedContext = CurContext;
2532 CurContext = New->getDeclContext();
2533 PushOnScopeChains(D: New, S: TUScope);
2534 CurContext = SavedContext;
2535 return New;
2536}
2537
2538/// Typedef declarations don't have linkage, but they still denote the same
2539/// entity if their types are the same.
2540/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2541/// isSameEntity.
2542static void
2543filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2544 LookupResult &Previous) {
2545 // This is only interesting when modules are enabled.
2546 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2547 return;
2548
2549 // Empty sets are uninteresting.
2550 if (Previous.empty())
2551 return;
2552
2553 LookupResult::Filter Filter = Previous.makeFilter();
2554 while (Filter.hasNext()) {
2555 NamedDecl *Old = Filter.next();
2556
2557 // Non-hidden declarations are never ignored.
2558 if (S.isVisible(D: Old))
2559 continue;
2560
2561 // Declarations of the same entity are not ignored, even if they have
2562 // different linkages.
2563 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2564 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2565 T2: Decl->getUnderlyingType()))
2566 continue;
2567
2568 // If both declarations give a tag declaration a typedef name for linkage
2569 // purposes, then they declare the same entity.
2570 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2571 Decl->getAnonDeclWithTypedefName())
2572 continue;
2573 }
2574
2575 Filter.erase();
2576 }
2577
2578 Filter.done();
2579}
2580
2581bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2582 QualType OldType;
2583 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2584 OldType = OldTypedef->getUnderlyingType();
2585 else
2586 OldType = Context.getTypeDeclType(Decl: Old);
2587 QualType NewType = New->getUnderlyingType();
2588
2589 if (NewType->isVariablyModifiedType()) {
2590 // Must not redefine a typedef with a variably-modified type.
2591 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2592 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2593 << Kind << NewType;
2594 if (Old->getLocation().isValid())
2595 notePreviousDefinition(Old, New: New->getLocation());
2596 New->setInvalidDecl();
2597 return true;
2598 }
2599
2600 if (OldType != NewType &&
2601 !OldType->isDependentType() &&
2602 !NewType->isDependentType() &&
2603 !Context.hasSameType(T1: OldType, T2: NewType)) {
2604 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2605 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2606 << Kind << NewType << OldType;
2607 if (Old->getLocation().isValid())
2608 notePreviousDefinition(Old, New: New->getLocation());
2609 New->setInvalidDecl();
2610 return true;
2611 }
2612 return false;
2613}
2614
2615void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2616 LookupResult &OldDecls) {
2617 // If the new decl is known invalid already, don't bother doing any
2618 // merging checks.
2619 if (New->isInvalidDecl()) return;
2620
2621 // Allow multiple definitions for ObjC built-in typedefs.
2622 // FIXME: Verify the underlying types are equivalent!
2623 if (getLangOpts().ObjC) {
2624 const IdentifierInfo *TypeID = New->getIdentifier();
2625 switch (TypeID->getLength()) {
2626 default: break;
2627 case 2:
2628 {
2629 if (!TypeID->isStr(Str: "id"))
2630 break;
2631 QualType T = New->getUnderlyingType();
2632 if (!T->isPointerType())
2633 break;
2634 if (!T->isVoidPointerType()) {
2635 QualType PT = T->castAs<PointerType>()->getPointeeType();
2636 if (!PT->isStructureType())
2637 break;
2638 }
2639 Context.setObjCIdRedefinitionType(T);
2640 // Install the built-in type for 'id', ignoring the current definition.
2641 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2642 modedTy: Context.getObjCIdType());
2643 return;
2644 }
2645 case 5:
2646 if (!TypeID->isStr(Str: "Class"))
2647 break;
2648 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2649 // Install the built-in type for 'Class', ignoring the current definition.
2650 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2651 modedTy: Context.getObjCClassType());
2652 return;
2653 case 3:
2654 if (!TypeID->isStr(Str: "SEL"))
2655 break;
2656 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2657 // Install the built-in type for 'SEL', ignoring the current definition.
2658 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2659 modedTy: Context.getObjCSelType());
2660 return;
2661 }
2662 // Fall through - the typedef name was not a builtin type.
2663 }
2664
2665 // Verify the old decl was also a type.
2666 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2667 if (!Old) {
2668 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2669 << New->getDeclName();
2670
2671 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2672 if (OldD->getLocation().isValid())
2673 notePreviousDefinition(Old: OldD, New: New->getLocation());
2674
2675 return New->setInvalidDecl();
2676 }
2677
2678 // If the old declaration is invalid, just give up here.
2679 if (Old->isInvalidDecl())
2680 return New->setInvalidDecl();
2681
2682 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2683 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2684 auto *NewTag = New->getAnonDeclWithTypedefName();
2685 NamedDecl *Hidden = nullptr;
2686 if (OldTag && NewTag &&
2687 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2688 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2689 // There is a definition of this tag, but it is not visible. Use it
2690 // instead of our tag.
2691 if (OldTD->isModed())
2692 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2693 modedTy: OldTD->getUnderlyingType());
2694 else
2695 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2696
2697 // An anonymous enum is recognized as a redeclaration only when its
2698 // typedef name gets merged, at which point the new enum and its
2699 // enumerators already have a distinct canonical type. Link the enum
2700 // declarations, but also retype the new enumerators because
2701 // setPreviousDecl() does not update QualTypes built before the merge;
2702 // otherwise the merged typedef and its enumerators disagree on the type
2703 // (GH213299).
2704 //
2705 // FIXME: The global module restriction only limits the impact of this
2706 // change; relax it if the issue shows up in other contexts.
2707 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2708 if (auto *NewEnum = dyn_cast<EnumDecl>(Val: NewTag)) {
2709 if (auto *OldEnum = dyn_cast<EnumDecl>(Val: OldTag)) {
2710 NewEnum->setPreviousDecl(OldEnum);
2711 QualType EnumType = Context.getCanonicalTagType(TD: OldEnum);
2712 for (auto *ECD : NewEnum->enumerators())
2713 ECD->setType(EnumType);
2714 }
2715 }
2716 }
2717
2718 // Make the old tag definition visible.
2719 makeMergedDefinitionVisible(ND: Hidden);
2720
2721 CleanupMergedEnum(S, New: NewTag);
2722 }
2723 }
2724
2725 // If the typedef types are not identical, reject them in all languages and
2726 // with any extensions enabled.
2727 if (isIncompatibleTypedef(Old, New))
2728 return;
2729
2730 // The types match. Link up the redeclaration chain and merge attributes if
2731 // the old declaration was a typedef.
2732 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2733 New->setPreviousDecl(Typedef);
2734 mergeDeclAttributes(New, Old);
2735 }
2736
2737 if (getLangOpts().MicrosoftExt)
2738 return;
2739
2740 if (getLangOpts().CPlusPlus) {
2741 // C++ [dcl.typedef]p2:
2742 // In a given non-class scope, a typedef specifier can be used to
2743 // redefine the name of any type declared in that scope to refer
2744 // to the type to which it already refers.
2745 if (!isa<CXXRecordDecl>(Val: CurContext))
2746 return;
2747
2748 // C++0x [dcl.typedef]p4:
2749 // In a given class scope, a typedef specifier can be used to redefine
2750 // any class-name declared in that scope that is not also a typedef-name
2751 // to refer to the type to which it already refers.
2752 //
2753 // This wording came in via DR424, which was a correction to the
2754 // wording in DR56, which accidentally banned code like:
2755 //
2756 // struct S {
2757 // typedef struct A { } A;
2758 // };
2759 //
2760 // in the C++03 standard. We implement the C++0x semantics, which
2761 // allow the above but disallow
2762 //
2763 // struct S {
2764 // typedef int I;
2765 // typedef int I;
2766 // };
2767 //
2768 // since that was the intent of DR56.
2769 if (!isa<TypedefNameDecl>(Val: Old))
2770 return;
2771
2772 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2773 << New->getDeclName();
2774 notePreviousDefinition(Old, New: New->getLocation());
2775 return New->setInvalidDecl();
2776 }
2777
2778 // Modules always permit redefinition of typedefs, as does C11.
2779 if (getLangOpts().Modules || getLangOpts().C11)
2780 return;
2781
2782 // If we have a redefinition of a typedef in C, emit a warning. This warning
2783 // is normally mapped to an error, but can be controlled with
2784 // -Wtypedef-redefinition. If either the original or the redefinition is
2785 // in a system header, don't emit this for compatibility with GCC.
2786 if (getDiagnostics().getSuppressSystemWarnings() &&
2787 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2788 (Old->isImplicit() ||
2789 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2790 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2791 return;
2792
2793 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2794 << New->getDeclName();
2795 notePreviousDefinition(Old, New: New->getLocation());
2796}
2797
2798void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2799 // If this was an unscoped enumeration, yank all of its enumerators
2800 // out of the scope.
2801 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2802 Scope *EnumScope = getNonFieldDeclScope(S);
2803 for (auto *ECD : ED->enumerators()) {
2804 assert(EnumScope->isDeclScope(ECD));
2805 EnumScope->RemoveDecl(D: ECD);
2806 IdResolver.RemoveDecl(D: ECD);
2807 }
2808 }
2809}
2810
2811/// DeclhasAttr - returns true if decl Declaration already has the target
2812/// attribute.
2813static bool DeclHasAttr(const Decl *D, const Attr *A) {
2814 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2815 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2816 for (const auto *i : D->attrs())
2817 if (i->getKind() == A->getKind()) {
2818 if (Ann) {
2819 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2820 return true;
2821 continue;
2822 }
2823 // FIXME: Don't hardcode this check
2824 if (OA && isa<OwnershipAttr>(Val: i))
2825 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2826 return true;
2827 }
2828
2829 return false;
2830}
2831
2832static bool isAttributeTargetADefinition(Decl *D) {
2833 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2834 return VD->isThisDeclarationADefinition();
2835 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2836 return TD->isCompleteDefinition() || TD->isBeingDefined();
2837 return true;
2838}
2839
2840/// Merge alignment attributes from \p Old to \p New, taking into account the
2841/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2842///
2843/// \return \c true if any attributes were added to \p New.
2844static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2845 // Look for alignas attributes on Old, and pick out whichever attribute
2846 // specifies the strictest alignment requirement.
2847 AlignedAttr *OldAlignasAttr = nullptr;
2848 AlignedAttr *OldStrictestAlignAttr = nullptr;
2849 unsigned OldAlign = 0;
2850 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2851 // FIXME: We have no way of representing inherited dependent alignments
2852 // in a case like:
2853 // template<int A, int B> struct alignas(A) X;
2854 // template<int A, int B> struct alignas(B) X {};
2855 // For now, we just ignore any alignas attributes which are not on the
2856 // definition in such a case.
2857 if (I->isAlignmentDependent())
2858 return false;
2859
2860 if (I->isAlignas())
2861 OldAlignasAttr = I;
2862
2863 unsigned Align = I->getAlignment(Ctx&: S.Context);
2864 if (Align > OldAlign) {
2865 OldAlign = Align;
2866 OldStrictestAlignAttr = I;
2867 }
2868 }
2869
2870 // Look for alignas attributes on New.
2871 AlignedAttr *NewAlignasAttr = nullptr;
2872 unsigned NewAlign = 0;
2873 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2874 if (I->isAlignmentDependent())
2875 return false;
2876
2877 if (I->isAlignas())
2878 NewAlignasAttr = I;
2879
2880 unsigned Align = I->getAlignment(Ctx&: S.Context);
2881 if (Align > NewAlign)
2882 NewAlign = Align;
2883 }
2884
2885 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2886 // Both declarations have 'alignas' attributes. We require them to match.
2887 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2888 // fall short. (If two declarations both have alignas, they must both match
2889 // every definition, and so must match each other if there is a definition.)
2890
2891 // If either declaration only contains 'alignas(0)' specifiers, then it
2892 // specifies the natural alignment for the type.
2893 if (OldAlign == 0 || NewAlign == 0) {
2894 QualType Ty;
2895 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2896 Ty = VD->getType();
2897 else
2898 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2899
2900 if (OldAlign == 0)
2901 OldAlign = S.Context.getTypeAlign(T: Ty);
2902 if (NewAlign == 0)
2903 NewAlign = S.Context.getTypeAlign(T: Ty);
2904 }
2905
2906 if (OldAlign != NewAlign) {
2907 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2908 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2909 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2910 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2911 }
2912 }
2913
2914 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2915 // C++11 [dcl.align]p6:
2916 // if any declaration of an entity has an alignment-specifier,
2917 // every defining declaration of that entity shall specify an
2918 // equivalent alignment.
2919 // C11 6.7.5/7:
2920 // If the definition of an object does not have an alignment
2921 // specifier, any other declaration of that object shall also
2922 // have no alignment specifier.
2923 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2924 << OldAlignasAttr;
2925 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2926 << OldAlignasAttr;
2927 }
2928
2929 bool AnyAdded = false;
2930
2931 // Ensure we have an attribute representing the strictest alignment.
2932 if (OldAlign > NewAlign) {
2933 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2934 Clone->setInherited(true);
2935 New->addAttr(A: Clone);
2936 AnyAdded = true;
2937 }
2938
2939 // Ensure we have an alignas attribute if the old declaration had one.
2940 if (OldAlignasAttr && !NewAlignasAttr &&
2941 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2942 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2943 Clone->setInherited(true);
2944 New->addAttr(A: Clone);
2945 AnyAdded = true;
2946 }
2947
2948 return AnyAdded;
2949}
2950
2951#define WANT_DECL_MERGE_LOGIC
2952#include "clang/Sema/AttrParsedAttrImpl.inc"
2953#undef WANT_DECL_MERGE_LOGIC
2954
2955static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2956 const InheritableAttr *Attr,
2957 AvailabilityMergeKind AMK) {
2958 // Diagnose any mutual exclusions between the attribute that we want to add
2959 // and attributes that already exist on the declaration.
2960 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2961 return false;
2962
2963 // This function copies an attribute Attr from a previous declaration to the
2964 // new declaration D if the new declaration doesn't itself have that attribute
2965 // yet or if that attribute allows duplicates.
2966 // If you're adding a new attribute that requires logic different from
2967 // "use explicit attribute on decl if present, else use attribute from
2968 // previous decl", for example if the attribute needs to be consistent
2969 // between redeclarations, you need to call a custom merge function here.
2970 InheritableAttr *NewAttr = nullptr;
2971 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2972 const IdentifierInfo *InferredPlatformII = nullptr;
2973 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2974 InferredPlatformII = Inf->getPlatform();
2975 NewAttr = S.mergeAndInferAvailabilityAttr(
2976 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2977 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2978 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2979 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2980 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2981 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2982 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2983 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2984 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2985 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2986 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2987 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2988 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2989 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2990 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2991 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2992 FirstArg: FA->getFirstArg());
2993 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2994 NewAttr = S.mergeFormatMatchesAttr(
2995 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2996 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2997 NewAttr = S.mergeModularFormatAttr(
2998 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2999 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
3000 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
3001 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
3002 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
3003 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
3004 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
3005 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
3006 Model: IA->getInheritanceModel());
3007 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
3008 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
3009 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
3010 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
3011 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
3012 isa<CUDAGlobalAttr>(Val: Attr))) {
3013 // CUDA target attributes are part of function signature for
3014 // overloading purposes and must not be merged.
3015 return false;
3016 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
3017 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
3018 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
3019 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
3020 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Val: Attr))
3021 NewAttr = S.Swift().mergeAttrAttr(D, SAA: *SAA);
3022 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
3023 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
3024 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
3025 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
3026 else if (isa<AlignedAttr>(Val: Attr))
3027 // AlignedAttrs are handled separately, because we need to handle all
3028 // such attributes on a declaration at the same time.
3029 NewAttr = nullptr;
3030 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
3031 (AMK == AvailabilityMergeKind::Override ||
3032 AMK == AvailabilityMergeKind::ProtocolImplementation ||
3033 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
3034 NewAttr = nullptr;
3035 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
3036 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
3037 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
3038 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
3039 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
3040 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
3041 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Val: Attr))
3042 NewAttr = S.Wasm().mergeExportNameAttr(D, AL: *ENA);
3043 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
3044 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
3045 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
3046 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
3047 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
3048 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
3049 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
3050 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
3051 Z: NT->getZ());
3052 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3053 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3054 Preferred: WS->getPreferred(),
3055 SpelledArgsCount: WS->getSpelledArgsCount());
3056 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3057 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3058 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3059 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3060 else if (isa<SuppressAttr>(Val: Attr))
3061 // Do nothing. Each redeclaration should be suppressed separately.
3062 NewAttr = nullptr;
3063 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3064 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3065 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3066 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3067 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3068 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3069
3070 if (NewAttr) {
3071 NewAttr->setInherited(true);
3072 D->addAttr(A: NewAttr);
3073 if (isa<MSInheritanceAttr>(Val: NewAttr))
3074 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3075 return true;
3076 }
3077
3078 return false;
3079}
3080
3081static const NamedDecl *getDefinition(const Decl *D) {
3082 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3083 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3084 return Def;
3085 return nullptr;
3086 }
3087 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3088 const VarDecl *Def = VD->getDefinition();
3089 if (Def)
3090 return Def;
3091 return VD->getActingDefinition();
3092 }
3093 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3094 const FunctionDecl *Def = nullptr;
3095 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3096 return Def;
3097 }
3098 return nullptr;
3099}
3100
3101static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3102 for (const auto *Attribute : D->attrs())
3103 if (Attribute->getKind() == Kind)
3104 return true;
3105 return false;
3106}
3107
3108/// checkNewAttributesAfterDef - If we already have a definition, check that
3109/// there are no new attributes in this declaration.
3110static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3111 if (!New->hasAttrs())
3112 return;
3113
3114 const NamedDecl *Def = getDefinition(D: Old);
3115 if (!Def || Def == New)
3116 return;
3117
3118 AttrVec &NewAttributes = New->getAttrs();
3119 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3120 Attr *NewAttribute = NewAttributes[I];
3121
3122 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3123 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3124 SkipBodyInfo SkipBody;
3125 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3126
3127 // If we're skipping this definition, drop the "alias" attribute.
3128 if (SkipBody.ShouldSkip) {
3129 NewAttributes.erase(CI: NewAttributes.begin() + I);
3130 --E;
3131 continue;
3132 }
3133 } else {
3134 VarDecl *VD = cast<VarDecl>(Val: New);
3135 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3136 VarDecl::TentativeDefinition
3137 ? diag::err_alias_after_tentative
3138 : diag::err_redefinition;
3139 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3140 if (Diag == diag::err_redefinition)
3141 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3142 else
3143 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3144 VD->setInvalidDecl();
3145 }
3146 ++I;
3147 continue;
3148 }
3149
3150 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3151 // Tentative definitions are only interesting for the alias check above.
3152 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3153 ++I;
3154 continue;
3155 }
3156 }
3157
3158 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3159 ++I;
3160 continue; // regular attr merging will take care of validating this.
3161 }
3162
3163 if (NewAttribute->getLocation().isInvalid()) {
3164 // An attribute with no source location was not written by the user. API
3165 // notes, in particular, are matched against whichever declaration the
3166 // compiler reaches, which can be a redeclaration that follows the
3167 // definition, possibly in a different module. There is nothing for the
3168 // user to correct, and erasing the attribute would silently change what
3169 // the annotated API means.
3170 ++I;
3171 continue;
3172 }
3173
3174 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3175 // C's _Noreturn is allowed to be added to a function after it is defined.
3176 ++I;
3177 continue;
3178 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3179 // msvc will allow a subsequent definition to add an uuid to a class
3180 ++I;
3181 continue;
3182 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3183 Val: NewAttribute) &&
3184 NewAttribute->isStandardAttributeSyntax()) {
3185 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3186 // deprecated attribute can later be re-declared with the attribute and
3187 // vice-versa.
3188 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3189 // maybe_unused attribute can later be redeclared with the attribute and
3190 // vice versa.
3191 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3192 // nodiscard attribute can later be redeclared with the attribute and
3193 // vice-versa.
3194 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3195 ++I;
3196 continue;
3197 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3198 if (AA->isAlignas()) {
3199 // C++11 [dcl.align]p6:
3200 // if any declaration of an entity has an alignment-specifier,
3201 // every defining declaration of that entity shall specify an
3202 // equivalent alignment.
3203 // C11 6.7.5/7:
3204 // If the definition of an object does not have an alignment
3205 // specifier, any other declaration of that object shall also
3206 // have no alignment specifier.
3207 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3208 << AA;
3209 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3210 << AA;
3211 NewAttributes.erase(CI: NewAttributes.begin() + I);
3212 --E;
3213 continue;
3214 }
3215 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3216 // If there is a C definition followed by a redeclaration with this
3217 // attribute then there are two different definitions. In C++, prefer the
3218 // standard diagnostics.
3219 if (!S.getLangOpts().CPlusPlus) {
3220 S.Diag(Loc: NewAttribute->getLocation(),
3221 DiagID: diag::err_loader_uninitialized_redeclaration);
3222 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3223 NewAttributes.erase(CI: NewAttributes.begin() + I);
3224 --E;
3225 continue;
3226 }
3227 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3228 cast<VarDecl>(Val: New)->isInline() &&
3229 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3230 // Don't warn about applying selectany to implicitly inline variables.
3231 // Older compilers and language modes would require the use of selectany
3232 // to make such variables inline, and it would have no effect if we
3233 // honored it.
3234 ++I;
3235 continue;
3236 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3237 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3238 // declarations after definitions.
3239 ++I;
3240 continue;
3241 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3242 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3243 // error since the definition will have already been created without
3244 // the semantic effects of the attribute having been applied.
3245 S.Diag(Loc: NewAttribute->getLocation(),
3246 DiagID: diag::err_sycl_entry_point_after_definition)
3247 << NewAttribute;
3248 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3249 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3250 ++I;
3251 continue;
3252 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3253 // SYCLExternalAttr may be added after a definition.
3254 ++I;
3255 continue;
3256 }
3257
3258 S.Diag(Loc: NewAttribute->getLocation(),
3259 DiagID: diag::warn_attribute_precede_definition);
3260 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3261 NewAttributes.erase(CI: NewAttributes.begin() + I);
3262 --E;
3263 }
3264}
3265
3266static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3267 const ConstInitAttr *CIAttr,
3268 bool AttrBeforeInit) {
3269 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3270
3271 // Figure out a good way to write this specifier on the old declaration.
3272 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3273 // enough of the attribute list spelling information to extract that without
3274 // heroics.
3275 std::string SuitableSpelling;
3276 if (S.getLangOpts().CPlusPlus20)
3277 SuitableSpelling = std::string(
3278 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3279 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3280 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3281 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3282 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3283 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3284 tok::r_square, tok::r_square}));
3285 if (SuitableSpelling.empty())
3286 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3287 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3288 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3289 tok::r_paren, tok::r_paren}));
3290 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3291 SuitableSpelling = "constinit";
3292 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3293 SuitableSpelling = "[[clang::require_constant_initialization]]";
3294 if (SuitableSpelling.empty())
3295 SuitableSpelling = "__attribute__((require_constant_initialization))";
3296 SuitableSpelling += " ";
3297
3298 if (AttrBeforeInit) {
3299 // extern constinit int a;
3300 // int a = 0; // error (missing 'constinit'), accepted as extension
3301 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3302 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3303 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3304 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3305 } else {
3306 // int a = 0;
3307 // constinit extern int a; // error (missing 'constinit')
3308 S.Diag(Loc: CIAttr->getLocation(),
3309 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3310 : diag::warn_require_const_init_added_too_late)
3311 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3312 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3313 << CIAttr->isConstinit()
3314 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3315 }
3316}
3317
3318void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3319 AvailabilityMergeKind AMK) {
3320 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3321 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3322 NewAttr->setInherited(true);
3323 New->addAttr(A: NewAttr);
3324 }
3325 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3326 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3327 NewAttr->setInherited(true);
3328 New->addAttr(A: NewAttr);
3329 }
3330
3331 if (!Old->hasAttrs() && !New->hasAttrs())
3332 return;
3333
3334 // [dcl.constinit]p1:
3335 // If the [constinit] specifier is applied to any declaration of a
3336 // variable, it shall be applied to the initializing declaration.
3337 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3338 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3339 if (bool(OldConstInit) != bool(NewConstInit)) {
3340 const auto *OldVD = cast<VarDecl>(Val: Old);
3341 auto *NewVD = cast<VarDecl>(Val: New);
3342
3343 // Find the initializing declaration. Note that we might not have linked
3344 // the new declaration into the redeclaration chain yet.
3345 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3346 if (!InitDecl &&
3347 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3348 InitDecl = NewVD;
3349
3350 if (InitDecl == NewVD) {
3351 // This is the initializing declaration. If it would inherit 'constinit',
3352 // that's ill-formed. (Note that we do not apply this to the attribute
3353 // form).
3354 if (OldConstInit && OldConstInit->isConstinit())
3355 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3356 /*AttrBeforeInit=*/true);
3357 } else if (NewConstInit) {
3358 // This is the first time we've been told that this declaration should
3359 // have a constant initializer. If we already saw the initializing
3360 // declaration, this is too late.
3361 if (InitDecl && InitDecl != NewVD) {
3362 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3363 /*AttrBeforeInit=*/false);
3364 NewVD->dropAttr<ConstInitAttr>();
3365 }
3366 }
3367 }
3368
3369 // Attributes declared post-definition are currently ignored.
3370 checkNewAttributesAfterDef(S&: *this, New, Old);
3371
3372 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3373 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3374 if (!OldA->isEquivalent(Other: NewA)) {
3375 // This redeclaration changes __asm__ label.
3376 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3377 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3378 }
3379 } else if (Old->isUsed()) {
3380 // This redeclaration adds an __asm__ label to a declaration that has
3381 // already been ODR-used.
3382 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3383 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3384 }
3385 }
3386
3387 // Re-declaration cannot add abi_tag's.
3388 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3389 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3390 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3391 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3392 Diag(Loc: NewAbiTagAttr->getLocation(),
3393 DiagID: diag::err_new_abi_tag_on_redeclaration)
3394 << NewTag;
3395 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3396 }
3397 }
3398 } else {
3399 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3400 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3401 }
3402 }
3403
3404 // This redeclaration adds a section attribute.
3405 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3406 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3407 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3408 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3409 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3410 }
3411 }
3412 }
3413
3414 // Redeclaration adds code-seg attribute.
3415 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3416 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3417 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3418 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3419 << 0 /*codeseg*/;
3420 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3421 }
3422
3423 if (!Old->hasAttrs())
3424 return;
3425
3426 bool foundAny = New->hasAttrs();
3427
3428 // Ensure that any moving of objects within the allocated map is done before
3429 // we process them.
3430 if (!foundAny) New->setAttrs(AttrVec());
3431
3432 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3433 // Ignore deprecated/unavailable/availability attributes if requested.
3434 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3435 if (isa<DeprecatedAttr>(Val: I) ||
3436 isa<UnavailableAttr>(Val: I) ||
3437 isa<AvailabilityAttr>(Val: I)) {
3438 switch (AMK) {
3439 case AvailabilityMergeKind::None:
3440 continue;
3441
3442 case AvailabilityMergeKind::Redeclaration:
3443 case AvailabilityMergeKind::Override:
3444 case AvailabilityMergeKind::ProtocolImplementation:
3445 case AvailabilityMergeKind::OptionalProtocolImplementation:
3446 LocalAMK = AMK;
3447 break;
3448 }
3449 }
3450
3451 // Already handled.
3452 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3453 continue;
3454
3455 // Don't propagate inferred noreturn or conflicting inline attributes to
3456 // explicit specializations.
3457 if (isa<InferredNoReturnAttr>(Val: I) || isa<AlwaysInlineAttr>(Val: I) ||
3458 isa<NoInlineAttr>(Val: I)) {
3459 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3460 FD &&
3461 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3462 continue;
3463 }
3464
3465 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3466 foundAny = true;
3467 }
3468
3469 if (mergeAlignedAttrs(S&: *this, New, Old))
3470 foundAny = true;
3471
3472 if (!foundAny) New->dropAttrs();
3473}
3474
3475void Sema::CheckAttributesOnDeducedType(Decl *D) {
3476 for (const Attr *A : D->attrs())
3477 checkAttrIsTypeDependent(D, A);
3478}
3479
3480// Returns the number of added attributes.
3481template <class T>
3482static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3483 Sema &S) {
3484 unsigned found = 0;
3485 for (const auto *I : From->specific_attrs<T>()) {
3486 if (!DeclHasAttr(To, I)) {
3487 T *newAttr = cast<T>(I->clone(S.Context));
3488 newAttr->setInherited(true);
3489 To->addAttr(A: newAttr);
3490 ++found;
3491 }
3492 }
3493 return found;
3494}
3495
3496template <class F>
3497static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3498 F &&propagator) {
3499 if (!From->hasAttrs()) {
3500 return;
3501 }
3502
3503 bool foundAny = To->hasAttrs();
3504
3505 // Ensure that any moving of objects within the allocated map is
3506 // done before we process them.
3507 if (!foundAny)
3508 To->setAttrs(AttrVec());
3509
3510 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3511
3512 if (!foundAny)
3513 To->dropAttrs();
3514}
3515
3516/// mergeParamDeclAttributes - Copy attributes from the old parameter
3517/// to the new one.
3518static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3519 const ParmVarDecl *oldDecl, Sema &S) {
3520 propagateAttributes(
3521 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3522 unsigned found = 0;
3523 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3524 // Propagate the lifetimebound and lifetime_capture_by attributes from
3525 // parameters to the most recent declaration. Note that this doesn't
3526 // include the implicit 'this' parameter, as the attribute is applied to
3527 // the function type in that case.
3528 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3529 found += propagateAttribute<LifetimeCaptureByAttr>(To, From, S);
3530 return found;
3531 });
3532}
3533
3534static bool EquivalentArrayTypes(QualType Old, QualType New,
3535 const ASTContext &Ctx) {
3536
3537 auto NoSizeInfo = [&Ctx](QualType Ty) {
3538 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3539 return true;
3540 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3541 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3542 return false;
3543 };
3544
3545 // `type[]` is equivalent to `type *` and `type[*]`.
3546 if (NoSizeInfo(Old) && NoSizeInfo(New))
3547 return true;
3548
3549 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3550 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3551 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3552 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3553 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3554 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3555 return false;
3556 return true;
3557 }
3558
3559 // Only compare size, ignore Size modifiers and CVR.
3560 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3561 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3562 Ctx.getAsConstantArrayType(T: New)->getSize();
3563 }
3564
3565 // Don't try to compare dependent sized array
3566 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3567 return true;
3568 }
3569
3570 return Old == New;
3571}
3572
3573static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3574 const ParmVarDecl *OldParam,
3575 Sema &S) {
3576 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3577 if (auto Newnullability = NewParam->getType()->getNullability()) {
3578 if (*Oldnullability != *Newnullability) {
3579 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3580 << DiagNullabilityKind(
3581 *Newnullability,
3582 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3583 != 0))
3584 << DiagNullabilityKind(
3585 *Oldnullability,
3586 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3587 != 0));
3588 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3589 }
3590 } else {
3591 QualType NewT = NewParam->getType();
3592 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3593 NewParam->setType(NewT);
3594 }
3595 }
3596 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3597 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3598 if (OldParamDT && NewParamDT &&
3599 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3600 QualType OldParamOT = OldParamDT->getOriginalType();
3601 QualType NewParamOT = NewParamDT->getOriginalType();
3602 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3603 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3604 << NewParam << NewParamOT;
3605 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3606 << OldParamOT;
3607 }
3608 }
3609}
3610
3611namespace {
3612
3613/// Used in MergeFunctionDecl to keep track of function parameters in
3614/// C.
3615struct GNUCompatibleParamWarning {
3616 ParmVarDecl *OldParm;
3617 ParmVarDecl *NewParm;
3618 QualType PromotedType;
3619};
3620
3621} // end anonymous namespace
3622
3623// Determine whether the previous declaration was a definition, implicit
3624// declaration, or a declaration.
3625template <typename T>
3626static std::pair<diag::kind, SourceLocation>
3627getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3628 diag::kind PrevDiag;
3629 SourceLocation OldLocation = Old->getLocation();
3630 if (Old->isThisDeclarationADefinition())
3631 PrevDiag = diag::note_previous_definition;
3632 else if (Old->isImplicit()) {
3633 PrevDiag = diag::note_previous_implicit_declaration;
3634 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3635 if (FD->getBuiltinID())
3636 PrevDiag = diag::note_previous_builtin_declaration;
3637 }
3638 if (OldLocation.isInvalid())
3639 OldLocation = New->getLocation();
3640 } else
3641 PrevDiag = diag::note_previous_declaration;
3642 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3643}
3644
3645/// canRedefineFunction - checks if a function can be redefined. Currently,
3646/// only extern inline functions can be redefined, and even then only in
3647/// GNU89 mode.
3648static bool canRedefineFunction(const FunctionDecl *FD,
3649 const LangOptions& LangOpts) {
3650 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3651 !LangOpts.CPlusPlus &&
3652 FD->isInlineSpecified() &&
3653 FD->getStorageClass() == SC_Extern);
3654}
3655
3656const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3657 const AttributedType *AT = T->getAs<AttributedType>();
3658 while (AT && !AT->isCallingConv())
3659 AT = AT->getModifiedType()->getAs<AttributedType>();
3660 return AT;
3661}
3662
3663template <typename T>
3664static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3665 const DeclContext *DC = Old->getDeclContext();
3666 if (DC->isRecord())
3667 return false;
3668
3669 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3670 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3671 return true;
3672 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3673 return true;
3674 return false;
3675}
3676
3677template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3678static bool isExternC(VarTemplateDecl *) { return false; }
3679static bool isExternC(FunctionTemplateDecl *) { return false; }
3680
3681/// Check whether a redeclaration of an entity introduced by a
3682/// using-declaration is valid, given that we know it's not an overload
3683/// (nor a hidden tag declaration).
3684template<typename ExpectedDecl>
3685static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3686 ExpectedDecl *New) {
3687 // C++11 [basic.scope.declarative]p4:
3688 // Given a set of declarations in a single declarative region, each of
3689 // which specifies the same unqualified name,
3690 // -- they shall all refer to the same entity, or all refer to functions
3691 // and function templates; or
3692 // -- exactly one declaration shall declare a class name or enumeration
3693 // name that is not a typedef name and the other declarations shall all
3694 // refer to the same variable or enumerator, or all refer to functions
3695 // and function templates; in this case the class name or enumeration
3696 // name is hidden (3.3.10).
3697
3698 // C++11 [namespace.udecl]p14:
3699 // If a function declaration in namespace scope or block scope has the
3700 // same name and the same parameter-type-list as a function introduced
3701 // by a using-declaration, and the declarations do not declare the same
3702 // function, the program is ill-formed.
3703
3704 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3705 if (Old &&
3706 !Old->getDeclContext()->getRedeclContext()->Equals(
3707 New->getDeclContext()->getRedeclContext()) &&
3708 !(isExternC(Old) && isExternC(New)))
3709 Old = nullptr;
3710
3711 if (!Old) {
3712 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3713 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3714 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3715 return true;
3716 }
3717 return false;
3718}
3719
3720static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3721 const FunctionDecl *B) {
3722 assert(A->getNumParams() == B->getNumParams());
3723
3724 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3725 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3726 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3727 if (AttrA == AttrB)
3728 return true;
3729 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3730 AttrA->isDynamic() == AttrB->isDynamic();
3731 };
3732
3733 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3734}
3735
3736/// If necessary, adjust the semantic declaration context for a qualified
3737/// declaration to name the correct inline namespace within the qualifier.
3738static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3739 DeclaratorDecl *OldD) {
3740 // The only case where we need to update the DeclContext is when
3741 // redeclaration lookup for a qualified name finds a declaration
3742 // in an inline namespace within the context named by the qualifier:
3743 //
3744 // inline namespace N { int f(); }
3745 // int ::f(); // Sema DC needs adjusting from :: to N::.
3746 //
3747 // For unqualified declarations, the semantic context *can* change
3748 // along the redeclaration chain (for local extern declarations,
3749 // extern "C" declarations, and friend declarations in particular).
3750 if (!NewD->getQualifier())
3751 return;
3752
3753 // NewD is probably already in the right context.
3754 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3755 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3756 if (NamedDC->Equals(DC: SemaDC))
3757 return;
3758
3759 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3760 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3761 "unexpected context for redeclaration");
3762
3763 auto *LexDC = NewD->getLexicalDeclContext();
3764 auto FixSemaDC = [=](NamedDecl *D) {
3765 if (!D)
3766 return;
3767 D->setDeclContext(SemaDC);
3768 D->setLexicalDeclContext(LexDC);
3769 };
3770
3771 FixSemaDC(NewD);
3772 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3773 FixSemaDC(FD->getDescribedFunctionTemplate());
3774 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3775 FixSemaDC(VD->getDescribedVarTemplate());
3776}
3777
3778bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3779 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3780 // Verify the old decl was also a function.
3781 FunctionDecl *Old = OldD->getAsFunction();
3782 if (!Old) {
3783 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3784 // We don't need to check the using friend pattern from other module unit
3785 // since we should have diagnosed such cases in its unit already.
3786 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3787 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3788 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3789 DiagID: diag::note_using_decl_target);
3790 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3791 << 0;
3792 return true;
3793 }
3794
3795 // Check whether the two declarations might declare the same function or
3796 // function template.
3797 if (FunctionTemplateDecl *NewTemplate =
3798 New->getDescribedFunctionTemplate()) {
3799 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3800 New: NewTemplate))
3801 return true;
3802 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3803 ->getAsFunction();
3804 } else {
3805 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3806 return true;
3807 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3808 }
3809 } else {
3810 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3811 << New->getDeclName();
3812 notePreviousDefinition(Old: OldD, New: New->getLocation());
3813 return true;
3814 }
3815 }
3816
3817 // If the old declaration was found in an inline namespace and the new
3818 // declaration was qualified, update the DeclContext to match.
3819 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3820
3821 // If the old declaration is invalid, just give up here.
3822 if (Old->isInvalidDecl())
3823 return true;
3824
3825 // Disallow redeclaration of some builtins.
3826 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3827 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3828 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3829 << Old << Old->getType();
3830 return true;
3831 }
3832
3833 diag::kind PrevDiag;
3834 SourceLocation OldLocation;
3835 std::tie(args&: PrevDiag, args&: OldLocation) =
3836 getNoteDiagForInvalidRedeclaration(Old, New);
3837
3838 // Don't complain about this if we're in GNU89 mode and the old function
3839 // is an extern inline function.
3840 // Don't complain about specializations. They are not supposed to have
3841 // storage classes.
3842 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3843 New->getStorageClass() == SC_Static &&
3844 Old->hasExternalFormalLinkage() &&
3845 !New->getTemplateSpecializationInfo() &&
3846 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3847 if (getLangOpts().MicrosoftExt) {
3848 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3849 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3850 } else {
3851 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
3852 << New << /*MixedLinkageUB=*/false;
3853 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3854 return true;
3855 }
3856 }
3857
3858 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3859 if (!Old->hasAttr<InternalLinkageAttr>()) {
3860 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3861 << ILA;
3862 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3863 New->dropAttr<InternalLinkageAttr>();
3864 }
3865
3866 if (auto *EA = New->getAttr<ErrorAttr>()) {
3867 if (!Old->hasAttr<ErrorAttr>()) {
3868 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3869 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3870 New->dropAttr<ErrorAttr>();
3871 }
3872 }
3873
3874 if (CheckRedeclarationInModule(New, Old))
3875 return true;
3876
3877 if (!getLangOpts().CPlusPlus) {
3878 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3879 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3880 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3881 << New << OldOvl;
3882
3883 // Try our best to find a decl that actually has the overloadable
3884 // attribute for the note. In most cases (e.g. programs with only one
3885 // broken declaration/definition), this won't matter.
3886 //
3887 // FIXME: We could do this if we juggled some extra state in
3888 // OverloadableAttr, rather than just removing it.
3889 const Decl *DiagOld = Old;
3890 if (OldOvl) {
3891 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3892 const auto *A = D->getAttr<OverloadableAttr>();
3893 return A && !A->isImplicit();
3894 });
3895 // If we've implicitly added *all* of the overloadable attrs to this
3896 // chain, emitting a "previous redecl" note is pointless.
3897 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3898 }
3899
3900 if (DiagOld)
3901 Diag(Loc: DiagOld->getLocation(),
3902 DiagID: diag::note_attribute_overloadable_prev_overload)
3903 << OldOvl;
3904
3905 if (OldOvl)
3906 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3907 else
3908 New->dropAttr<OverloadableAttr>();
3909 }
3910 }
3911
3912 // It is not permitted to redeclare an SME function with different SME
3913 // attributes.
3914 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3915 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3916 << New->getType() << Old->getType();
3917 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3918 return true;
3919 }
3920
3921 // If a function is first declared with a calling convention, but is later
3922 // declared or defined without one, all following decls assume the calling
3923 // convention of the first.
3924 //
3925 // It's OK if a function is first declared without a calling convention,
3926 // but is later declared or defined with the default calling convention.
3927 //
3928 // To test if either decl has an explicit calling convention, we look for
3929 // AttributedType sugar nodes on the type as written. If they are missing or
3930 // were canonicalized away, we assume the calling convention was implicit.
3931 //
3932 // Note also that we DO NOT return at this point, because we still have
3933 // other tests to run.
3934 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3935 QualType NewQType = Context.getCanonicalType(T: New->getType());
3936 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3937 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3938 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3939 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3940 bool RequiresAdjustment = false;
3941
3942 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3943 FunctionDecl *First = Old->getFirstDecl();
3944 const FunctionType *FT =
3945 First->getType().getCanonicalType()->castAs<FunctionType>();
3946 FunctionType::ExtInfo FI = FT->getExtInfo();
3947 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3948 if (!NewCCExplicit) {
3949 // Inherit the CC from the previous declaration if it was specified
3950 // there but not here.
3951 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3952 RequiresAdjustment = true;
3953 } else if (Old->getBuiltinID()) {
3954 // Builtin attribute isn't propagated to the new one yet at this point,
3955 // so we check if the old one is a builtin.
3956
3957 // Calling Conventions on a Builtin aren't really useful and setting a
3958 // default calling convention and cdecl'ing some builtin redeclarations is
3959 // common, so warn and ignore the calling convention on the redeclaration.
3960 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3961 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3962 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3963 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3964 RequiresAdjustment = true;
3965 } else {
3966 // Calling conventions aren't compatible, so complain.
3967 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3968 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3969 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3970 << !FirstCCExplicit
3971 << (!FirstCCExplicit ? "" :
3972 FunctionType::getNameForCallConv(CC: FI.getCC()));
3973
3974 // Put the note on the first decl, since it is the one that matters.
3975 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3976 return true;
3977 }
3978 }
3979
3980 // FIXME: diagnose the other way around?
3981 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3982 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3983 RequiresAdjustment = true;
3984 }
3985
3986 // If the declaration is marked with cfi_unchecked_callee but the definition
3987 // isn't, the definition is also cfi_unchecked_callee.
3988 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3989 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3990 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3991 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3992
3993 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3994 EPI2.CFIUncheckedCallee = true;
3995 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3996 Args: FPT2->getParamTypes(), EPI: EPI2);
3997 NewType = cast<FunctionType>(Val&: NewQType);
3998 New->setType(NewQType);
3999 }
4000 }
4001 }
4002
4003 // Merge regparm attribute.
4004 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
4005 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
4006 if (NewTypeInfo.getHasRegParm()) {
4007 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
4008 << NewType->getRegParmType()
4009 << OldType->getRegParmType();
4010 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4011 return true;
4012 }
4013
4014 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
4015 RequiresAdjustment = true;
4016 }
4017
4018 // Merge ns_returns_retained attribute.
4019 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4020 if (NewTypeInfo.getProducesResult()) {
4021 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
4022 << "'ns_returns_retained'";
4023 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4024 return true;
4025 }
4026
4027 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
4028 RequiresAdjustment = true;
4029 }
4030
4031 if (OldTypeInfo.getNoCallerSavedRegs() !=
4032 NewTypeInfo.getNoCallerSavedRegs()) {
4033 if (NewTypeInfo.getNoCallerSavedRegs()) {
4034 AnyX86NoCallerSavedRegistersAttr *Attr =
4035 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4036 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
4037 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4038 return true;
4039 }
4040
4041 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
4042 RequiresAdjustment = true;
4043 }
4044
4045 if (RequiresAdjustment) {
4046 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4047 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
4048 New->setType(QualType(AdjustedType, 0));
4049 NewQType = Context.getCanonicalType(T: New->getType());
4050 }
4051
4052 // If this redeclaration makes the function inline, we may need to add it to
4053 // UndefinedButUsed.
4054 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4055 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4056 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4057 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4058 y: SourceLocation()));
4059
4060 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4061 // about it.
4062 if (New->hasAttr<GNUInlineAttr>() &&
4063 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4064 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4065 }
4066
4067 // If pass_object_size params don't match up perfectly, this isn't a valid
4068 // redeclaration.
4069 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4070 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4071 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4072 << New->getDeclName();
4073 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4074 return true;
4075 }
4076
4077 QualType OldQTypeForComparison = OldQType;
4078 if (Context.hasAnyFunctionEffects()) {
4079 const auto OldFX = Old->getFunctionEffects();
4080 const auto NewFX = New->getFunctionEffects();
4081 if (OldFX != NewFX) {
4082 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4083 for (const auto &Diff : Diffs) {
4084 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4085 Diag(Loc: New->getLocation(),
4086 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4087 << Diff.effectName();
4088 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4089 }
4090 }
4091 // Following a warning, we could skip merging effects from the previous
4092 // declaration, but that would trigger an additional "conflicting types"
4093 // error.
4094 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4095 FunctionEffectSet::Conflicts MergeErrs;
4096 FunctionEffectSet MergedFX =
4097 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4098 if (!MergeErrs.empty())
4099 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4100 OldLoc: Old->getLocation());
4101
4102 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4103 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4104 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4105 Args: NewFPT->getParamTypes(), EPI);
4106
4107 New->setType(ModQT);
4108 NewQType = New->getType();
4109
4110 // Revise OldQTForComparison to include the merged effects,
4111 // so as not to fail due to differences later.
4112 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4113 EPI = OldFPT->getExtProtoInfo();
4114 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4115 OldQTypeForComparison = Context.getFunctionType(
4116 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4117 }
4118 if (OldFX.empty()) {
4119 // A redeclaration may add the attribute to a previously seen function
4120 // body which needs to be verified.
4121 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4122 }
4123 }
4124 }
4125 }
4126
4127 if (getLangOpts().CPlusPlus) {
4128 OldQType = Context.getCanonicalType(T: Old->getType());
4129 NewQType = Context.getCanonicalType(T: New->getType());
4130
4131 // Go back to the type source info to compare the declared return types,
4132 // per C++1y [dcl.type.auto]p13:
4133 // Redeclarations or specializations of a function or function template
4134 // with a declared return type that uses a placeholder type shall also
4135 // use that placeholder, not a deduced type.
4136 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4137 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4138 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4139 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4140 OldT: OldDeclaredReturnType)) {
4141 QualType ResQT;
4142 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4143 OldDeclaredReturnType->isObjCObjectPointerType())
4144 // FIXME: This does the wrong thing for a deduced return type.
4145 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4146 if (ResQT.isNull()) {
4147 if (New->isCXXClassMember() && New->isOutOfLine())
4148 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4149 << New << New->getReturnTypeSourceRange();
4150 else if (Old->isExternC() && New->isExternC() &&
4151 !Old->hasAttr<OverloadableAttr>() &&
4152 !New->hasAttr<OverloadableAttr>())
4153 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4154 else
4155 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4156 << New->getReturnTypeSourceRange();
4157 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4158 << Old->getReturnTypeSourceRange();
4159 return true;
4160 }
4161 else
4162 NewQType = ResQT;
4163 }
4164
4165 QualType OldReturnType = OldType->getReturnType();
4166 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4167 if (OldReturnType != NewReturnType) {
4168 // If this function has a deduced return type and has already been
4169 // defined, copy the deduced value from the old declaration.
4170 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4171 if (OldAT && OldAT->isDeduced()) {
4172 QualType DT = OldAT->getDeducedType();
4173 if (DT.isNull()) {
4174 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4175 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4176 } else {
4177 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4178 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4179 }
4180 }
4181 }
4182
4183 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4184 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4185 if (OldMethod && NewMethod) {
4186 // Preserve triviality.
4187 NewMethod->setTrivial(OldMethod->isTrivial());
4188
4189 // MSVC allows explicit template specialization at class scope:
4190 // 2 CXXMethodDecls referring to the same function will be injected.
4191 // We don't want a redeclaration error.
4192 bool IsClassScopeExplicitSpecialization =
4193 OldMethod->isFunctionTemplateSpecialization() &&
4194 NewMethod->isFunctionTemplateSpecialization();
4195 bool isFriend = NewMethod->getFriendObjectKind();
4196
4197 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4198 !IsClassScopeExplicitSpecialization) {
4199 // -- Member function declarations with the same name and the
4200 // same parameter types cannot be overloaded if any of them
4201 // is a static member function declaration.
4202 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4203 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4204 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4205 return true;
4206 }
4207
4208 // C++ [class.mem]p1:
4209 // [...] A member shall not be declared twice in the
4210 // member-specification, except that a nested class or member
4211 // class template can be declared and then later defined.
4212 if (!inTemplateInstantiation()) {
4213 unsigned NewDiag;
4214 if (isa<CXXConstructorDecl>(Val: OldMethod))
4215 NewDiag = diag::err_constructor_redeclared;
4216 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4217 NewDiag = diag::err_destructor_redeclared;
4218 else if (isa<CXXConversionDecl>(Val: NewMethod))
4219 NewDiag = diag::err_conv_function_redeclared;
4220 else
4221 NewDiag = diag::err_member_redeclared;
4222
4223 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4224 } else {
4225 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4226 << New << New->getType();
4227 }
4228 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4229 return true;
4230
4231 // Complain if this is an explicit declaration of a special
4232 // member that was initially declared implicitly.
4233 //
4234 // As an exception, it's okay to befriend such methods in order
4235 // to permit the implicit constructor/destructor/operator calls.
4236 } else if (OldMethod->isImplicit()) {
4237 if (isFriend) {
4238 NewMethod->setImplicit();
4239 } else {
4240 Diag(Loc: NewMethod->getLocation(),
4241 DiagID: diag::err_definition_of_implicitly_declared_member)
4242 << New << OldMethod->getSpecialMemberKind();
4243 return true;
4244 }
4245 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4246 Diag(Loc: NewMethod->getLocation(),
4247 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4248 << OldMethod->getSpecialMemberKind();
4249 return true;
4250 }
4251 }
4252
4253 // C++1z [over.load]p2
4254 // Certain function declarations cannot be overloaded:
4255 // -- Function declarations that differ only in the return type,
4256 // the exception specification, or both cannot be overloaded.
4257
4258 // Check the exception specifications match. This may recompute the type of
4259 // both Old and New if it resolved exception specifications, so grab the
4260 // types again after this. Because this updates the type, we do this before
4261 // any of the other checks below, which may update the "de facto" NewQType
4262 // but do not necessarily update the type of New.
4263 if (CheckEquivalentExceptionSpec(Old, New))
4264 return true;
4265
4266 // C++11 [dcl.attr.noreturn]p1:
4267 // The first declaration of a function shall specify the noreturn
4268 // attribute if any declaration of that function specifies the noreturn
4269 // attribute.
4270 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4271 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4272 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4273 << NRA;
4274 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4275 }
4276
4277 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4278 // When a function is declared with SYCL_EXTERNAL, that macro must be
4279 // used on the first declaration of that function in the translation unit.
4280 // Redeclarations of the function in the same translation unit may
4281 // optionally use SYCL_EXTERNAL, but this is not required.
4282 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4283 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4284 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4285 << SEA;
4286 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4287 }
4288
4289 // (C++98 8.3.5p3):
4290 // All declarations for a function shall agree exactly in both the
4291 // return type and the parameter-type-list.
4292 // We also want to respect all the extended bits except noreturn.
4293
4294 // noreturn should now match unless the old type info didn't have it.
4295 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4296 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4297 const FunctionType *OldTypeForComparison
4298 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4299 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4300 assert(OldQTypeForComparison.isCanonical());
4301 }
4302
4303 if (haveIncompatibleLanguageLinkages(Old, New)) {
4304 // As a special case, retain the language linkage from previous
4305 // declarations of a friend function as an extension.
4306 //
4307 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4308 // and is useful because there's otherwise no way to specify language
4309 // linkage within class scope.
4310 //
4311 // Check cautiously as the friend object kind isn't yet complete.
4312 if (New->getFriendObjectKind() != Decl::FOK_None) {
4313 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4314 Diag(Loc: OldLocation, DiagID: PrevDiag);
4315 } else {
4316 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4317 Diag(Loc: OldLocation, DiagID: PrevDiag);
4318 return true;
4319 }
4320 }
4321
4322 // HLSL check parameters for matching ABI specifications.
4323 if (getLangOpts().HLSL) {
4324 if (HLSL().CheckCompatibleParameterABI(New, Old))
4325 return true;
4326
4327 // If no errors are generated when checking parameter ABIs we can check if
4328 // the two declarations have the same type ignoring the ABIs and if so,
4329 // the declarations can be merged. This case for merging is only valid in
4330 // HLSL because there are no valid cases of merging mismatched parameter
4331 // ABIs except the HLSL implicit in and explicit in.
4332 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4333 U: NewQType))
4334 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4335 // Fall through for conflicting redeclarations and redefinitions.
4336 }
4337
4338 // If the function types are compatible, merge the declarations. Ignore the
4339 // exception specifier because it was already checked above in
4340 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4341 // about incompatible types under -fms-compatibility.
4342 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4343 U: NewQType))
4344 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4345
4346 // If the types are imprecise (due to dependent constructs in friends or
4347 // local extern declarations), it's OK if they differ. We'll check again
4348 // during instantiation.
4349 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4350 return false;
4351
4352 // Fall through for conflicting redeclarations and redefinitions.
4353 }
4354
4355 // C: Function types need to be compatible, not identical. This handles
4356 // duplicate function decls like "void f(int); void f(enum X);" properly.
4357 if (!getLangOpts().CPlusPlus) {
4358 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4359 // type is specified by a function definition that contains a (possibly
4360 // empty) identifier list, both shall agree in the number of parameters
4361 // and the type of each parameter shall be compatible with the type that
4362 // results from the application of default argument promotions to the
4363 // type of the corresponding identifier. ...
4364 // This cannot be handled by ASTContext::typesAreCompatible() because that
4365 // doesn't know whether the function type is for a definition or not when
4366 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4367 // we need to cover here is that the number of arguments agree as the
4368 // default argument promotion rules were already checked by
4369 // ASTContext::typesAreCompatible().
4370 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4371 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4372 if (Old->hasInheritedPrototype())
4373 Old = Old->getCanonicalDecl();
4374 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4375 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4376 return true;
4377 }
4378
4379 // If we are merging two functions where only one of them has a prototype,
4380 // we may have enough information to decide to issue a diagnostic that the
4381 // function without a prototype will change behavior in C23. This handles
4382 // cases like:
4383 // void i(); void i(int j);
4384 // void i(int j); void i();
4385 // void i(); void i(int j) {}
4386 // See ActOnFinishFunctionBody() for other cases of the behavior change
4387 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4388 // type without a prototype.
4389 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4390 !New->isImplicit() && !Old->isImplicit()) {
4391 const FunctionDecl *WithProto, *WithoutProto;
4392 if (New->hasWrittenPrototype()) {
4393 WithProto = New;
4394 WithoutProto = Old;
4395 } else {
4396 WithProto = Old;
4397 WithoutProto = New;
4398 }
4399
4400 if (WithProto->getNumParams() != 0) {
4401 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4402 // The one without the prototype will be changing behavior in C23, so
4403 // warn about that one so long as it's a user-visible declaration.
4404 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4405 if (WithoutProto == New)
4406 IsWithoutProtoADef = NewDeclIsDefn;
4407 else
4408 IsWithProtoADef = NewDeclIsDefn;
4409 Diag(Loc: WithoutProto->getLocation(),
4410 DiagID: diag::warn_non_prototype_changes_behavior)
4411 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4412 << (WithoutProto == Old) << IsWithProtoADef;
4413
4414 // The reason the one without the prototype will be changing behavior
4415 // is because of the one with the prototype, so note that so long as
4416 // it's a user-visible declaration. There is one exception to this:
4417 // when the new declaration is a definition without a prototype, the
4418 // old declaration with a prototype is not the cause of the issue,
4419 // and that does not need to be noted because the one with a
4420 // prototype will not change behavior in C23.
4421 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4422 !IsWithoutProtoADef)
4423 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4424 }
4425 }
4426 }
4427
4428 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4429 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4430 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4431 const FunctionProtoType *OldProto = nullptr;
4432 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4433 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4434 // The old declaration provided a function prototype, but the
4435 // new declaration does not. Merge in the prototype.
4436 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4437 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4438 Args: OldProto->getParamTypes(),
4439 EPI: OldProto->getExtProtoInfo());
4440 New->setType(NewQType);
4441 New->setHasInheritedPrototype();
4442
4443 // Synthesize parameters with the same types.
4444 SmallVector<ParmVarDecl *, 16> Params;
4445 for (const auto &ParamType : OldProto->param_types()) {
4446 ParmVarDecl *Param = ParmVarDecl::Create(
4447 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4448 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4449 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4450 Param->setImplicit();
4451 Params.push_back(Elt: Param);
4452 }
4453
4454 New->setParams(Params);
4455 }
4456
4457 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4458 }
4459 }
4460
4461 // Check if the function types are compatible when pointer size address
4462 // spaces are ignored.
4463 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4464 return false;
4465
4466 // GNU C permits a K&R definition to follow a prototype declaration
4467 // if the declared types of the parameters in the K&R definition
4468 // match the types in the prototype declaration, even when the
4469 // promoted types of the parameters from the K&R definition differ
4470 // from the types in the prototype. GCC then keeps the types from
4471 // the prototype.
4472 //
4473 // If a variadic prototype is followed by a non-variadic K&R definition,
4474 // the K&R definition becomes variadic. This is sort of an edge case, but
4475 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4476 // C99 6.9.1p8.
4477 if (!getLangOpts().CPlusPlus &&
4478 Old->hasPrototype() && !New->hasPrototype() &&
4479 New->getType()->getAs<FunctionProtoType>() &&
4480 Old->getNumParams() == New->getNumParams()) {
4481 SmallVector<QualType, 16> ArgTypes;
4482 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4483 const FunctionProtoType *OldProto
4484 = Old->getType()->getAs<FunctionProtoType>();
4485 const FunctionProtoType *NewProto
4486 = New->getType()->getAs<FunctionProtoType>();
4487
4488 // Determine whether this is the GNU C extension.
4489 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4490 NewProto->getReturnType());
4491 bool LooseCompatible = !MergedReturn.isNull();
4492 for (unsigned Idx = 0, End = Old->getNumParams();
4493 LooseCompatible && Idx != End; ++Idx) {
4494 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4495 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4496 if (Context.typesAreCompatible(T1: OldParm->getType(),
4497 T2: NewProto->getParamType(i: Idx))) {
4498 ArgTypes.push_back(Elt: NewParm->getType());
4499 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4500 T2: NewParm->getType(),
4501 /*CompareUnqualified=*/true)) {
4502 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4503 .PromotedType: NewProto->getParamType(i: Idx) };
4504 Warnings.push_back(Elt: Warn);
4505 ArgTypes.push_back(Elt: NewParm->getType());
4506 } else
4507 LooseCompatible = false;
4508 }
4509
4510 if (LooseCompatible) {
4511 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4512 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4513 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4514 << Warnings[Warn].PromotedType
4515 << Warnings[Warn].OldParm->getType();
4516 if (Warnings[Warn].OldParm->getLocation().isValid())
4517 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4518 DiagID: diag::note_previous_declaration);
4519 }
4520
4521 if (MergeTypeWithOld)
4522 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4523 EPI: OldProto->getExtProtoInfo()));
4524 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4525 }
4526
4527 // Fall through to diagnose conflicting types.
4528 }
4529
4530 // A function that has already been declared has been redeclared or
4531 // defined with a different type; show an appropriate diagnostic.
4532
4533 // If the previous declaration was an implicitly-generated builtin
4534 // declaration, then at the very least we should use a specialized note.
4535 unsigned BuiltinID;
4536 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4537 // If it's actually a library-defined builtin function like 'malloc'
4538 // or 'printf', just warn about the incompatible redeclaration.
4539 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4540 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4541 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4542 << Old << Old->getType();
4543 return false;
4544 }
4545
4546 PrevDiag = diag::note_previous_builtin_declaration;
4547 }
4548
4549 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4550 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4551 return true;
4552}
4553
4554bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4555 Scope *S, bool MergeTypeWithOld) {
4556 // Merge the attributes
4557 mergeDeclAttributes(New, Old);
4558
4559 // Merge "pure" flag.
4560 if (Old->isPureVirtual())
4561 New->setIsPureVirtual();
4562
4563 // Merge "used" flag.
4564 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4565 New->setIsUsed();
4566
4567 // Merge attributes from the parameters. These can mismatch with K&R
4568 // declarations.
4569 if (New->getNumParams() == Old->getNumParams())
4570 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4571 ParmVarDecl *NewParam = New->getParamDecl(i);
4572 ParmVarDecl *OldParam = Old->getParamDecl(i);
4573 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4574 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4575 }
4576
4577 if (getLangOpts().CPlusPlus)
4578 return MergeCXXFunctionDecl(New, Old, S);
4579
4580 // Merge the function types so the we get the composite types for the return
4581 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4582 // was visible.
4583 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4584 if (!Merged.isNull() && MergeTypeWithOld)
4585 New->setType(Merged);
4586
4587 return false;
4588}
4589
4590void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4591 ObjCMethodDecl *oldMethod) {
4592 // Merge the attributes, including deprecated/unavailable
4593 AvailabilityMergeKind MergeKind =
4594 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4595 ? (oldMethod->isOptional()
4596 ? AvailabilityMergeKind::OptionalProtocolImplementation
4597 : AvailabilityMergeKind::ProtocolImplementation)
4598 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4599 ? AvailabilityMergeKind::Redeclaration
4600 : AvailabilityMergeKind::Override;
4601
4602 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4603
4604 // Merge attributes from the parameters.
4605 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4606 oe = oldMethod->param_end();
4607 for (ObjCMethodDecl::param_iterator
4608 ni = newMethod->param_begin(), ne = newMethod->param_end();
4609 ni != ne && oi != oe; ++ni, ++oi)
4610 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4611
4612 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4613}
4614
4615static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4616 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4617
4618 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4619 ? diag::err_redefinition_different_type
4620 : diag::err_redeclaration_different_type)
4621 << New->getDeclName() << New->getType() << Old->getType();
4622
4623 diag::kind PrevDiag;
4624 SourceLocation OldLocation;
4625 std::tie(args&: PrevDiag, args&: OldLocation)
4626 = getNoteDiagForInvalidRedeclaration(Old, New);
4627 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4628 New->setInvalidDecl();
4629}
4630
4631void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4632 bool MergeTypeWithOld) {
4633 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4634 return;
4635
4636 QualType MergedT;
4637 if (getLangOpts().CPlusPlus) {
4638 if (New->getType()->isUndeducedType()) {
4639 // We don't know what the new type is until the initializer is attached.
4640 return;
4641 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4642 // These could still be something that needs exception specs checked.
4643 return MergeVarDeclExceptionSpecs(New, Old);
4644 }
4645 // C++ [basic.link]p10:
4646 // [...] the types specified by all declarations referring to a given
4647 // object or function shall be identical, except that declarations for an
4648 // array object can specify array types that differ by the presence or
4649 // absence of a major array bound (8.3.4).
4650 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4651 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4652 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4653
4654 // We are merging a variable declaration New into Old. If it has an array
4655 // bound, and that bound differs from Old's bound, we should diagnose the
4656 // mismatch.
4657 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4658 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4659 PrevVD = PrevVD->getPreviousDecl()) {
4660 QualType PrevVDTy = PrevVD->getType();
4661 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4662 continue;
4663
4664 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4665 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4666 }
4667 }
4668
4669 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4670 if (Context.hasSameType(T1: OldArray->getElementType(),
4671 T2: NewArray->getElementType()))
4672 MergedT = New->getType();
4673 }
4674 // FIXME: Check visibility. New is hidden but has a complete type. If New
4675 // has no array bound, it should not inherit one from Old, if Old is not
4676 // visible.
4677 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4678 if (Context.hasSameType(T1: OldArray->getElementType(),
4679 T2: NewArray->getElementType()))
4680 MergedT = Old->getType();
4681 }
4682 }
4683 else if (New->getType()->isObjCObjectPointerType() &&
4684 Old->getType()->isObjCObjectPointerType()) {
4685 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4686 Old->getType());
4687 }
4688 } else {
4689 // C 6.2.7p2:
4690 // All declarations that refer to the same object or function shall have
4691 // compatible type.
4692 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4693 }
4694 if (MergedT.isNull()) {
4695 // It's OK if we couldn't merge types if either type is dependent, for a
4696 // block-scope variable. In other cases (static data members of class
4697 // templates, variable templates, ...), we require the types to be
4698 // equivalent.
4699 // FIXME: The C++ standard doesn't say anything about this.
4700 if ((New->getType()->isDependentType() ||
4701 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4702 // If the old type was dependent, we can't merge with it, so the new type
4703 // becomes dependent for now. We'll reproduce the original type when we
4704 // instantiate the TypeSourceInfo for the variable.
4705 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4706 New->setType(Context.DependentTy);
4707 return;
4708 }
4709 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4710 }
4711
4712 // Don't actually update the type on the new declaration if the old
4713 // declaration was an extern declaration in a different scope.
4714 if (MergeTypeWithOld)
4715 New->setType(MergedT);
4716}
4717
4718static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4719 LookupResult &Previous) {
4720 // C11 6.2.7p4:
4721 // For an identifier with internal or external linkage declared
4722 // in a scope in which a prior declaration of that identifier is
4723 // visible, if the prior declaration specifies internal or
4724 // external linkage, the type of the identifier at the later
4725 // declaration becomes the composite type.
4726 //
4727 // If the variable isn't visible, we do not merge with its type.
4728 if (Previous.isShadowed())
4729 return false;
4730
4731 if (S.getLangOpts().CPlusPlus) {
4732 // C++11 [dcl.array]p3:
4733 // If there is a preceding declaration of the entity in the same
4734 // scope in which the bound was specified, an omitted array bound
4735 // is taken to be the same as in that earlier declaration.
4736 return NewVD->isPreviousDeclInSameBlockScope() ||
4737 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4738 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4739 } else {
4740 // If the old declaration was function-local, don't merge with its
4741 // type unless we're in the same function.
4742 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4743 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4744 }
4745}
4746
4747void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4748 // If the new decl is already invalid, don't do any other checking.
4749 if (New->isInvalidDecl())
4750 return;
4751
4752 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4753 return;
4754
4755 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4756
4757 // Verify the old decl was also a variable or variable template.
4758 VarDecl *Old = nullptr;
4759 VarTemplateDecl *OldTemplate = nullptr;
4760 if (Previous.isSingleResult()) {
4761 if (NewTemplate) {
4762 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4763 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4764
4765 if (auto *Shadow =
4766 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4767 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4768 return New->setInvalidDecl();
4769 } else {
4770 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4771
4772 if (auto *Shadow =
4773 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4774 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4775 return New->setInvalidDecl();
4776 }
4777 }
4778 if (!Old) {
4779 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4780 << New->getDeclName();
4781 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4782 New: New->getLocation());
4783 return New->setInvalidDecl();
4784 }
4785
4786 // If the old declaration was found in an inline namespace and the new
4787 // declaration was qualified, update the DeclContext to match.
4788 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4789
4790 // Ensure the template parameters are compatible.
4791 if (NewTemplate &&
4792 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4793 Old: OldTemplate->getTemplateParameters(),
4794 /*Complain=*/true, Kind: TPL_TemplateMatch))
4795 return New->setInvalidDecl();
4796
4797 // C++ [class.mem]p1:
4798 // A member shall not be declared twice in the member-specification [...]
4799 //
4800 // Here, we need only consider static data members.
4801 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4802 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4803 << New->getIdentifier();
4804 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4805 New->setInvalidDecl();
4806 }
4807
4808 if (NewTemplate && OldTemplate)
4809 mergeDeclAttributes(New: NewTemplate, Old: OldTemplate);
4810
4811 mergeDeclAttributes(New, Old);
4812
4813 // Warn if an already-defined variable is made a weak_import in a subsequent
4814 // declaration
4815 if (New->hasAttr<WeakImportAttr>())
4816 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4817 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4818 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4819 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4820 // Remove weak_import attribute on new declaration.
4821 New->dropAttr<WeakImportAttr>();
4822 break;
4823 }
4824 }
4825
4826 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4827 if (!Old->hasAttr<InternalLinkageAttr>()) {
4828 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4829 << ILA;
4830 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4831 New->dropAttr<InternalLinkageAttr>();
4832 }
4833
4834 // Merge the types.
4835 VarDecl *MostRecent = Old->getMostRecentDecl();
4836 if (MostRecent != Old) {
4837 MergeVarDeclTypes(New, Old: MostRecent,
4838 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4839 if (New->isInvalidDecl())
4840 return;
4841 }
4842
4843 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4844 if (New->isInvalidDecl())
4845 return;
4846
4847 diag::kind PrevDiag;
4848 SourceLocation OldLocation;
4849 std::tie(args&: PrevDiag, args&: OldLocation) =
4850 getNoteDiagForInvalidRedeclaration(Old, New);
4851
4852 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4853 if (New->getStorageClass() == SC_Static &&
4854 !New->isStaticDataMember() &&
4855 Old->hasExternalFormalLinkage()) {
4856 if (getLangOpts().MicrosoftExt) {
4857 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4858 << New->getDeclName();
4859 Diag(Loc: OldLocation, DiagID: PrevDiag);
4860 } else {
4861 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4862 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4863 // the older C language modes.
4864 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4865 << New->getDeclName()
4866 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4867 Diag(Loc: OldLocation, DiagID: PrevDiag);
4868 return New->setInvalidDecl();
4869 }
4870 }
4871
4872 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4873 // external linkage within a translation unit. Before C2y this was UB
4874 // (C11 6.2.2p7).
4875 //
4876 // In C, a local shadow prevents a block-scope extern from inheriting the
4877 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4878 // external linkage, creating the conflict.
4879 //
4880 // In C++, block-scope extern declarations target the enclosing namespace
4881 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4882 // the extern always inherits internal linkage. No conflict arises.
4883 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4884 New->hasExternalStorage() && Previous.isShadowed() &&
4885 Old->getFormalLinkage() == Linkage::Internal) {
4886 Diag(Loc: New->getLocation(), DiagID: diag::err_internal_extern_mismatch)
4887 << New->getDeclName() << getLangOpts().C2y;
4888 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4889 return New->setInvalidDecl();
4890 }
4891
4892 // C99 6.2.2p4:
4893 // For an identifier declared with the storage-class specifier
4894 // extern in a scope in which a prior declaration of that
4895 // identifier is visible,23) if the prior declaration specifies
4896 // internal or external linkage, the linkage of the identifier at
4897 // the later declaration is the same as the linkage specified at
4898 // the prior declaration. If no prior declaration is visible, or
4899 // if the prior declaration specifies no linkage, then the
4900 // identifier has external linkage.
4901 if (New->hasExternalStorage() && Old->hasLinkage())
4902 /* Okay */;
4903 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4904 !New->isStaticDataMember() &&
4905 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4906 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4907 Diag(Loc: OldLocation, DiagID: PrevDiag);
4908 return New->setInvalidDecl();
4909 }
4910
4911 // Check if extern is followed by non-extern and vice-versa.
4912 if (New->hasExternalStorage() &&
4913 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4914 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4915 Diag(Loc: OldLocation, DiagID: PrevDiag);
4916 return New->setInvalidDecl();
4917 }
4918 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4919 !New->hasExternalStorage()) {
4920 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4921 Diag(Loc: OldLocation, DiagID: PrevDiag);
4922 return New->setInvalidDecl();
4923 }
4924
4925 if (CheckRedeclarationInModule(New, Old))
4926 return;
4927
4928 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4929
4930 // FIXME: The test for external storage here seems wrong? We still
4931 // need to check for mismatches.
4932 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4933 // Don't complain about out-of-line definitions of static members.
4934 !(Old->getLexicalDeclContext()->isRecord() &&
4935 !New->getLexicalDeclContext()->isRecord())) {
4936 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4937 Diag(Loc: OldLocation, DiagID: PrevDiag);
4938 return New->setInvalidDecl();
4939 }
4940
4941 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4942 if (VarDecl *Def = Old->getDefinition()) {
4943 // C++1z [dcl.fcn.spec]p4:
4944 // If the definition of a variable appears in a translation unit before
4945 // its first declaration as inline, the program is ill-formed.
4946 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4947 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4948 }
4949 }
4950
4951 // If this redeclaration makes the variable inline, we may need to add it to
4952 // UndefinedButUsed.
4953 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4954 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4955 !Old->isInAnotherModuleUnit())
4956 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4957 y: SourceLocation()));
4958
4959 if (New->getTLSKind() != Old->getTLSKind()) {
4960 if (!Old->getTLSKind()) {
4961 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4962 Diag(Loc: OldLocation, DiagID: PrevDiag);
4963 } else if (!New->getTLSKind()) {
4964 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4965 Diag(Loc: OldLocation, DiagID: PrevDiag);
4966 } else {
4967 // Do not allow redeclaration to change the variable between requiring
4968 // static and dynamic initialization.
4969 // FIXME: GCC allows this, but uses the TLS keyword on the first
4970 // declaration to determine the kind. Do we need to be compatible here?
4971 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4972 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4973 Diag(Loc: OldLocation, DiagID: PrevDiag);
4974 }
4975 }
4976
4977 // C++ doesn't have tentative definitions, so go right ahead and check here.
4978 if (getLangOpts().CPlusPlus) {
4979 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4980 Old->getCanonicalDecl()->isConstexpr()) {
4981 // This definition won't be a definition any more once it's been merged.
4982 Diag(Loc: New->getLocation(),
4983 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4984 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4985 VarDecl *Def = Old->getDefinition();
4986 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4987 return;
4988 if (Old->isInvalidDecl())
4989 New->setInvalidDecl();
4990 }
4991 } else {
4992 // C++ may not have a tentative definition rule, but it has a different
4993 // rule about what constitutes a definition in the first place. See
4994 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4995 // contains the extern specifier and doesn't have an initializer, it's fine
4996 // in C++.
4997 if (New->getTLSKind() != VarDecl::TLS_None &&
4998 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4999 VarDecl *Def = Old->getDefinition();
5000 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New)) {
5001 return;
5002 }
5003 } else if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
5004 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
5005 << New;
5006 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
5007 }
5008 }
5009
5010 if (haveIncompatibleLanguageLinkages(Old, New)) {
5011 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
5012 Diag(Loc: OldLocation, DiagID: PrevDiag);
5013 New->setInvalidDecl();
5014 return;
5015 }
5016
5017 // Merge "used" flag.
5018 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
5019 New->setIsUsed();
5020
5021 // Keep a chain of previous declarations.
5022 New->setPreviousDecl(Old);
5023 if (NewTemplate)
5024 NewTemplate->setPreviousDecl(OldTemplate);
5025
5026 // Inherit access appropriately.
5027 New->setAccess(Old->getAccess());
5028 if (NewTemplate)
5029 NewTemplate->setAccess(New->getAccess());
5030
5031 if (Old->isInline())
5032 New->setImplicitlyInline();
5033}
5034
5035void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
5036 SourceManager &SrcMgr = getSourceManager();
5037 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
5038 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
5039 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
5040 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
5041 auto &HSI = PP.getHeaderSearchInfo();
5042 StringRef HdrFilename =
5043 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
5044
5045 auto noteFromModuleOrInclude = [&](Module *Mod,
5046 SourceLocation IncLoc) -> bool {
5047 // Redefinition errors with modules are common with non modular mapped
5048 // headers, example: a non-modular header H in module A that also gets
5049 // included directly in a TU. Pointing twice to the same header/definition
5050 // is confusing, try to get better diagnostics when modules is on.
5051 if (IncLoc.isValid()) {
5052 if (Mod) {
5053 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
5054 << HdrFilename.str() << Mod->getFullModuleName();
5055 if (!Mod->DefinitionLoc.isInvalid())
5056 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
5057 << Mod->getFullModuleName();
5058 } else {
5059 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
5060 << HdrFilename.str();
5061 }
5062 return true;
5063 }
5064
5065 return false;
5066 };
5067
5068 // Is it the same file and same offset? Provide more information on why
5069 // this leads to a redefinition error.
5070 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5071 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
5072 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5073 bool EmittedDiag =
5074 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5075 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5076
5077 // If the header has no guards, emit a note suggesting one.
5078 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5079 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5080
5081 if (EmittedDiag)
5082 return;
5083 }
5084
5085 // Redefinition coming from different files or couldn't do better above.
5086 if (Old->getLocation().isValid())
5087 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5088}
5089
5090bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5091 if ((!hasVisibleDefinition(D: Old) ||
5092 isFromSameSingleIncludeHeader(PrevD: Old, NewLoc: New->getLocation())) &&
5093 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5094 isa<VarTemplateSpecializationDecl>(Val: New) ||
5095 New->getDescribedVarTemplate() ||
5096 !New->getTemplateParameterLists().empty() ||
5097 New->getDeclContext()->isDependentContext() ||
5098 New->hasAttr<SelectAnyAttr>())) {
5099 // The previous definition is hidden, and multiple definitions are
5100 // permitted (in separate TUs). Demote this to a declaration.
5101 New->demoteThisDefinitionToDeclaration();
5102
5103 // Make the canonical definition visible.
5104 if (auto *OldTD = Old->getDescribedVarTemplate())
5105 makeMergedDefinitionVisible(ND: OldTD);
5106 makeMergedDefinitionVisible(ND: Old);
5107 return false;
5108 } else {
5109 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5110 notePreviousDefinition(Old, New: New->getLocation());
5111 New->setInvalidDecl();
5112 return true;
5113 }
5114}
5115
5116Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5117 DeclSpec &DS,
5118 const ParsedAttributesView &DeclAttrs,
5119 RecordDecl *&AnonRecord) {
5120 return ParsedFreeStandingDeclSpec(
5121 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5122}
5123
5124// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5125// disambiguate entities defined in different scopes.
5126// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5127// compatibility.
5128// We will pick our mangling number depending on which version of MSVC is being
5129// targeted.
5130static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5131 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5132 ? S->getMSCurManglingNumber()
5133 : S->getMSLastManglingNumber();
5134}
5135
5136void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5137 if (!Context.getLangOpts().CPlusPlus)
5138 return;
5139
5140 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5141 // If this tag is the direct child of a class, number it if
5142 // it is anonymous.
5143 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5144 return;
5145 MangleNumberingContext &MCtx =
5146 Context.getManglingNumberContext(DC: Tag->getParent());
5147 Context.setManglingNumber(
5148 ND: Tag, Number: MCtx.getManglingNumber(
5149 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5150 return;
5151 }
5152
5153 // If this tag isn't a direct child of a class, number it if it is local.
5154 MangleNumberingContext *MCtx;
5155 Decl *ManglingContextDecl;
5156 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5157 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5158 if (MCtx) {
5159 Context.setManglingNumber(
5160 ND: Tag, Number: MCtx->getManglingNumber(
5161 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5162 }
5163}
5164
5165namespace {
5166struct NonCLikeKind {
5167 enum {
5168 None,
5169 BaseClass,
5170 DefaultMemberInit,
5171 Lambda,
5172 Friend,
5173 OtherMember,
5174 Invalid,
5175 } Kind = None;
5176 SourceRange Range;
5177
5178 explicit operator bool() { return Kind != None; }
5179};
5180}
5181
5182/// Determine whether a class is C-like, according to the rules of C++
5183/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5184static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5185 if (RD->isInvalidDecl())
5186 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5187
5188 // C++ [dcl.typedef]p9: [P1766R1]
5189 // An unnamed class with a typedef name for linkage purposes shall not
5190 //
5191 // -- have any base classes
5192 if (RD->getNumBases())
5193 return {.Kind: NonCLikeKind::BaseClass,
5194 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5195 RD->bases_end()[-1].getEndLoc())};
5196 bool Invalid = false;
5197 for (Decl *D : RD->decls()) {
5198 // Don't complain about things we already diagnosed.
5199 if (D->isInvalidDecl()) {
5200 Invalid = true;
5201 continue;
5202 }
5203
5204 // -- have any [...] default member initializers
5205 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5206 if (FD->hasInClassInitializer()) {
5207 auto *Init = FD->getInClassInitializer();
5208 return {.Kind: NonCLikeKind::DefaultMemberInit,
5209 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5210 }
5211 continue;
5212 }
5213
5214 // FIXME: We don't allow friend declarations. This violates the wording of
5215 // P1766, but not the intent.
5216 if (isa<FriendDecl>(Val: D))
5217 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5218
5219 // -- declare any members other than non-static data members, member
5220 // enumerations, or member classes,
5221 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5222 isa<EnumDecl>(Val: D))
5223 continue;
5224 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5225 if (!MemberRD) {
5226 if (D->isImplicit())
5227 continue;
5228 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5229 }
5230
5231 // -- contain a lambda-expression,
5232 if (MemberRD->isLambda())
5233 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5234
5235 // and all member classes shall also satisfy these requirements
5236 // (recursively).
5237 if (MemberRD->isThisDeclarationADefinition()) {
5238 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5239 return Kind;
5240 }
5241 }
5242
5243 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5244}
5245
5246void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5247 TypedefNameDecl *NewTD) {
5248 if (TagFromDeclSpec->isInvalidDecl())
5249 return;
5250
5251 // Do nothing if the tag already has a name for linkage purposes.
5252 if (TagFromDeclSpec->hasNameForLinkage())
5253 return;
5254
5255 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5256 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5257
5258 // The type must match the tag exactly; no qualifiers allowed.
5259 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5260 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5261 if (getLangOpts().CPlusPlus)
5262 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5263 return;
5264 }
5265
5266 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5267 // An unnamed class with a typedef name for linkage purposes shall [be
5268 // C-like].
5269 //
5270 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5271 // shouldn't happen, but there are constructs that the language rule doesn't
5272 // disallow for which we can't reasonably avoid computing linkage early.
5273 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5274 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5275 : NonCLikeKind();
5276 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5277 if (NonCLike || ChangesLinkage) {
5278 if (NonCLike.Kind == NonCLikeKind::Invalid)
5279 return;
5280
5281 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5282 if (ChangesLinkage) {
5283 // If the linkage changes, we can't accept this as an extension.
5284 if (NonCLike.Kind == NonCLikeKind::None)
5285 DiagID = diag::err_typedef_changes_linkage;
5286 else
5287 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5288 }
5289
5290 SourceLocation FixitLoc =
5291 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5292 llvm::SmallString<40> TextToInsert;
5293 TextToInsert += ' ';
5294 TextToInsert += NewTD->getIdentifier()->getName();
5295
5296 Diag(Loc: FixitLoc, DiagID)
5297 << isa<TypeAliasDecl>(Val: NewTD)
5298 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5299 if (NonCLike.Kind != NonCLikeKind::None) {
5300 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5301 << NonCLike.Kind - 1 << NonCLike.Range;
5302 }
5303 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5304 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5305
5306 if (ChangesLinkage)
5307 return;
5308 }
5309
5310 // Otherwise, set this as the anon-decl typedef for the tag.
5311 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5312
5313 // Now that we have a name for the tag, process API notes again.
5314 ProcessAPINotes(D: TagFromDeclSpec);
5315}
5316
5317static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5318 DeclSpec::TST T = DS.getTypeSpecType();
5319 switch (T) {
5320 case DeclSpec::TST_class:
5321 return 0;
5322 case DeclSpec::TST_struct:
5323 return 1;
5324 case DeclSpec::TST_interface:
5325 return 2;
5326 case DeclSpec::TST_union:
5327 return 3;
5328 case DeclSpec::TST_enum:
5329 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5330 if (ED->isScopedUsingClassTag())
5331 return 5;
5332 if (ED->isScoped())
5333 return 6;
5334 }
5335 return 4;
5336 default:
5337 llvm_unreachable("unexpected type specifier");
5338 }
5339}
5340
5341Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5342 DeclSpec &DS,
5343 const ParsedAttributesView &DeclAttrs,
5344 MultiTemplateParamsArg TemplateParams,
5345 bool IsExplicitInstantiation,
5346 RecordDecl *&AnonRecord,
5347 SourceLocation EllipsisLoc) {
5348 Decl *TagD = nullptr;
5349 TagDecl *Tag = nullptr;
5350 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5351 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5352 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5353 DS.getTypeSpecType() == DeclSpec::TST_union ||
5354 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5355 TagD = DS.getRepAsDecl();
5356
5357 if (!TagD) // We probably had an error
5358 return nullptr;
5359
5360 // Note that the above type specs guarantee that the
5361 // type rep is a Decl, whereas in many of the others
5362 // it's a Type.
5363 if (isa<TagDecl>(Val: TagD))
5364 Tag = cast<TagDecl>(Val: TagD);
5365 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5366 Tag = CTD->getTemplatedDecl();
5367 }
5368
5369 if (Tag) {
5370 handleTagNumbering(Tag, TagScope: S);
5371 Tag->setFreeStanding();
5372 if (Tag->isInvalidDecl())
5373 return Tag;
5374 }
5375
5376 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5377 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5378 // or incomplete types shall not be restrict-qualified."
5379 if (TypeQuals & DeclSpec::TQ_restrict)
5380 Diag(Loc: DS.getRestrictSpecLoc(),
5381 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5382 << DS.getSourceRange();
5383 }
5384
5385 if (DS.isInlineSpecified())
5386 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5387 << getLangOpts().CPlusPlus17;
5388
5389 if (DS.hasConstexprSpecifier()) {
5390 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5391 // and definitions of functions and variables.
5392 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5393 // the declaration of a function or function template
5394 if (Tag)
5395 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5396 << GetDiagnosticTypeSpecifierID(DS)
5397 << static_cast<int>(DS.getConstexprSpecifier());
5398 else if (getLangOpts().C23)
5399 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5400 else
5401 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5402 << static_cast<int>(DS.getConstexprSpecifier());
5403 // Don't emit warnings after this error.
5404 return TagD;
5405 }
5406
5407 DiagnoseFunctionSpecifiers(DS);
5408
5409 if (DS.isFriendSpecified()) {
5410 // If we're dealing with a decl but not a TagDecl, assume that
5411 // whatever routines created it handled the friendship aspect.
5412 if (TagD && !Tag)
5413 return nullptr;
5414 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5415 }
5416
5417 assert(EllipsisLoc.isInvalid() &&
5418 "Friend ellipsis but not friend-specified?");
5419
5420 // Track whether this decl-specifier declares anything.
5421 bool DeclaresAnything = true;
5422
5423 // Handle anonymous struct definitions.
5424 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5425 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5426 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5427 if (getLangOpts().CPlusPlus ||
5428 Record->getDeclContext()->isRecord()) {
5429 // If CurContext is a DeclContext that can contain statements,
5430 // RecursiveASTVisitor won't visit the decls that
5431 // BuildAnonymousStructOrUnion() will put into CurContext.
5432 // Also store them here so that they can be part of the
5433 // DeclStmt that gets created in this case.
5434 // FIXME: Also return the IndirectFieldDecls created by
5435 // BuildAnonymousStructOr union, for the same reason?
5436 if (CurContext->isFunctionOrMethod())
5437 AnonRecord = Record;
5438 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5439 Policy: Context.getPrintingPolicy());
5440 }
5441
5442 DeclaresAnything = false;
5443 }
5444 }
5445
5446 // C11 6.7.2.1p2:
5447 // A struct-declaration that does not declare an anonymous structure or
5448 // anonymous union shall contain a struct-declarator-list.
5449 //
5450 // This rule also existed in C89 and C99; the grammar for struct-declaration
5451 // did not permit a struct-declaration without a struct-declarator-list.
5452 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5453 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5454 // Check for Microsoft C extension: anonymous struct/union member.
5455 // Handle 2 kinds of anonymous struct/union:
5456 // struct STRUCT;
5457 // union UNION;
5458 // and
5459 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5460 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5461 if ((Tag && Tag->getDeclName()) ||
5462 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5463 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5464 : DS.getRepAsType().get()->getAsRecordDecl();
5465 if (Record && getLangOpts().MSAnonymousStructs) {
5466 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5467 << Record->isUnion() << DS.getSourceRange();
5468 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5469 }
5470
5471 DeclaresAnything = false;
5472 }
5473 }
5474
5475 // Skip all the checks below if we have a type error.
5476 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5477 (TagD && TagD->isInvalidDecl()))
5478 return TagD;
5479
5480 if (getLangOpts().CPlusPlus &&
5481 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5482 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5483 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5484 !Enum->isInvalidDecl())
5485 DeclaresAnything = false;
5486
5487 if (!DS.isMissingDeclaratorOk()) {
5488 // Customize diagnostic for a typedef missing a name.
5489 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5490 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5491 << DS.getSourceRange();
5492 else
5493 DeclaresAnything = false;
5494 }
5495
5496 if (DS.isModulePrivateSpecified() &&
5497 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5498 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5499 << Tag->getTagKind()
5500 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5501
5502 ActOnDocumentableDecl(D: TagD);
5503
5504 // C 6.7/2:
5505 // A declaration [...] shall declare at least a declarator [...], a tag,
5506 // or the members of an enumeration.
5507 // C++ [dcl.dcl]p3:
5508 // [If there are no declarators], and except for the declaration of an
5509 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5510 // names into the program, or shall redeclare a name introduced by a
5511 // previous declaration.
5512 if (!DeclaresAnything) {
5513 // In C, we allow this as a (popular) extension / bug. Don't bother
5514 // producing further diagnostics for redundant qualifiers after this.
5515 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5516 ? diag::err_no_declarators
5517 : diag::ext_no_declarators)
5518 << DS.getSourceRange();
5519 return TagD;
5520 }
5521
5522 // C++ [dcl.stc]p1:
5523 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5524 // init-declarator-list of the declaration shall not be empty.
5525 // C++ [dcl.fct.spec]p1:
5526 // If a cv-qualifier appears in a decl-specifier-seq, the
5527 // init-declarator-list of the declaration shall not be empty.
5528 //
5529 // Spurious qualifiers here appear to be valid in C.
5530 unsigned DiagID = diag::warn_standalone_specifier;
5531 if (getLangOpts().CPlusPlus)
5532 DiagID = diag::ext_standalone_specifier;
5533
5534 // Note that a linkage-specification sets a storage class, but
5535 // 'extern "C" struct foo;' is actually valid and not theoretically
5536 // useless.
5537 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5538 if (SCS == DeclSpec::SCS_mutable)
5539 // Since mutable is not a viable storage class specifier in C, there is
5540 // no reason to treat it as an extension. Instead, diagnose as an error.
5541 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5542 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5543 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5544 << DeclSpec::getSpecifierName(S: SCS);
5545 }
5546
5547 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5548 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5549 << DeclSpec::getSpecifierName(S: TSCS);
5550 if (DS.getTypeQualifiers()) {
5551 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5552 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5553 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5554 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5555 // Restrict is covered above.
5556 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5557 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5558 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5559 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5560 }
5561
5562 // Warn about ignored type attributes, for example:
5563 // __attribute__((aligned)) struct A;
5564 // Attributes should be placed after tag to apply to type declaration.
5565 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5566 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5567 if (TypeSpecType == DeclSpec::TST_class ||
5568 TypeSpecType == DeclSpec::TST_struct ||
5569 TypeSpecType == DeclSpec::TST_interface ||
5570 TypeSpecType == DeclSpec::TST_union ||
5571 TypeSpecType == DeclSpec::TST_enum) {
5572
5573 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5574 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5575 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5576 DiagnosticId = diag::warn_attribute_ignored;
5577 else if (AL.isRegularKeywordAttribute())
5578 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5579 else
5580 DiagnosticId = diag::warn_declspec_attribute_ignored;
5581 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5582 << AL << GetDiagnosticTypeSpecifierID(DS);
5583 };
5584
5585 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5586 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5587 }
5588 }
5589
5590 return TagD;
5591}
5592
5593/// We are trying to inject an anonymous member into the given scope;
5594/// check if there's an existing declaration that can't be overloaded.
5595///
5596/// \return true if this is a forbidden redeclaration
5597static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5598 DeclContext *Owner,
5599 DeclarationName Name,
5600 SourceLocation NameLoc, bool IsUnion,
5601 StorageClass SC) {
5602 LookupResult R(SemaRef, Name, NameLoc,
5603 Owner->isRecord() ? Sema::LookupMemberName
5604 : Sema::LookupOrdinaryName,
5605 RedeclarationKind::ForVisibleRedeclaration);
5606 if (!SemaRef.LookupName(R, S)) return false;
5607
5608 // Pick a representative declaration.
5609 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5610 assert(PrevDecl && "Expected a non-null Decl");
5611
5612 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5613 return false;
5614
5615 if (SC == StorageClass::SC_None &&
5616 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5617 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5618 if (!Owner->isRecord())
5619 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5620 return false;
5621 }
5622
5623 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5624 << IsUnion << Name;
5625 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5626
5627 return true;
5628}
5629
5630void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5631 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5632 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5633}
5634
5635void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5636 if (!getLangOpts().CPlusPlus)
5637 return;
5638
5639 // This function can be parsed before we have validated the
5640 // structure as an anonymous struct
5641 if (Record->isAnonymousStructOrUnion())
5642 return;
5643
5644 const NamedDecl *First = 0;
5645 for (const Decl *D : Record->decls()) {
5646 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5647 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5648 continue;
5649 if (!First)
5650 First = ND;
5651 else
5652 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5653 }
5654}
5655
5656/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5657/// anonymous struct or union AnonRecord into the owning context Owner
5658/// and scope S. This routine will be invoked just after we realize
5659/// that an unnamed union or struct is actually an anonymous union or
5660/// struct, e.g.,
5661///
5662/// @code
5663/// union {
5664/// int i;
5665/// float f;
5666/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5667/// // f into the surrounding scope.x
5668/// @endcode
5669///
5670/// This routine is recursive, injecting the names of nested anonymous
5671/// structs/unions into the owning context and scope as well.
5672static bool
5673InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5674 RecordDecl *AnonRecord, AccessSpecifier AS,
5675 StorageClass SC,
5676 SmallVectorImpl<NamedDecl *> &Chaining) {
5677 bool Invalid = false;
5678
5679 // Look every FieldDecl and IndirectFieldDecl with a name.
5680 for (auto *D : AnonRecord->decls()) {
5681 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5682 cast<NamedDecl>(Val: D)->getDeclName()) {
5683 ValueDecl *VD = cast<ValueDecl>(Val: D);
5684 // C++ [class.union]p2:
5685 // The names of the members of an anonymous union shall be
5686 // distinct from the names of any other entity in the
5687 // scope in which the anonymous union is declared.
5688
5689 bool FieldInvalid = CheckAnonMemberRedeclaration(
5690 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5691 IsUnion: AnonRecord->isUnion(), SC);
5692 if (FieldInvalid)
5693 Invalid = true;
5694
5695 // Inject the IndirectFieldDecl even if invalid, because later
5696 // diagnostics may depend on it being present, see findDefaultInitializer.
5697
5698 // C++ [class.union]p2:
5699 // For the purpose of name lookup, after the anonymous union
5700 // definition, the members of the anonymous union are
5701 // considered to have been defined in the scope in which the
5702 // anonymous union is declared.
5703 unsigned OldChainingSize = Chaining.size();
5704 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5705 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5706 else
5707 Chaining.push_back(Elt: VD);
5708
5709 assert(Chaining.size() >= 2);
5710 NamedDecl **NamedChain =
5711 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5712 for (unsigned i = 0; i < Chaining.size(); i++)
5713 NamedChain[i] = Chaining[i];
5714
5715 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5716 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5717 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5718
5719 for (const auto *Attr : VD->attrs())
5720 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5721
5722 IndirectField->setAccess(AS);
5723 IndirectField->setImplicit();
5724 IndirectField->setInvalidDecl(FieldInvalid);
5725 SemaRef.PushOnScopeChains(D: IndirectField, S);
5726
5727 // That includes picking up the appropriate access specifier.
5728 if (AS != AS_none)
5729 IndirectField->setAccess(AS);
5730
5731 Chaining.resize(N: OldChainingSize);
5732 }
5733 }
5734
5735 return Invalid;
5736}
5737
5738/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5739/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5740/// illegal input values are mapped to SC_None.
5741static StorageClass
5742StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5743 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5744 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5745 "Parser allowed 'typedef' as storage class VarDecl.");
5746 switch (StorageClassSpec) {
5747 case DeclSpec::SCS_unspecified: return SC_None;
5748 case DeclSpec::SCS_extern:
5749 if (DS.isExternInLinkageSpec())
5750 return SC_None;
5751 return SC_Extern;
5752 case DeclSpec::SCS_static: return SC_Static;
5753 case DeclSpec::SCS_auto: return SC_Auto;
5754 case DeclSpec::SCS_register: return SC_Register;
5755 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5756 // Illegal SCSs map to None: error reporting is up to the caller.
5757 case DeclSpec::SCS_mutable: // Fall through.
5758 case DeclSpec::SCS_typedef: return SC_None;
5759 }
5760 llvm_unreachable("unknown storage class specifier");
5761}
5762
5763static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5764 assert(Record->hasInClassInitializer());
5765
5766 for (const auto *I : Record->decls()) {
5767 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5768 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5769 FD = IFD->getAnonField();
5770 if (FD && FD->hasInClassInitializer())
5771 return FD->getLocation();
5772 }
5773
5774 llvm_unreachable("couldn't find in-class initializer");
5775}
5776
5777static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5778 SourceLocation DefaultInitLoc) {
5779 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5780 return;
5781
5782 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5783 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5784}
5785
5786static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5787 CXXRecordDecl *AnonUnion) {
5788 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5789 return;
5790
5791 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5792}
5793
5794Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5795 AccessSpecifier AS,
5796 RecordDecl *Record,
5797 const PrintingPolicy &Policy) {
5798 DeclContext *Owner = Record->getDeclContext();
5799
5800 // Diagnose whether this anonymous struct/union is an extension.
5801 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5802 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5803 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5804 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5805 else if (!Record->isUnion() && !getLangOpts().C11)
5806 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5807
5808 // C and C++ require different kinds of checks for anonymous
5809 // structs/unions.
5810 bool Invalid = false;
5811 if (getLangOpts().CPlusPlus) {
5812 const char *PrevSpec = nullptr;
5813 if (Record->isUnion()) {
5814 // C++ [class.union]p6:
5815 // C++17 [class.union.anon]p2:
5816 // Anonymous unions declared in a named namespace or in the
5817 // global namespace shall be declared static.
5818 unsigned DiagID;
5819 DeclContext *OwnerScope = Owner->getRedeclContext();
5820 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5821 (OwnerScope->isTranslationUnit() ||
5822 (OwnerScope->isNamespace() &&
5823 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5824 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5825 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5826
5827 // Recover by adding 'static'.
5828 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5829 PrevSpec, DiagID, Policy);
5830 }
5831 // C++ [class.union]p6:
5832 // A storage class is not allowed in a declaration of an
5833 // anonymous union in a class scope.
5834 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5835 isa<RecordDecl>(Val: Owner)) {
5836 Diag(Loc: DS.getStorageClassSpecLoc(),
5837 DiagID: diag::err_anonymous_union_with_storage_spec)
5838 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5839
5840 // Recover by removing the storage specifier.
5841 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5842 Loc: SourceLocation(),
5843 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5844 }
5845 }
5846
5847 // Ignore const/volatile/restrict qualifiers.
5848 if (DS.getTypeQualifiers()) {
5849 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5850 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5851 << Record->isUnion() << "const"
5852 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5853 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5854 Diag(Loc: DS.getVolatileSpecLoc(),
5855 DiagID: diag::ext_anonymous_struct_union_qualified)
5856 << Record->isUnion() << "volatile"
5857 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5858 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5859 Diag(Loc: DS.getRestrictSpecLoc(),
5860 DiagID: diag::ext_anonymous_struct_union_qualified)
5861 << Record->isUnion() << "restrict"
5862 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5863 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5864 Diag(Loc: DS.getAtomicSpecLoc(),
5865 DiagID: diag::ext_anonymous_struct_union_qualified)
5866 << Record->isUnion() << "_Atomic"
5867 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5868 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5869 Diag(Loc: DS.getUnalignedSpecLoc(),
5870 DiagID: diag::ext_anonymous_struct_union_qualified)
5871 << Record->isUnion() << "__unaligned"
5872 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5873
5874 DS.ClearTypeQualifiers();
5875 }
5876
5877 // C++ [class.union]p2:
5878 // The member-specification of an anonymous union shall only
5879 // define non-static data members. [Note: nested types and
5880 // functions cannot be declared within an anonymous union. ]
5881 for (auto *Mem : Record->decls()) {
5882 // Ignore invalid declarations; we already diagnosed them.
5883 if (Mem->isInvalidDecl())
5884 continue;
5885
5886 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5887 // C++ [class.union]p3:
5888 // An anonymous union shall not have private or protected
5889 // members (clause 11).
5890 assert(FD->getAccess() != AS_none);
5891 if (FD->getAccess() != AS_public) {
5892 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5893 << Record->isUnion() << (FD->getAccess() == AS_protected);
5894 Invalid = true;
5895 }
5896
5897 // C++ [class.union]p1
5898 // An object of a class with a non-trivial constructor, a non-trivial
5899 // copy constructor, a non-trivial destructor, or a non-trivial copy
5900 // assignment operator cannot be a member of a union, nor can an
5901 // array of such objects.
5902 if (CheckNontrivialField(FD))
5903 Invalid = true;
5904 } else if (Mem->isImplicit()) {
5905 // Any implicit members are fine.
5906 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5907 // This is a type that showed up in an
5908 // elaborated-type-specifier inside the anonymous struct or
5909 // union, but which actually declares a type outside of the
5910 // anonymous struct or union. It's okay.
5911 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5912 if (!MemRecord->isAnonymousStructOrUnion() &&
5913 MemRecord->getDeclName()) {
5914 // Visual C++ allows type definition in anonymous struct or union.
5915 if (getLangOpts().MicrosoftExt)
5916 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5917 << Record->isUnion();
5918 else {
5919 // This is a nested type declaration.
5920 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5921 << Record->isUnion();
5922 Invalid = true;
5923 }
5924 } else {
5925 // This is an anonymous type definition within another anonymous type.
5926 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5927 // not part of standard C++.
5928 Diag(Loc: MemRecord->getLocation(),
5929 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5930 << Record->isUnion();
5931 }
5932 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5933 // Any access specifier is fine.
5934 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5935 // In C++1z, static_assert declarations are also fine.
5936 } else {
5937 // We have something that isn't a non-static data
5938 // member. Complain about it.
5939 unsigned DK = diag::err_anonymous_record_bad_member;
5940 if (isa<TypeDecl>(Val: Mem))
5941 DK = diag::err_anonymous_record_with_type;
5942 else if (isa<FunctionDecl>(Val: Mem))
5943 DK = diag::err_anonymous_record_with_function;
5944 else if (isa<VarDecl>(Val: Mem))
5945 DK = diag::err_anonymous_record_with_static;
5946
5947 // Visual C++ allows type definition in anonymous struct or union.
5948 if (getLangOpts().MicrosoftExt &&
5949 DK == diag::err_anonymous_record_with_type)
5950 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5951 << Record->isUnion();
5952 else {
5953 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5954 Invalid = true;
5955 }
5956 }
5957 }
5958
5959 // C++11 [class.union]p8 (DR1460):
5960 // At most one variant member of a union may have a
5961 // brace-or-equal-initializer.
5962 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5963 Owner->isRecord())
5964 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5965 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5966 }
5967
5968 if (!Record->isUnion() && !Owner->isRecord()) {
5969 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5970 << getLangOpts().CPlusPlus;
5971 Invalid = true;
5972 }
5973
5974 // C++ [dcl.dcl]p3:
5975 // [If there are no declarators], and except for the declaration of an
5976 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5977 // names into the program
5978 // C++ [class.mem]p2:
5979 // each such member-declaration shall either declare at least one member
5980 // name of the class or declare at least one unnamed bit-field
5981 //
5982 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5983 if (getLangOpts().CPlusPlus && Record->field_empty())
5984 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5985
5986 // Mock up a declarator.
5987 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5988 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5989 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5990 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5991
5992 // Create a declaration for this anonymous struct/union.
5993 NamedDecl *Anon = nullptr;
5994 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5995 Anon = FieldDecl::Create(
5996 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5997 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5998 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5999 /*InitStyle=*/ICIS_NoInit);
6000 Anon->setAccess(AS);
6001 ProcessDeclAttributes(S, D: Anon, PD: Dc);
6002
6003 if (getLangOpts().CPlusPlus)
6004 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
6005 } else {
6006 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
6007 if (SCSpec == DeclSpec::SCS_mutable) {
6008 // mutable can only appear on non-static class members, so it's always
6009 // an error here
6010 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
6011 Invalid = true;
6012 SC = SC_None;
6013 }
6014
6015 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
6016 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
6017 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
6018 if (Invalid)
6019 Anon->setInvalidDecl();
6020
6021 ProcessDeclAttributes(S, D: Anon, PD: Dc);
6022
6023 // Default-initialize the implicit variable. This initialization will be
6024 // trivial in almost all cases, except if a union member has an in-class
6025 // initializer:
6026 // union { int n = 0; };
6027 ActOnUninitializedDecl(dcl: Anon);
6028 }
6029 Anon->setImplicit();
6030
6031 // Mark this as an anonymous struct/union type.
6032 Record->setAnonymousStructOrUnion(true);
6033
6034 // Add the anonymous struct/union object to the current
6035 // context. We'll be referencing this object when we refer to one of
6036 // its members.
6037 Owner->addDecl(D: Anon);
6038
6039 // Inject the members of the anonymous struct/union into the owning
6040 // context and into the identifier resolver chain for name lookup
6041 // purposes.
6042 SmallVector<NamedDecl*, 2> Chain;
6043 Chain.push_back(Elt: Anon);
6044
6045 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
6046 Chaining&: Chain))
6047 Invalid = true;
6048
6049 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
6050 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6051 MangleNumberingContext *MCtx;
6052 Decl *ManglingContextDecl;
6053 std::tie(args&: MCtx, args&: ManglingContextDecl) =
6054 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
6055 if (MCtx) {
6056 Context.setManglingNumber(
6057 ND: NewVD, Number: MCtx->getManglingNumber(
6058 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
6059 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
6060 }
6061 }
6062 }
6063
6064 if (Invalid)
6065 Anon->setInvalidDecl();
6066
6067 return Anon;
6068}
6069
6070Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
6071 RecordDecl *Record) {
6072 assert(Record && "expected a record!");
6073
6074 // Mock up a declarator.
6075 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6076 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6077 assert(TInfo && "couldn't build declarator info for anonymous struct");
6078
6079 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6080 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6081
6082 // Create a declaration for this anonymous struct.
6083 NamedDecl *Anon =
6084 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6085 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6086 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6087 /*InitStyle=*/ICIS_NoInit);
6088 Anon->setImplicit();
6089
6090 // Add the anonymous struct object to the current context.
6091 CurContext->addDecl(D: Anon);
6092
6093 // Inject the members of the anonymous struct into the current
6094 // context and into the identifier resolver chain for name lookup
6095 // purposes.
6096 SmallVector<NamedDecl*, 2> Chain;
6097 Chain.push_back(Elt: Anon);
6098
6099 RecordDecl *RecordDef = Record->getDefinition();
6100 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6101 DiagID: diag::err_field_incomplete_or_sizeless) ||
6102 InjectAnonymousStructOrUnionMembers(
6103 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6104 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6105 Anon->setInvalidDecl();
6106 ParentDecl->setInvalidDecl();
6107 }
6108
6109 return Anon;
6110}
6111
6112DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6113 return GetNameFromUnqualifiedId(Name: D.getName());
6114}
6115
6116DeclarationNameInfo
6117Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6118 DeclarationNameInfo NameInfo;
6119 NameInfo.setLoc(Name.StartLocation);
6120
6121 switch (Name.getKind()) {
6122
6123 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6124 case UnqualifiedIdKind::IK_Identifier:
6125 NameInfo.setName(Name.Identifier);
6126 return NameInfo;
6127
6128 case UnqualifiedIdKind::IK_DeductionGuideName: {
6129 // C++ [temp.deduct.guide]p3:
6130 // The simple-template-id shall name a class template specialization.
6131 // The template-name shall be the same identifier as the template-name
6132 // of the simple-template-id.
6133 // These together intend to imply that the template-name shall name a
6134 // class template.
6135 // FIXME: template<typename T> struct X {};
6136 // template<typename T> using Y = X<T>;
6137 // Y(int) -> Y<int>;
6138 // satisfies these rules but does not name a class template.
6139 TemplateName TN = Name.TemplateName.get().get();
6140 auto *Template = TN.getAsTemplateDecl();
6141 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6142 Diag(Loc: Name.StartLocation,
6143 DiagID: diag::err_deduction_guide_name_not_class_template)
6144 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6145 if (Template)
6146 NoteTemplateLocation(Decl: *Template);
6147 return DeclarationNameInfo();
6148 }
6149
6150 NameInfo.setName(
6151 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6152 return NameInfo;
6153 }
6154
6155 case UnqualifiedIdKind::IK_OperatorFunctionId:
6156 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6157 Op: Name.OperatorFunctionId.Operator));
6158 NameInfo.setCXXOperatorNameRange(SourceRange(
6159 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6160 return NameInfo;
6161
6162 case UnqualifiedIdKind::IK_LiteralOperatorId:
6163 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6164 II: Name.Identifier));
6165 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6166 return NameInfo;
6167
6168 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6169 TypeSourceInfo *TInfo;
6170 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6171 if (Ty.isNull())
6172 return DeclarationNameInfo();
6173 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6174 Ty: Context.getCanonicalType(T: Ty)));
6175 NameInfo.setNamedTypeInfo(TInfo);
6176 return NameInfo;
6177 }
6178
6179 case UnqualifiedIdKind::IK_ConstructorName: {
6180 TypeSourceInfo *TInfo;
6181 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6182 if (Ty.isNull())
6183 return DeclarationNameInfo();
6184 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6185 Ty: Context.getCanonicalType(T: Ty)));
6186 NameInfo.setNamedTypeInfo(TInfo);
6187 return NameInfo;
6188 }
6189
6190 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6191 // In well-formed code, we can only have a constructor
6192 // template-id that refers to the current context, so go there
6193 // to find the actual type being constructed.
6194 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6195 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6196 return DeclarationNameInfo();
6197
6198 // Determine the type of the class being constructed.
6199 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6200
6201 // FIXME: Check two things: that the template-id names the same type as
6202 // CurClassType, and that the template-id does not occur when the name
6203 // was qualified.
6204
6205 NameInfo.setName(
6206 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6207 // FIXME: should we retrieve TypeSourceInfo?
6208 NameInfo.setNamedTypeInfo(nullptr);
6209 return NameInfo;
6210 }
6211
6212 case UnqualifiedIdKind::IK_DestructorName: {
6213 TypeSourceInfo *TInfo;
6214 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6215 if (Ty.isNull())
6216 return DeclarationNameInfo();
6217 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6218 Ty: Context.getCanonicalType(T: Ty)));
6219 NameInfo.setNamedTypeInfo(TInfo);
6220 return NameInfo;
6221 }
6222
6223 case UnqualifiedIdKind::IK_TemplateId: {
6224 TemplateName TName = Name.TemplateId->Template.get();
6225 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6226 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6227 }
6228
6229 } // switch (Name.getKind())
6230
6231 llvm_unreachable("Unknown name kind");
6232}
6233
6234static QualType getCoreType(QualType Ty) {
6235 do {
6236 if (Ty->isPointerOrReferenceType())
6237 Ty = Ty->getPointeeType();
6238 else if (Ty->isArrayType())
6239 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6240 else
6241 return Ty.withoutLocalFastQualifiers();
6242 } while (true);
6243}
6244
6245/// hasSimilarParameters - Determine whether the C++ functions Declaration
6246/// and Definition have "nearly" matching parameters. This heuristic is
6247/// used to improve diagnostics in the case where an out-of-line function
6248/// definition doesn't match any declaration within the class or namespace.
6249/// Also sets Params to the list of indices to the parameters that differ
6250/// between the declaration and the definition. If hasSimilarParameters
6251/// returns true and Params is empty, then all of the parameters match.
6252static bool hasSimilarParameters(ASTContext &Context,
6253 FunctionDecl *Declaration,
6254 FunctionDecl *Definition,
6255 SmallVectorImpl<unsigned> &Params) {
6256 Params.clear();
6257 if (Declaration->param_size() != Definition->param_size())
6258 return false;
6259 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6260 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6261 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6262
6263 // The parameter types are identical
6264 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6265 continue;
6266
6267 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6268 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6269 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6270 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6271
6272 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6273 (DeclTyName && DeclTyName == DefTyName))
6274 Params.push_back(Elt: Idx);
6275 else // The two parameters aren't even close
6276 return false;
6277 }
6278
6279 return true;
6280}
6281
6282/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6283/// declarator needs to be rebuilt in the current instantiation.
6284/// Any bits of declarator which appear before the name are valid for
6285/// consideration here. That's specifically the type in the decl spec
6286/// and the base type in any member-pointer chunks.
6287static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6288 DeclarationName Name) {
6289 // The types we specifically need to rebuild are:
6290 // - typenames, typeofs, and decltypes
6291 // - types which will become injected class names
6292 // Of course, we also need to rebuild any type referencing such a
6293 // type. It's safest to just say "dependent", but we call out a
6294 // few cases here.
6295
6296 DeclSpec &DS = D.getMutableDeclSpec();
6297 switch (DS.getTypeSpecType()) {
6298 case DeclSpec::TST_typename:
6299 case DeclSpec::TST_typeofType:
6300 case DeclSpec::TST_typeof_unqualType:
6301#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6302#include "clang/Basic/BuiltinTraits.inc"
6303 case DeclSpec::TST_atomic: {
6304 // Grab the type from the parser.
6305 TypeSourceInfo *TSI = nullptr;
6306 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6307 if (T.isNull() || !T->isInstantiationDependentType()) break;
6308
6309 // Make sure there's a type source info. This isn't really much
6310 // of a waste; most dependent types should have type source info
6311 // attached already.
6312 if (!TSI)
6313 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6314
6315 // Rebuild the type in the current instantiation.
6316 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6317 if (!TSI) return true;
6318
6319 // Store the new type back in the decl spec.
6320 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6321 DS.UpdateTypeRep(Rep: LocType);
6322 break;
6323 }
6324
6325 case DeclSpec::TST_decltype:
6326 case DeclSpec::TST_typeof_unqualExpr:
6327 case DeclSpec::TST_typeofExpr: {
6328 Expr *E = DS.getRepAsExpr();
6329 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6330 if (Result.isInvalid()) return true;
6331 DS.UpdateExprRep(Rep: Result.get());
6332 break;
6333 }
6334
6335 default:
6336 // Nothing to do for these decl specs.
6337 break;
6338 }
6339
6340 // It doesn't matter what order we do this in.
6341 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6342 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6343
6344 // The only type information in the declarator which can come
6345 // before the declaration name is the base type of a member
6346 // pointer.
6347 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6348 continue;
6349
6350 // Rebuild the scope specifier in-place.
6351 CXXScopeSpec &SS = Chunk.Mem.Scope();
6352 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6353 return true;
6354 }
6355
6356 return false;
6357}
6358
6359/// Returns true if the declaration is declared in a system header or from a
6360/// system macro.
6361static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6362 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6363 SM.isInSystemMacro(loc: D->getLocation());
6364}
6365
6366void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6367 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6368 // of system decl.
6369 if (D->getPreviousDecl() || D->isImplicit())
6370 return;
6371 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6372 if (Status != ReservedIdentifierStatus::NotReserved &&
6373 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6374 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6375 << D << static_cast<int>(Status);
6376 }
6377}
6378
6379Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6380 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6381
6382 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6383 // declaration only if the `bind_to_declaration` extension is set.
6384 SmallVector<FunctionDecl *, 4> Bases;
6385 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6386 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6387 TP: llvm::omp::TraitProperty::
6388 implementation_extension_bind_to_declaration))
6389 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6390 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6391
6392 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6393
6394 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6395 Dcl && Dcl->getDeclContext()->isFileContext())
6396 Dcl->setTopLevelDeclInObjCContainer();
6397
6398 if (!Bases.empty())
6399 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6400 Bases);
6401
6402 return Dcl;
6403}
6404
6405bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6406 DeclarationNameInfo NameInfo) {
6407 DeclarationName Name = NameInfo.getName();
6408
6409 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6410 while (Record && Record->isAnonymousStructOrUnion())
6411 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6412 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6413 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6414 return true;
6415 }
6416
6417 return false;
6418}
6419
6420bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6421 DeclarationName Name,
6422 SourceLocation Loc,
6423 TemplateIdAnnotation *TemplateId,
6424 bool IsMemberSpecialization) {
6425 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6426 "without nested-name-specifier");
6427 DeclContext *Cur = CurContext;
6428 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6429 Cur = Cur->getParent();
6430
6431 // If the user provided a superfluous scope specifier that refers back to the
6432 // class in which the entity is already declared, diagnose and ignore it.
6433 //
6434 // class X {
6435 // void X::f();
6436 // };
6437 //
6438 // Note, it was once ill-formed to give redundant qualification in all
6439 // contexts, but that rule was removed by DR482.
6440 if (Cur->Equals(DC)) {
6441 if (Cur->isRecord()) {
6442 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6443 : diag::err_member_extra_qualification)
6444 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6445 SS.clear();
6446 } else {
6447 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6448 }
6449 return false;
6450 }
6451
6452 // Check whether the qualifying scope encloses the scope of the original
6453 // declaration. For a template-id, we perform the checks in
6454 // CheckTemplateSpecializationScope.
6455 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6456 Cur = Cur->getEnclosingNonExpansionStatementContext();
6457 if (Cur->isRecord())
6458 Diag(Loc, DiagID: diag::err_member_qualification)
6459 << Name << SS.getRange();
6460 else if (isa<TranslationUnitDecl>(Val: DC))
6461 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6462 << Name << SS.getRange();
6463 else if (isa<FunctionDecl>(Val: Cur))
6464 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6465 << Name << SS.getRange();
6466 else if (isa<BlockDecl>(Val: Cur))
6467 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6468 << Name << SS.getRange();
6469 else if (isa<ExportDecl>(Val: Cur)) {
6470 if (!isa<NamespaceDecl>(Val: DC))
6471 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6472 << Name << SS.getRange();
6473 else
6474 // The cases that DC is not NamespaceDecl should be handled in
6475 // CheckRedeclarationExported.
6476 return false;
6477 } else
6478 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6479 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6480
6481 return true;
6482 }
6483
6484 if (Cur->isRecord()) {
6485 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6486 // An explicit specialization may be declared in any scope in which the
6487 // corresponding primary template may be defined.
6488 if (IsMemberSpecialization)
6489 return false;
6490
6491 // Cannot qualify members within a class.
6492 Diag(Loc, DiagID: diag::err_member_qualification)
6493 << Name << SS.getRange();
6494 SS.clear();
6495
6496 // C++ constructors and destructors with incorrect scopes can break
6497 // our AST invariants by having the wrong underlying types. If
6498 // that's the case, then drop this declaration entirely.
6499 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6500 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6501 !Context.hasSameType(
6502 T1: Name.getCXXNameType(),
6503 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6504 return true;
6505
6506 return false;
6507 }
6508
6509 // C++23 [temp.names]p5:
6510 // The keyword template shall not appear immediately after a declarative
6511 // nested-name-specifier.
6512 //
6513 // First check the template-id (if any), and then check each component of the
6514 // nested-name-specifier in reverse order.
6515 //
6516 // FIXME: nested-name-specifiers in friend declarations are declarative,
6517 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6518 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6519 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6520 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6521
6522 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6523 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6524 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6525 SourceLocation TemplateKeywordLoc;
6526 switch (TL.getTypeLocClass()) {
6527 case TypeLoc::TemplateSpecialization: {
6528 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6529 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6530 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6531 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6532 << TST.getLocalSourceRange();
6533 break;
6534 }
6535 case TypeLoc::Decltype:
6536 case TypeLoc::PackIndexing: {
6537 const Type *T = TL.getTypePtr();
6538 // C++23 [expr.prim.id.qual]p2:
6539 // [...] A declarative nested-name-specifier shall not have a
6540 // computed-type-specifier.
6541 //
6542 // CWG2858 changed this from 'decltype-specifier' to
6543 // 'computed-type-specifier'.
6544 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6545 << T->isDecltypeType() << TL.getSourceRange();
6546 break;
6547 }
6548 case TypeLoc::DependentName:
6549 NextTL =
6550 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6551 break;
6552 default:
6553 break;
6554 }
6555 if (TemplateKeywordLoc.isValid())
6556 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6557 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6558 }
6559
6560 return false;
6561}
6562
6563NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6564 MultiTemplateParamsArg TemplateParamLists) {
6565 // TODO: consider using NameInfo for diagnostic.
6566 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6567 DeclarationName Name = NameInfo.getName();
6568
6569 // All of these full declarators require an identifier. If it doesn't have
6570 // one, the ParsedFreeStandingDeclSpec action should be used.
6571 if (D.isDecompositionDeclarator()) {
6572 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6573 } else if (!Name) {
6574 if (!D.isInvalidType()) // Reject this if we think it is valid.
6575 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6576 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6577 return nullptr;
6578 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6579 return nullptr;
6580
6581 DeclContext *DC = CurContext;
6582 if (D.getCXXScopeSpec().isInvalid())
6583 D.setInvalidType();
6584 else if (D.getCXXScopeSpec().isSet()) {
6585 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6586 UPPC: UPPC_DeclarationQualifier))
6587 return nullptr;
6588
6589 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6590 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6591 if (!DC || isa<EnumDecl>(Val: DC)) {
6592 // If we could not compute the declaration context, it's because the
6593 // declaration context is dependent but does not refer to a class,
6594 // class template, or class template partial specialization. Complain
6595 // and return early, to avoid the coming semantic disaster.
6596 Diag(Loc: D.getIdentifierLoc(),
6597 DiagID: diag::err_template_qualified_declarator_no_match)
6598 << D.getCXXScopeSpec().getScopeRep()
6599 << D.getCXXScopeSpec().getRange();
6600 return nullptr;
6601 }
6602 bool IsDependentContext = DC->isDependentContext();
6603
6604 if (!IsDependentContext &&
6605 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6606 return nullptr;
6607
6608 // If a class is incomplete, do not parse entities inside it.
6609 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6610 Diag(Loc: D.getIdentifierLoc(),
6611 DiagID: diag::err_member_def_undefined_record)
6612 << Name << DC << D.getCXXScopeSpec().getRange();
6613 return nullptr;
6614 }
6615 if (!D.getDeclSpec().isFriendSpecified()) {
6616 TemplateIdAnnotation *TemplateId =
6617 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6618 ? D.getName().TemplateId
6619 : nullptr;
6620 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6621 Loc: D.getIdentifierLoc(), TemplateId,
6622 /*IsMemberSpecialization=*/false)) {
6623 if (DC->isRecord())
6624 return nullptr;
6625
6626 D.setInvalidType();
6627 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6628 D.setInvalidType();
6629 }
6630 }
6631
6632 // Check whether we need to rebuild the type of the given
6633 // declaration in the current instantiation.
6634 if (EnteringContext && IsDependentContext &&
6635 TemplateParamLists.size() != 0) {
6636 ContextRAII SavedContext(*this, DC);
6637 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6638 D.setInvalidType();
6639 }
6640 }
6641
6642 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6643 QualType R = TInfo->getType();
6644
6645 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6646 UPPC: UPPC_DeclarationType))
6647 D.setInvalidType();
6648
6649 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6650 forRedeclarationInCurContext());
6651
6652 // See if this is a redefinition of a variable in the same scope.
6653 if (!D.getCXXScopeSpec().isSet()) {
6654 bool IsLinkageLookup = false;
6655 bool CreateBuiltins = false;
6656
6657 // If the declaration we're planning to build will be a function
6658 // or object with linkage, then look for another declaration with
6659 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6660 //
6661 // If the declaration we're planning to build will be declared with
6662 // external linkage in the translation unit, create any builtin with
6663 // the same name.
6664 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6665 /* Do nothing*/;
6666 else if (CurContext->isFunctionOrMethod() &&
6667 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6668 R->isFunctionType())) {
6669 IsLinkageLookup = true;
6670 CreateBuiltins =
6671 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6672 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6673 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6674 CreateBuiltins = true;
6675
6676 if (IsLinkageLookup) {
6677 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6678 Previous.setRedeclarationKind(
6679 RedeclarationKind::ForExternalRedeclaration);
6680 }
6681
6682 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6683 } else { // Something like "int foo::x;"
6684 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6685
6686 // C++ [dcl.meaning]p1:
6687 // When the declarator-id is qualified, the declaration shall refer to a
6688 // previously declared member of the class or namespace to which the
6689 // qualifier refers (or, in the case of a namespace, of an element of the
6690 // inline namespace set of that namespace (7.3.1)) or to a specialization
6691 // thereof; [...]
6692 //
6693 // Note that we already checked the context above, and that we do not have
6694 // enough information to make sure that Previous contains the declaration
6695 // we want to match. For example, given:
6696 //
6697 // class X {
6698 // void f();
6699 // void f(float);
6700 // };
6701 //
6702 // void X::f(int) { } // ill-formed
6703 //
6704 // In this case, Previous will point to the overload set
6705 // containing the two f's declared in X, but neither of them
6706 // matches.
6707
6708 RemoveUsingDecls(R&: Previous);
6709 }
6710
6711 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6712 TPD && TPD->isTemplateParameter()) {
6713 // Older versions of clang allowed the names of function/variable templates
6714 // to shadow the names of their template parameters. For the compatibility
6715 // purposes we detect such cases and issue a default-to-error warning that
6716 // can be disabled with -Wno-strict-primary-template-shadow.
6717 if (!D.isInvalidType()) {
6718 bool AllowForCompatibility = false;
6719 if (Scope *DeclParent = S->getDeclParent();
6720 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6721 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6722 TemplateParamParent->isDeclScope(D: TPD);
6723 }
6724 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6725 SupportedForCompatibility: AllowForCompatibility);
6726 }
6727
6728 // Just pretend that we didn't see the previous declaration.
6729 Previous.clear();
6730 }
6731
6732 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6733 // Forget that the previous declaration is the injected-class-name.
6734 Previous.clear();
6735
6736 // In C++, the previous declaration we find might be a tag type
6737 // (class or enum). In this case, the new declaration will hide the
6738 // tag type. Note that this applies to functions, function templates, and
6739 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6740 if (Previous.isSingleTagDecl() &&
6741 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6742 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6743 Previous.clear();
6744
6745 // Check that there are no default arguments other than in the parameters
6746 // of a function declaration (C++ only).
6747 if (getLangOpts().CPlusPlus)
6748 CheckExtraCXXDefaultArguments(D);
6749
6750 /// Get the innermost enclosing declaration scope.
6751 S = S->getDeclParent();
6752
6753 NamedDecl *New;
6754
6755 bool AddToScope = true;
6756 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6757 if (TemplateParamLists.size()) {
6758 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6759 return nullptr;
6760 }
6761
6762 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6763 } else if (R->isFunctionType()) {
6764 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6765 TemplateParamLists,
6766 AddToScope);
6767 } else {
6768 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6769 AddToScope);
6770 }
6771
6772 if (!New)
6773 return nullptr;
6774
6775 warnOnCTypeHiddenInCPlusPlus(D: New);
6776
6777 // If this has an identifier and is not a function template specialization,
6778 // add it to the scope stack.
6779 if (New->getDeclName() && AddToScope)
6780 PushOnScopeChains(D: New, S);
6781
6782 if (OpenMP().isInOpenMPDeclareTargetContext())
6783 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6784
6785 return New;
6786}
6787
6788/// Helper method to turn variable array types into constant array
6789/// types in certain situations which would otherwise be errors (for
6790/// GCC compatibility).
6791static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6792 ASTContext &Context,
6793 bool &SizeIsNegative,
6794 llvm::APSInt &Oversized) {
6795 // This method tries to turn a variable array into a constant
6796 // array even when the size isn't an ICE. This is necessary
6797 // for compatibility with code that depends on gcc's buggy
6798 // constant expression folding, like struct {char x[(int)(char*)2];}
6799 SizeIsNegative = false;
6800 Oversized = 0;
6801
6802 if (T->isDependentType())
6803 return QualType();
6804
6805 QualifierCollector Qs;
6806 const Type *Ty = Qs.strip(type: T);
6807
6808 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6809 QualType Pointee = PTy->getPointeeType();
6810 QualType FixedType =
6811 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6812 Oversized);
6813 if (FixedType.isNull()) return FixedType;
6814 FixedType = Context.getPointerType(T: FixedType);
6815 return Qs.apply(Context, QT: FixedType);
6816 }
6817 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6818 QualType Inner = PTy->getInnerType();
6819 QualType FixedType =
6820 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6821 Oversized);
6822 if (FixedType.isNull()) return FixedType;
6823 FixedType = Context.getParenType(NamedType: FixedType);
6824 return Qs.apply(Context, QT: FixedType);
6825 }
6826
6827 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6828 if (!VLATy)
6829 return QualType();
6830
6831 QualType ElemTy = VLATy->getElementType();
6832 if (ElemTy->isVariablyModifiedType()) {
6833 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6834 SizeIsNegative, Oversized);
6835 if (ElemTy.isNull())
6836 return QualType();
6837 }
6838
6839 Expr::EvalResult Result;
6840 if (!VLATy->getSizeExpr() ||
6841 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6842 return QualType();
6843
6844 llvm::APSInt Res = Result.Val.getInt();
6845
6846 // Check whether the array size is negative.
6847 if (Res.isSigned() && Res.isNegative()) {
6848 SizeIsNegative = true;
6849 return QualType();
6850 }
6851
6852 // Check whether the array is too large to be addressed.
6853 unsigned ActiveSizeBits =
6854 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6855 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6856 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6857 : Res.getActiveBits();
6858 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6859 Oversized = std::move(Res);
6860 return QualType();
6861 }
6862
6863 QualType FoldedArrayType = Context.getConstantArrayType(
6864 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6865 return Qs.apply(Context, QT: FoldedArrayType);
6866}
6867
6868static void
6869FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6870 SrcTL = SrcTL.getUnqualifiedLoc();
6871 DstTL = DstTL.getUnqualifiedLoc();
6872 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6873 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6874 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6875 DstTL: DstPTL.getPointeeLoc());
6876 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6877 return;
6878 }
6879 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6880 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6881 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6882 DstTL: DstPTL.getInnerLoc());
6883 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6884 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6885 return;
6886 }
6887 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6888 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6889 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6890 TypeLoc DstElemTL = DstATL.getElementLoc();
6891 if (VariableArrayTypeLoc SrcElemATL =
6892 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6893 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6894 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6895 } else {
6896 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6897 }
6898 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6899 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6900 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6901}
6902
6903/// Helper method to turn variable array types into constant array
6904/// types in certain situations which would otherwise be errors (for
6905/// GCC compatibility).
6906static TypeSourceInfo*
6907TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6908 ASTContext &Context,
6909 bool &SizeIsNegative,
6910 llvm::APSInt &Oversized) {
6911 QualType FixedTy
6912 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6913 SizeIsNegative, Oversized);
6914 if (FixedTy.isNull())
6915 return nullptr;
6916 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6917 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6918 DstTL: FixedTInfo->getTypeLoc());
6919 return FixedTInfo;
6920}
6921
6922bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6923 QualType &T, SourceLocation Loc,
6924 unsigned FailedFoldDiagID) {
6925 bool SizeIsNegative;
6926 llvm::APSInt Oversized;
6927 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6928 TInfo, Context, SizeIsNegative, Oversized);
6929 if (FixedTInfo) {
6930 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6931 TInfo = FixedTInfo;
6932 T = FixedTInfo->getType();
6933 return true;
6934 }
6935
6936 if (SizeIsNegative)
6937 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6938 else if (Oversized.getBoolValue())
6939 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6940 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6941 /*UpperCase=*/false, /*InsertSeparators=*/true);
6942 else if (FailedFoldDiagID)
6943 Diag(Loc, DiagID: FailedFoldDiagID);
6944 return false;
6945}
6946
6947void
6948Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6949 if (!getLangOpts().CPlusPlus &&
6950 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6951 // Don't need to track declarations in the TU in C.
6952 return;
6953
6954 // Note that we have a locally-scoped external with this name.
6955 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6956}
6957
6958NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6959 // FIXME: We can have multiple results via __attribute__((overloadable)).
6960 auto Result = Context.getExternCContextDecl()->lookup(Name);
6961 return Result.empty() ? nullptr : *Result.begin();
6962}
6963
6964void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6965 // FIXME: We should probably indicate the identifier in question to avoid
6966 // confusion for constructs like "virtual int a(), b;"
6967 if (DS.isVirtualSpecified())
6968 Diag(Loc: DS.getVirtualSpecLoc(),
6969 DiagID: diag::err_virtual_non_function);
6970
6971 if (DS.hasExplicitSpecifier())
6972 Diag(Loc: DS.getExplicitSpecLoc(),
6973 DiagID: diag::err_explicit_non_function);
6974
6975 if (DS.isNoreturnSpecified())
6976 Diag(Loc: DS.getNoreturnSpecLoc(),
6977 DiagID: diag::err_noreturn_non_function);
6978}
6979
6980NamedDecl*
6981Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6982 TypeSourceInfo *TInfo, LookupResult &Previous) {
6983 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6984 if (D.getCXXScopeSpec().isSet()) {
6985 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6986 << D.getCXXScopeSpec().getRange();
6987 D.setInvalidType();
6988 // Pretend we didn't see the scope specifier.
6989 DC = CurContext;
6990 Previous.clear();
6991 }
6992
6993 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6994
6995 if (D.getDeclSpec().isInlineSpecified())
6996 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6997 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6998 ? diag::warn_ms_inline_non_function
6999 : diag::err_inline_non_function)
7000 << getLangOpts().CPlusPlus17;
7001 if (D.getDeclSpec().hasConstexprSpecifier())
7002 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
7003 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7004
7005 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
7006 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
7007 Diag(Loc: D.getName().StartLocation,
7008 DiagID: diag::err_deduction_guide_invalid_specifier)
7009 << "typedef";
7010 else
7011 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
7012 << D.getName().getSourceRange();
7013 return nullptr;
7014 }
7015
7016 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
7017 if (!NewTD) return nullptr;
7018
7019 // Handle attributes prior to checking for duplicates in MergeVarDecl
7020 ProcessDeclAttributes(S, D: NewTD, PD: D);
7021
7022 CheckTypedefForVariablyModifiedType(S, D: NewTD);
7023
7024 bool Redeclaration = D.isRedeclaration();
7025 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
7026 D.setRedeclaration(Redeclaration);
7027 return ND;
7028}
7029
7030void
7031Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
7032 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7033 // then it shall have block scope.
7034 // Note that variably modified types must be fixed before merging the decl so
7035 // that redeclarations will match.
7036 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7037 QualType T = TInfo->getType();
7038
7039 if (!CheckVariablyModifiedTypeUse(T, Loc: TInfo->getTypeLoc().getBeginLoc())) {
7040 NewTD->setInvalidDecl();
7041 return;
7042 }
7043
7044 if (T->isVariablyModifiedType()) {
7045 setFunctionHasBranchProtectedScope();
7046
7047 if (S->getFnParent() == nullptr) {
7048 bool SizeIsNegative;
7049 llvm::APSInt Oversized;
7050 TypeSourceInfo *FixedTInfo =
7051 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7052 SizeIsNegative,
7053 Oversized);
7054 if (FixedTInfo) {
7055 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
7056 NewTD->setTypeSourceInfo(FixedTInfo);
7057 } else {
7058 if (SizeIsNegative)
7059 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
7060 else if (T->isVariableArrayType())
7061 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
7062 else if (Oversized.getBoolValue())
7063 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
7064 << toString(I: Oversized, Radix: 10);
7065 else
7066 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
7067 NewTD->setInvalidDecl();
7068 }
7069 }
7070 }
7071}
7072
7073NamedDecl*
7074Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
7075 LookupResult &Previous, bool &Redeclaration) {
7076
7077 // Find the shadowed declaration before filtering for scope.
7078 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
7079
7080 // Merge the decl with the existing one if appropriate. If the decl is
7081 // in an outer scope, it isn't the same thing.
7082 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
7083 /*AllowInlineNamespace*/false);
7084 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
7085 if (!Previous.empty()) {
7086 Redeclaration = true;
7087 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
7088 } else {
7089 inferGslPointerAttribute(TD: NewTD);
7090 }
7091
7092 if (ShadowedDecl && !Redeclaration)
7093 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7094
7095 // If this is the C FILE type, notify the AST context.
7096 if (IdentifierInfo *II = NewTD->getIdentifier())
7097 if (!NewTD->isInvalidDecl() &&
7098 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7099 switch (II->getNotableIdentifierID()) {
7100 case tok::NotableIdentifierKind::FILE:
7101 Context.setFILEDecl(NewTD);
7102 break;
7103 case tok::NotableIdentifierKind::jmp_buf:
7104 Context.setjmp_bufDecl(NewTD);
7105 break;
7106 case tok::NotableIdentifierKind::sigjmp_buf:
7107 Context.setsigjmp_bufDecl(NewTD);
7108 break;
7109 case tok::NotableIdentifierKind::ucontext_t:
7110 Context.setucontext_tDecl(NewTD);
7111 break;
7112 case tok::NotableIdentifierKind::float_t:
7113 case tok::NotableIdentifierKind::double_t:
7114 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7115 break;
7116 default:
7117 break;
7118 }
7119 }
7120
7121 return NewTD;
7122}
7123
7124/// Determines whether the given declaration is an out-of-scope
7125/// previous declaration.
7126///
7127/// This routine should be invoked when name lookup has found a
7128/// previous declaration (PrevDecl) that is not in the scope where a
7129/// new declaration by the same name is being introduced. If the new
7130/// declaration occurs in a local scope, previous declarations with
7131/// linkage may still be considered previous declarations (C99
7132/// 6.2.2p4-5, C++ [basic.link]p6).
7133///
7134/// \param PrevDecl the previous declaration found by name
7135/// lookup
7136///
7137/// \param DC the context in which the new declaration is being
7138/// declared.
7139///
7140/// \returns true if PrevDecl is an out-of-scope previous declaration
7141/// for a new delcaration with the same name.
7142static bool
7143isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7144 ASTContext &Context) {
7145 if (!PrevDecl)
7146 return false;
7147
7148 if (!PrevDecl->hasLinkage())
7149 return false;
7150
7151 if (Context.getLangOpts().CPlusPlus) {
7152 // C++ [basic.link]p6:
7153 // If there is a visible declaration of an entity with linkage
7154 // having the same name and type, ignoring entities declared
7155 // outside the innermost enclosing namespace scope, the block
7156 // scope declaration declares that same entity and receives the
7157 // linkage of the previous declaration.
7158 DeclContext *OuterContext = DC->getRedeclContext();
7159 if (!OuterContext->isFunctionOrMethod())
7160 // This rule only applies to block-scope declarations.
7161 return false;
7162
7163 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7164 if (PrevOuterContext->isRecord())
7165 // We found a member function: ignore it.
7166 return false;
7167
7168 // Find the innermost enclosing namespace for the new and
7169 // previous declarations.
7170 OuterContext = OuterContext->getEnclosingNamespaceContext();
7171 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7172
7173 // The previous declaration is in a different namespace, so it
7174 // isn't the same function.
7175 if (!OuterContext->Equals(DC: PrevOuterContext))
7176 return false;
7177 }
7178
7179 return true;
7180}
7181
7182static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7183 CXXScopeSpec &SS = D.getCXXScopeSpec();
7184 if (!SS.isSet()) return;
7185 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7186}
7187
7188void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7189 LangAS ImplAS = LangAS::opencl_private;
7190 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7191 // __opencl_c_program_scope_global_variables feature, the address space
7192 // for a variable at program scope or a static or extern variable inside
7193 // a function are inferred to be __global.
7194 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7195 Var->hasGlobalStorage())
7196 ImplAS = LangAS::opencl_global;
7197 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7198}
7199
7200static bool checkWeakAttrCompatibility(Sema &S, const NamedDecl &ND,
7201 const WeakAttr &Attr) {
7202 const NamedDecl *D = &ND;
7203 // IFuncAttr is not inherited, so a redeclaration may need to check the
7204 // attributes on the definition instead.
7205 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND))
7206 if (const FunctionDecl *Def = FD->getDefinition())
7207 D = Def;
7208 return DiagnoseMutualExclusions(S, D, A: &Attr);
7209}
7210
7211static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7212 // 'weak' only applies to declarations with external linkage.
7213 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7214 if (!ND.isExternallyVisible()) {
7215 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7216 ND.dropAttr<WeakAttr>();
7217 } else if (!checkWeakAttrCompatibility(S, ND, Attr: *Attr)) {
7218 // A forward #pragma weak adds the attribute without checking mutual
7219 // exclusions during attribute processing.
7220 ND.dropAttr<WeakAttr>();
7221 }
7222 }
7223}
7224
7225static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7226 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7227 if (ND.isExternallyVisible()) {
7228 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7229 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7230 }
7231 }
7232}
7233
7234static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7235 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7236 if (VD->hasInit()) {
7237 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7238 assert(VD->isThisDeclarationADefinition() &&
7239 "Broken AliasAttr handled late!");
7240 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7241 VD->dropAttr<AliasAttr>();
7242 }
7243 }
7244 }
7245}
7246
7247static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7248 // 'selectany' only applies to externally visible variable declarations.
7249 // It does not apply to functions.
7250 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7251 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7252 S.Diag(Loc: Attr->getLocation(),
7253 DiagID: diag::err_attribute_selectany_non_extern_data);
7254 ND.dropAttr<SelectAnyAttr>();
7255 }
7256 }
7257}
7258
7259static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7260 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7261 if (!ND.isExternallyVisible())
7262 S.Diag(Loc: Attr->getLocation(),
7263 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7264 }
7265}
7266
7267static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7268 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7269 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7270 bool IsAnonymousNS = false;
7271 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7272 if (VD) {
7273 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7274 while (NS && !IsAnonymousNS) {
7275 IsAnonymousNS = NS->isAnonymousNamespace();
7276 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7277 }
7278 }
7279 // dll attributes require external linkage. Static locals may have external
7280 // linkage but still cannot be explicitly imported or exported.
7281 // In Microsoft mode, a variable defined in anonymous namespace must have
7282 // external linkage in order to be exported.
7283 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7284 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7285 (!AnonNSInMicrosoftMode &&
7286 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7287 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7288 << &ND << Attr;
7289 ND.setInvalidDecl();
7290 }
7291 }
7292}
7293
7294static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7295 // Check the attributes on the function type and function params, if any.
7296 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7297 FD = FD->getMostRecentDecl();
7298 // Don't declare this variable in the second operand of the for-statement;
7299 // GCC miscompiles that by ending its lifetime before evaluating the
7300 // third operand. See gcc.gnu.org/PR86769.
7301 AttributedTypeLoc ATL;
7302 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7303 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7304 TL = ATL.getModifiedLoc()) {
7305 // The [[lifetimebound]] attribute can be applied to the implicit object
7306 // parameter of a non-static member function (other than a ctor or dtor)
7307 // by applying it to the function type.
7308 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7309 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7310 int NoImplicitObjectError = -1;
7311 if (!MD)
7312 NoImplicitObjectError = 0;
7313 else if (MD->isStatic())
7314 NoImplicitObjectError = 1;
7315 else if (MD->isExplicitObjectMemberFunction())
7316 NoImplicitObjectError = 2;
7317 if (NoImplicitObjectError != -1) {
7318 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7319 << NoImplicitObjectError << A->getRange();
7320 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7321 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7322 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7323 } else if (MD->getReturnType()->isVoidType()) {
7324 S.Diag(
7325 Loc: MD->getLocation(),
7326 DiagID: diag::
7327 err_lifetimebound_implicit_object_parameter_void_return_type);
7328 }
7329 }
7330 }
7331
7332 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7333 const ParmVarDecl *P = FD->getParamDecl(i: I);
7334
7335 // The [[lifetimebound]] attribute can be applied to a function parameter
7336 // only if the function returns a value.
7337 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7338 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7339 S.Diag(Loc: A->getLocation(),
7340 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7341 }
7342 }
7343 }
7344 }
7345}
7346
7347static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7348 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7349 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7350}
7351
7352static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7353 // Ensure that an auto decl is deduced otherwise the checks below might cache
7354 // the wrong linkage.
7355 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7356
7357 checkWeakAttr(S, ND);
7358 checkWeakRefAttr(S, ND);
7359 checkAliasAttr(S, ND);
7360 checkSelectAnyAttr(S, ND);
7361 checkHybridPatchableAttr(S, ND);
7362 checkInheritableAttr(S, ND);
7363 checkLifetimeBoundAttr(S, ND);
7364}
7365
7366static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7367 NamedDecl *NewDecl,
7368 bool IsSpecialization,
7369 bool IsDefinition) {
7370 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7371 return;
7372
7373 bool IsTemplate = false;
7374 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7375 OldDecl = OldTD->getTemplatedDecl();
7376 IsTemplate = true;
7377 if (!IsSpecialization)
7378 IsDefinition = false;
7379 }
7380 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7381 NewDecl = NewTD->getTemplatedDecl();
7382 IsTemplate = true;
7383 }
7384
7385 if (!OldDecl || !NewDecl)
7386 return;
7387
7388 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7389 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7390 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7391 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7392
7393 // dllimport and dllexport are inheritable attributes so we have to exclude
7394 // inherited attribute instances.
7395 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7396 (NewExportAttr && !NewExportAttr->isInherited());
7397
7398 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7399 // the only exception being explicit specializations.
7400 // Implicitly generated declarations are also excluded for now because there
7401 // is no other way to switch these to use dllimport or dllexport.
7402 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7403
7404 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7405 // Allow with a warning for free functions and global variables.
7406 bool JustWarn = false;
7407 if (!OldDecl->isCXXClassMember()) {
7408 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7409 if (VD && !VD->getDescribedVarTemplate())
7410 JustWarn = true;
7411 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7412 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7413 JustWarn = true;
7414 }
7415
7416 // We cannot change a declaration that's been used because IR has already
7417 // been emitted. Dllimported functions will still work though (modulo
7418 // address equality) as they can use the thunk.
7419 if (OldDecl->isUsed())
7420 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7421 JustWarn = false;
7422
7423 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7424 : diag::err_attribute_dll_redeclaration;
7425 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7426 << NewDecl
7427 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7428 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7429 if (!JustWarn) {
7430 NewDecl->setInvalidDecl();
7431 return;
7432 }
7433 }
7434
7435 // A redeclaration is not allowed to drop a dllimport attribute, the only
7436 // exceptions being inline function definitions (except for function
7437 // templates), local extern declarations, qualified friend declarations or
7438 // special MSVC extension: in the last case, the declaration is treated as if
7439 // it were marked dllexport.
7440 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7441 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7442 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7443 // Ignore static data because out-of-line definitions are diagnosed
7444 // separately.
7445 IsStaticDataMember = VD->isStaticDataMember();
7446 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7447 VarDecl::DeclarationOnly;
7448 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7449 IsInline = FD->isInlined();
7450 IsQualifiedFriend = FD->getQualifier() &&
7451 FD->getFriendObjectKind() == Decl::FOK_Declared;
7452 }
7453
7454 if (OldImportAttr && !HasNewAttr &&
7455 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7456 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7457 if (IsMicrosoftABI && IsDefinition) {
7458 if (IsSpecialization) {
7459 S.Diag(
7460 Loc: NewDecl->getLocation(),
7461 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7462 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7463 NewDecl->dropAttr<DLLImportAttr>();
7464 } else {
7465 S.Diag(Loc: NewDecl->getLocation(),
7466 DiagID: diag::warn_redeclaration_without_import_attribute)
7467 << NewDecl;
7468 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7469 NewDecl->dropAttr<DLLImportAttr>();
7470 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7471 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7472 }
7473 } else if (IsMicrosoftABI && IsSpecialization) {
7474 assert(!IsDefinition);
7475 // MSVC allows this. Keep the inherited attribute.
7476 } else {
7477 S.Diag(Loc: NewDecl->getLocation(),
7478 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7479 << NewDecl << OldImportAttr;
7480 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7481 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7482 OldDecl->dropAttr<DLLImportAttr>();
7483 NewDecl->dropAttr<DLLImportAttr>();
7484 }
7485 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7486 // In MinGW, seeing a function declared inline drops the dllimport
7487 // attribute.
7488 OldDecl->dropAttr<DLLImportAttr>();
7489 NewDecl->dropAttr<DLLImportAttr>();
7490 S.Diag(Loc: NewDecl->getLocation(),
7491 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7492 << NewDecl << OldImportAttr;
7493 }
7494
7495 // A specialization of a class template member function is processed here
7496 // since it's a redeclaration. If the parent class is dllexport, the
7497 // specialization inherits that attribute. This doesn't happen automatically
7498 // since the parent class isn't instantiated until later.
7499 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7500 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7501 !NewImportAttr && !NewExportAttr) {
7502 if (const DLLExportAttr *ParentExportAttr =
7503 MD->getParent()->getAttr<DLLExportAttr>()) {
7504 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7505 NewAttr->setInherited(true);
7506 NewDecl->addAttr(A: NewAttr);
7507 }
7508 }
7509 }
7510}
7511
7512/// Given that we are within the definition of the given function,
7513/// will that definition behave like C99's 'inline', where the
7514/// definition is discarded except for optimization purposes?
7515static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7516 // Try to avoid calling GetGVALinkageForFunction.
7517
7518 // All cases of this require the 'inline' keyword.
7519 if (!FD->isInlined()) return false;
7520
7521 // This is only possible in C++ with the gnu_inline attribute.
7522 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7523 return false;
7524
7525 // Okay, go ahead and call the relatively-more-expensive function.
7526 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7527}
7528
7529/// Determine whether a variable is extern "C" prior to attaching
7530/// an initializer. We can't just call isExternC() here, because that
7531/// will also compute and cache whether the declaration is externally
7532/// visible, which might change when we attach the initializer.
7533///
7534/// This can only be used if the declaration is known to not be a
7535/// redeclaration of an internal linkage declaration.
7536///
7537/// For instance:
7538///
7539/// auto x = []{};
7540///
7541/// Attaching the initializer here makes this declaration not externally
7542/// visible, because its type has internal linkage.
7543///
7544/// FIXME: This is a hack.
7545template<typename T>
7546static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7547 if (S.getLangOpts().CPlusPlus) {
7548 // In C++, the overloadable attribute negates the effects of extern "C".
7549 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7550 return false;
7551
7552 // So do CUDA's host/device attributes.
7553 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7554 D->template hasAttr<CUDAHostAttr>()))
7555 return false;
7556 }
7557 return D->isExternC();
7558}
7559
7560static bool shouldConsiderLinkage(const VarDecl *VD) {
7561 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7562 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7563 isa<OMPDeclareMapperDecl>(Val: DC))
7564 return VD->hasExternalStorage();
7565 if (DC->isFileContext())
7566 return true;
7567 if (DC->isRecord())
7568 return false;
7569 if (DC->getDeclKind() == Decl::HLSLBuffer)
7570 return false;
7571
7572 if (isa<RequiresExprBodyDecl, CXXExpansionStmtDecl>(Val: DC))
7573 return false;
7574 llvm_unreachable("Unexpected context");
7575}
7576
7577static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7578 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7579 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7580 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7581 return true;
7582 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(Val: DC))
7583 return false;
7584 llvm_unreachable("Unexpected context");
7585}
7586
7587static bool hasParsedAttr(Scope *S, const Declarator &PD,
7588 ParsedAttr::Kind Kind) {
7589 // Check decl attributes on the DeclSpec.
7590 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7591 return true;
7592
7593 // Walk the declarator structure, checking decl attributes that were in a type
7594 // position to the decl itself.
7595 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7596 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7597 return true;
7598 }
7599
7600 // Finally, check attributes on the decl itself.
7601 return PD.getAttributes().hasAttribute(K: Kind) ||
7602 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7603}
7604
7605bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7606 if (!DC->isFunctionOrMethod())
7607 return false;
7608
7609 // If this is a local extern function or variable declared within a function
7610 // template, don't add it into the enclosing namespace scope until it is
7611 // instantiated; it might have a dependent type right now.
7612 if (DC->isDependentContext())
7613 return true;
7614
7615 // C++11 [basic.link]p7:
7616 // When a block scope declaration of an entity with linkage is not found to
7617 // refer to some other declaration, then that entity is a member of the
7618 // innermost enclosing namespace.
7619 //
7620 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7621 // semantically-enclosing namespace, not a lexically-enclosing one.
7622 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7623 DC = DC->getParent();
7624 return true;
7625}
7626
7627/// Returns true if given declaration has external C language linkage.
7628static bool isDeclExternC(const Decl *D) {
7629 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7630 return FD->isExternC();
7631 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7632 return VD->isExternC();
7633
7634 llvm_unreachable("Unknown type of decl!");
7635}
7636
7637/// Returns true if there hasn't been any invalid type diagnosed.
7638static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7639 DeclContext *DC = NewVD->getDeclContext();
7640 QualType R = NewVD->getType();
7641
7642 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7643 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7644 // argument.
7645 if (R->isImageType() || R->isPipeType()) {
7646 Se.Diag(Loc: NewVD->getLocation(),
7647 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7648 << R;
7649 NewVD->setInvalidDecl();
7650 return false;
7651 }
7652
7653 // OpenCL v1.2 s6.9.r:
7654 // The event type cannot be used to declare a program scope variable.
7655 // OpenCL v2.0 s6.9.q:
7656 // The clk_event_t and reserve_id_t types cannot be declared in program
7657 // scope.
7658 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7659 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7660 Se.Diag(Loc: NewVD->getLocation(),
7661 DiagID: diag::err_invalid_type_for_program_scope_var)
7662 << R;
7663 NewVD->setInvalidDecl();
7664 return false;
7665 }
7666 }
7667
7668 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7669 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7670 LO: Se.getLangOpts())) {
7671 QualType NR = R.getCanonicalType();
7672 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7673 NR->isReferenceType()) {
7674 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7675 NR->isFunctionReferenceType()) {
7676 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7677 << NR->isReferenceType();
7678 NewVD->setInvalidDecl();
7679 return false;
7680 }
7681 NR = NR->getPointeeType();
7682 }
7683 }
7684
7685 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7686 LO: Se.getLangOpts())) {
7687 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7688 // half array type (unless the cl_khr_fp16 extension is enabled).
7689 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7690 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7691 NewVD->setInvalidDecl();
7692 return false;
7693 }
7694 }
7695
7696 // OpenCL v1.2 s6.9.r:
7697 // The event type cannot be used with the __local, __constant and __global
7698 // address space qualifiers.
7699 if (R->isEventT()) {
7700 if (R.getAddressSpace() != LangAS::opencl_private) {
7701 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7702 NewVD->setInvalidDecl();
7703 return false;
7704 }
7705 }
7706
7707 if (R->isSamplerT()) {
7708 // OpenCL v1.2 s6.9.b p4:
7709 // The sampler type cannot be used with the __local and __global address
7710 // space qualifiers.
7711 if (R.getAddressSpace() == LangAS::opencl_local ||
7712 R.getAddressSpace() == LangAS::opencl_global) {
7713 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7714 NewVD->setInvalidDecl();
7715 }
7716
7717 // OpenCL v1.2 s6.12.14.1:
7718 // A global sampler must be declared with either the constant address
7719 // space qualifier or with the const qualifier.
7720 if (DC->isTranslationUnit() &&
7721 !(R.getAddressSpace() == LangAS::opencl_constant ||
7722 R.isConstQualified())) {
7723 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7724 NewVD->setInvalidDecl();
7725 }
7726 if (NewVD->isInvalidDecl())
7727 return false;
7728 }
7729
7730 return true;
7731}
7732
7733template <typename AttrTy>
7734static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7735 const TypedefNameDecl *TND = TT->getDecl();
7736 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7737 AttrTy *Clone = Attribute->clone(S.Context);
7738 Clone->setInherited(true);
7739 D->addAttr(A: Clone);
7740 }
7741}
7742
7743// This function emits warning and a corresponding note based on the
7744// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7745// declarations of an annotated type must be const qualified.
7746static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7747 QualType VarType = VD->getType().getCanonicalType();
7748
7749 // Ignore local declarations (for now) and those with const qualification.
7750 // TODO: Local variables should not be allowed if their type declaration has
7751 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7752 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7753 return;
7754
7755 if (VarType->isArrayType()) {
7756 // Retrieve element type for array declarations.
7757 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7758 }
7759
7760 const RecordDecl *RD = VarType->getAsRecordDecl();
7761
7762 // Check if the record declaration is present and if it has any attributes.
7763 if (RD == nullptr)
7764 return;
7765
7766 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7767 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7768 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7769 return;
7770 }
7771}
7772
7773void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7774 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7775 "NewD is not a function or variable");
7776
7777 if (PendingExportedNames.empty())
7778 return;
7779 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7780 if (getLangOpts().CPlusPlus && !FD->isExternC())
7781 return;
7782 }
7783 IdentifierInfo *IdentName = NewD->getIdentifier();
7784 if (IdentName == nullptr)
7785 return;
7786 auto PendingName = PendingExportedNames.find(Val: IdentName);
7787 if (PendingName != PendingExportedNames.end()) {
7788 auto &Label = PendingName->second;
7789 if (!Label.Used) {
7790 Label.Used = true;
7791 if (NewD->hasExternalFormalLinkage())
7792 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7793 else
7794 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7795 }
7796 }
7797}
7798
7799// Checks if VD is declared at global scope or with C language linkage.
7800static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7801 return Name.getAsIdentifierInfo() &&
7802 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7803 !VD->getDescribedVarTemplate() &&
7804 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7805 VD->isExternC());
7806}
7807
7808void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7809 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7810
7811 // Quickly return if the function does not have an `asm` attribute.
7812 if (E == nullptr)
7813 return;
7814
7815 // The parser guarantees this is a string.
7816 StringLiteral *SE = cast<StringLiteral>(Val: E);
7817 StringRef Label = SE->getString();
7818 QualType R = TInfo->getType();
7819 if (R->isIncompleteType())
7820 return;
7821 if (S->getFnParent() != nullptr) {
7822 switch (SC) {
7823 case SC_None:
7824 case SC_Auto:
7825 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7826 break;
7827 case SC_Register:
7828 // Local Named register
7829 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl())) {
7830 const auto &TI = Context.getTargetInfo();
7831 if (!TI.isValidGCCRegisterName(Name: Label))
7832 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7833 else if (!TI.validateLocalRegisterVariable(
7834 RegName: TI.getNormalizedGCCRegisterName(Name: Label,
7835 /*ReturnCanonical=*/true)))
7836 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_local_var_reg) << Label;
7837 }
7838 break;
7839 case SC_Static:
7840 case SC_Extern:
7841 case SC_PrivateExtern:
7842 break;
7843 }
7844 } else if (SC == SC_Register) {
7845 // Global Named register
7846 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7847 const auto &TI = Context.getTargetInfo();
7848 bool HasSizeMismatch;
7849
7850 if (!TI.isValidGCCRegisterName(Name: Label))
7851 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7852 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7853 HasSizeMismatch))
7854 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7855 else if (HasSizeMismatch)
7856 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7857 }
7858
7859 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7860 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7861 DiagID: diag::err_asm_unsupported_register_type)
7862 << TInfo->getTypeLoc().getSourceRange();
7863 NewVD->setInvalidDecl(true);
7864 }
7865 }
7866}
7867
7868NamedDecl *Sema::ActOnVariableDeclarator(
7869 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7870 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7871 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7872 QualType R = TInfo->getType();
7873 DeclarationName Name = GetNameForDeclarator(D).getName();
7874
7875 IdentifierInfo *II = Name.getAsIdentifierInfo();
7876 bool IsPlaceholderVariable = false;
7877
7878 if (D.isDecompositionDeclarator()) {
7879 // Take the name of the first declarator as our name for diagnostic
7880 // purposes.
7881 auto &Decomp = D.getDecompositionDeclarator();
7882 if (!Decomp.bindings().empty()) {
7883 II = Decomp.bindings()[0].Name;
7884 Name = II;
7885 }
7886 } else if (!II) {
7887 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7888 return nullptr;
7889 }
7890
7891
7892 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7893 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7894 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7895 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7896
7897 IsPlaceholderVariable = true;
7898
7899 if (!Previous.empty()) {
7900 NamedDecl *PrevDecl = *Previous.begin();
7901 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7902 DC: DC->getRedeclContext());
7903 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7904 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7905 if (IsPlaceholderVariable)
7906 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7907 }
7908 }
7909 }
7910
7911 // dllimport globals without explicit storage class are treated as extern. We
7912 // have to change the storage class this early to get the right DeclContext.
7913 if (SC == SC_None && !DC->isRecord() &&
7914 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7915 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7916 SC = SC_Extern;
7917
7918 DeclContext *OriginalDC = DC;
7919 bool IsLocalExternDecl = SC == SC_Extern &&
7920 adjustContextForLocalExternDecl(DC);
7921
7922 if (SCSpec == DeclSpec::SCS_mutable) {
7923 // mutable can only appear on non-static class members, so it's always
7924 // an error here
7925 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7926 D.setInvalidType();
7927 SC = SC_None;
7928 }
7929
7930 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7931 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7932 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7933 // In C++11, the 'register' storage class specifier is deprecated.
7934 // Suppress the warning in system macros, it's used in macros in some
7935 // popular C system headers, such as in glibc's htonl() macro.
7936 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7937 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7938 : diag::warn_deprecated_register)
7939 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7940 }
7941
7942 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7943
7944 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7945 // C99 6.9p2: The storage-class specifiers auto and register shall not
7946 // appear in the declaration specifiers in an external declaration.
7947 // Global Register+Asm is a GNU extension we support.
7948 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7949 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7950 D.setInvalidType();
7951 }
7952 }
7953
7954 // If this variable has a VLA type and an initializer, try to
7955 // fold to a constant-sized type. This is otherwise invalid.
7956 if (D.hasInitializer() && R->isVariableArrayType())
7957 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7958 /*DiagID=*/FailedFoldDiagID: 0);
7959
7960 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7961 const AutoType *AT = TL.getTypePtr();
7962 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7963 }
7964
7965 bool IsMemberSpecialization = false;
7966 bool IsVariableTemplateSpecialization = false;
7967 bool IsPartialSpecialization = false;
7968 bool IsVariableTemplate = false;
7969 VarDecl *NewVD = nullptr;
7970 VarTemplateDecl *NewTemplate = nullptr;
7971 TemplateParameterList *TemplateParams = nullptr;
7972 if (!getLangOpts().CPlusPlus) {
7973 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7974 Id: II, T: R, TInfo, S: SC);
7975
7976 if (R->getContainedDeducedType())
7977 ParsingInitForAutoVars.insert(Ptr: NewVD);
7978
7979 if (D.isInvalidType())
7980 NewVD->setInvalidDecl();
7981
7982 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7983 NewVD->hasLocalStorage())
7984 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7985 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7986 } else {
7987 bool Invalid = false;
7988 // Match up the template parameter lists with the scope specifier, then
7989 // determine whether we have a template or a template specialization.
7990 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7991 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7992 SS: D.getCXXScopeSpec(),
7993 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7994 ? D.getName().TemplateId
7995 : nullptr,
7996 ParamLists: TemplateParamLists,
7997 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7998
7999 if (TemplateParams) {
8000 if (DC->isDependentContext()) {
8001 ContextRAII SavedContext(*this, DC);
8002 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8003 Invalid = true;
8004 }
8005
8006 if (!TemplateParams->size() &&
8007 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8008 // There is an extraneous 'template<>' for this variable. Complain
8009 // about it, but allow the declaration of the variable.
8010 Diag(Loc: TemplateParams->getTemplateLoc(),
8011 DiagID: diag::err_template_variable_noparams)
8012 << II
8013 << SourceRange(TemplateParams->getTemplateLoc(),
8014 TemplateParams->getRAngleLoc());
8015 TemplateParams = nullptr;
8016 } else {
8017 // Check that we can declare a template here.
8018 if (CheckTemplateDeclScope(S, TemplateParams))
8019 return nullptr;
8020
8021 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8022 // This is an explicit specialization or a partial specialization.
8023 IsVariableTemplateSpecialization = true;
8024 IsPartialSpecialization = TemplateParams->size() > 0;
8025 } else { // if (TemplateParams->size() > 0)
8026 // This is a template declaration.
8027 IsVariableTemplate = true;
8028
8029 // Only C++1y supports variable templates (N3651).
8030 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
8031 }
8032 }
8033 } else {
8034 // Check that we can declare a member specialization here.
8035 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
8036 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
8037 return nullptr;
8038 assert((Invalid ||
8039 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
8040 "should have a 'template<>' for this decl");
8041 }
8042
8043 bool IsExplicitSpecialization =
8044 IsVariableTemplateSpecialization && !IsPartialSpecialization;
8045
8046 // C++ [temp.expl.spec]p2:
8047 // The declaration in an explicit-specialization shall not be an
8048 // export-declaration. An explicit specialization shall not use a
8049 // storage-class-specifier other than thread_local.
8050 //
8051 // We use the storage-class-specifier from DeclSpec because we may have
8052 // added implicit 'extern' for declarations with __declspec(dllimport)!
8053 if (SCSpec != DeclSpec::SCS_unspecified &&
8054 (IsExplicitSpecialization || IsMemberSpecialization)) {
8055 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8056 DiagID: diag::ext_explicit_specialization_storage_class)
8057 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8058 }
8059
8060 if (CurContext->isRecord()) {
8061 if (SC == SC_Static) {
8062 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
8063 // Walk up the enclosing DeclContexts to check for any that are
8064 // incompatible with static data members.
8065 const DeclContext *FunctionOrMethod = nullptr;
8066 const CXXRecordDecl *AnonStruct = nullptr;
8067 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8068 if (Ctxt->isFunctionOrMethod()) {
8069 FunctionOrMethod = Ctxt;
8070 break;
8071 }
8072 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
8073 if (ParentDecl && !ParentDecl->getDeclName()) {
8074 AnonStruct = ParentDecl;
8075 break;
8076 }
8077 }
8078 if (FunctionOrMethod) {
8079 // C++ [class.static.data]p5: A local class shall not have static
8080 // data members.
8081 Diag(Loc: D.getIdentifierLoc(),
8082 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
8083 << Name << RD->getDeclName() << RD->getTagKind();
8084 Invalid = true;
8085 } else if (AnonStruct) {
8086 // C++ [class.static.data]p4: Unnamed classes and classes contained
8087 // directly or indirectly within unnamed classes shall not contain
8088 // static data members.
8089 Diag(Loc: D.getIdentifierLoc(),
8090 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
8091 << Name << AnonStruct->getTagKind();
8092 Invalid = true;
8093 } else if (RD->isUnion()) {
8094 // C++98 [class.union]p1: If a union contains a static data member,
8095 // the program is ill-formed. C++11 drops this restriction.
8096 DiagCompat(Loc: D.getIdentifierLoc(),
8097 CompatDiagId: diag_compat::static_data_member_in_union)
8098 << Name;
8099 }
8100 }
8101 } else if (IsVariableTemplate || IsPartialSpecialization) {
8102 // There is no such thing as a member field template.
8103 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
8104 << II << TemplateParams->getSourceRange();
8105 // Recover by pretending this is a static data member template.
8106 SC = SC_Static;
8107 }
8108 } else if (DC->isRecord()) {
8109 // This is an out-of-line definition of a static data member.
8110 switch (SC) {
8111 case SC_None:
8112 break;
8113 case SC_Static:
8114 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8115 DiagID: diag::err_static_out_of_line)
8116 << FixItHint::CreateRemoval(
8117 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8118 break;
8119 case SC_Auto:
8120 case SC_Register:
8121 case SC_Extern:
8122 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8123 // to names of variables declared in a block or to function parameters.
8124 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8125 // of class members
8126
8127 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8128 DiagID: diag::err_storage_class_for_static_member)
8129 << FixItHint::CreateRemoval(
8130 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8131 break;
8132 case SC_PrivateExtern:
8133 llvm_unreachable("C storage class in c++!");
8134 }
8135 }
8136
8137 if (IsVariableTemplateSpecialization) {
8138 SourceLocation TemplateKWLoc =
8139 TemplateParamLists.size() > 0
8140 ? TemplateParamLists[0]->getTemplateLoc()
8141 : SourceLocation();
8142 DeclResult Res = ActOnVarTemplateSpecialization(
8143 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8144 IsPartialSpecialization);
8145 if (Res.isInvalid())
8146 return nullptr;
8147 NewVD = cast<VarDecl>(Val: Res.get());
8148 AddToScope = false;
8149 } else if (D.isDecompositionDeclarator()) {
8150 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8151 LSquareLoc: D.getIdentifierLoc(), RSquareLoc: D.getEndLoc(), T: R,
8152 TInfo, S: SC, Bindings);
8153 } else
8154 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8155 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8156
8157 // If this is supposed to be a variable template, create it as such.
8158 if (IsVariableTemplate) {
8159 NewTemplate =
8160 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8161 Params: TemplateParams, Decl: NewVD);
8162 NewVD->setDescribedVarTemplate(NewTemplate);
8163 }
8164
8165 // If this decl has an auto type in need of deduction, make a note of the
8166 // Decl so we can diagnose uses of it in its own initializer.
8167 if (R->getContainedDeducedType())
8168 ParsingInitForAutoVars.insert(Ptr: NewVD);
8169
8170 if (D.isInvalidType() || Invalid) {
8171 NewVD->setInvalidDecl();
8172 if (NewTemplate)
8173 NewTemplate->setInvalidDecl();
8174 }
8175
8176 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8177
8178 // If we have any template parameter lists that don't directly belong to
8179 // the variable (matching the scope specifier), store them.
8180 // An explicit variable template specialization does not own any template
8181 // parameter lists.
8182 unsigned VDTemplateParamLists =
8183 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8184 if (TemplateParamLists.size() > VDTemplateParamLists)
8185 NewVD->setTemplateParameterListsInfo(
8186 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8187 }
8188
8189 if (D.getDeclSpec().isInlineSpecified()) {
8190 if (!getLangOpts().CPlusPlus) {
8191 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8192 << 0;
8193 } else if (CurContext->isFunctionOrMethod()) {
8194 // 'inline' is not allowed on block scope variable declaration.
8195 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8196 DiagID: diag::err_inline_declaration_block_scope) << Name
8197 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8198 } else {
8199 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8200 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8201 : diag::compat_pre_cxx17_inline_variable);
8202 NewVD->setInlineSpecified();
8203 }
8204 }
8205
8206 // Set the lexical context. If the declarator has a C++ scope specifier, the
8207 // lexical context will be different from the semantic context.
8208 NewVD->setLexicalDeclContext(CurContext);
8209 if (NewTemplate)
8210 NewTemplate->setLexicalDeclContext(CurContext);
8211
8212 if (IsLocalExternDecl) {
8213 if (D.isDecompositionDeclarator())
8214 for (auto *B : Bindings)
8215 B->setLocalExternDecl();
8216 else
8217 NewVD->setLocalExternDecl();
8218 }
8219
8220 bool EmitTLSUnsupportedError = false;
8221 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8222 // C++11 [dcl.stc]p4:
8223 // When thread_local is applied to a variable of block scope the
8224 // storage-class-specifier static is implied if it does not appear
8225 // explicitly.
8226 // Core issue: 'static' is not implied if the variable is declared
8227 // 'extern'.
8228 if (NewVD->hasLocalStorage() &&
8229 (SCSpec != DeclSpec::SCS_unspecified ||
8230 TSCS != DeclSpec::TSCS_thread_local ||
8231 !DC->isFunctionOrMethod()))
8232 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8233 DiagID: diag::err_thread_non_global)
8234 << DeclSpec::getSpecifierName(S: TSCS);
8235 else if (!Context.getTargetInfo().isTLSSupported()) {
8236 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8237 // Postpone error emission until we've collected attributes required to
8238 // figure out whether it's a host or device variable and whether the
8239 // error should be ignored.
8240 EmitTLSUnsupportedError = true;
8241 // We still need to mark the variable as TLS so it shows up in AST with
8242 // proper storage class for other tools to use even if we're not going
8243 // to emit any code for it.
8244 NewVD->setTSCSpec(TSCS);
8245 } else
8246 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8247 DiagID: diag::err_thread_unsupported);
8248 } else
8249 NewVD->setTSCSpec(TSCS);
8250 }
8251
8252 switch (D.getDeclSpec().getConstexprSpecifier()) {
8253 case ConstexprSpecKind::Unspecified:
8254 break;
8255
8256 case ConstexprSpecKind::Consteval:
8257 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8258 DiagID: diag::err_constexpr_wrong_decl_kind)
8259 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8260 [[fallthrough]];
8261
8262 case ConstexprSpecKind::Constexpr:
8263 NewVD->setConstexpr(true);
8264 // C++1z [dcl.spec.constexpr]p1:
8265 // A static data member declared with the constexpr specifier is
8266 // implicitly an inline variable.
8267 if (NewVD->isStaticDataMember() &&
8268 (getLangOpts().CPlusPlus17 ||
8269 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8270 NewVD->setImplicitlyInline();
8271 break;
8272
8273 case ConstexprSpecKind::Constinit:
8274 if (!NewVD->hasGlobalStorage())
8275 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8276 DiagID: diag::err_constinit_local_variable);
8277 else
8278 NewVD->addAttr(
8279 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8280 S: ConstInitAttr::Keyword_constinit));
8281 break;
8282 }
8283
8284 // C99 6.7.4p3
8285 // An inline definition of a function with external linkage shall
8286 // not contain a definition of a modifiable object with static or
8287 // thread storage duration...
8288 // We only apply this when the function is required to be defined
8289 // elsewhere, i.e. when the function is not 'extern inline'. Note
8290 // that a local variable with thread storage duration still has to
8291 // be marked 'static'. Also note that it's possible to get these
8292 // semantics in C++ using __attribute__((gnu_inline)).
8293 if (SC == SC_Static && S->getFnParent() != nullptr &&
8294 !NewVD->getType().isConstQualified()) {
8295 FunctionDecl *CurFD = getCurFunctionDecl();
8296 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8297 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8298 DiagID: diag::warn_static_local_in_extern_inline);
8299 MaybeSuggestAddingStaticToDecl(D: CurFD);
8300 }
8301 }
8302
8303 if (D.getDeclSpec().isModulePrivateSpecified()) {
8304 if (IsVariableTemplateSpecialization)
8305 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8306 << (IsPartialSpecialization ? 1 : 0)
8307 << FixItHint::CreateRemoval(
8308 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8309 else if (IsMemberSpecialization)
8310 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8311 << 2
8312 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8313 else if (NewVD->hasLocalStorage())
8314 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8315 << 0 << NewVD
8316 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8317 << FixItHint::CreateRemoval(
8318 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8319 else {
8320 NewVD->setModulePrivate();
8321 if (NewTemplate)
8322 NewTemplate->setModulePrivate();
8323 for (auto *B : Bindings)
8324 B->setModulePrivate();
8325 }
8326 }
8327
8328 if (getLangOpts().OpenCL) {
8329 deduceOpenCLAddressSpace(Var: NewVD);
8330
8331 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8332 if (TSC != TSCS_unspecified) {
8333 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8334 DiagID: diag::err_opencl_unknown_type_specifier)
8335 << getLangOpts().getOpenCLVersionString()
8336 << DeclSpec::getSpecifierName(S: TSC) << 1;
8337 NewVD->setInvalidDecl();
8338 }
8339 }
8340
8341 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8342 // address space if the table has local storage (semantic checks elsewhere
8343 // will produce an error anyway).
8344 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8345 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8346 !NewVD->hasLocalStorage()) {
8347 QualType Type = Context.getAddrSpaceQualType(
8348 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8349 NewVD->setType(Type);
8350 }
8351 }
8352
8353 LoadExternalExtnameUndeclaredIdentifiers();
8354
8355 if (Expr *E = D.getAsmLabel()) {
8356 // The parser guarantees this is a string.
8357 StringLiteral *SE = cast<StringLiteral>(Val: E);
8358 StringRef Label = SE->getString();
8359
8360 // Insert the asm attribute.
8361 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8362 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8363 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8364 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8365 if (I != ExtnameUndeclaredIdentifiers.end()) {
8366 if (isDeclExternC(D: NewVD)) {
8367 NewVD->addAttr(A: I->second);
8368 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8369 } else if (NewVD->getDeclContext()
8370 ->getRedeclContext()
8371 ->isTranslationUnit())
8372 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8373 << /*Variable*/ 1 << NewVD;
8374 }
8375 }
8376
8377 // Handle attributes prior to checking for duplicates in MergeVarDecl
8378 ProcessDeclAttributes(S, D: NewVD, PD: D);
8379
8380 if (getLangOpts().HLSL)
8381 HLSL().ActOnVariableDeclarator(VD: NewVD);
8382
8383 if (getLangOpts().OpenACC)
8384 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8385
8386 // FIXME: This is probably the wrong location to be doing this and we should
8387 // probably be doing this for more attributes (especially for function
8388 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8389 // the code to copy attributes would be generated by TableGen.
8390 if (R->isFunctionPointerType())
8391 if (const auto *TT = R->getAs<TypedefType>())
8392 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8393
8394 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8395 if (EmitTLSUnsupportedError &&
8396 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8397 (getLangOpts().OpenMPIsTargetDevice &&
8398 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8399 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8400 DiagID: diag::err_thread_unsupported);
8401
8402 if (EmitTLSUnsupportedError &&
8403 (LangOpts.SYCLIsDevice ||
8404 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8405 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8406 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8407 // storage [duration]."
8408 if (SC == SC_None && S->getFnParent() != nullptr &&
8409 (NewVD->hasAttr<CUDASharedAttr>() ||
8410 NewVD->hasAttr<CUDAConstantAttr>())) {
8411 NewVD->setStorageClass(SC_Static);
8412 }
8413 }
8414
8415 // Ensure that dllimport globals without explicit storage class are treated as
8416 // extern. The storage class is set above using parsed attributes. Now we can
8417 // check the VarDecl itself.
8418 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8419 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8420 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8421
8422 // In auto-retain/release, infer strong retension for variables of
8423 // retainable type.
8424 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8425 NewVD->setInvalidDecl();
8426
8427 // Check the ASM label here, as we need to know all other attributes of the
8428 // Decl first. Otherwise, we can't know if the asm label refers to the
8429 // host or device in a CUDA context. The device has other registers than
8430 // host and we must know where the function will be placed.
8431 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8432
8433 // Find the shadowed declaration before filtering for scope.
8434 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8435 ? getShadowedDeclaration(D: NewVD, R: Previous)
8436 : nullptr;
8437
8438 // Don't consider existing declarations that are in a different
8439 // scope and are out-of-semantic-context declarations (if the new
8440 // declaration has linkage).
8441 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8442 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8443 IsMemberSpecialization ||
8444 IsVariableTemplateSpecialization);
8445
8446 // Check whether the previous declaration is in the same block scope. This
8447 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8448 if (getLangOpts().CPlusPlus &&
8449 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8450 NewVD->setPreviousDeclInSameBlockScope(
8451 Previous.isSingleResult() && !Previous.isShadowed() &&
8452 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8453
8454 if (!getLangOpts().CPlusPlus) {
8455 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8456 } else {
8457 // If this is an explicit specialization of a static data member, check it.
8458 if (IsMemberSpecialization && !IsVariableTemplate &&
8459 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8460 CheckMemberSpecialization(Member: NewVD, Previous))
8461 NewVD->setInvalidDecl();
8462
8463 // Merge the decl with the existing one if appropriate.
8464 if (!Previous.empty()) {
8465 if (Previous.isSingleResult() &&
8466 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8467 D.getCXXScopeSpec().isSet()) {
8468 // The user tried to define a non-static data member
8469 // out-of-line (C++ [dcl.meaning]p1).
8470 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8471 << D.getCXXScopeSpec().getRange();
8472 Previous.clear();
8473 NewVD->setInvalidDecl();
8474 }
8475 } else if (D.getCXXScopeSpec().isSet() &&
8476 !IsVariableTemplateSpecialization) {
8477 // No previous declaration in the qualifying scope.
8478 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8479 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8480 << D.getCXXScopeSpec().getRange();
8481 NewVD->setInvalidDecl();
8482
8483 // if this is a member specialization, we don't have any primary template
8484 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8485 // that anything that attempts to refer to this invalid declaration can
8486 // act as if there IS a primary instantiation.
8487 if (NewTemplate && IsMemberSpecialization) {
8488 VarDecl *FakeVD =
8489 VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
8490 Id: II, T: R, TInfo, S: SC);
8491 FakeVD->setInvalidDecl();
8492 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8493 C&: Context, DC, L: D.getIdentifierLoc(), Name, Params: TemplateParams, Decl: FakeVD);
8494 FakeInstantiatedFrom->setInvalidDecl();
8495 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8496 }
8497 }
8498
8499 if (!IsPlaceholderVariable)
8500 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8501
8502 // CheckVariableDeclaration will set NewVD as invalid if something is in
8503 // error like WebAssembly tables being declared as arrays with a non-zero
8504 // size, but then parsing continues and emits further errors on that line.
8505 // To avoid that we check here if it happened and return nullptr.
8506 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8507 return nullptr;
8508
8509 if (NewTemplate) {
8510 VarTemplateDecl *PrevVarTemplate =
8511 NewVD->getPreviousDecl()
8512 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8513 : nullptr;
8514
8515 // Check the template parameter list of this declaration, possibly
8516 // merging in the template parameter list from the previous variable
8517 // template declaration.
8518 if (CheckTemplateParameterList(
8519 NewParams: TemplateParams,
8520 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8521 : nullptr,
8522 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8523 DC->isDependentContext())
8524 ? TPC_ClassTemplateMember
8525 : TPC_Other))
8526 NewVD->setInvalidDecl();
8527 }
8528 }
8529
8530 if (IsMemberSpecialization) {
8531 if (NewTemplate && NewVD->getPreviousDecl()) {
8532 NewTemplate->setMemberSpecialization();
8533 } else if (IsPartialSpecialization) {
8534 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8535 ->setMemberSpecialization();
8536 }
8537 }
8538
8539 // Diagnose shadowed variables iff this isn't a redeclaration.
8540 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8541 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8542
8543 ProcessPragmaWeak(S, D: NewVD);
8544 ProcessPragmaExport(NewD: NewVD);
8545
8546 // If this is the first declaration of an extern C variable, update
8547 // the map of such variables.
8548 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8549 isIncompleteDeclExternC(S&: *this, D: NewVD))
8550 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8551
8552 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8553 MangleNumberingContext *MCtx;
8554 Decl *ManglingContextDecl;
8555 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8556 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8557 if (MCtx) {
8558 Context.setManglingNumber(
8559 ND: NewVD, Number: MCtx->getManglingNumber(
8560 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8561 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8562 }
8563 }
8564
8565 // Special handling of variable named 'main'.
8566 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8567 // C++ [basic.start.main]p3:
8568 // A program that declares
8569 // - a variable main at global scope, or
8570 // - an entity named main with C language linkage (in any namespace)
8571 // is ill-formed
8572 if (getLangOpts().CPlusPlus)
8573 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8574 << NewVD->isExternC();
8575
8576 // In C, and external-linkage variable named main results in undefined
8577 // behavior.
8578 else if (NewVD->hasExternalFormalLinkage())
8579 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8580 }
8581
8582 if (D.isRedeclaration() && !Previous.empty()) {
8583 NamedDecl *Prev = Previous.getRepresentativeDecl();
8584 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8585 IsDefinition: D.isFunctionDefinition());
8586 }
8587
8588 if (NewTemplate) {
8589 if (NewVD->isInvalidDecl())
8590 NewTemplate->setInvalidDecl();
8591 ActOnDocumentableDecl(D: NewTemplate);
8592 return NewTemplate;
8593 }
8594
8595 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8596 CompleteMemberSpecialization(Member: NewVD, Previous);
8597
8598 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8599
8600 return NewVD;
8601}
8602
8603/// Enum describing the %select options in diag::warn_decl_shadow.
8604enum ShadowedDeclKind {
8605 SDK_Local,
8606 SDK_Global,
8607 SDK_StaticMember,
8608 SDK_Field,
8609 SDK_Typedef,
8610 SDK_Using,
8611 SDK_StructuredBinding
8612};
8613
8614/// Determine what kind of declaration we're shadowing.
8615static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8616 const DeclContext *OldDC) {
8617 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8618 return SDK_Using;
8619 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8620 return SDK_Typedef;
8621 else if (isa<BindingDecl>(Val: ShadowedDecl))
8622 return SDK_StructuredBinding;
8623 else if (isa<RecordDecl>(Val: OldDC))
8624 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8625
8626 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8627}
8628
8629/// Return the location of the capture if the given lambda captures the given
8630/// variable \p VD, or an invalid source location otherwise.
8631static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8632 const ValueDecl *VD) {
8633 for (const Capture &Capture : LSI->Captures) {
8634 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8635 return Capture.getLocation();
8636 }
8637 return SourceLocation();
8638}
8639
8640static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8641 const LookupResult &R) {
8642 // Only diagnose if we're shadowing an unambiguous field or variable.
8643 if (R.getResultKind() != LookupResultKind::Found)
8644 return false;
8645
8646 // Return false if warning is ignored.
8647 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8648}
8649
8650NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8651 const LookupResult &R) {
8652 if (!shouldWarnIfShadowedDecl(Diags, R))
8653 return nullptr;
8654
8655 // Don't diagnose declarations at file scope.
8656 if (D->hasGlobalStorage() && !D->isStaticLocal())
8657 return nullptr;
8658
8659 NamedDecl *ShadowedDecl = R.getFoundDecl();
8660 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8661 : nullptr;
8662}
8663
8664NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8665 const LookupResult &R) {
8666 // Don't warn if typedef declaration is part of a class
8667 if (D->getDeclContext()->isRecord())
8668 return nullptr;
8669
8670 if (!shouldWarnIfShadowedDecl(Diags, R))
8671 return nullptr;
8672
8673 NamedDecl *ShadowedDecl = R.getFoundDecl();
8674 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8675}
8676
8677NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8678 const LookupResult &R) {
8679 if (!shouldWarnIfShadowedDecl(Diags, R))
8680 return nullptr;
8681
8682 NamedDecl *ShadowedDecl = R.getFoundDecl();
8683 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8684 : nullptr;
8685}
8686
8687void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8688 const LookupResult &R) {
8689 DeclContext *NewDC = D->getDeclContext();
8690
8691 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8692 DeclContext *FnDC = getFunctionLevelDeclContext();
8693 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDC)) {
8694 // Fields aren't shadowed in C++ static members or in member functions
8695 // with an explicit object parameter.
8696 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8697 return;
8698 } else if (isa<FunctionDecl>(Val: FnDC)) {
8699 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8700 // inline-defined friend function, since that's the only way to
8701 // introduce a non-member function inside a class body. Friends have
8702 // no implicit `this`, so nothing here can shadow a field.
8703 return;
8704 }
8705 // Fields shadowed by constructor parameters are a special case. Usually
8706 // the constructor initializes the field with the parameter.
8707 if (isa<CXXConstructorDecl>(Val: NewDC))
8708 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8709 // Remember that this was shadowed so we can either warn about its
8710 // modification or its existence depending on warning settings.
8711 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8712 return;
8713 }
8714 }
8715
8716 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8717 if (shadowedVar->isExternC()) {
8718 // For shadowing external vars, make sure that we point to the global
8719 // declaration, not a locally scoped extern declaration.
8720 for (auto *I : shadowedVar->redecls())
8721 if (I->isFileVarDecl()) {
8722 ShadowedDecl = I;
8723 break;
8724 }
8725 }
8726
8727 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8728
8729 unsigned WarningDiag = diag::warn_decl_shadow;
8730 SourceLocation CaptureLoc;
8731 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8732 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8733 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8734 // Handle both VarDecl and BindingDecl in lambda contexts
8735 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8736 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8737 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8738 if (RD->getLambdaCaptureDefault() == LCD_None) {
8739 // Try to avoid warnings for lambdas with an explicit capture
8740 // list. Warn only when the lambda captures the shadowed decl
8741 // explicitly.
8742 CaptureLoc = getCaptureLocation(LSI, VD);
8743 if (CaptureLoc.isInvalid())
8744 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8745 } else {
8746 // Remember that this was shadowed so we can avoid the warning if
8747 // the shadowed decl isn't captured and the warning settings allow
8748 // it.
8749 cast<LambdaScopeInfo>(Val: getCurFunction())
8750 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8751 return;
8752 }
8753 }
8754 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8755 // If lambda can capture this, then emit default shadowing warning,
8756 // Otherwise it is not really a shadowing case since field is not
8757 // available in lambda's body.
8758 // At this point we don't know that lambda can capture this, so
8759 // remember that this was shadowed and delay until we know.
8760 cast<LambdaScopeInfo>(Val: getCurFunction())
8761 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8762 return;
8763 }
8764 }
8765 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8766 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8767 bool HasLocalStorage = false;
8768 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8769 HasLocalStorage = VD->hasLocalStorage();
8770 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8771 HasLocalStorage =
8772 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8773
8774 if (HasLocalStorage) {
8775 // A variable can't shadow a local variable or binding in an enclosing
8776 // scope, if they are separated by a non-capturing declaration
8777 // context.
8778 for (DeclContext *ParentDC = NewDC;
8779 ParentDC && !ParentDC->Equals(DC: OldDC);
8780 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8781 // Only block literals, captured statements, and lambda expressions
8782 // can capture; other scopes don't.
8783 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8784 !isLambdaCallOperator(DC: ParentDC))
8785 return;
8786 }
8787 }
8788 }
8789 }
8790 }
8791
8792 // Never warn about shadowing a placeholder variable.
8793 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8794 return;
8795
8796 // Only warn about certain kinds of shadowing for class members.
8797 if (NewDC) {
8798 // In particular, don't warn about shadowing non-class members.
8799 if (NewDC->isRecord() && !OldDC->isRecord())
8800 return;
8801
8802 // Skip shadowing check if we're in a class scope, dealing with an enum
8803 // constant in a different context.
8804 DeclContext *ReDC = NewDC->getRedeclContext();
8805 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8806 return;
8807
8808 // TODO: should we warn about static data members shadowing
8809 // static data members from base classes?
8810
8811 // TODO: don't diagnose for inaccessible shadowed members.
8812 // This is hard to do perfectly because we might friend the
8813 // shadowing context, but that's just a false negative.
8814 }
8815
8816 DeclarationName Name = R.getLookupName();
8817
8818 // Emit warning and note.
8819 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8820 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8821 if (!CaptureLoc.isInvalid())
8822 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8823 << Name << /*explicitly*/ 1;
8824 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8825}
8826
8827void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8828 for (const auto &Shadow : LSI->ShadowingDecls) {
8829 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8830 // Try to avoid the warning when the shadowed decl isn't captured.
8831 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8832 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8833 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8834 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8835 Diag(Loc: Shadow.VD->getLocation(),
8836 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8837 : diag::warn_decl_shadow)
8838 << Shadow.VD->getDeclName()
8839 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8840 if (CaptureLoc.isValid())
8841 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8842 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8843 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8844 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8845 Diag(Loc: Shadow.VD->getLocation(),
8846 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8847 : diag::warn_decl_shadow_uncaptured_local)
8848 << Shadow.VD->getDeclName()
8849 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8850 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8851 }
8852 }
8853}
8854
8855void Sema::CheckShadow(Scope *S, VarDecl *D) {
8856 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8857 return;
8858
8859 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8860 Sema::LookupOrdinaryName,
8861 RedeclarationKind::ForVisibleRedeclaration);
8862 LookupName(R, S);
8863 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8864 CheckShadow(D, ShadowedDecl, R);
8865}
8866
8867/// Check if 'E', which is an expression that is about to be modified, refers
8868/// to a constructor parameter that shadows a field.
8869void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8870 // Quickly ignore expressions that can't be shadowing ctor parameters.
8871 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8872 return;
8873 E = E->IgnoreParenImpCasts();
8874 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8875 if (!DRE)
8876 return;
8877 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8878 auto I = ShadowingDecls.find(Val: D);
8879 if (I == ShadowingDecls.end())
8880 return;
8881 const NamedDecl *ShadowedDecl = I->second;
8882 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8883 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8884 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8885 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8886
8887 // Avoid issuing multiple warnings about the same decl.
8888 ShadowingDecls.erase(I);
8889}
8890
8891/// Check for conflict between this global or extern "C" declaration and
8892/// previous global or extern "C" declarations. This is only used in C++.
8893template<typename T>
8894static bool checkGlobalOrExternCConflict(
8895 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8896 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8897 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8898
8899 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8900 // The common case: this global doesn't conflict with any extern "C"
8901 // declaration.
8902 return false;
8903 }
8904
8905 if (Prev) {
8906 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8907 // Both the old and new declarations have C language linkage. This is a
8908 // redeclaration.
8909 Previous.clear();
8910 Previous.addDecl(D: Prev);
8911 return true;
8912 }
8913
8914 // This is a global, non-extern "C" declaration, and there is a previous
8915 // non-global extern "C" declaration. Diagnose if this is a variable
8916 // declaration.
8917 if (!isa<VarDecl>(ND))
8918 return false;
8919 } else {
8920 // The declaration is extern "C". Check for any declaration in the
8921 // translation unit which might conflict.
8922 if (IsGlobal) {
8923 // We have already performed the lookup into the translation unit.
8924 IsGlobal = false;
8925 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8926 I != E; ++I) {
8927 if (isa<VarDecl>(Val: *I)) {
8928 Prev = *I;
8929 break;
8930 }
8931 }
8932 } else {
8933 DeclContext::lookup_result R =
8934 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8935 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8936 I != E; ++I) {
8937 if (isa<VarDecl>(Val: *I)) {
8938 Prev = *I;
8939 break;
8940 }
8941 // FIXME: If we have any other entity with this name in global scope,
8942 // the declaration is ill-formed, but that is a defect: it breaks the
8943 // 'stat' hack, for instance. Only variables can have mangled name
8944 // clashes with extern "C" declarations, so only they deserve a
8945 // diagnostic.
8946 }
8947 }
8948
8949 if (!Prev)
8950 return false;
8951 }
8952
8953 // Use the first declaration's location to ensure we point at something which
8954 // is lexically inside an extern "C" linkage-spec.
8955 assert(Prev && "should have found a previous declaration to diagnose");
8956 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8957 Prev = FD->getFirstDecl();
8958 else
8959 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8960
8961 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8962 << IsGlobal << ND;
8963 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8964 << IsGlobal;
8965 return false;
8966}
8967
8968/// Apply special rules for handling extern "C" declarations. Returns \c true
8969/// if we have found that this is a redeclaration of some prior entity.
8970///
8971/// Per C++ [dcl.link]p6:
8972/// Two declarations [for a function or variable] with C language linkage
8973/// with the same name that appear in different scopes refer to the same
8974/// [entity]. An entity with C language linkage shall not be declared with
8975/// the same name as an entity in global scope.
8976template<typename T>
8977static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8978 LookupResult &Previous) {
8979 if (!S.getLangOpts().CPlusPlus) {
8980 // In C, when declaring a global variable, look for a corresponding 'extern'
8981 // variable declared in function scope. We don't need this in C++, because
8982 // we find local extern decls in the surrounding file-scope DeclContext.
8983 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8984 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8985 Previous.clear();
8986 Previous.addDecl(D: Prev);
8987 return true;
8988 }
8989 }
8990 return false;
8991 }
8992
8993 // A declaration in the translation unit can conflict with an extern "C"
8994 // declaration.
8995 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8996 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8997
8998 // An extern "C" declaration can conflict with a declaration in the
8999 // translation unit or can be a redeclaration of an extern "C" declaration
9000 // in another scope.
9001 if (isIncompleteDeclExternC(S,ND))
9002 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
9003
9004 // Neither global nor extern "C": nothing to do.
9005 return false;
9006}
9007
9008static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
9009 QualType T) {
9010 QualType CanonT = SemaRef.Context.getCanonicalType(T);
9011 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
9012 // any of its members, even recursively, shall not have an atomic type, or a
9013 // variably modified type, or a type that is volatile or restrict qualified.
9014 if (CanonT->isVariablyModifiedType()) {
9015 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
9016 return true;
9017 }
9018
9019 // Arrays are qualified by their element type, so get the base type (this
9020 // works on non-arrays as well).
9021 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
9022
9023 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
9024 CanonT.isRestrictQualified()) {
9025 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
9026 return true;
9027 }
9028
9029 if (CanonT->isRecordType()) {
9030 const RecordDecl *RD = CanonT->getAsRecordDecl();
9031 if (!RD->isInvalidDecl() &&
9032 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
9033 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
9034 }))
9035 return true;
9036 }
9037
9038 return false;
9039}
9040
9041static bool isSYCLAddressSpace(LangAS AS) {
9042 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
9043}
9044
9045void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
9046 // If the decl is already known invalid, don't check it.
9047 if (NewVD->isInvalidDecl())
9048 return;
9049
9050 SourceLocation VMLoc = NewVD->getLocation();
9051 if (TypeSourceInfo *TSI = NewVD->getTypeSourceInfo())
9052 VMLoc = TSI->getTypeLoc().getBeginLoc();
9053 if (!CheckVariablyModifiedTypeUse(T: NewVD->getType(), Loc: VMLoc)) {
9054 NewVD->setInvalidDecl();
9055 return;
9056 }
9057
9058 QualType T = NewVD->getType();
9059
9060 // Defer checking an 'auto' type until its initializer is attached.
9061 if (T->isUndeducedType())
9062 return;
9063
9064 if (NewVD->hasAttrs())
9065 CheckAlignasUnderalignment(D: NewVD);
9066
9067 if (T->isObjCObjectType()) {
9068 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
9069 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
9070 T = Context.getObjCObjectPointerType(OIT: T);
9071 NewVD->setType(T);
9072 }
9073
9074 // The top-level type of a variable declaration cannot have a SYCL address
9075 // space qualifier.
9076 if (getLangOpts().isSYCL()) {
9077 LangAS AS = Context.getBaseElementType(QT: T).getAddressSpace();
9078 if (isSYCLAddressSpace(AS)) {
9079 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sycl_address_space_qualified_object)
9080 << Qualifiers::getAddrSpaceAsString(AS);
9081 NewVD->setInvalidDecl();
9082 return;
9083 }
9084 }
9085
9086 // Emit an error if an address space was applied to decl with local storage.
9087 // This includes arrays of objects with address space qualifiers, but not
9088 // automatic variables that point to other address spaces.
9089 // ISO/IEC TR 18037 S5.1.2
9090 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9091 T.getAddressSpace() != LangAS::Default) {
9092 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
9093 NewVD->setInvalidDecl();
9094 return;
9095 }
9096
9097 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9098 // scope.
9099 if (getLangOpts().OpenCLVersion == 120 &&
9100 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
9101 LO: getLangOpts()) &&
9102 NewVD->isStaticLocal()) {
9103 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
9104 NewVD->setInvalidDecl();
9105 return;
9106 }
9107
9108 if (getLangOpts().OpenCL) {
9109 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
9110 return;
9111
9112 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9113 if (NewVD->hasAttr<BlocksAttr>()) {
9114 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
9115 return;
9116 }
9117
9118 if (T->isBlockPointerType()) {
9119 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9120 // can't use 'extern' storage class.
9121 if (!T.isConstQualified()) {
9122 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
9123 << 0 /*const*/;
9124 NewVD->setInvalidDecl();
9125 return;
9126 }
9127 if (NewVD->hasExternalStorage()) {
9128 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
9129 NewVD->setInvalidDecl();
9130 return;
9131 }
9132 }
9133
9134 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9135 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9136 NewVD->hasExternalStorage()) {
9137 if (!T->isSamplerT() && !T->isDependentType() &&
9138 !(T.getAddressSpace() == LangAS::opencl_constant ||
9139 (T.getAddressSpace() == LangAS::opencl_global &&
9140 getOpenCLOptions().areProgramScopeVariablesSupported(
9141 Opts: getLangOpts())))) {
9142 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9143 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
9144 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9145 << Scope << "global or constant";
9146 else
9147 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9148 << Scope << "constant";
9149 NewVD->setInvalidDecl();
9150 return;
9151 }
9152 } else {
9153 if (T.getAddressSpace() == LangAS::opencl_global) {
9154 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9155 << 1 /*is any function*/ << "global";
9156 NewVD->setInvalidDecl();
9157 return;
9158 }
9159 // When this extension is enabled, 'local' variables are permitted in
9160 // non-kernel functions and within nested scopes of kernel functions,
9161 // bypassing standard OpenCL address space restrictions.
9162 bool AllowFunctionScopeLocalVariables =
9163 T.getAddressSpace() == LangAS::opencl_local &&
9164 getOpenCLOptions().isAvailableOption(
9165 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9166 if (AllowFunctionScopeLocalVariables) {
9167 // Direct pass: No further diagnostics needed for this specific case.
9168 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9169 T.getAddressSpace() == LangAS::opencl_local) {
9170 FunctionDecl *FD = getCurFunctionDecl();
9171 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9172 // in functions.
9173 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9174 if (T.getAddressSpace() == LangAS::opencl_constant)
9175 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9176 << 0 /*non-kernel only*/ << "constant";
9177 else
9178 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9179 << 0 /*non-kernel only*/ << "local";
9180 NewVD->setInvalidDecl();
9181 return;
9182 }
9183 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9184 // in the outermost scope of a kernel function.
9185 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9186 if (!getCurScope()->isFunctionScope()) {
9187 if (T.getAddressSpace() == LangAS::opencl_constant)
9188 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9189 << "constant";
9190 else
9191 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9192 << "local";
9193 NewVD->setInvalidDecl();
9194 return;
9195 }
9196 }
9197 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9198 // If we are parsing a template we didn't deduce an addr
9199 // space yet.
9200 T.getAddressSpace() != LangAS::Default) {
9201 // Do not allow other address spaces on automatic variable.
9202 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9203 NewVD->setInvalidDecl();
9204 return;
9205 }
9206 }
9207 }
9208
9209 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9210 && !NewVD->hasAttr<BlocksAttr>()) {
9211 if (getLangOpts().getGC() != LangOptions::NonGC)
9212 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9213 else {
9214 assert(!getLangOpts().ObjCAutoRefCount);
9215 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9216 }
9217 }
9218
9219 // WebAssembly tables must be static with a zero length and can't be
9220 // declared within functions.
9221 if (T->isWebAssemblyTableType()) {
9222 if (getCurScope()->getParent()) { // Parent is null at top-level
9223 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9224 NewVD->setInvalidDecl();
9225 return;
9226 }
9227 if (NewVD->getStorageClass() != SC_Static) {
9228 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9229 NewVD->setInvalidDecl();
9230 return;
9231 }
9232 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9233 if (!ATy || ATy->getZExtSize() != 0) {
9234 Diag(Loc: NewVD->getLocation(),
9235 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9236 NewVD->setInvalidDecl();
9237 return;
9238 }
9239 }
9240
9241 // zero sized static arrays are not allowed in HIP device functions
9242 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9243 if (FunctionDecl *FD = getCurFunctionDecl();
9244 FD &&
9245 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9246 if (const ConstantArrayType *ArrayT =
9247 getASTContext().getAsConstantArrayType(T);
9248 ArrayT && ArrayT->isZeroSize()) {
9249 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9250 }
9251 }
9252 }
9253
9254 bool isVM = T->isVariablyModifiedType();
9255 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9256 NewVD->hasAttr<BlocksAttr>())
9257 setFunctionHasBranchProtectedScope();
9258
9259 if ((isVM && NewVD->hasLinkage()) ||
9260 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9261 bool SizeIsNegative;
9262 llvm::APSInt Oversized;
9263 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9264 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9265 QualType FixedT;
9266 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9267 FixedT = FixedTInfo->getType();
9268 else if (FixedTInfo) {
9269 // Type and type-as-written are canonically different. We need to fix up
9270 // both types separately.
9271 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9272 Oversized);
9273 }
9274 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9275 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9276 // FIXME: This won't give the correct result for
9277 // int a[10][n];
9278 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9279
9280 if (NewVD->isFileVarDecl())
9281 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9282 << SizeRange;
9283 else if (NewVD->isStaticLocal())
9284 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9285 << SizeRange;
9286 else
9287 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9288 << SizeRange;
9289 NewVD->setInvalidDecl();
9290 return;
9291 }
9292
9293 if (!FixedTInfo) {
9294 if (NewVD->isFileVarDecl())
9295 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9296 else
9297 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9298 NewVD->setInvalidDecl();
9299 return;
9300 }
9301
9302 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9303 NewVD->setType(FixedT);
9304 NewVD->setTypeSourceInfo(FixedTInfo);
9305 }
9306
9307 if (T->isVoidType()) {
9308 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9309 // of objects and functions.
9310 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9311 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9312 << T;
9313 NewVD->setInvalidDecl();
9314 return;
9315 }
9316 }
9317
9318 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9319 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9320 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9321 NewVD->setInvalidDecl();
9322 return;
9323 }
9324
9325 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9326 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9327 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9328 NewVD->setInvalidDecl();
9329 return;
9330 }
9331
9332 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9333 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9334 NewVD->setInvalidDecl();
9335 return;
9336 }
9337
9338 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9339 !T->isDependentType() &&
9340 RequireLiteralType(Loc: NewVD->getLocation(), T,
9341 DiagID: diag::err_constexpr_var_non_literal)) {
9342 NewVD->setInvalidDecl();
9343 return;
9344 }
9345
9346 // PPC MMA non-pointer types are not allowed as non-local variable types.
9347 if (Context.getTargetInfo().getTriple().isPPC64() &&
9348 !NewVD->isLocalVarDecl() &&
9349 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9350 NewVD->setInvalidDecl();
9351 return;
9352 }
9353
9354 // Check that SVE types are only used in functions with SVE available.
9355 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9356 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9357 llvm::StringMap<bool> CallerFeatureMap;
9358 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9359 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9360 FeatureMap: CallerFeatureMap)) {
9361 NewVD->setInvalidDecl();
9362 return;
9363 }
9364 }
9365
9366 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9367 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9368 llvm::StringMap<bool> CallerFeatureMap;
9369 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9370 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9371 FeatureMap: CallerFeatureMap);
9372 }
9373
9374 // Global, static or variable sized objects of HLX types are not allowed.
9375 if (Hexagon().isHLXVectorType(T) &&
9376 (NewVD->hasGlobalStorage() || T->isVariableArrayType())) {
9377 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_hlx_invalid_object);
9378 NewVD->setInvalidDecl();
9379 return;
9380 }
9381
9382 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9383 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewVD->getLocation())) {
9384 NewVD->setInvalidDecl();
9385 return;
9386 }
9387 }
9388
9389 if (T.hasAddressSpace() &&
9390 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9391 NewVD->setInvalidDecl();
9392 return;
9393 }
9394}
9395
9396bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9397 CheckVariableDeclarationType(NewVD);
9398
9399 // If the decl is already known invalid, don't check it.
9400 if (NewVD->isInvalidDecl())
9401 return false;
9402
9403 // If we did not find anything by this name, look for a non-visible
9404 // extern "C" declaration with the same name.
9405 if (Previous.empty() &&
9406 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9407 Previous.setShadowed();
9408
9409 if (!Previous.empty()) {
9410 MergeVarDecl(New: NewVD, Previous);
9411 return true;
9412 }
9413 return false;
9414}
9415
9416bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9417 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9418
9419 // Look for methods in base classes that this method might override.
9420 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9421 /*DetectVirtual=*/false);
9422 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9423 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9424 DeclarationName Name = MD->getDeclName();
9425
9426 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9427 // We really want to find the base class destructor here.
9428 Name = Context.DeclarationNames.getCXXDestructorName(
9429 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9430 }
9431
9432 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9433 CXXMethodDecl *BaseMD =
9434 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9435 if (!BaseMD || !BaseMD->isVirtual() ||
9436 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9437 /*ConsiderCudaAttrs=*/true))
9438 continue;
9439 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9440 continue;
9441 if (Overridden.insert(Ptr: BaseMD).second) {
9442 MD->addOverriddenMethod(MD: BaseMD);
9443 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9444 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9445 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9446 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9447 }
9448
9449 // A method can only override one function from each base class. We
9450 // don't track indirectly overridden methods from bases of bases.
9451 return true;
9452 }
9453
9454 return false;
9455 };
9456
9457 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9458 return !Overridden.empty();
9459}
9460
9461namespace {
9462 // Struct for holding all of the extra arguments needed by
9463 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9464 struct ActOnFDArgs {
9465 Scope *S;
9466 Declarator &D;
9467 MultiTemplateParamsArg TemplateParamLists;
9468 bool AddToScope;
9469 };
9470} // end anonymous namespace
9471
9472namespace {
9473
9474// Callback to only accept typo corrections that have a non-zero edit distance.
9475// Also only accept corrections that have the same parent decl.
9476class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9477 public:
9478 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9479 CXXRecordDecl *Parent)
9480 : Context(Context), OriginalFD(TypoFD),
9481 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9482
9483 bool ValidateCandidate(const TypoCorrection &candidate) override {
9484 if (candidate.getEditDistance() == 0)
9485 return false;
9486
9487 SmallVector<unsigned, 1> MismatchedParams;
9488 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9489 CDeclEnd = candidate.end();
9490 CDecl != CDeclEnd; ++CDecl) {
9491 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9492
9493 if (FD && !FD->hasBody() &&
9494 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9495 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9496 CXXRecordDecl *Parent = MD->getParent();
9497 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9498 return true;
9499 } else if (!ExpectedParent) {
9500 return true;
9501 }
9502 }
9503 }
9504
9505 return false;
9506 }
9507
9508 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9509 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9510 }
9511
9512 private:
9513 ASTContext &Context;
9514 FunctionDecl *OriginalFD;
9515 CXXRecordDecl *ExpectedParent;
9516};
9517
9518} // end anonymous namespace
9519
9520void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9521 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9522}
9523
9524/// Generate diagnostics for an invalid function redeclaration.
9525///
9526/// This routine handles generating the diagnostic messages for an invalid
9527/// function redeclaration, including finding possible similar declarations
9528/// or performing typo correction if there are no previous declarations with
9529/// the same name.
9530///
9531/// Returns a NamedDecl iff typo correction was performed and substituting in
9532/// the new declaration name does not cause new errors.
9533static NamedDecl *DiagnoseInvalidRedeclaration(
9534 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9535 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9536 DeclarationName Name = NewFD->getDeclName();
9537 DeclContext *NewDC = NewFD->getDeclContext();
9538 SmallVector<unsigned, 1> MismatchedParams;
9539 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9540 TypoCorrection Correction;
9541 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9542 unsigned DiagMsg =
9543 IsLocalFriend ? diag::err_no_matching_local_friend :
9544 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9545 diag::err_member_decl_does_not_match;
9546 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9547 IsLocalFriend ? Sema::LookupLocalFriendName
9548 : Sema::LookupOrdinaryName,
9549 RedeclarationKind::ForVisibleRedeclaration);
9550
9551 NewFD->setInvalidDecl();
9552 if (IsLocalFriend)
9553 SemaRef.LookupName(R&: Prev, S);
9554 else
9555 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9556 assert(!Prev.isAmbiguous() &&
9557 "Cannot have an ambiguity in previous-declaration lookup");
9558 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9559 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9560 MD ? MD->getParent() : nullptr);
9561 if (!Prev.empty()) {
9562 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9563 Func != FuncEnd; ++Func) {
9564 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9565 if (FD &&
9566 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9567 // Add 1 to the index so that 0 can mean the mismatch didn't
9568 // involve a parameter
9569 unsigned ParamNum =
9570 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9571 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9572 }
9573 }
9574 // If the qualified name lookup yielded nothing, try typo correction
9575 } else if ((Correction = SemaRef.CorrectTypo(
9576 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9577 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9578 Mode: CorrectTypoKind::ErrorRecovery,
9579 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9580 // Set up everything for the call to ActOnFunctionDeclarator
9581 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9582 IdLoc: ExtraArgs.D.getIdentifierLoc());
9583 Previous.clear();
9584 Previous.setLookupName(Correction.getCorrection());
9585 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9586 CDeclEnd = Correction.end();
9587 CDecl != CDeclEnd; ++CDecl) {
9588 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9589 if (FD && !FD->hasBody() &&
9590 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9591 Previous.addDecl(D: FD);
9592 }
9593 }
9594 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9595
9596 NamedDecl *Result;
9597 // Retry building the function declaration with the new previous
9598 // declarations, and with errors suppressed.
9599 {
9600 // Trap errors.
9601 Sema::SFINAETrap Trap(SemaRef);
9602
9603 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9604 // pieces need to verify the typo-corrected C++ declaration and hopefully
9605 // eliminate the need for the parameter pack ExtraArgs.
9606 Result = SemaRef.ActOnFunctionDeclarator(
9607 S: ExtraArgs.S, D&: ExtraArgs.D,
9608 DC: Correction.getCorrectionDecl()->getDeclContext(),
9609 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9610 AddToScope&: ExtraArgs.AddToScope);
9611
9612 if (Trap.hasErrorOccurred())
9613 Result = nullptr;
9614 }
9615
9616 if (Result) {
9617 // Determine which correction we picked.
9618 Decl *Canonical = Result->getCanonicalDecl();
9619 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9620 I != E; ++I)
9621 if ((*I)->getCanonicalDecl() == Canonical)
9622 Correction.setCorrectionDecl(*I);
9623
9624 // Let Sema know about the correction.
9625 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9626 SemaRef.diagnoseTypo(
9627 Correction,
9628 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9629 ? diag::err_no_matching_local_friend_suggest
9630 : diag::err_member_decl_does_not_match_suggest)
9631 << Name << NewDC << IsDefinition);
9632 return Result;
9633 }
9634
9635 // Pretend the typo correction never occurred
9636 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9637 IdLoc: ExtraArgs.D.getIdentifierLoc());
9638 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9639 Previous.clear();
9640 Previous.setLookupName(Name);
9641 }
9642
9643 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9644 << Name << NewDC << IsDefinition << NewFD->getLocation();
9645
9646 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9647 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9648 CXXRecordDecl *RD = NewMD->getParent();
9649 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9650 << RD->getName() << RD->getLocation();
9651 }
9652
9653 bool NewFDisConst = NewMD && NewMD->isConst();
9654
9655 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9656 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9657 NearMatch != NearMatchEnd; ++NearMatch) {
9658 FunctionDecl *FD = NearMatch->first;
9659 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9660 bool FDisConst = MD && MD->isConst();
9661 bool IsMember = MD || !IsLocalFriend;
9662
9663 // FIXME: These notes are poorly worded for the local friend case.
9664 if (unsigned Idx = NearMatch->second) {
9665 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9666 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9667 if (Loc.isInvalid()) Loc = FD->getLocation();
9668 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9669 : diag::note_local_decl_close_param_match)
9670 << Idx << FDParam->getType()
9671 << NewFD->getParamDecl(i: Idx - 1)->getType();
9672 } else if (FDisConst != NewFDisConst) {
9673 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9674 DiagID: diag::note_member_def_close_const_match)
9675 << NewFDisConst << FD->getSourceRange().getEnd();
9676 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9677 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9678 Code: " const");
9679 else if (FTI.hasMethodTypeQualifiers() &&
9680 FTI.getConstQualifierLoc().isValid())
9681 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9682 } else {
9683 SemaRef.Diag(Loc: FD->getLocation(),
9684 DiagID: IsMember ? diag::note_member_def_close_match
9685 : diag::note_local_decl_close_match);
9686 }
9687 }
9688 return nullptr;
9689}
9690
9691static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9692 switch (D.getDeclSpec().getStorageClassSpec()) {
9693 default: llvm_unreachable("Unknown storage class!");
9694 case DeclSpec::SCS_auto:
9695 case DeclSpec::SCS_register:
9696 case DeclSpec::SCS_mutable:
9697 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9698 DiagID: diag::err_typecheck_sclass_func);
9699 D.getMutableDeclSpec().ClearStorageClassSpecs();
9700 D.setInvalidType();
9701 break;
9702 case DeclSpec::SCS_unspecified: break;
9703 case DeclSpec::SCS_extern:
9704 if (D.getDeclSpec().isExternInLinkageSpec())
9705 return SC_None;
9706 return SC_Extern;
9707 case DeclSpec::SCS_static: {
9708 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9709 // C99 6.7.1p5:
9710 // The declaration of an identifier for a function that has
9711 // block scope shall have no explicit storage-class specifier
9712 // other than extern
9713 // See also (C++ [dcl.stc]p4).
9714 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9715 DiagID: diag::err_static_block_func);
9716 break;
9717 } else
9718 return SC_Static;
9719 }
9720 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9721 }
9722
9723 // No explicit storage class has already been returned
9724 return SC_None;
9725}
9726
9727static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9728 DeclContext *DC, QualType &R,
9729 TypeSourceInfo *TInfo,
9730 StorageClass SC,
9731 bool &IsVirtualOkay) {
9732 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9733 DeclarationName Name = NameInfo.getName();
9734
9735 FunctionDecl *NewFD = nullptr;
9736 bool isInline = D.getDeclSpec().isInlineSpecified();
9737
9738 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9739 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9740 (SemaRef.getLangOpts().C23 &&
9741 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9742
9743 if (SemaRef.getLangOpts().C23)
9744 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9745 DiagID: diag::err_c23_constexpr_not_variable);
9746 else
9747 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9748 DiagID: diag::err_constexpr_wrong_decl_kind)
9749 << static_cast<int>(ConstexprKind);
9750 ConstexprKind = ConstexprSpecKind::Unspecified;
9751 D.getMutableDeclSpec().ClearConstexprSpec();
9752 }
9753
9754 if (!SemaRef.getLangOpts().CPlusPlus) {
9755 // Determine whether the function was written with a prototype. This is
9756 // true when:
9757 // - there is a prototype in the declarator, or
9758 // - the type R of the function is some kind of typedef or other non-
9759 // attributed reference to a type name (which eventually refers to a
9760 // function type). Note, we can't always look at the adjusted type to
9761 // check this case because attributes may cause a non-function
9762 // declarator to still have a function type. e.g.,
9763 // typedef void func(int a);
9764 // __attribute__((noreturn)) func other_func; // This has a prototype
9765 bool HasPrototype =
9766 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9767 (D.getDeclSpec().isTypeRep() &&
9768 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9769 ->isFunctionProtoType()) ||
9770 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9771 assert(
9772 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9773 "Strict prototypes are required");
9774
9775 NewFD = FunctionDecl::Create(
9776 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9777 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9778 ConstexprKind: ConstexprSpecKind::Unspecified,
9779 /*TrailingRequiresClause=*/{});
9780 if (D.isInvalidType())
9781 NewFD->setInvalidDecl();
9782
9783 return NewFD;
9784 }
9785
9786 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9787 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9788
9789 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9790
9791 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9792 // This is a C++ constructor declaration.
9793 assert(DC->isRecord() &&
9794 "Constructors can only be declared in a member context");
9795
9796 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9797 return CXXConstructorDecl::Create(
9798 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9799 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9800 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9801 Inherited: InheritedConstructor(), TrailingRequiresClause);
9802
9803 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9804 // This is a C++ destructor declaration.
9805 if (DC->isRecord()) {
9806 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9807 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9808 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9809 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9810 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9811 /*isImplicitlyDeclared=*/false, ConstexprKind,
9812 TrailingRequiresClause);
9813 // User defined destructors start as not selected if the class definition is still
9814 // not done.
9815 if (Record->isBeingDefined())
9816 NewDD->setIneligibleOrNotSelected(true);
9817
9818 // If the destructor needs an implicit exception specification, set it
9819 // now. FIXME: It'd be nice to be able to create the right type to start
9820 // with, but the type needs to reference the destructor declaration.
9821 if (SemaRef.getLangOpts().CPlusPlus11)
9822 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9823
9824 IsVirtualOkay = true;
9825 return NewDD;
9826
9827 } else {
9828 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9829 D.setInvalidType();
9830
9831 // Create a FunctionDecl to satisfy the function definition parsing
9832 // code path.
9833 return FunctionDecl::Create(
9834 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9835 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9836 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9837 }
9838
9839 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9840 if (!DC->isRecord()) {
9841 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9842 DiagID: diag::err_conv_function_not_member);
9843 return nullptr;
9844 }
9845
9846 SemaRef.CheckConversionDeclarator(D, R, SC);
9847 if (D.isInvalidType())
9848 return nullptr;
9849
9850 IsVirtualOkay = true;
9851 return CXXConversionDecl::Create(
9852 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9853 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9854 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9855 TrailingRequiresClause);
9856
9857 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9858 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9859 return nullptr;
9860 return CXXDeductionGuideDecl::Create(
9861 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9862 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9863 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9864 } else if (DC->isRecord()) {
9865 // If the name of the function is the same as the name of the record,
9866 // then this must be an invalid constructor that has a return type.
9867 // (The parser checks for a return type and makes the declarator a
9868 // constructor if it has no return type).
9869 if (Name.getAsIdentifierInfo() &&
9870 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9871 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9872 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9873 << SourceRange(D.getIdentifierLoc());
9874 return nullptr;
9875 }
9876
9877 // This is a C++ method declaration.
9878 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9879 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9880 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9881 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9882 IsVirtualOkay = !Ret->isStatic();
9883 return Ret;
9884 } else {
9885 bool isFriend =
9886 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9887 if (!isFriend && SemaRef.CurContext->isRecord())
9888 return nullptr;
9889
9890 // Determine whether the function was written with a
9891 // prototype. This true when:
9892 // - we're in C++ (where every function has a prototype),
9893 return FunctionDecl::Create(
9894 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9895 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9896 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9897 }
9898}
9899
9900enum OpenCLParamType {
9901 ValidKernelParam,
9902 PtrPtrKernelParam,
9903 PtrKernelParam,
9904 InvalidAddrSpacePtrKernelParam,
9905 InvalidKernelParam,
9906 RecordKernelParam
9907};
9908
9909static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9910 // Size dependent types are just typedefs to normal integer types
9911 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9912 // integers other than by their names.
9913 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9914
9915 // Remove typedefs one by one until we reach a typedef
9916 // for a size dependent type.
9917 QualType DesugaredTy = Ty;
9918 do {
9919 ArrayRef<StringRef> Names(SizeTypeNames);
9920 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9921 if (Names.end() != Match)
9922 return true;
9923
9924 Ty = DesugaredTy;
9925 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9926 } while (DesugaredTy != Ty);
9927
9928 return false;
9929}
9930
9931static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9932 if (PT->isDependentType())
9933 return InvalidKernelParam;
9934
9935 if (PT->isPointerOrReferenceType()) {
9936 QualType PointeeType = PT->getPointeeType();
9937 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9938 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9939 PointeeType.getAddressSpace() == LangAS::Default)
9940 return InvalidAddrSpacePtrKernelParam;
9941
9942 if (PointeeType->isPointerType()) {
9943 // This is a pointer to pointer parameter.
9944 // Recursively check inner type.
9945 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9946 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9947 ParamKind == InvalidKernelParam)
9948 return ParamKind;
9949
9950 // OpenCL v3.0 s6.11.a:
9951 // A restriction to pass pointers to pointers only applies to OpenCL C
9952 // v1.2 or below.
9953 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9954 return ValidKernelParam;
9955
9956 return PtrPtrKernelParam;
9957 }
9958
9959 // C++ for OpenCL v1.0 s2.4:
9960 // Moreover the types used in parameters of the kernel functions must be:
9961 // Standard layout types for pointer parameters. The same applies to
9962 // reference if an implementation supports them in kernel parameters.
9963 if (S.getLangOpts().OpenCLCPlusPlus &&
9964 !S.getOpenCLOptions().isAvailableOption(
9965 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9966 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9967 bool IsStandardLayoutType = true;
9968 if (CXXRec) {
9969 // If template type is not ODR-used its definition is only available
9970 // in the template definition not its instantiation.
9971 // FIXME: This logic doesn't work for types that depend on template
9972 // parameter (PR58590).
9973 if (!CXXRec->hasDefinition())
9974 CXXRec = CXXRec->getTemplateInstantiationPattern();
9975 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9976 IsStandardLayoutType = false;
9977 }
9978 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9979 !IsStandardLayoutType)
9980 return InvalidKernelParam;
9981 }
9982
9983 // OpenCL v1.2 s6.9.p:
9984 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9985 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9986 return ValidKernelParam;
9987
9988 return PtrKernelParam;
9989 }
9990
9991 // OpenCL v1.2 s6.9.k:
9992 // Arguments to kernel functions in a program cannot be declared with the
9993 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9994 // uintptr_t or a struct and/or union that contain fields declared to be one
9995 // of these built-in scalar types.
9996 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9997 return InvalidKernelParam;
9998
9999 if (PT->isImageType())
10000 return PtrKernelParam;
10001
10002 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
10003 return InvalidKernelParam;
10004
10005 // OpenCL extension spec v1.2 s9.5:
10006 // This extension adds support for half scalar and vector types as built-in
10007 // types that can be used for arithmetic operations, conversions etc.
10008 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
10009 PT->isHalfType())
10010 return InvalidKernelParam;
10011
10012 // Look into an array argument to check if it has a forbidden type.
10013 if (PT->isArrayType()) {
10014 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
10015 // Call ourself to check an underlying type of an array. Since the
10016 // getPointeeOrArrayElementType returns an innermost type which is not an
10017 // array, this recursive call only happens once.
10018 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
10019 }
10020
10021 // C++ for OpenCL v1.0 s2.4:
10022 // Moreover the types used in parameters of the kernel functions must be:
10023 // Trivial and standard-layout types C++17 [basic.types] (plain old data
10024 // types) for parameters passed by value;
10025 if (S.getLangOpts().OpenCLCPlusPlus &&
10026 !S.getOpenCLOptions().isAvailableOption(
10027 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
10028 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
10029 return InvalidKernelParam;
10030
10031 if (PT->isRecordType())
10032 return RecordKernelParam;
10033
10034 return ValidKernelParam;
10035}
10036
10037static void checkIsValidOpenCLKernelParameter(
10038 Sema &S,
10039 Declarator &D,
10040 ParmVarDecl *Param,
10041 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
10042 QualType PT = Param->getType();
10043
10044 // Cache the valid types we encounter to avoid rechecking structs that are
10045 // used again
10046 if (ValidTypes.count(Ptr: PT.getTypePtr()))
10047 return;
10048
10049 switch (getOpenCLKernelParameterType(S, PT)) {
10050 case PtrPtrKernelParam:
10051 // OpenCL v3.0 s6.11.a:
10052 // A kernel function argument cannot be declared as a pointer to a pointer
10053 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
10054 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
10055 D.setInvalidType();
10056 return;
10057
10058 case InvalidAddrSpacePtrKernelParam:
10059 // OpenCL v1.0 s6.5:
10060 // __kernel function arguments declared to be a pointer of a type can point
10061 // to one of the following address spaces only : __global, __local or
10062 // __constant.
10063 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
10064 D.setInvalidType();
10065 return;
10066
10067 // OpenCL v1.2 s6.9.k:
10068 // Arguments to kernel functions in a program cannot be declared with the
10069 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10070 // uintptr_t or a struct and/or union that contain fields declared to be
10071 // one of these built-in scalar types.
10072
10073 case InvalidKernelParam:
10074 // OpenCL v1.2 s6.8 n:
10075 // A kernel function argument cannot be declared
10076 // of event_t type.
10077 // Do not diagnose half type since it is diagnosed as invalid argument
10078 // type for any function elsewhere.
10079 if (!PT->isHalfType()) {
10080 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10081
10082 // Explain what typedefs are involved.
10083 const TypedefType *Typedef = nullptr;
10084 while ((Typedef = PT->getAs<TypedefType>())) {
10085 SourceLocation Loc = Typedef->getDecl()->getLocation();
10086 // SourceLocation may be invalid for a built-in type.
10087 if (Loc.isValid())
10088 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
10089 PT = Typedef->desugar();
10090 }
10091 }
10092
10093 D.setInvalidType();
10094 return;
10095
10096 case PtrKernelParam:
10097 case ValidKernelParam:
10098 ValidTypes.insert(Ptr: PT.getTypePtr());
10099 return;
10100
10101 case RecordKernelParam:
10102 break;
10103 }
10104
10105 // Track nested structs we will inspect
10106 SmallVector<const Decl *, 4> VisitStack;
10107
10108 // Track where we are in the nested structs. Items will migrate from
10109 // VisitStack to HistoryStack as we do the DFS for bad field.
10110 SmallVector<const FieldDecl *, 4> HistoryStack;
10111 HistoryStack.push_back(Elt: nullptr);
10112
10113 // At this point we already handled everything except of a RecordType.
10114 assert(PT->isRecordType() && "Unexpected type.");
10115 const auto *PD = PT->castAsRecordDecl();
10116 VisitStack.push_back(Elt: PD);
10117 assert(VisitStack.back() && "First decl null?");
10118
10119 do {
10120 const Decl *Next = VisitStack.pop_back_val();
10121 if (!Next) {
10122 assert(!HistoryStack.empty());
10123 // Found a marker, we have gone up a level
10124 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10125 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
10126
10127 continue;
10128 }
10129
10130 // Adds everything except the original parameter declaration (which is not a
10131 // field itself) to the history stack.
10132 const RecordDecl *RD;
10133 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
10134 HistoryStack.push_back(Elt: Field);
10135
10136 QualType FieldTy = Field->getType();
10137 // Other field types (known to be valid or invalid) are handled while we
10138 // walk around RecordDecl::fields().
10139 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10140 "Unexpected type.");
10141 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10142
10143 RD = FieldRecTy->castAsRecordDecl();
10144 } else {
10145 RD = cast<RecordDecl>(Val: Next);
10146 }
10147
10148 // Add a null marker so we know when we've gone back up a level
10149 VisitStack.push_back(Elt: nullptr);
10150
10151 for (const auto *FD : RD->fields()) {
10152 QualType QT = FD->getType();
10153
10154 if (ValidTypes.count(Ptr: QT.getTypePtr()))
10155 continue;
10156
10157 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
10158 if (ParamType == ValidKernelParam)
10159 continue;
10160
10161 if (ParamType == RecordKernelParam) {
10162 VisitStack.push_back(Elt: FD);
10163 continue;
10164 }
10165
10166 // OpenCL v1.2 s6.9.p:
10167 // Arguments to kernel functions that are declared to be a struct or union
10168 // do not allow OpenCL objects to be passed as elements of the struct or
10169 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10170 // of SVM.
10171 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10172 ParamType == InvalidAddrSpacePtrKernelParam) {
10173 S.Diag(Loc: Param->getLocation(),
10174 DiagID: diag::err_record_with_pointers_kernel_param)
10175 << PT->isUnionType()
10176 << PT;
10177 } else {
10178 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10179 }
10180
10181 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10182 << PD->getDeclName();
10183
10184 // We have an error, now let's go back up through history and show where
10185 // the offending field came from
10186 for (ArrayRef<const FieldDecl *>::const_iterator
10187 I = HistoryStack.begin() + 1,
10188 E = HistoryStack.end();
10189 I != E; ++I) {
10190 const FieldDecl *OuterField = *I;
10191 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10192 << OuterField->getType();
10193 }
10194
10195 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10196 << QT->isPointerType()
10197 << QT;
10198 D.setInvalidType();
10199 return;
10200 }
10201 } while (!VisitStack.empty());
10202}
10203
10204/// Find the DeclContext in which a tag is implicitly declared if we see an
10205/// elaborated type specifier in the specified context, and lookup finds
10206/// nothing.
10207static DeclContext *getTagInjectionContext(DeclContext *DC) {
10208 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10209 DC = DC->getParent();
10210 return DC;
10211}
10212
10213/// Find the Scope in which a tag is implicitly declared if we see an
10214/// elaborated type specifier in the specified context, and lookup finds
10215/// nothing.
10216static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10217 while (S->isClassScope() ||
10218 (LangOpts.CPlusPlus &&
10219 S->isFunctionPrototypeScope()) ||
10220 ((S->getFlags() & Scope::DeclScope) == 0) ||
10221 (S->getEntity() && S->getEntity()->isTransparentContext()))
10222 S = S->getParent();
10223 return S;
10224}
10225
10226/// Determine whether a declaration matches a known function in namespace std.
10227static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10228 unsigned BuiltinID) {
10229 switch (BuiltinID) {
10230 case Builtin::BI__GetExceptionInfo:
10231 // No type checking whatsoever.
10232 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10233
10234 case Builtin::BIaddressof:
10235 case Builtin::BI__addressof:
10236 case Builtin::BIforward:
10237 case Builtin::BIforward_like:
10238 case Builtin::BImove:
10239 case Builtin::BImove_if_noexcept:
10240 case Builtin::BIas_const: {
10241 // Ensure that we don't treat the algorithm
10242 // OutputIt std::move(InputIt, InputIt, OutputIt)
10243 // as the builtin std::move.
10244 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10245 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10246 }
10247
10248 default:
10249 return false;
10250 }
10251}
10252
10253void Sema::addImplicitCallingConvAbiTag(FunctionDecl *FD) {
10254 const auto *FT = FD->getType()->getAs<FunctionType>();
10255 if (!FT)
10256 return;
10257
10258 StringRef Tag;
10259 switch (FT->getCallConv()) {
10260#define CC_VLS_CASE(ABI_VLEN) \
10261 case CC_RISCVVLSCall_##ABI_VLEN: \
10262 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10263 break;
10264 CC_VLS_CASE(32)
10265 CC_VLS_CASE(64)
10266 CC_VLS_CASE(128)
10267 CC_VLS_CASE(256)
10268 CC_VLS_CASE(512)
10269 CC_VLS_CASE(1024)
10270 CC_VLS_CASE(2048)
10271 CC_VLS_CASE(4096)
10272 CC_VLS_CASE(8192)
10273 CC_VLS_CASE(16384)
10274 CC_VLS_CASE(32768)
10275 CC_VLS_CASE(65536)
10276#undef CC_VLS_CASE
10277 default:
10278 return;
10279 }
10280
10281 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10282 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10283
10284 SmallVector<StringRef, 4> Tags;
10285 if (Old)
10286 llvm::append_range(C&: Tags, R: Old->tags());
10287 if (llvm::is_contained(Range&: Tags, Element: Tag))
10288 return;
10289 Tags.push_back(Elt: Tag);
10290
10291 AbiTagAttr *Merged =
10292 Old ? AbiTagAttr::Create(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(), CommonInfo: *Old)
10293 : AbiTagAttr::CreateImplicit(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(),
10294 Range: FD->getLocation());
10295 FD->dropAttr<AbiTagAttr>();
10296 FD->addAttr(A: Merged);
10297 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10298 FD->addAttr(A: Existing[I]);
10299}
10300
10301NamedDecl*
10302Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10303 TypeSourceInfo *TInfo, LookupResult &Previous,
10304 MultiTemplateParamsArg TemplateParamListsRef,
10305 bool &AddToScope) {
10306 QualType R = TInfo->getType();
10307
10308 assert(R->isFunctionType());
10309 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10310 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10311
10312 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10313 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10314 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10315 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10316 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10317 TemplateParamLists.back() = Invented;
10318 else
10319 TemplateParamLists.push_back(Elt: Invented);
10320 }
10321
10322 // TODO: consider using NameInfo for diagnostic.
10323 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10324 DeclarationName Name = NameInfo.getName();
10325 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10326
10327 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10328 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10329 DiagID: diag::err_invalid_thread)
10330 << DeclSpec::getSpecifierName(S: TSCS);
10331
10332 if (D.isFirstDeclarationOfMember())
10333 adjustMemberFunctionCC(
10334 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10335 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10336
10337 bool isFriend = false;
10338 FunctionTemplateDecl *FunctionTemplate = nullptr;
10339 bool isMemberSpecialization = false;
10340 bool isFunctionTemplateSpecialization = false;
10341
10342 bool HasExplicitTemplateArgs = false;
10343 TemplateArgumentListInfo TemplateArgs;
10344
10345 bool isVirtualOkay = false;
10346
10347 DeclContext *OriginalDC = DC;
10348 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10349
10350 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10351 IsVirtualOkay&: isVirtualOkay);
10352 if (!NewFD) return nullptr;
10353
10354 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10355 NewFD->setTopLevelDeclInObjCContainer();
10356
10357 // Set the lexical context. If this is a function-scope declaration, or has a
10358 // C++ scope specifier, or is the object of a friend declaration, the lexical
10359 // context will be different from the semantic context.
10360 NewFD->setLexicalDeclContext(CurContext);
10361
10362 if (IsLocalExternDecl)
10363 NewFD->setLocalExternDecl();
10364
10365 if (getLangOpts().CPlusPlus) {
10366 // The rules for implicit inlines changed in C++20 for methods and friends
10367 // with an in-class definition (when such a definition is not attached to
10368 // the global module). This does not affect declarations that are already
10369 // inline (whether explicitly or implicitly by being declared constexpr,
10370 // consteval, etc).
10371 // FIXME: We need a better way to separate C++ standard and clang modules.
10372 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10373 !NewFD->getOwningModule() ||
10374 NewFD->isFromGlobalModule() ||
10375 NewFD->getOwningModule()->isHeaderLikeModule();
10376 bool isInline = D.getDeclSpec().isInlineSpecified();
10377 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10378 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10379 isFriend = D.getDeclSpec().isFriendSpecified();
10380 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10381 // Pre-C++20 [class.friend]p5
10382 // A function can be defined in a friend declaration of a
10383 // class . . . . Such a function is implicitly inline.
10384 // Post C++20 [class.friend]p7
10385 // Such a function is implicitly an inline function if it is attached
10386 // to the global module.
10387 NewFD->setImplicitlyInline();
10388 }
10389
10390 // If this is a method defined in an __interface, and is not a constructor
10391 // or an overloaded operator, then set the pure flag (isVirtual will already
10392 // return true).
10393 if (const CXXRecordDecl *Parent =
10394 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10395 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10396 NewFD->setIsPureVirtual(true);
10397
10398 // C++ [class.union]p2
10399 // A union can have member functions, but not virtual functions.
10400 if (isVirtual && Parent->isUnion()) {
10401 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10402 NewFD->setInvalidDecl();
10403 }
10404 if ((Parent->isClass() || Parent->isStruct()) &&
10405 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10406 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10407 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10408 if (auto *Def = Parent->getDefinition())
10409 Def->setInitMethod(true);
10410 }
10411 }
10412
10413 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10414 isMemberSpecialization = false;
10415 isFunctionTemplateSpecialization = false;
10416 if (D.isInvalidType())
10417 NewFD->setInvalidDecl();
10418
10419 // Match up the template parameter lists with the scope specifier, then
10420 // determine whether we have a template or a template specialization.
10421 bool Invalid = false;
10422 TemplateIdAnnotation *TemplateId =
10423 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10424 ? D.getName().TemplateId
10425 : nullptr;
10426 TemplateParameterList *TemplateParams =
10427 MatchTemplateParametersToScopeSpecifier(
10428 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10429 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10430 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10431 if (TemplateParams) {
10432 // Check that we can declare a template here.
10433 if (CheckTemplateDeclScope(S, TemplateParams))
10434 NewFD->setInvalidDecl();
10435
10436 if (TemplateParams->size() > 0) {
10437 // This is a function template
10438
10439 // A destructor cannot be a template.
10440 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10441 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10442 NewFD->setInvalidDecl();
10443 // Function template with explicit template arguments.
10444 } else if (TemplateId) {
10445 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10446 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10447 NewFD->setInvalidDecl();
10448 }
10449
10450 // If we're adding a template to a dependent context, we may need to
10451 // rebuilding some of the types used within the template parameter list,
10452 // now that we know what the current instantiation is.
10453 if (DC->isDependentContext()) {
10454 ContextRAII SavedContext(*this, DC);
10455 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10456 Invalid = true;
10457 }
10458
10459 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10460 L: NewFD->getLocation(),
10461 Name, Params: TemplateParams,
10462 Decl: NewFD);
10463 FunctionTemplate->setLexicalDeclContext(CurContext);
10464 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10465
10466 // For source fidelity, store the other template param lists.
10467 if (TemplateParamLists.size() > 1) {
10468 NewFD->setTemplateParameterListsInfo(Context,
10469 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10470 .drop_back(N: 1));
10471 }
10472 } else {
10473 // This is a function template specialization.
10474 isFunctionTemplateSpecialization = true;
10475 // For source fidelity, store all the template param lists.
10476 if (TemplateParamLists.size() > 0)
10477 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10478
10479 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10480 if (isFriend) {
10481 // We want to remove the "template<>", found here.
10482 SourceRange RemoveRange = TemplateParams->getSourceRange();
10483
10484 // If we remove the template<> and the name is not a
10485 // template-id, we're actually silently creating a problem:
10486 // the friend declaration will refer to an untemplated decl,
10487 // and clearly the user wants a template specialization. So
10488 // we need to insert '<>' after the name.
10489 SourceLocation InsertLoc;
10490 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10491 InsertLoc = D.getName().getSourceRange().getEnd();
10492 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10493 }
10494
10495 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10496 << Name << RemoveRange
10497 << FixItHint::CreateRemoval(RemoveRange)
10498 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10499 Invalid = true;
10500
10501 // Recover by faking up an empty template argument list.
10502 HasExplicitTemplateArgs = true;
10503 TemplateArgs.setLAngleLoc(InsertLoc);
10504 TemplateArgs.setRAngleLoc(InsertLoc);
10505 }
10506 }
10507 } else {
10508 // Check that we can declare a template here.
10509 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10510 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10511 NewFD->setInvalidDecl();
10512
10513 // All template param lists were matched against the scope specifier:
10514 // this is NOT (an explicit specialization of) a template.
10515 if (TemplateParamLists.size() > 0)
10516 // For source fidelity, store all the template param lists.
10517 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10518
10519 // "friend void foo<>(int);" is an implicit specialization decl.
10520 if (isFriend && TemplateId)
10521 isFunctionTemplateSpecialization = true;
10522 }
10523
10524 // If this is a function template specialization and the unqualified-id of
10525 // the declarator-id is a template-id, convert the template argument list
10526 // into our AST format and check for unexpanded packs.
10527 if (isFunctionTemplateSpecialization && TemplateId) {
10528 HasExplicitTemplateArgs = true;
10529
10530 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10531 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10532 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10533 TemplateId->NumArgs);
10534 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10535
10536 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10537 // declaration of a function template partial specialization? Should we
10538 // consider the unexpanded pack context to be a partial specialization?
10539 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10540 if (DiagnoseUnexpandedParameterPack(
10541 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10542 : UPPC_ExplicitSpecialization))
10543 NewFD->setInvalidDecl();
10544 }
10545 }
10546
10547 if (Invalid) {
10548 NewFD->setInvalidDecl();
10549 if (FunctionTemplate)
10550 FunctionTemplate->setInvalidDecl();
10551 }
10552
10553 // C++ [dcl.fct.spec]p5:
10554 // The virtual specifier shall only be used in declarations of
10555 // nonstatic class member functions that appear within a
10556 // member-specification of a class declaration; see 10.3.
10557 //
10558 if (isVirtual && !NewFD->isInvalidDecl()) {
10559 if (!isVirtualOkay) {
10560 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10561 DiagID: diag::err_virtual_non_function);
10562 } else if (!CurContext->isRecord()) {
10563 // 'virtual' was specified outside of the class.
10564 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10565 DiagID: diag::err_virtual_out_of_class)
10566 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10567 } else if (NewFD->getDescribedFunctionTemplate()) {
10568 // C++ [temp.mem]p3:
10569 // A member function template shall not be virtual.
10570 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10571 DiagID: diag::err_virtual_member_function_template)
10572 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10573 } else {
10574 // Okay: Add virtual to the method.
10575 NewFD->setVirtualAsWritten(true);
10576 }
10577
10578 if (getLangOpts().CPlusPlus14 &&
10579 NewFD->getReturnType()->isUndeducedType())
10580 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10581 }
10582
10583 // C++ [dcl.fct.spec]p3:
10584 // The inline specifier shall not appear on a block scope function
10585 // declaration.
10586 if (isInline && !NewFD->isInvalidDecl()) {
10587 if (CurContext->isFunctionOrMethod()) {
10588 // 'inline' is not allowed on block scope function declaration.
10589 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10590 DiagID: diag::err_inline_declaration_block_scope) << Name
10591 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10592 }
10593 }
10594
10595 // C++ [dcl.fct.spec]p6:
10596 // The explicit specifier shall be used only in the declaration of a
10597 // constructor or conversion function within its class definition;
10598 // see 12.3.1 and 12.3.2.
10599 if (hasExplicit && !NewFD->isInvalidDecl() &&
10600 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10601 if (!CurContext->isRecord()) {
10602 // 'explicit' was specified outside of the class.
10603 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10604 DiagID: diag::err_explicit_out_of_class)
10605 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10606 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10607 !isa<CXXConversionDecl>(Val: NewFD)) {
10608 // 'explicit' was specified on a function that wasn't a constructor
10609 // or conversion function.
10610 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10611 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10612 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10613 }
10614 }
10615
10616 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10617 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10618 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10619 // are implicitly inline.
10620 NewFD->setImplicitlyInline();
10621
10622 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10623 // be either constructors or to return a literal type. Therefore,
10624 // destructors cannot be declared constexpr.
10625 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10626 (!getLangOpts().CPlusPlus20 ||
10627 ConstexprKind == ConstexprSpecKind::Consteval)) {
10628 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10629 << static_cast<int>(ConstexprKind);
10630 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10631 ? ConstexprSpecKind::Unspecified
10632 : ConstexprSpecKind::Constexpr);
10633 }
10634 // C++20 [dcl.constexpr]p2: An allocation function, or a
10635 // deallocation function shall not be declared with the consteval
10636 // specifier.
10637 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10638 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10639 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10640 DiagID: diag::err_invalid_consteval_decl_kind)
10641 << NewFD;
10642 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10643 }
10644 }
10645
10646 // If __module_private__ was specified, mark the function accordingly.
10647 if (D.getDeclSpec().isModulePrivateSpecified()) {
10648 if (isFunctionTemplateSpecialization) {
10649 SourceLocation ModulePrivateLoc
10650 = D.getDeclSpec().getModulePrivateSpecLoc();
10651 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10652 << 0
10653 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10654 } else {
10655 NewFD->setModulePrivate();
10656 if (FunctionTemplate)
10657 FunctionTemplate->setModulePrivate();
10658 }
10659 }
10660
10661 if (isFriend) {
10662 if (FunctionTemplate) {
10663 FunctionTemplate->setObjectOfFriendDecl();
10664 FunctionTemplate->setAccess(AS_public);
10665 }
10666 NewFD->setObjectOfFriendDecl();
10667 NewFD->setAccess(AS_public);
10668 }
10669
10670 // If a function is defined as defaulted or deleted, mark it as such now.
10671 // We'll do the relevant checks on defaulted / deleted functions later.
10672 switch (D.getFunctionDefinitionKind()) {
10673 case FunctionDefinitionKind::Declaration:
10674 case FunctionDefinitionKind::Definition:
10675 break;
10676
10677 case FunctionDefinitionKind::Defaulted:
10678 NewFD->setDefaulted();
10679 break;
10680
10681 case FunctionDefinitionKind::Deleted:
10682 NewFD->setDeletedAsWritten();
10683 break;
10684 }
10685
10686 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10687 D.isFunctionDefinition()) {
10688 // Pre C++20 [class.mfct]p2:
10689 // A member function may be defined (8.4) in its class definition, in
10690 // which case it is an inline member function (7.1.2)
10691 // Post C++20 [class.mfct]p1:
10692 // If a member function is attached to the global module and is defined
10693 // in its class definition, it is inline.
10694 NewFD->setImplicitlyInline();
10695 }
10696
10697 if (!isFriend && SC != SC_None) {
10698 // C++ [temp.expl.spec]p2:
10699 // The declaration in an explicit-specialization shall not be an
10700 // export-declaration. An explicit specialization shall not use a
10701 // storage-class-specifier other than thread_local.
10702 //
10703 // We diagnose friend declarations with storage-class-specifiers
10704 // elsewhere.
10705 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10706 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10707 DiagID: diag::ext_explicit_specialization_storage_class)
10708 << FixItHint::CreateRemoval(
10709 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10710 }
10711
10712 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10713 assert(isa<CXXMethodDecl>(NewFD) &&
10714 "Out-of-line member function should be a CXXMethodDecl");
10715 // C++ [class.static]p1:
10716 // A data or function member of a class may be declared static
10717 // in a class definition, in which case it is a static member of
10718 // the class.
10719
10720 // Complain about the 'static' specifier if it's on an out-of-line
10721 // member function definition.
10722
10723 // MSVC permits the use of a 'static' storage specifier on an
10724 // out-of-line member function template declaration and class member
10725 // template declaration (MSVC versions before 2015), warn about this.
10726 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10727 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10728 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10729 (getLangOpts().MSVCCompat &&
10730 NewFD->getDescribedFunctionTemplate()))
10731 ? diag::ext_static_out_of_line
10732 : diag::err_static_out_of_line)
10733 << FixItHint::CreateRemoval(
10734 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10735 }
10736 }
10737
10738 // C++11 [except.spec]p15:
10739 // A deallocation function with no exception-specification is treated
10740 // as if it were specified with noexcept(true).
10741 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10742 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10743 !FPT->hasExceptionSpec())
10744 NewFD->setType(Context.getFunctionType(
10745 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10746 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10747
10748 // C++20 [dcl.inline]/7
10749 // If an inline function or variable that is attached to a named module
10750 // is declared in a definition domain, it shall be defined in that
10751 // domain.
10752 // So, if the current declaration does not have a definition, we must
10753 // check at the end of the TU (or when the PMF starts) to see that we
10754 // have a definition at that point.
10755 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10756 NewFD->isInNamedModule()) {
10757 PendingInlineFuncDecls.insert(Ptr: NewFD);
10758 }
10759 }
10760
10761 // Filter out previous declarations that don't match the scope.
10762 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10763 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10764 isMemberSpecialization ||
10765 isFunctionTemplateSpecialization);
10766
10767 LoadExternalExtnameUndeclaredIdentifiers();
10768
10769 // Handle GNU asm-label extension (encoded as an attribute).
10770 if (Expr *E = D.getAsmLabel()) {
10771 // The parser guarantees this is a string.
10772 StringLiteral *SE = cast<StringLiteral>(Val: E);
10773 NewFD->addAttr(
10774 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10775 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10776 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10777 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10778 if (I != ExtnameUndeclaredIdentifiers.end()) {
10779 if (isDeclExternC(D: NewFD)) {
10780 NewFD->addAttr(A: I->second);
10781 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10782 } else if (NewFD->getDeclContext()
10783 ->getRedeclContext()
10784 ->isTranslationUnit())
10785 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10786 << /*Variable*/0 << NewFD;
10787 }
10788 }
10789
10790 // Copy the parameter declarations from the declarator D to the function
10791 // declaration NewFD, if they are available. First scavenge them into Params.
10792 SmallVector<ParmVarDecl*, 16> Params;
10793 unsigned FTIIdx;
10794 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10795 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10796
10797 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10798 // function that takes no arguments, not a function that takes a
10799 // single void argument.
10800 // We let through "const void" here because Sema::GetTypeForDeclarator
10801 // already checks for that case.
10802 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10803 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10804 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10805 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10806 Param->setDeclContext(NewFD);
10807 Params.push_back(Elt: Param);
10808
10809 if (Param->isInvalidDecl())
10810 NewFD->setInvalidDecl();
10811 }
10812 }
10813
10814 if (!getLangOpts().CPlusPlus) {
10815 // In C, find all the tag declarations from the prototype and move them
10816 // into the function DeclContext. Remove them from the surrounding tag
10817 // injection context of the function, which is typically but not always
10818 // the TU.
10819 DeclContext *PrototypeTagContext =
10820 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10821 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10822 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10823
10824 // We don't want to reparent enumerators. Look at their parent enum
10825 // instead.
10826 if (!TD) {
10827 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10828 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10829 }
10830 if (!TD)
10831 continue;
10832 DeclContext *TagDC = TD->getLexicalDeclContext();
10833 if (!TagDC->containsDecl(D: TD))
10834 continue;
10835 TagDC->removeDecl(D: TD);
10836 TD->setDeclContext(NewFD);
10837 NewFD->addDecl(D: TD);
10838
10839 // Preserve the lexical DeclContext if it is not the surrounding tag
10840 // injection context of the FD. In this example, the semantic context of
10841 // E will be f and the lexical context will be S, while both the
10842 // semantic and lexical contexts of S will be f:
10843 // void f(struct S { enum E { a } f; } s);
10844 if (TagDC != PrototypeTagContext)
10845 TD->setLexicalDeclContext(TagDC);
10846 }
10847 }
10848 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10849 // When we're declaring a function with a typedef, typeof, etc as in the
10850 // following example, we'll need to synthesize (unnamed)
10851 // parameters for use in the declaration.
10852 //
10853 // @code
10854 // typedef void fn(int);
10855 // fn f;
10856 // @endcode
10857
10858 // Synthesize a parameter for each argument type.
10859 for (const auto &AI : FT->param_types()) {
10860 ParmVarDecl *Param =
10861 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10862 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10863 Params.push_back(Elt: Param);
10864 }
10865 } else {
10866 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10867 "Should not need args for typedef of non-prototype fn");
10868 }
10869
10870 // Finally, we know we have the right number of parameters, install them.
10871 NewFD->setParams(Params);
10872
10873 // If this declarator is a declaration and not a definition, its parameters
10874 // will not be pushed onto a scope chain. That means we will not issue any
10875 // reserved identifier warnings for the declaration, but we will for the
10876 // definition. Handle those here.
10877 if (!D.isFunctionDefinition()) {
10878 for (const ParmVarDecl *PVD : Params)
10879 warnOnReservedIdentifier(D: PVD);
10880 }
10881
10882 if (D.getDeclSpec().isNoreturnSpecified())
10883 NewFD->addAttr(
10884 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10885
10886 // Functions returning a variably modified type violate C99 6.7.5.2p2
10887 // because all functions have linkage.
10888 if (!NewFD->isInvalidDecl() &&
10889 NewFD->getReturnType()->isVariablyModifiedType()) {
10890 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10891 NewFD->setInvalidDecl();
10892 }
10893
10894 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10895 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10896 !NewFD->hasAttr<SectionAttr>())
10897 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10898 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10899 Range: PragmaClangTextSection.PragmaLocation));
10900
10901 // Apply an implicit SectionAttr if #pragma code_seg is active.
10902 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10903 !NewFD->hasAttr<SectionAttr>()) {
10904 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10905 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10906 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10907 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10908 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10909 ASTContext::PSF_Read,
10910 TheDecl: NewFD))
10911 NewFD->dropAttr<SectionAttr>();
10912 }
10913
10914 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10915 // active.
10916 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10917 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10918 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10919 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10920
10921 // Apply an implicit CodeSegAttr from class declspec or
10922 // apply an implicit SectionAttr from #pragma code_seg if active.
10923 if (!NewFD->hasAttr<CodeSegAttr>()) {
10924 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10925 IsDefinition: D.isFunctionDefinition())) {
10926 NewFD->addAttr(A: SAttr);
10927 }
10928 }
10929
10930 // Handle attributes.
10931 ProcessDeclAttributes(S, D: NewFD, PD: D);
10932 addImplicitCallingConvAbiTag(FD: NewFD);
10933 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10934 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10935 !NewTVA->isDefaultVersion() &&
10936 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10937 // Don't add to scope fmv functions declarations if fmv disabled
10938 AddToScope = false;
10939 return NewFD;
10940 }
10941
10942 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10943 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10944 // type.
10945 //
10946 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10947 // type declaration will generate a compilation error.
10948 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10949 if (AddressSpace != LangAS::Default) {
10950 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10951 NewFD->setInvalidDecl();
10952 }
10953 }
10954
10955 if (!getLangOpts().CPlusPlus) {
10956 // Perform semantic checking on the function declaration.
10957 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10958 CheckMain(FD: NewFD, D: D.getDeclSpec());
10959
10960 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10961 CheckMSVCRTEntryPoint(FD: NewFD);
10962
10963 if (!NewFD->isInvalidDecl())
10964 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10965 IsMemberSpecialization: isMemberSpecialization,
10966 DeclIsDefn: D.isFunctionDefinition()));
10967 else if (!Previous.empty())
10968 // Recover gracefully from an invalid redeclaration.
10969 D.setRedeclaration(true);
10970 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10971 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10972 "previous declaration set still overloaded");
10973
10974 // Diagnose no-prototype function declarations with calling conventions that
10975 // don't support variadic calls. Only do this in C and do it after merging
10976 // possibly prototyped redeclarations.
10977 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10978 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10979 CallingConv CC = FT->getExtInfo().getCC();
10980 if (!supportsVariadicCall(CC)) {
10981 // Windows system headers sometimes accidentally use stdcall without
10982 // (void) parameters, so we relax this to a warning.
10983 int DiagID =
10984 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10985 Diag(Loc: NewFD->getLocation(), DiagID)
10986 << FunctionType::getNameForCallConv(CC);
10987 }
10988 }
10989
10990 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10991 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10992 checkNonTrivialCUnion(
10993 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10994 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10995 } else {
10996 // C++11 [replacement.functions]p3:
10997 // The program's definitions shall not be specified as inline.
10998 //
10999 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
11000 //
11001 // Suppress the diagnostic if the function is __attribute__((used)), since
11002 // that forces an external definition to be emitted.
11003 if (D.getDeclSpec().isInlineSpecified() &&
11004 NewFD->isReplaceableGlobalAllocationFunction() &&
11005 !NewFD->hasAttr<UsedAttr>())
11006 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
11007 DiagID: diag::ext_operator_new_delete_declared_inline)
11008 << NewFD->getDeclName();
11009
11010 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
11011 // C++20 [dcl.decl.general]p4:
11012 // The optional requires-clause in an init-declarator or
11013 // member-declarator shall be present only if the declarator declares a
11014 // templated function.
11015 //
11016 // C++20 [temp.pre]p8:
11017 // An entity is templated if it is
11018 // - a template,
11019 // - an entity defined or created in a templated entity,
11020 // - a member of a templated entity,
11021 // - an enumerator for an enumeration that is a templated entity, or
11022 // - the closure type of a lambda-expression appearing in the
11023 // declaration of a templated entity.
11024 //
11025 // [Note 6: A local class, a local or block variable, or a friend
11026 // function defined in a templated entity is a templated entity.
11027 // — end note]
11028 //
11029 // A templated function is a function template or a function that is
11030 // templated. A templated class is a class template or a class that is
11031 // templated. A templated variable is a variable template or a variable
11032 // that is templated.
11033 if (!FunctionTemplate) {
11034 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
11035 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
11036 // An explicit specialization shall not have a trailing
11037 // requires-clause unless it declares a function template.
11038 //
11039 // Since a friend function template specialization cannot be
11040 // definition, and since a non-template friend declaration with a
11041 // trailing requires-clause must be a definition, we diagnose
11042 // friend function template specializations with trailing
11043 // requires-clauses on the same path as explicit specializations
11044 // even though they aren't necessarily prohibited by the same
11045 // language rule.
11046 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
11047 << isFriend;
11048 } else if (isFriend && NewFD->isTemplated() &&
11049 !D.isFunctionDefinition()) {
11050 // C++ [temp.friend]p9:
11051 // A non-template friend declaration with a requires-clause shall be
11052 // a definition.
11053 Diag(Loc: NewFD->getBeginLoc(),
11054 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
11055 NewFD->setInvalidDecl();
11056 } else if (!NewFD->isTemplated() ||
11057 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
11058 Diag(Loc: TRC->getBeginLoc(),
11059 DiagID: diag::err_constrained_non_templated_function);
11060 }
11061 }
11062 }
11063
11064 // We do not add HD attributes to specializations here because
11065 // they may have different constexpr-ness compared to their
11066 // templates and, after maybeAddHostDeviceAttrs() is applied,
11067 // may end up with different effective targets. Instead, a
11068 // specialization inherits its target attributes from its template
11069 // in the CheckFunctionTemplateSpecialization() call below.
11070 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11071 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
11072
11073 // Handle explicit specializations of function templates
11074 // and friend function declarations with an explicit
11075 // template argument list.
11076 if (isFunctionTemplateSpecialization) {
11077 bool isDependentSpecialization = false;
11078 if (isFriend) {
11079 // For friend function specializations, this is a dependent
11080 // specialization if its semantic context is dependent, its
11081 // qualifier is dependent, its type is dependent, or its template-id is
11082 // dependent.
11083 isDependentSpecialization =
11084 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11085 NewFD->getType()->isDependentType() ||
11086 (HasExplicitTemplateArgs &&
11087 TemplateSpecializationType::
11088 anyInstantiationDependentTemplateArguments(
11089 Args: TemplateArgs.arguments()));
11090 assert((!isDependentSpecialization ||
11091 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11092 "dependent friend function specialization without template "
11093 "args");
11094 } else {
11095 // For class-scope explicit specializations of function templates,
11096 // if the lexical context is dependent, then the specialization
11097 // is dependent.
11098 isDependentSpecialization =
11099 CurContext->isRecord() && CurContext->isDependentContext();
11100 }
11101
11102 TemplateArgumentListInfo *ExplicitTemplateArgs =
11103 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11104 if (isDependentSpecialization) {
11105 // If it's a dependent specialization, it may not be possible
11106 // to determine the primary template (for explicit specializations)
11107 // or befriended declaration (for friends) until the enclosing
11108 // template is instantiated. In such cases, we store the declarations
11109 // found by name lookup and defer resolution until instantiation.
11110 if (CheckDependentFunctionTemplateSpecialization(
11111 FD: NewFD, ExplicitTemplateArgs, Previous))
11112 NewFD->setInvalidDecl();
11113 } else if (!NewFD->isInvalidDecl()) {
11114 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
11115 Previous))
11116 NewFD->setInvalidDecl();
11117 }
11118 } else if (isMemberSpecialization && !FunctionTemplate) {
11119 if (CheckMemberSpecialization(Member: NewFD, Previous))
11120 NewFD->setInvalidDecl();
11121 }
11122
11123 // Perform semantic checking on the function declaration.
11124 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11125 CheckMain(FD: NewFD, D: D.getDeclSpec());
11126
11127 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11128 CheckMSVCRTEntryPoint(FD: NewFD);
11129
11130 if (!NewFD->isInvalidDecl())
11131 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
11132 IsMemberSpecialization: isMemberSpecialization,
11133 DeclIsDefn: D.isFunctionDefinition()));
11134 else if (!Previous.empty())
11135 // Recover gracefully from an invalid redeclaration.
11136 D.setRedeclaration(true);
11137
11138 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11139 !D.isRedeclaration() ||
11140 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11141 "previous declaration set still overloaded");
11142
11143 NamedDecl *PrincipalDecl = (FunctionTemplate
11144 ? cast<NamedDecl>(Val: FunctionTemplate)
11145 : NewFD);
11146
11147 if (isFriend && NewFD->getPreviousDecl()) {
11148 AccessSpecifier Access = AS_public;
11149 if (!NewFD->isInvalidDecl())
11150 Access = NewFD->getPreviousDecl()->getAccess();
11151
11152 NewFD->setAccess(Access);
11153 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11154 }
11155
11156 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11157 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
11158 PrincipalDecl->setNonMemberOperator();
11159
11160 // If we have a function template, check the template parameter
11161 // list. This will check and merge default template arguments.
11162 if (FunctionTemplate) {
11163 FunctionTemplateDecl *PrevTemplate =
11164 FunctionTemplate->getPreviousDecl();
11165 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
11166 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
11167 : nullptr,
11168 TPC: D.getDeclSpec().isFriendSpecified()
11169 ? (D.isFunctionDefinition()
11170 ? TPC_FriendFunctionTemplateDefinition
11171 : TPC_FriendFunctionTemplate)
11172 : (D.getCXXScopeSpec().isSet() &&
11173 DC && DC->isRecord() &&
11174 DC->isDependentContext())
11175 ? TPC_ClassTemplateMember
11176 : TPC_FunctionTemplate);
11177 }
11178
11179 if (NewFD->isInvalidDecl()) {
11180 // Ignore all the rest of this.
11181 } else if (!D.isRedeclaration()) {
11182 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
11183 .AddToScope: AddToScope };
11184 // Fake up an access specifier if it's supposed to be a class member.
11185 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
11186 NewFD->setAccess(AS_public);
11187
11188 // Qualified decls generally require a previous declaration.
11189 if (D.getCXXScopeSpec().isSet()) {
11190 // ...with the major exception of templated-scope or
11191 // dependent-scope friend declarations.
11192
11193 // TODO: we currently also suppress this check in dependent
11194 // contexts because (1) the parameter depth will be off when
11195 // matching friend templates and (2) we might actually be
11196 // selecting a friend based on a dependent factor. But there
11197 // are situations where these conditions don't apply and we
11198 // can actually do this check immediately.
11199 //
11200 // Unless the scope is dependent, it's always an error if qualified
11201 // redeclaration lookup found nothing at all. Diagnose that now;
11202 // nothing will diagnose that error later.
11203 if (isFriend &&
11204 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
11205 (!Previous.empty() && CurContext->isDependentContext()))) {
11206 // ignore these
11207 } else if (NewFD->isCPUDispatchMultiVersion() ||
11208 NewFD->isCPUSpecificMultiVersion()) {
11209 // ignore this, we allow the redeclaration behavior here to create new
11210 // versions of the function.
11211 } else {
11212 // The user tried to provide an out-of-line definition for a
11213 // function that is a member of a class or namespace, but there
11214 // was no such member function declared (C++ [class.mfct]p2,
11215 // C++ [namespace.memdef]p2). For example:
11216 //
11217 // class X {
11218 // void f() const;
11219 // };
11220 //
11221 // void X::f() { } // ill-formed
11222 //
11223 // Complain about this problem, and attempt to suggest close
11224 // matches (e.g., those that differ only in cv-qualifiers and
11225 // whether the parameter types are references).
11226
11227 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11228 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11229 AddToScope = ExtraArgs.AddToScope;
11230 return Result;
11231 }
11232 }
11233
11234 // Unqualified local friend declarations are required to resolve
11235 // to something.
11236 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11237 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11238 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11239 AddToScope = ExtraArgs.AddToScope;
11240 return Result;
11241 }
11242 }
11243 } else if (!D.isFunctionDefinition() &&
11244 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11245 !isFriend && !isFunctionTemplateSpecialization &&
11246 !isMemberSpecialization) {
11247 // An out-of-line member function declaration must also be a
11248 // definition (C++ [class.mfct]p2).
11249 // Note that this is not the case for explicit specializations of
11250 // function templates or member functions of class templates, per
11251 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11252 // extension for compatibility with old SWIG code which likes to
11253 // generate them.
11254 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11255 << D.getCXXScopeSpec().getRange();
11256 }
11257 }
11258
11259 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11260 // Any top level function could potentially be specified as an entry.
11261 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11262 HLSL().ActOnTopLevelFunction(FD: NewFD);
11263
11264 if (NewFD->hasAttr<HLSLShaderAttr>())
11265 HLSL().CheckEntryPoint(FD: NewFD);
11266
11267 // Resources cannot be passed to functions that are not inlined.
11268 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11269 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11270 QualType ParamTy = PVD->getType().getNonReferenceType();
11271 QualType EltTy = Context.getBaseElementType(QT: ParamTy);
11272 // `isCompleteType` forces completion of the element type without
11273 // reporting an error (diagnosed elsewhere) so the resource parameter
11274 // check is valid.
11275 if (!EltTy->isDependentType() &&
11276 isCompleteType(Loc: PVD->getLocation(), T: EltTy) &&
11277 ParamTy->isHLSLIntangibleType()) {
11278 Diag(Loc: PVD->getLocation(),
11279 DiagID: diag::err_hlsl_resource_param_in_noinline_function)
11280 << ParamTy;
11281 Diag(Loc: NoInline->getLocation(), DiagID: diag::note_attribute);
11282 }
11283 }
11284 }
11285 }
11286
11287 // If this is the first declaration of a library builtin function, add
11288 // attributes as appropriate.
11289 if (!D.isRedeclaration()) {
11290 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11291 if (unsigned BuiltinID = II->getBuiltinID()) {
11292 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11293 if (!InStdNamespace &&
11294 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11295 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11296 // Validate the type matches unless this builtin is specified as
11297 // matching regardless of its declared type.
11298 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11299 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11300 } else {
11301 ASTContext::GetBuiltinTypeError Error;
11302 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11303 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11304
11305 if (!Error && !BuiltinType.isNull() &&
11306 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11307 T: NewFD->getType(), U: BuiltinType))
11308 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11309 }
11310 }
11311 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11312 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11313 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11314 }
11315 }
11316 }
11317 }
11318
11319 ProcessPragmaWeak(S, D: NewFD);
11320 ProcessPragmaExport(NewD: NewFD);
11321 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11322
11323 AddKnownFunctionAttributes(FD: NewFD);
11324 // The above can add the format attribute for known builtin/library functions
11325 // which is required by the modular_format attribute, thus
11326 // validate modular_format now after those attributes have been added.
11327 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11328
11329 if (NewFD->hasAttr<OverloadableAttr>() &&
11330 !NewFD->getType()->getAs<FunctionProtoType>()) {
11331 Diag(Loc: NewFD->getLocation(),
11332 DiagID: diag::err_attribute_overloadable_no_prototype)
11333 << NewFD;
11334 NewFD->dropAttr<OverloadableAttr>();
11335 }
11336
11337 // If there's a #pragma GCC visibility in scope, and this isn't a class
11338 // member, set the visibility of this function.
11339 if (!DC->isRecord() && NewFD->isExternallyVisible())
11340 AddPushedVisibilityAttribute(RD: NewFD);
11341
11342 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11343 // marking the function.
11344 ObjC().AddCFAuditedAttribute(D: NewFD);
11345
11346 // If this is a function definition, check if we have to apply any
11347 // attributes (i.e. optnone and no_builtin) due to a pragma.
11348 if (D.isFunctionDefinition()) {
11349 AddRangeBasedOptnone(FD: NewFD);
11350 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11351 AddSectionMSAllocText(FD: NewFD);
11352 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11353 }
11354
11355 // If this is the first declaration of an extern C variable, update
11356 // the map of such variables.
11357 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11358 isIncompleteDeclExternC(S&: *this, D: NewFD))
11359 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11360
11361 // Set this FunctionDecl's range up to the right paren.
11362 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11363
11364 if (D.isRedeclaration() && !Previous.empty()) {
11365 NamedDecl *Prev = Previous.getRepresentativeDecl();
11366 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11367 IsSpecialization: isMemberSpecialization ||
11368 isFunctionTemplateSpecialization,
11369 IsDefinition: D.isFunctionDefinition());
11370 }
11371
11372 if (getLangOpts().CUDA) {
11373 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11374 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11375 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11376 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11377 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11378 << CUDA().getConfigureFuncName();
11379 Context.setcudaConfigureCallDecl(NewFD);
11380 }
11381 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11382 !NewFD->isInvalidDecl() &&
11383 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11384 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11385 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11386 << CUDA().getConfigureFuncName();
11387 Context.setcudaGetParameterBufferDecl(NewFD);
11388 }
11389 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11390 !NewFD->isInvalidDecl() &&
11391 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11392 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11393 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11394 << CUDA().getConfigureFuncName();
11395 Context.setcudaLaunchDeviceDecl(NewFD);
11396 }
11397 }
11398 }
11399
11400 MarkUnusedFileScopedDecl(D: NewFD);
11401
11402 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11403 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11404 if (SC == SC_Static) {
11405 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11406 D.setInvalidType();
11407 }
11408
11409 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11410 if (!NewFD->getReturnType()->isVoidType()) {
11411 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11412 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11413 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11414 : FixItHint());
11415 D.setInvalidType();
11416 }
11417
11418 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11419 for (auto *Param : NewFD->parameters())
11420 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11421
11422 if (getLangOpts().OpenCLCPlusPlus) {
11423 if (DC->isRecord()) {
11424 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11425 D.setInvalidType();
11426 }
11427 if (FunctionTemplate) {
11428 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11429 D.setInvalidType();
11430 }
11431 }
11432 }
11433
11434 if (getLangOpts().CPlusPlus) {
11435 // Precalculate whether this is a friend function template with a constraint
11436 // that depends on an enclosing template, per [temp.friend]p9.
11437 if (isFriend && FunctionTemplate &&
11438 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11439 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11440
11441 // C++ [temp.friend]p9:
11442 // A friend function template with a constraint that depends on a
11443 // template parameter from an enclosing template shall be a definition.
11444 if (!D.isFunctionDefinition()) {
11445 Diag(Loc: NewFD->getBeginLoc(),
11446 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11447 NewFD->setInvalidDecl();
11448 }
11449 }
11450
11451 if (FunctionTemplate) {
11452 if (NewFD->isInvalidDecl())
11453 FunctionTemplate->setInvalidDecl();
11454 return FunctionTemplate;
11455 }
11456
11457 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11458 CompleteMemberSpecialization(Member: NewFD, Previous);
11459 }
11460
11461 for (const ParmVarDecl *Param : NewFD->parameters()) {
11462 QualType PT = Param->getType();
11463
11464 // WebAssembly tables can't be used as function parameters.
11465 if (Context.getTargetInfo().getTriple().isWasm()) {
11466 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11467 Diag(Loc: Param->getTypeSpecStartLoc(),
11468 DiagID: diag::err_wasm_table_as_function_parameter);
11469 D.setInvalidType();
11470 }
11471 }
11472 }
11473
11474 // Diagnose availability attributes. Availability cannot be used on functions
11475 // that are run during load/unload.
11476 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11477 if (NewFD->hasAttr<ConstructorAttr>()) {
11478 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11479 << 1;
11480 NewFD->dropAttr<AvailabilityAttr>();
11481 }
11482 if (NewFD->hasAttr<DestructorAttr>()) {
11483 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11484 << 2;
11485 NewFD->dropAttr<AvailabilityAttr>();
11486 }
11487 }
11488
11489 // Diagnose no_builtin attribute on function declaration that are not a
11490 // definition.
11491 // FIXME: We should really be doing this in
11492 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11493 // the FunctionDecl and at this point of the code
11494 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11495 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11496 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11497 switch (D.getFunctionDefinitionKind()) {
11498 case FunctionDefinitionKind::Defaulted:
11499 case FunctionDefinitionKind::Deleted:
11500 Diag(Loc: NBA->getLocation(),
11501 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11502 << NBA->getSpelling();
11503 break;
11504 case FunctionDefinitionKind::Declaration:
11505 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11506 << NBA->getSpelling();
11507 break;
11508 case FunctionDefinitionKind::Definition:
11509 break;
11510 }
11511
11512 // Similar to no_builtin logic above, at this point of the code
11513 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11514 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11515 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11516 !NewFD->isInvalidDecl() &&
11517 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11518 ExternalDeclarations.push_back(Elt: NewFD);
11519
11520 // Used for a warning on the 'next' declaration when used with a
11521 // `routine(name)`.
11522 if (getLangOpts().OpenACC)
11523 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11524
11525 return NewFD;
11526}
11527
11528/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11529/// when __declspec(code_seg) "is applied to a class, all member functions of
11530/// the class and nested classes -- this includes compiler-generated special
11531/// member functions -- are put in the specified segment."
11532/// The actual behavior is a little more complicated. The Microsoft compiler
11533/// won't check outer classes if there is an active value from #pragma code_seg.
11534/// The CodeSeg is always applied from the direct parent but only from outer
11535/// classes when the #pragma code_seg stack is empty. See:
11536/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11537/// available since MS has removed the page.
11538static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11539 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11540 if (!Method)
11541 return nullptr;
11542 const CXXRecordDecl *Parent = Method->getParent();
11543 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11544 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11545 NewAttr->setImplicit(true);
11546 return NewAttr;
11547 }
11548
11549 // The Microsoft compiler won't check outer classes for the CodeSeg
11550 // when the #pragma code_seg stack is active.
11551 if (S.CodeSegStack.CurrentValue)
11552 return nullptr;
11553
11554 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11555 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11556 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11557 NewAttr->setImplicit(true);
11558 return NewAttr;
11559 }
11560 }
11561 return nullptr;
11562}
11563
11564Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11565 bool IsDefinition) {
11566 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11567 return A;
11568 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11569 CodeSegStack.CurrentValue)
11570 return SectionAttr::CreateImplicit(
11571 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11572 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11573 return nullptr;
11574}
11575
11576bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11577 QualType NewT, QualType OldT) {
11578 if (!NewD->getLexicalDeclContext()->isDependentContext())
11579 return true;
11580
11581 // For dependently-typed local extern declarations and friends, we can't
11582 // perform a correct type check in general until instantiation:
11583 //
11584 // int f();
11585 // template<typename T> void g() { T f(); }
11586 //
11587 // (valid if g() is only instantiated with T = int).
11588 if (NewT->isDependentType() &&
11589 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11590 return false;
11591
11592 // Similarly, if the previous declaration was a dependent local extern
11593 // declaration, we don't really know its type yet.
11594 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11595 return false;
11596
11597 return true;
11598}
11599
11600bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11601 if (!D->getLexicalDeclContext()->isDependentContext())
11602 return true;
11603
11604 // Don't chain dependent friend function definitions until instantiation, to
11605 // permit cases like
11606 //
11607 // void func();
11608 // template<typename T> class C1 { friend void func() {} };
11609 // template<typename T> class C2 { friend void func() {} };
11610 //
11611 // ... which is valid if only one of C1 and C2 is ever instantiated.
11612 //
11613 // FIXME: This need only apply to function definitions. For now, we proxy
11614 // this by checking for a file-scope function. We do not want this to apply
11615 // to friend declarations nominating member functions, because that gets in
11616 // the way of access checks.
11617 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11618 return false;
11619
11620 auto *VD = dyn_cast<ValueDecl>(Val: D);
11621 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11622 return !VD || !PrevVD ||
11623 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11624 OldT: PrevVD->getType());
11625}
11626
11627/// Check the target or target_version attribute of the function for
11628/// MultiVersion validity.
11629///
11630/// Returns true if there was an error, false otherwise.
11631static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11632 const auto *TA = FD->getAttr<TargetAttr>();
11633 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11634
11635 assert((TA || TVA) && "Expecting target or target_version attribute");
11636
11637 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11638 enum ErrType { Feature = 0, Architecture = 1 };
11639
11640 if (TA) {
11641 ParsedTargetAttr ParseInfo =
11642 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11643 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11644 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11645 << Architecture << ParseInfo.CPU;
11646 return true;
11647 }
11648 for (const auto &Feat : ParseInfo.Features) {
11649 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11650 if (Feat[0] == '-') {
11651 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11652 << Feature << ("no-" + BareFeat);
11653 return true;
11654 }
11655
11656 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11657 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11658 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11659 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11660 << Feature << BareFeat;
11661 return true;
11662 }
11663 }
11664 }
11665
11666 if (TVA) {
11667 llvm::SmallVector<StringRef, 8> Feats;
11668 ParsedTargetAttr ParseInfo;
11669 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11670 ParseInfo =
11671 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11672 for (auto &Feat : ParseInfo.Features)
11673 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11674 } else {
11675 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11676 TVA->getFeatures(Out&: Feats);
11677 }
11678 for (const auto &Feat : Feats) {
11679 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11680 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11681 << Feature << Feat;
11682 return true;
11683 }
11684 }
11685 }
11686 return false;
11687}
11688
11689// Provide a white-list of attributes that are allowed to be combined with
11690// multiversion functions.
11691static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11692 MultiVersionKind MVKind) {
11693 // Note: this list/diagnosis must match the list in
11694 // checkMultiversionAttributesAllSame.
11695 switch (Kind) {
11696 default:
11697 return false;
11698 case attr::ArmLocallyStreaming:
11699 return MVKind == MultiVersionKind::TargetVersion ||
11700 MVKind == MultiVersionKind::TargetClones;
11701 case attr::Used:
11702 return MVKind == MultiVersionKind::Target;
11703 case attr::NonNull:
11704 case attr::NoThrow:
11705 return true;
11706 }
11707}
11708
11709static bool checkNonMultiVersionCompatAttributes(Sema &S,
11710 const FunctionDecl *FD,
11711 const FunctionDecl *CausedFD,
11712 MultiVersionKind MVKind) {
11713 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11714 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11715 << static_cast<unsigned>(MVKind) << A;
11716 if (CausedFD)
11717 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11718 return true;
11719 };
11720
11721 for (const Attr *A : FD->attrs()) {
11722 switch (A->getKind()) {
11723 case attr::CPUDispatch:
11724 case attr::CPUSpecific:
11725 if (MVKind != MultiVersionKind::CPUDispatch &&
11726 MVKind != MultiVersionKind::CPUSpecific)
11727 return Diagnose(S, A);
11728 break;
11729 case attr::Target:
11730 if (MVKind != MultiVersionKind::Target)
11731 return Diagnose(S, A);
11732 break;
11733 case attr::TargetVersion:
11734 if (MVKind != MultiVersionKind::TargetVersion &&
11735 MVKind != MultiVersionKind::TargetClones)
11736 return Diagnose(S, A);
11737 break;
11738 case attr::TargetClones:
11739 if (MVKind != MultiVersionKind::TargetClones &&
11740 MVKind != MultiVersionKind::TargetVersion)
11741 return Diagnose(S, A);
11742 break;
11743 default:
11744 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11745 return Diagnose(S, A);
11746 break;
11747 }
11748 }
11749 return false;
11750}
11751
11752bool Sema::areMultiversionVariantFunctionsCompatible(
11753 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11754 const PartialDiagnostic &NoProtoDiagID,
11755 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11756 const PartialDiagnosticAt &NoSupportDiagIDAt,
11757 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11758 bool ConstexprSupported, bool CLinkageMayDiffer) {
11759 enum DoesntSupport {
11760 FuncTemplates = 0,
11761 VirtFuncs = 1,
11762 DeducedReturn = 2,
11763 Constructors = 3,
11764 Destructors = 4,
11765 DeletedFuncs = 5,
11766 DefaultedFuncs = 6,
11767 ConstexprFuncs = 7,
11768 ConstevalFuncs = 8,
11769 Lambda = 9,
11770 };
11771 enum Different {
11772 CallingConv = 0,
11773 ReturnType = 1,
11774 ConstexprSpec = 2,
11775 InlineSpec = 3,
11776 Linkage = 4,
11777 LanguageLinkage = 5,
11778 };
11779
11780 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11781 !OldFD->getType()->getAs<FunctionProtoType>()) {
11782 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11783 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11784 return true;
11785 }
11786
11787 if (NoProtoDiagID.getDiagID() != 0 &&
11788 !NewFD->getType()->getAs<FunctionProtoType>())
11789 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11790
11791 if (!TemplatesSupported &&
11792 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11793 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11794 << FuncTemplates;
11795
11796 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11797 if (NewCXXFD->isVirtual())
11798 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11799 << VirtFuncs;
11800
11801 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11802 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11803 << Constructors;
11804
11805 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11806 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11807 << Destructors;
11808 }
11809
11810 if (NewFD->isDeleted())
11811 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11812 << DeletedFuncs;
11813
11814 if (NewFD->isDefaulted())
11815 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11816 << DefaultedFuncs;
11817
11818 if (!ConstexprSupported && NewFD->isConstexpr())
11819 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11820 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11821
11822 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11823 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11824 QualType NewReturnType = NewType->getReturnType();
11825
11826 if (NewReturnType->isUndeducedType())
11827 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11828 << DeducedReturn;
11829
11830 // Ensure the return type is identical.
11831 if (OldFD) {
11832 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11833 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11834 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11835 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11836
11837 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11838 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11839
11840 bool ArmStreamingCCMismatched = false;
11841 if (OldFPT && NewFPT) {
11842 unsigned Diff =
11843 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11844 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11845 // cannot be mixed.
11846 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11847 FunctionType::SME_PStateSMCompatibleMask))
11848 ArmStreamingCCMismatched = true;
11849 }
11850
11851 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11852 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11853
11854 QualType OldReturnType = OldType->getReturnType();
11855
11856 if (OldReturnType != NewReturnType)
11857 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11858
11859 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11860 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11861
11862 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11863 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11864
11865 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11866 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11867
11868 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11869 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11870
11871 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11872 NewLoc: NewFD->getLocation()))
11873 return true;
11874 }
11875 return false;
11876}
11877
11878static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11879 const FunctionDecl *NewFD,
11880 bool CausesMV,
11881 MultiVersionKind MVKind) {
11882 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11883 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11884 if (OldFD)
11885 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11886 return true;
11887 }
11888
11889 bool IsCPUSpecificCPUDispatchMVKind =
11890 MVKind == MultiVersionKind::CPUDispatch ||
11891 MVKind == MultiVersionKind::CPUSpecific;
11892
11893 if (CausesMV && OldFD &&
11894 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11895 return true;
11896
11897 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11898 return true;
11899
11900 // Only allow transition to MultiVersion if it hasn't been used.
11901 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11902 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11903 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11904 return true;
11905 }
11906
11907 return S.areMultiversionVariantFunctionsCompatible(
11908 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11909 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11910 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11911 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11912 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11913 << static_cast<unsigned>(MVKind)),
11914 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11915 S.PDiag(DiagID: diag::err_multiversion_diff)),
11916 /*TemplatesSupported=*/false,
11917 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11918 /*CLinkageMayDiffer=*/false);
11919}
11920
11921/// Check the validity of a multiversion function declaration that is the
11922/// first of its kind. Also sets the multiversion'ness' of the function itself.
11923///
11924/// This sets NewFD->isInvalidDecl() to true if there was an error.
11925///
11926/// Returns true if there was an error, false otherwise.
11927static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11928 MultiVersionKind MVKind = FD->getMultiVersionKind();
11929 assert(MVKind != MultiVersionKind::None &&
11930 "Function lacks multiversion attribute");
11931 const auto *TA = FD->getAttr<TargetAttr>();
11932 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11933 // The target attribute only causes MV if this declaration is the default,
11934 // otherwise it is treated as a normal function.
11935 if (TA && !TA->isDefaultVersion())
11936 return false;
11937
11938 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11939 FD->setInvalidDecl();
11940 return true;
11941 }
11942
11943 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11944 FD->setInvalidDecl();
11945 return true;
11946 }
11947
11948 FD->setIsMultiVersion();
11949 return false;
11950}
11951
11952static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11953 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11954 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11955 return true;
11956 }
11957
11958 return false;
11959}
11960
11961static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11962 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11963 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11964 return;
11965
11966 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11967 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11968
11969 if (MVKindTo == MultiVersionKind::None &&
11970 (MVKindFrom == MultiVersionKind::TargetVersion ||
11971 MVKindFrom == MultiVersionKind::TargetClones))
11972 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11973 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11974}
11975
11976static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11977 FunctionDecl *NewFD,
11978 bool &Redeclaration,
11979 NamedDecl *&OldDecl,
11980 LookupResult &Previous) {
11981 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11982
11983 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11984 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11985 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11986 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11987
11988 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11989
11990 // The definitions should be allowed in any order. If we have discovered
11991 // a new target version and the preceeding was the default, then add the
11992 // corresponding attribute to it.
11993 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11994
11995 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11996 // to change, this is a simple redeclaration.
11997 if (NewTA && !NewTA->isDefaultVersion() &&
11998 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11999 return false;
12000
12001 // Otherwise, this decl causes MultiVersioning.
12002 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
12003 MVKind: NewTVA ? MultiVersionKind::TargetVersion
12004 : MultiVersionKind::Target)) {
12005 NewFD->setInvalidDecl();
12006 return true;
12007 }
12008
12009 if (CheckMultiVersionValue(S, FD: NewFD)) {
12010 NewFD->setInvalidDecl();
12011 return true;
12012 }
12013
12014 // If this is 'default', permit the forward declaration.
12015 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
12016 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
12017 Redeclaration = true;
12018 OldDecl = OldFD;
12019 OldFD->setIsMultiVersion();
12020 NewFD->setIsMultiVersion();
12021 return false;
12022 }
12023
12024 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
12025 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
12026 NewFD->setInvalidDecl();
12027 return true;
12028 }
12029
12030 if (NewTA) {
12031 ParsedTargetAttr OldParsed =
12032 S.getASTContext().getTargetInfo().parseTargetAttr(
12033 Str: OldTA->getFeaturesStr());
12034 llvm::sort(C&: OldParsed.Features);
12035 ParsedTargetAttr NewParsed =
12036 S.getASTContext().getTargetInfo().parseTargetAttr(
12037 Str: NewTA->getFeaturesStr());
12038 // Sort order doesn't matter, it just needs to be consistent.
12039 llvm::sort(C&: NewParsed.Features);
12040 if (OldParsed == NewParsed) {
12041 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12042 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12043 NewFD->setInvalidDecl();
12044 return true;
12045 }
12046 }
12047
12048 for (const auto *FD : OldFD->redecls()) {
12049 const auto *CurTA = FD->getAttr<TargetAttr>();
12050 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
12051 // We allow forward declarations before ANY multiversioning attributes, but
12052 // nothing after the fact.
12053 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
12054 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12055 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12056 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12057 << (NewTA ? 0 : 2);
12058 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
12059 NewFD->setInvalidDecl();
12060 return true;
12061 }
12062 }
12063
12064 OldFD->setIsMultiVersion();
12065 NewFD->setIsMultiVersion();
12066 Redeclaration = false;
12067 OldDecl = nullptr;
12068 Previous.clear();
12069 return false;
12070}
12071
12072static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
12073 MultiVersionKind OldKind = Old->getMultiVersionKind();
12074 MultiVersionKind NewKind = New->getMultiVersionKind();
12075
12076 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12077 NewKind == MultiVersionKind::None)
12078 return true;
12079
12080 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12081 switch (OldKind) {
12082 case MultiVersionKind::TargetVersion:
12083 return NewKind == MultiVersionKind::TargetClones;
12084 case MultiVersionKind::TargetClones:
12085 return NewKind == MultiVersionKind::TargetVersion;
12086 default:
12087 return false;
12088 }
12089 } else {
12090 switch (OldKind) {
12091 case MultiVersionKind::CPUDispatch:
12092 return NewKind == MultiVersionKind::CPUSpecific;
12093 case MultiVersionKind::CPUSpecific:
12094 return NewKind == MultiVersionKind::CPUDispatch;
12095 default:
12096 return false;
12097 }
12098 }
12099}
12100
12101/// Check the validity of a new function declaration being added to an existing
12102/// multiversioned declaration collection.
12103static bool CheckMultiVersionAdditionalDecl(
12104 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12105 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12106 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12107 LookupResult &Previous) {
12108
12109 // Disallow mixing of multiversioning types.
12110 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
12111 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
12112 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12113 NewFD->setInvalidDecl();
12114 return true;
12115 }
12116
12117 // Add the default target_version attribute if it's missing.
12118 patchDefaultTargetVersion(From: OldFD, To: NewFD);
12119 patchDefaultTargetVersion(From: NewFD, To: OldFD);
12120
12121 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12122 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12123 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12124 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12125
12126 ParsedTargetAttr NewParsed;
12127 if (NewTA) {
12128 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
12129 Str: NewTA->getFeaturesStr());
12130 llvm::sort(C&: NewParsed.Features);
12131 }
12132 llvm::SmallVector<StringRef, 8> NewFeats;
12133 if (NewTVA) {
12134 NewTVA->getFeatures(Out&: NewFeats);
12135 llvm::sort(C&: NewFeats);
12136 }
12137
12138 bool UseMemberUsingDeclRules =
12139 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12140
12141 bool MayNeedOverloadableChecks =
12142 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
12143
12144 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12145 // of a previous member of the MultiVersion set.
12146 for (NamedDecl *ND : Previous) {
12147 FunctionDecl *CurFD = ND->getAsFunction();
12148 if (!CurFD || CurFD->isInvalidDecl())
12149 continue;
12150 if (MayNeedOverloadableChecks &&
12151 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
12152 continue;
12153
12154 switch (NewMVKind) {
12155 case MultiVersionKind::None:
12156 assert(OldMVKind == MultiVersionKind::TargetClones &&
12157 "Only target_clones can be omitted in subsequent declarations");
12158 break;
12159 case MultiVersionKind::Target: {
12160 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12161 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12162 NewFD->setIsMultiVersion();
12163 Redeclaration = true;
12164 OldDecl = ND;
12165 return false;
12166 }
12167
12168 ParsedTargetAttr CurParsed =
12169 S.getASTContext().getTargetInfo().parseTargetAttr(
12170 Str: CurTA->getFeaturesStr());
12171 llvm::sort(C&: CurParsed.Features);
12172 if (CurParsed == NewParsed) {
12173 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12174 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12175 NewFD->setInvalidDecl();
12176 return true;
12177 }
12178 break;
12179 }
12180 case MultiVersionKind::TargetVersion: {
12181 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12182 if (CurTVA->getName() == NewTVA->getName()) {
12183 NewFD->setIsMultiVersion();
12184 Redeclaration = true;
12185 OldDecl = ND;
12186 return false;
12187 }
12188 llvm::SmallVector<StringRef, 8> CurFeats;
12189 CurTVA->getFeatures(Out&: CurFeats);
12190 llvm::sort(C&: CurFeats);
12191
12192 if (CurFeats == NewFeats) {
12193 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12194 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12195 NewFD->setInvalidDecl();
12196 return true;
12197 }
12198 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12199 // Default
12200 if (NewFeats.empty())
12201 break;
12202
12203 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12204 llvm::SmallVector<StringRef, 8> CurFeats;
12205 CurClones->getFeatures(Out&: CurFeats, Index: I);
12206 llvm::sort(C&: CurFeats);
12207
12208 if (CurFeats == NewFeats) {
12209 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12210 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12211 NewFD->setInvalidDecl();
12212 return true;
12213 }
12214 }
12215 }
12216 break;
12217 }
12218 case MultiVersionKind::TargetClones: {
12219 assert(NewClones && "MultiVersionKind does not match attribute type");
12220 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12221 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12222 !std::equal(first1: CurClones->featuresStrs_begin(),
12223 last1: CurClones->featuresStrs_end(),
12224 first2: NewClones->featuresStrs_begin())) {
12225 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
12226 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12227 NewFD->setInvalidDecl();
12228 return true;
12229 }
12230 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12231 llvm::SmallVector<StringRef, 8> CurFeats;
12232 CurTVA->getFeatures(Out&: CurFeats);
12233 llvm::sort(C&: CurFeats);
12234
12235 // Default
12236 if (CurFeats.empty())
12237 break;
12238
12239 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12240 NewFeats.clear();
12241 NewClones->getFeatures(Out&: NewFeats, Index: I);
12242 llvm::sort(C&: NewFeats);
12243
12244 if (CurFeats == NewFeats) {
12245 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12246 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12247 NewFD->setInvalidDecl();
12248 return true;
12249 }
12250 }
12251 break;
12252 }
12253 Redeclaration = true;
12254 OldDecl = CurFD;
12255 NewFD->setIsMultiVersion();
12256 return false;
12257 }
12258 case MultiVersionKind::CPUSpecific:
12259 case MultiVersionKind::CPUDispatch: {
12260 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12261 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12262 // Handle CPUDispatch/CPUSpecific versions.
12263 // Only 1 CPUDispatch function is allowed, this will make it go through
12264 // the redeclaration errors.
12265 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12266 CurFD->hasAttr<CPUDispatchAttr>()) {
12267 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12268 std::equal(
12269 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12270 first2: NewCPUDisp->cpus_begin(),
12271 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12272 return Cur->getName() == New->getName();
12273 })) {
12274 NewFD->setIsMultiVersion();
12275 Redeclaration = true;
12276 OldDecl = ND;
12277 return false;
12278 }
12279
12280 // If the declarations don't match, this is an error condition.
12281 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12282 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12283 NewFD->setInvalidDecl();
12284 return true;
12285 }
12286 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12287 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12288 std::equal(
12289 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12290 first2: NewCPUSpec->cpus_begin(),
12291 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12292 return Cur->getName() == New->getName();
12293 })) {
12294 NewFD->setIsMultiVersion();
12295 Redeclaration = true;
12296 OldDecl = ND;
12297 return false;
12298 }
12299
12300 // Only 1 version of CPUSpecific is allowed for each CPU.
12301 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12302 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12303 if (CurII == NewII) {
12304 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12305 << NewII;
12306 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12307 NewFD->setInvalidDecl();
12308 return true;
12309 }
12310 }
12311 }
12312 }
12313 break;
12314 }
12315 }
12316 }
12317
12318 // Redeclarations of a target_clones function may omit the attribute, in which
12319 // case it will be inherited during declaration merging.
12320 if (NewMVKind == MultiVersionKind::None &&
12321 OldMVKind == MultiVersionKind::TargetClones) {
12322 NewFD->setIsMultiVersion();
12323 Redeclaration = true;
12324 OldDecl = OldFD;
12325 return false;
12326 }
12327
12328 // Else, this is simply a non-redecl case. Checking the 'value' is only
12329 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12330 // handled in the attribute adding step.
12331 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12332 NewFD->setInvalidDecl();
12333 return true;
12334 }
12335
12336 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12337 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12338 NewFD->setInvalidDecl();
12339 return true;
12340 }
12341
12342 // Permit forward declarations in the case where these two are compatible.
12343 if (!OldFD->isMultiVersion()) {
12344 OldFD->setIsMultiVersion();
12345 NewFD->setIsMultiVersion();
12346 Redeclaration = true;
12347 OldDecl = OldFD;
12348 return false;
12349 }
12350
12351 NewFD->setIsMultiVersion();
12352 Redeclaration = false;
12353 OldDecl = nullptr;
12354 Previous.clear();
12355 return false;
12356}
12357
12358/// Check the validity of a mulitversion function declaration.
12359/// Also sets the multiversion'ness' of the function itself.
12360///
12361/// This sets NewFD->isInvalidDecl() to true if there was an error.
12362///
12363/// Returns true if there was an error, false otherwise.
12364static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12365 bool &Redeclaration, NamedDecl *&OldDecl,
12366 LookupResult &Previous) {
12367 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12368
12369 // Check if FMV is disabled.
12370 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12371 return false;
12372
12373 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12374 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12375 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12376 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12377 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12378 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12379
12380 // Main isn't allowed to become a multiversion function, however it IS
12381 // permitted to have 'main' be marked with the 'target' optimization hint,
12382 // for 'target_version' only default is allowed.
12383 if (NewFD->isMain()) {
12384 if (MVKind != MultiVersionKind::None &&
12385 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12386 !(MVKind == MultiVersionKind::TargetVersion &&
12387 NewTVA->isDefaultVersion())) {
12388 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12389 NewFD->setInvalidDecl();
12390 return true;
12391 }
12392 return false;
12393 }
12394
12395 // Target attribute on AArch64 is not used for multiversioning
12396 if (NewTA && TI.getTriple().isAArch64())
12397 return false;
12398
12399 // Target attribute on RISCV is not used for multiversioning
12400 if (NewTA && TI.getTriple().isRISCV())
12401 return false;
12402
12403 if (!OldDecl || !OldDecl->getAsFunction() ||
12404 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12405 DC: NewFD->getDeclContext()->getRedeclContext())) {
12406 // If there's no previous declaration, AND this isn't attempting to cause
12407 // multiversioning, this isn't an error condition.
12408 if (MVKind == MultiVersionKind::None)
12409 return false;
12410 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12411 }
12412
12413 FunctionDecl *OldFD = OldDecl->getAsFunction();
12414
12415 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12416 return false;
12417
12418 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12419 // for target_clones and target_version.
12420 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12421 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12422 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12423 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12424 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12425 NewFD->setInvalidDecl();
12426 return true;
12427 }
12428
12429 if (!OldFD->isMultiVersion()) {
12430 switch (MVKind) {
12431 case MultiVersionKind::Target:
12432 case MultiVersionKind::TargetVersion:
12433 return CheckDeclarationCausesMultiVersioning(
12434 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12435 case MultiVersionKind::TargetClones:
12436 if (OldFD->isUsed(CheckUsedAttr: false)) {
12437 NewFD->setInvalidDecl();
12438 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12439 }
12440 OldFD->setIsMultiVersion();
12441 break;
12442
12443 case MultiVersionKind::CPUDispatch:
12444 case MultiVersionKind::CPUSpecific:
12445 case MultiVersionKind::None:
12446 break;
12447 }
12448 }
12449
12450 // At this point, we have a multiversion function decl (in OldFD) AND an
12451 // appropriate attribute in the current function decl (unless it's allowed to
12452 // omit the attribute). Resolve that these are still compatible with previous
12453 // declarations.
12454 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12455 NewCPUSpec, NewClones, Redeclaration,
12456 OldDecl, Previous);
12457}
12458
12459static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12460 bool IsPure = NewFD->hasAttr<PureAttr>();
12461 bool IsConst = NewFD->hasAttr<ConstAttr>();
12462
12463 // If there are no pure or const attributes, there's nothing to check.
12464 if (!IsPure && !IsConst)
12465 return;
12466
12467 // If the function is marked both pure and const, we retain the const
12468 // attribute because it makes stronger guarantees than the pure attribute, and
12469 // we drop the pure attribute explicitly to prevent later confusion about
12470 // semantics.
12471 if (IsPure && IsConst) {
12472 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12473 NewFD->dropAttrs<PureAttr>();
12474 }
12475
12476 // Constructors and destructors are functions which return void, so are
12477 // handled here as well.
12478 if (NewFD->getReturnType()->isVoidType()) {
12479 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12480 << IsConst;
12481 NewFD->dropAttrs<PureAttr, ConstAttr>();
12482 }
12483}
12484
12485bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12486 LookupResult &Previous,
12487 bool IsMemberSpecialization,
12488 bool DeclIsDefn) {
12489 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12490 "Variably modified return types are not handled here");
12491
12492 // Determine whether the type of this function should be merged with
12493 // a previous visible declaration. This never happens for functions in C++,
12494 // and always happens in C if the previous declaration was visible.
12495 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12496 !Previous.isShadowed();
12497
12498 bool Redeclaration = false;
12499 NamedDecl *OldDecl = nullptr;
12500 bool MayNeedOverloadableChecks = false;
12501
12502 inferLifetimeCaptureByAttribute(FD: NewFD);
12503 // Merge or overload the declaration with an existing declaration of
12504 // the same name, if appropriate.
12505 if (!Previous.empty()) {
12506 // Determine whether NewFD is an overload of PrevDecl or
12507 // a declaration that requires merging. If it's an overload,
12508 // there's no more work to do here; we'll just add the new
12509 // function to the scope.
12510 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12511 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12512 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12513 Redeclaration = true;
12514 OldDecl = Candidate;
12515 }
12516 } else {
12517 MayNeedOverloadableChecks = true;
12518 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12519 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12520 case OverloadKind::Match:
12521 Redeclaration = true;
12522 break;
12523
12524 case OverloadKind::NonFunction:
12525 Redeclaration = true;
12526 break;
12527
12528 case OverloadKind::Overload:
12529 Redeclaration = false;
12530 break;
12531 }
12532 }
12533 }
12534
12535 // Check for a previous extern "C" declaration with this name.
12536 if (!Redeclaration &&
12537 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12538 if (!Previous.empty()) {
12539 // This is an extern "C" declaration with the same name as a previous
12540 // declaration, and thus redeclares that entity...
12541 Redeclaration = true;
12542 OldDecl = Previous.getFoundDecl();
12543 MergeTypeWithPrevious = false;
12544
12545 // ... except in the presence of __attribute__((overloadable)).
12546 if (OldDecl->hasAttr<OverloadableAttr>() ||
12547 NewFD->hasAttr<OverloadableAttr>()) {
12548 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12549 MayNeedOverloadableChecks = true;
12550 Redeclaration = false;
12551 OldDecl = nullptr;
12552 }
12553 }
12554 }
12555 }
12556
12557 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12558 return Redeclaration;
12559
12560 // PPC MMA non-pointer types are not allowed as function return types.
12561 if (Context.getTargetInfo().getTriple().isPPC64() &&
12562 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12563 NewFD->setInvalidDecl();
12564 }
12565
12566 CheckConstPureAttributesUsage(S&: *this, NewFD);
12567
12568 // C++ [dcl.spec.auto.general]p12:
12569 // Return type deduction for a templated function with a placeholder in its
12570 // declared type occurs when the definition is instantiated even if the
12571 // function body contains a return statement with a non-type-dependent
12572 // operand.
12573 //
12574 // C++ [temp.dep.expr]p3:
12575 // An id-expression is type-dependent if it is a template-id that is not a
12576 // concept-id and is dependent; or if its terminal name is:
12577 // - [...]
12578 // - associated by name lookup with one or more declarations of member
12579 // functions of a class that is the current instantiation declared with a
12580 // return type that contains a placeholder type,
12581 // - [...]
12582 //
12583 // If this is a templated function with a placeholder in its return type,
12584 // make the placeholder type dependent since it won't be deduced until the
12585 // definition is instantiated. We do this here because it needs to happen
12586 // for implicitly instantiated member functions/member function templates.
12587 if (getLangOpts().CPlusPlus14 &&
12588 (NewFD->isDependentContext() &&
12589 NewFD->getReturnType()->isUndeducedType())) {
12590 const FunctionProtoType *FPT =
12591 NewFD->getType()->castAs<FunctionProtoType>();
12592 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12593 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12594 EPI: FPT->getExtProtoInfo()));
12595 }
12596
12597 // C++11 [dcl.constexpr]p8:
12598 // A constexpr specifier for a non-static member function that is not
12599 // a constructor declares that member function to be const.
12600 //
12601 // This needs to be delayed until we know whether this is an out-of-line
12602 // definition of a static member function.
12603 //
12604 // This rule is not present in C++1y, so we produce a backwards
12605 // compatibility warning whenever it happens in C++11.
12606 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12607 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12608 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12609 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12610 CXXMethodDecl *OldMD = nullptr;
12611 if (OldDecl)
12612 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12613 if (!OldMD || !OldMD->isStatic()) {
12614 const FunctionProtoType *FPT =
12615 MD->getType()->castAs<FunctionProtoType>();
12616 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12617 EPI.TypeQuals.addConst();
12618 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12619 Args: FPT->getParamTypes(), EPI));
12620
12621 // Warn that we did this, if we're not performing template instantiation.
12622 // In that case, we'll have warned already when the template was defined.
12623 if (!inTemplateInstantiation()) {
12624 SourceLocation AddConstLoc;
12625 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12626 .IgnoreParens().getAs<FunctionTypeLoc>())
12627 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12628
12629 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12630 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12631 }
12632 }
12633 }
12634
12635 if (Redeclaration) {
12636 // NewFD and OldDecl represent declarations that need to be
12637 // merged.
12638 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12639 NewDeclIsDefn: DeclIsDefn)) {
12640 NewFD->setInvalidDecl();
12641 return Redeclaration;
12642 }
12643
12644 Previous.clear();
12645 Previous.addDecl(D: OldDecl);
12646
12647 if (FunctionTemplateDecl *OldTemplateDecl =
12648 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12649 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12650 FunctionTemplateDecl *NewTemplateDecl
12651 = NewFD->getDescribedFunctionTemplate();
12652 assert(NewTemplateDecl && "Template/non-template mismatch");
12653
12654 // The call to MergeFunctionDecl above may have created some state in
12655 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12656 // can add it as a redeclaration.
12657 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12658
12659 NewFD->setPreviousDeclaration(OldFD);
12660 if (NewFD->isCXXClassMember()) {
12661 NewFD->setAccess(OldTemplateDecl->getAccess());
12662 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12663 }
12664
12665 // If this is an explicit specialization of a member that is a function
12666 // template, mark it as a member specialization.
12667 if (IsMemberSpecialization &&
12668 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12669 NewTemplateDecl->setMemberSpecialization();
12670 assert(OldTemplateDecl->isMemberSpecialization());
12671 // Explicit specializations of a member template do not inherit deleted
12672 // status from the parent member template that they are specializing.
12673 if (OldFD->isDeleted()) {
12674 // FIXME: This assert will not hold in the presence of modules.
12675 assert(OldFD->getCanonicalDecl() == OldFD);
12676 // FIXME: We need an update record for this AST mutation.
12677 OldFD->setDeletedAsWritten(D: false);
12678 }
12679 }
12680
12681 } else {
12682 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12683 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12684 // This needs to happen first so that 'inline' propagates.
12685 NewFD->setPreviousDeclaration(OldFD);
12686 if (NewFD->isCXXClassMember())
12687 NewFD->setAccess(OldFD->getAccess());
12688 }
12689 }
12690 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12691 !NewFD->getAttr<OverloadableAttr>()) {
12692 assert((Previous.empty() ||
12693 llvm::any_of(Previous,
12694 [](const NamedDecl *ND) {
12695 return ND->hasAttr<OverloadableAttr>();
12696 })) &&
12697 "Non-redecls shouldn't happen without overloadable present");
12698
12699 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12700 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12701 return FD && !FD->hasAttr<OverloadableAttr>();
12702 });
12703
12704 if (OtherUnmarkedIter != Previous.end()) {
12705 Diag(Loc: NewFD->getLocation(),
12706 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12707 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12708 DiagID: diag::note_attribute_overloadable_prev_overload)
12709 << false;
12710
12711 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12712 }
12713 }
12714
12715 if (LangOpts.OpenMP)
12716 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12717
12718 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12719 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12720
12721 if (NewFD->hasAttr<SYCLExternalAttr>())
12722 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12723
12724 // Semantic checking for this function declaration (in isolation).
12725
12726 if (getLangOpts().CPlusPlus) {
12727 // C++-specific checks.
12728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12729 CheckConstructor(Constructor);
12730 } else if (CXXDestructorDecl *Destructor =
12731 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12732 // We check here for invalid destructor names.
12733 // If we have a friend destructor declaration that is dependent, we can't
12734 // diagnose right away because cases like this are still valid:
12735 // template <class T> struct A { friend T::X::~Y(); };
12736 // struct B { struct Y { ~Y(); }; using X = Y; };
12737 // template struct A<B>;
12738 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12739 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12740 !Destructor->getDeclName().isDependentName())) {
12741 CanQualType ClassType =
12742 Context.getCanonicalTagType(TD: Destructor->getParent());
12743
12744 DeclarationName Name =
12745 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12746 if (NewFD->getDeclName() != Name) {
12747 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12748 NewFD->setInvalidDecl();
12749 return Redeclaration;
12750 }
12751 }
12752 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12753 if (auto *TD = Guide->getDescribedFunctionTemplate())
12754 CheckDeductionGuideTemplate(TD);
12755
12756 // A deduction guide is not on the list of entities that can be
12757 // explicitly specialized.
12758 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12759 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12760 << /*explicit specialization*/ 1;
12761 }
12762
12763 // Find any virtual functions that this function overrides.
12764 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12765 if (!Method->isFunctionTemplateSpecialization() &&
12766 !Method->getDescribedFunctionTemplate() &&
12767 Method->isCanonicalDecl()) {
12768 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12769 }
12770 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12771 // C++2a [class.virtual]p6
12772 // A virtual method shall not have a requires-clause.
12773 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12774 DiagID: diag::err_constrained_virtual_method);
12775
12776 if (Method->isStatic())
12777 checkThisInStaticMemberFunctionType(Method);
12778 }
12779
12780 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12781 ActOnConversionDeclarator(Conversion);
12782
12783 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12784 if (NewFD->isOverloadedOperator() &&
12785 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12786 NewFD->setInvalidDecl();
12787 return Redeclaration;
12788 }
12789
12790 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12791 if (NewFD->getLiteralIdentifier() &&
12792 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12793 NewFD->setInvalidDecl();
12794 return Redeclaration;
12795 }
12796
12797 // In C++, check default arguments now that we have merged decls. Unless
12798 // the lexical context is the class, because in this case this is done
12799 // during delayed parsing anyway.
12800 if (!CurContext->isRecord())
12801 CheckCXXDefaultArguments(FD: NewFD);
12802
12803 // If this function is declared as being extern "C", then check to see if
12804 // the function returns a UDT (class, struct, or union type) that is not C
12805 // compatible, and if it does, warn the user.
12806 // But, issue any diagnostic on the first declaration only.
12807 if (Previous.empty() && NewFD->isExternC()) {
12808 QualType R = NewFD->getReturnType();
12809 if (R->isIncompleteType() && !R->isVoidType())
12810 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12811 << NewFD << R;
12812 else if (!R.isPODType(Context) && !R->isVoidType() &&
12813 !R->isObjCObjectPointerType())
12814 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12815 }
12816
12817 // C++1z [dcl.fct]p6:
12818 // [...] whether the function has a non-throwing exception-specification
12819 // [is] part of the function type
12820 //
12821 // This results in an ABI break between C++14 and C++17 for functions whose
12822 // declared type includes an exception-specification in a parameter or
12823 // return type. (Exception specifications on the function itself are OK in
12824 // most cases, and exception specifications are not permitted in most other
12825 // contexts where they could make it into a mangling.)
12826 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12827 auto HasNoexcept = [&](QualType T) -> bool {
12828 // Strip off declarator chunks that could be between us and a function
12829 // type. We don't need to look far, exception specifications are very
12830 // restricted prior to C++17.
12831 if (auto *RT = T->getAs<ReferenceType>())
12832 T = RT->getPointeeType();
12833 else if (T->isAnyPointerType())
12834 T = T->getPointeeType();
12835 else if (auto *MPT = T->getAs<MemberPointerType>())
12836 T = MPT->getPointeeType();
12837 if (auto *FPT = T->getAs<FunctionProtoType>())
12838 if (FPT->isNothrow())
12839 return true;
12840 return false;
12841 };
12842
12843 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12844 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12845 for (QualType T : FPT->param_types())
12846 AnyNoexcept |= HasNoexcept(T);
12847 if (AnyNoexcept)
12848 Diag(Loc: NewFD->getLocation(),
12849 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12850 << NewFD;
12851 }
12852
12853 if (!Redeclaration && LangOpts.CUDA) {
12854 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12855 for (auto *Parm : NewFD->parameters()) {
12856 if (!Parm->getType()->isDependentType() &&
12857 Parm->hasAttr<CUDAGridConstantAttr>() &&
12858 !(IsKernel && Parm->getType().isConstQualified()))
12859 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12860 DiagID: diag::err_cuda_grid_constant_not_allowed);
12861 }
12862 CUDA().checkTargetOverload(NewFD, Previous);
12863 }
12864 }
12865
12866 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12867 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12868
12869 return Redeclaration;
12870}
12871
12872void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12873 // [basic.start.main]p3
12874 // The main function shall not be declared with C linkage-specification.
12875 if (FD->isExternCContext())
12876 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12877
12878 // C++11 [basic.start.main]p3:
12879 // A program that [...] declares main to be inline, static or
12880 // constexpr is ill-formed.
12881 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12882 // appear in a declaration of main.
12883 // static main is not an error under C99, but we should warn about it.
12884 // We accept _Noreturn main as an extension.
12885 if (FD->getStorageClass() == SC_Static)
12886 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12887 ? diag::err_static_main : diag::warn_static_main)
12888 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12889 if (FD->isInlineSpecified())
12890 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12891 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12892 if (DS.isNoreturnSpecified()) {
12893 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12894 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12895 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12896 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12897 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12898 }
12899 if (FD->isConstexpr()) {
12900 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12901 << FD->isConsteval()
12902 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12903 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12904 }
12905
12906 if (getLangOpts().OpenCL) {
12907 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12908 << FD->hasAttr<DeviceKernelAttr>();
12909 FD->setInvalidDecl();
12910 return;
12911 }
12912
12913 if (FD->hasAttr<SYCLExternalAttr>()) {
12914 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12915 << FD->getAttr<SYCLExternalAttr>();
12916 FD->setInvalidDecl();
12917 return;
12918 }
12919
12920 // Functions named main in hlsl are default entries, but don't have specific
12921 // signatures they are required to conform to.
12922 if (getLangOpts().HLSL)
12923 return;
12924
12925 QualType T = FD->getType();
12926 assert(T->isFunctionType() && "function decl is not of function type");
12927 const FunctionType* FT = T->castAs<FunctionType>();
12928
12929 // Set default calling convention for main()
12930 if (FT->getCallConv() != CC_C) {
12931 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12932 FD->setType(QualType(FT, 0));
12933 T = Context.getCanonicalType(T: FD->getType());
12934 }
12935
12936 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12937 // In C with GNU extensions we allow main() to have non-integer return
12938 // type, but we should warn about the extension, and we disable the
12939 // implicit-return-zero rule.
12940
12941 // GCC in C mode accepts qualified 'int'.
12942 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12943 FD->setHasImplicitReturnZero(true);
12944 else {
12945 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12946 SourceRange RTRange = FD->getReturnTypeSourceRange();
12947 if (RTRange.isValid())
12948 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12949 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12950 }
12951 } else {
12952 // In C and C++, main magically returns 0 if you fall off the end;
12953 // set the flag which tells us that.
12954 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12955
12956 // All the standards say that main() should return 'int'.
12957 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12958 FD->setHasImplicitReturnZero(true);
12959 else {
12960 // Otherwise, this is just a flat-out error.
12961 SourceRange RTRange = FD->getReturnTypeSourceRange();
12962 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12963 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12964 : FixItHint());
12965 FD->setInvalidDecl(true);
12966 }
12967
12968 // [basic.start.main]p3:
12969 // A program that declares a function main that belongs to the global scope
12970 // and is attached to a named module is ill-formed.
12971 if (FD->isInNamedModule()) {
12972 const SourceLocation start = FD->getTypeSpecStartLoc();
12973 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12974 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12975 }
12976 }
12977
12978 // Treat protoless main() as nullary.
12979 if (isa<FunctionNoProtoType>(Val: FT)) return;
12980
12981 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12982 unsigned nparams = FTP->getNumParams();
12983 assert(FD->getNumParams() == nparams);
12984
12985 bool HasExtraParameters = (nparams > 3);
12986
12987 if (FTP->isVariadic()) {
12988 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12989 // FIXME: if we had information about the location of the ellipsis, we
12990 // could add a FixIt hint to remove it as a parameter.
12991 }
12992
12993 // Darwin passes an undocumented fourth argument of type char**. If
12994 // other platforms start sprouting these, the logic below will start
12995 // getting shifty.
12996 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12997 HasExtraParameters = false;
12998
12999 if (HasExtraParameters) {
13000 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
13001 FD->setInvalidDecl(true);
13002 nparams = 3;
13003 }
13004
13005 // FIXME: a lot of the following diagnostics would be improved
13006 // if we had some location information about types.
13007
13008 QualType CharPP =
13009 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
13010 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
13011
13012 for (unsigned i = 0; i < nparams; ++i) {
13013 QualType AT = FTP->getParamType(i);
13014
13015 bool mismatch = true;
13016
13017 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
13018 mismatch = false;
13019 else if (Expected[i] == CharPP) {
13020 // As an extension, the following forms are okay:
13021 // char const **
13022 // char const * const *
13023 // char * const *
13024
13025 QualifierCollector qs;
13026 const PointerType* PT;
13027 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
13028 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
13029 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
13030 T2: Context.CharTy)) {
13031 qs.removeConst();
13032 mismatch = !qs.empty();
13033 }
13034 }
13035
13036 if (mismatch) {
13037 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
13038 // TODO: suggest replacing given type with expected type
13039 FD->setInvalidDecl(true);
13040 }
13041 }
13042
13043 if (nparams == 1 && !FD->isInvalidDecl()) {
13044 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
13045 }
13046
13047 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13048 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13049 FD->setInvalidDecl();
13050 }
13051}
13052
13053static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
13054
13055 // Default calling convention for main and wmain is __cdecl
13056 if (FD->getName() == "main" || FD->getName() == "wmain")
13057 return false;
13058
13059 // Default calling convention for MinGW and Cygwin is __cdecl
13060 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13061 if (T.isOSCygMing())
13062 return false;
13063
13064 // Default calling convention for WinMain, wWinMain and DllMain
13065 // is __stdcall on 32 bit Windows
13066 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13067 return true;
13068
13069 return false;
13070}
13071
13072void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
13073 QualType T = FD->getType();
13074 assert(T->isFunctionType() && "function decl is not of function type");
13075 const FunctionType *FT = T->castAs<FunctionType>();
13076
13077 // Set an implicit return of 'zero' if the function can return some integral,
13078 // enumeration, pointer or nullptr type.
13079 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
13080 FT->getReturnType()->isAnyPointerType() ||
13081 FT->getReturnType()->isNullPtrType())
13082 // DllMain is exempt because a return value of zero means it failed.
13083 if (FD->getName() != "DllMain")
13084 FD->setHasImplicitReturnZero(true);
13085
13086 // Explicitly specified calling conventions are applied to MSVC entry points
13087 if (!hasExplicitCallingConv(T)) {
13088 if (isDefaultStdCall(FD, S&: *this)) {
13089 if (FT->getCallConv() != CC_X86StdCall) {
13090 FT = Context.adjustFunctionType(
13091 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
13092 FD->setType(QualType(FT, 0));
13093 }
13094 } else if (FT->getCallConv() != CC_C) {
13095 FT = Context.adjustFunctionType(Fn: FT,
13096 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
13097 FD->setType(QualType(FT, 0));
13098 }
13099 }
13100
13101 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13102 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13103 FD->setInvalidDecl();
13104 }
13105}
13106
13107bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
13108 // FIXME: Need strict checking. In C89, we need to check for
13109 // any assignment, increment, decrement, function-calls, or
13110 // commas outside of a sizeof. In C99, it's the same list,
13111 // except that the aforementioned are allowed in unevaluated
13112 // expressions. Everything else falls under the
13113 // "may accept other forms of constant expressions" exception.
13114 //
13115 // Regular C++ code will not end up here (exceptions: language extensions,
13116 // OpenCL C++ etc), so the constant expression rules there don't matter.
13117 if (Init->isValueDependent()) {
13118 assert(Init->containsErrors() &&
13119 "Dependent code should only occur in error-recovery path.");
13120 return true;
13121 }
13122 const Expr *Culprit;
13123 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
13124 return false;
13125
13126 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13127 // casts and parentheses that it does not look through: under ARC an
13128 // object-pointer initializer is an `ImplicitCastExpr
13129 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13130 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13131 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13132 // the ObjC-specific classification and per-element reporting below can see
13133 // the underlying literal regardless of how it is wrapped.
13134 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13135
13136 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13137 if (getLangOpts().ObjCConstantLiterals &&
13138 isa<ObjCObjectLiteral>(Val: CulpritLiteral)) {
13139
13140 // For collection literals, iterate the elements to point at the specific
13141 // offender. These per-element checks mirror the constant-initializer rules
13142 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13143 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13144 // constant object literal, and dictionary keys must additionally be string
13145 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13146 // `id`, so the isa<> classification is done on the unwrapped expression.
13147 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(Val: CulpritLiteral)) {
13148 for (const Expr *Elm : ALE->elements()) {
13149 if (!isa<ObjCObjectLiteral>(Val: Elm->IgnoreImpCasts()) ||
13150 !Elm->isConstantInitializer(Ctx&: Context)) {
13151 Diag(Loc: Elm->getExprLoc(),
13152 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13153 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
13154 return true;
13155 }
13156 }
13157 }
13158
13159 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(Val: CulpritLiteral)) {
13160 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13161 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
13162
13163 // Keys must be constant string literals.
13164 if (!isa<ObjCStringLiteral>(Val: Elm.Key->IgnoreImpCasts()) ||
13165 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
13166 Diag(Loc: Elm.Key->getExprLoc(),
13167 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13168 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
13169 return true;
13170 }
13171
13172 // Values must be constant object literals.
13173 if (!isa<ObjCObjectLiteral>(Val: Elm.Value->IgnoreImpCasts()) ||
13174 !Elm.Value->isConstantInitializer(Ctx&: Context)) {
13175 Diag(Loc: Elm.Value->getExprLoc(),
13176 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13177 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
13178 return true;
13179 }
13180 }
13181 }
13182
13183 Diag(Loc: CulpritLiteral->getExprLoc(),
13184 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13185 << ObjC().CheckLiteralKind(FromE: Init) << CulpritLiteral->getSourceRange();
13186 return true;
13187 }
13188
13189 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13190 return true;
13191}
13192
13193namespace {
13194 // Visits an initialization expression to see if OrigDecl is evaluated in
13195 // its own initialization and throws a warning if it does.
13196 class SelfReferenceChecker
13197 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13198 Sema &S;
13199 Decl *OrigDecl;
13200 bool isRecordType;
13201 bool isPODType;
13202 bool isReferenceType;
13203 bool isInCXXOperatorCall;
13204
13205 bool isInitList;
13206 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13207
13208 public:
13209 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
13210
13211 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13212 S(S), OrigDecl(OrigDecl) {
13213 isPODType = false;
13214 isRecordType = false;
13215 isReferenceType = false;
13216 isInCXXOperatorCall = false;
13217 isInitList = false;
13218 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
13219 isPODType = VD->getType().isPODType(Context: S.Context);
13220 isRecordType = VD->getType()->isRecordType();
13221 isReferenceType = VD->getType()->isReferenceType();
13222 }
13223 }
13224
13225 // For most expressions, just call the visitor. For initializer lists,
13226 // track the index of the field being initialized since fields are
13227 // initialized in order allowing use of previously initialized fields.
13228 void CheckExpr(Expr *E) {
13229 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
13230 if (!InitList) {
13231 Visit(S: E);
13232 return;
13233 }
13234
13235 // Track and increment the index here.
13236 isInitList = true;
13237 InitFieldIndex.push_back(Elt: 0);
13238 for (auto *Child : InitList->children()) {
13239 CheckExpr(E: cast<Expr>(Val: Child));
13240 ++InitFieldIndex.back();
13241 }
13242 InitFieldIndex.pop_back();
13243 }
13244
13245 // Returns true if MemberExpr is checked and no further checking is needed.
13246 // Returns false if additional checking is required.
13247 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13248 llvm::SmallVector<FieldDecl*, 4> Fields;
13249 Expr *Base = E;
13250 bool ReferenceField = false;
13251
13252 // Get the field members used.
13253 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13254 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13255 if (!FD)
13256 return false;
13257 Fields.push_back(Elt: FD);
13258 if (FD->getType()->isReferenceType())
13259 ReferenceField = true;
13260 Base = ME->getBase()->IgnoreParenImpCasts();
13261 }
13262
13263 // Keep checking only if the base Decl is the same.
13264 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13265 if (!DRE || DRE->getDecl() != OrigDecl)
13266 return false;
13267
13268 // A reference field can be bound to an unininitialized field.
13269 if (CheckReference && !ReferenceField)
13270 return true;
13271
13272 // Convert FieldDecls to their index number.
13273 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13274 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13275 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13276
13277 // See if a warning is needed by checking the first difference in index
13278 // numbers. If field being used has index less than the field being
13279 // initialized, then the use is safe.
13280 for (auto UsedIter = UsedFieldIndex.begin(),
13281 UsedEnd = UsedFieldIndex.end(),
13282 OrigIter = InitFieldIndex.begin(),
13283 OrigEnd = InitFieldIndex.end();
13284 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13285 if (*UsedIter < *OrigIter)
13286 return true;
13287 if (*UsedIter > *OrigIter)
13288 break;
13289 }
13290
13291 // TODO: Add a different warning which will print the field names.
13292 HandleDeclRefExpr(DRE);
13293 return true;
13294 }
13295
13296 // For most expressions, the cast is directly above the DeclRefExpr.
13297 // For conditional operators, the cast can be outside the conditional
13298 // operator if both expressions are DeclRefExpr's.
13299 void HandleValue(Expr *E) {
13300 E = E->IgnoreParens();
13301 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13302 HandleDeclRefExpr(DRE);
13303 return;
13304 }
13305
13306 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13307 Visit(S: CO->getCond());
13308 HandleValue(E: CO->getTrueExpr());
13309 HandleValue(E: CO->getFalseExpr());
13310 return;
13311 }
13312
13313 if (BinaryConditionalOperator *BCO =
13314 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13315 Visit(S: BCO->getCond());
13316 HandleValue(E: BCO->getFalseExpr());
13317 return;
13318 }
13319
13320 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13321 if (Expr *SE = OVE->getSourceExpr())
13322 HandleValue(E: SE);
13323 return;
13324 }
13325
13326 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13327 if (BO->getOpcode() == BO_Comma) {
13328 Visit(S: BO->getLHS());
13329 HandleValue(E: BO->getRHS());
13330 return;
13331 }
13332 }
13333
13334 if (isa<MemberExpr>(Val: E)) {
13335 if (isInitList) {
13336 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13337 CheckReference: false /*CheckReference*/))
13338 return;
13339 }
13340
13341 Expr *Base = E->IgnoreParenImpCasts();
13342 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13343 // Check for static member variables and don't warn on them.
13344 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13345 return;
13346 Base = ME->getBase()->IgnoreParenImpCasts();
13347 }
13348 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13349 HandleDeclRefExpr(DRE);
13350 return;
13351 }
13352
13353 Visit(S: E);
13354 }
13355
13356 // Reference types not handled in HandleValue are handled here since all
13357 // uses of references are bad, not just r-value uses.
13358 void VisitDeclRefExpr(DeclRefExpr *E) {
13359 if (isReferenceType)
13360 HandleDeclRefExpr(DRE: E);
13361 }
13362
13363 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13364 if (E->getCastKind() == CK_LValueToRValue) {
13365 HandleValue(E: E->getSubExpr());
13366 return;
13367 }
13368
13369 Inherited::VisitImplicitCastExpr(S: E);
13370 }
13371
13372 void VisitMemberExpr(MemberExpr *E) {
13373 if (isInitList) {
13374 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13375 return;
13376 }
13377
13378 // Don't warn on arrays since they can be treated as pointers.
13379 if (E->getType()->canDecayToPointerType()) return;
13380
13381 // Warn when a non-static method call is followed by non-static member
13382 // field accesses, which is followed by a DeclRefExpr.
13383 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13384 bool Warn = (MD && !MD->isStatic());
13385 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13386 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13387 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13388 Warn = false;
13389 Base = ME->getBase()->IgnoreParenImpCasts();
13390 }
13391
13392 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13393 if (Warn)
13394 HandleDeclRefExpr(DRE);
13395 return;
13396 }
13397
13398 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13399 // Visit that expression.
13400 Visit(S: Base);
13401 }
13402
13403 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13404 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13405 Expr *Callee = E->getCallee();
13406
13407 if (isa<UnresolvedLookupExpr>(Val: Callee))
13408 return Inherited::VisitCXXOperatorCallExpr(S: E);
13409
13410 Visit(S: Callee);
13411 for (auto Arg: E->arguments())
13412 HandleValue(E: Arg->IgnoreParenImpCasts());
13413 }
13414
13415 void VisitLambdaExpr(LambdaExpr *E) {
13416 if (!isInCXXOperatorCall) {
13417 Inherited::VisitLambdaExpr(LE: E);
13418 return;
13419 }
13420
13421 for (Expr *Init : E->capture_inits())
13422 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13423 HandleDeclRefExpr(DRE);
13424 else if (Init)
13425 Visit(S: Init);
13426 }
13427
13428 void VisitUnaryOperator(UnaryOperator *E) {
13429 // For POD record types, addresses of its own members are well-defined.
13430 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13431 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13432 if (!isPODType)
13433 HandleValue(E: E->getSubExpr());
13434 return;
13435 }
13436
13437 if (E->isIncrementDecrementOp()) {
13438 HandleValue(E: E->getSubExpr());
13439 return;
13440 }
13441
13442 Inherited::VisitUnaryOperator(S: E);
13443 }
13444
13445 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13446
13447 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13448 if (E->getConstructor()->isCopyConstructor()) {
13449 Expr *ArgExpr = E->getArg(Arg: 0);
13450 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13451 if (ILE->getNumInits() == 1)
13452 ArgExpr = ILE->getInit(Init: 0);
13453 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13454 if (ICE->getCastKind() == CK_NoOp)
13455 ArgExpr = ICE->getSubExpr();
13456 HandleValue(E: ArgExpr);
13457 return;
13458 }
13459 Inherited::VisitCXXConstructExpr(S: E);
13460 }
13461
13462 void VisitCallExpr(CallExpr *E) {
13463 // Treat std::move as a use.
13464 if (E->isCallToStdMove()) {
13465 HandleValue(E: E->getArg(Arg: 0));
13466 return;
13467 }
13468
13469 Inherited::VisitCallExpr(CE: E);
13470 }
13471
13472 void VisitBinaryOperator(BinaryOperator *E) {
13473 if (E->isCompoundAssignmentOp()) {
13474 HandleValue(E: E->getLHS());
13475 Visit(S: E->getRHS());
13476 return;
13477 }
13478
13479 Inherited::VisitBinaryOperator(S: E);
13480 }
13481
13482 // A custom visitor for BinaryConditionalOperator is needed because the
13483 // regular visitor would check the condition and true expression separately
13484 // but both point to the same place giving duplicate diagnostics.
13485 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13486 Visit(S: E->getCond());
13487 Visit(S: E->getFalseExpr());
13488 }
13489
13490 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13491 Decl* ReferenceDecl = DRE->getDecl();
13492 if (OrigDecl != ReferenceDecl) return;
13493 unsigned diag;
13494 if (isReferenceType) {
13495 diag = diag::warn_uninit_self_reference_in_reference_init;
13496 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13497 diag = diag::warn_static_self_reference_in_init;
13498 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13499 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13500 DRE->getDecl()->getType()->isRecordType()) {
13501 diag = diag::warn_uninit_self_reference_in_init;
13502 } else {
13503 // Local variables will be handled by the CFG analysis.
13504 return;
13505 }
13506
13507 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13508 PD: S.PDiag(DiagID: diag)
13509 << DRE->getDecl() << OrigDecl->getLocation()
13510 << DRE->getSourceRange());
13511 }
13512 };
13513
13514 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13515 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13516 bool DirectInit) {
13517 // Parameters arguments are occassionially constructed with itself,
13518 // for instance, in recursive functions. Skip them.
13519 if (isa<ParmVarDecl>(Val: OrigDecl))
13520 return;
13521
13522 // Skip checking for file-scope constexpr variables - constant evaluation
13523 // will produce appropriate errors without needing runtime diagnostics.
13524 // Local constexpr should still emit runtime warnings.
13525 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13526 VD && VD->isConstexpr() && VD->isFileVarDecl())
13527 return;
13528
13529 E = E->IgnoreParens();
13530
13531 // Skip checking T a = a where T is not a record or reference type.
13532 // Doing so is a way to silence uninitialized warnings.
13533 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13534 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13535 if (ICE->getCastKind() == CK_LValueToRValue)
13536 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13537 if (DRE->getDecl() == OrigDecl)
13538 return;
13539
13540 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13541 }
13542} // end anonymous namespace
13543
13544namespace {
13545 // Simple wrapper to add the name of a variable or (if no variable is
13546 // available) a DeclarationName into a diagnostic.
13547 struct VarDeclOrName {
13548 VarDecl *VDecl;
13549 DeclarationName Name;
13550
13551 friend const Sema::SemaDiagnosticBuilder &
13552 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13553 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13554 }
13555 };
13556} // end anonymous namespace
13557
13558QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13559 DeclarationName Name, QualType Type,
13560 TypeSourceInfo *TSI,
13561 SourceRange Range, bool DirectInit,
13562 Expr *Init) {
13563 bool IsInitCapture = !VDecl;
13564 assert((!VDecl || !VDecl->isInitCapture()) &&
13565 "init captures are expected to be deduced prior to initialization");
13566
13567 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13568
13569 DeducedType *Deduced = Type->getContainedDeducedType();
13570 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13571
13572 // Diagnose auto array declarations in C23, unless it's a supported extension.
13573 if (getLangOpts().C23 && Type->isArrayType() &&
13574 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13575 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13576 << (int)Deduced->getContainedAutoType()->getKeyword()
13577 << /*in array decl*/ 23 << Range;
13578 return QualType();
13579 }
13580
13581 // C++11 [dcl.spec.auto]p3
13582 if (!Init) {
13583 assert(VDecl && "no init for init capture deduction?");
13584
13585 // Except for class argument deduction, and then for an initializing
13586 // declaration only, i.e. no static at class scope or extern.
13587 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13588 VDecl->hasExternalStorage() ||
13589 VDecl->isStaticDataMember()) {
13590 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13591 << VDecl->getDeclName() << Type;
13592 return QualType();
13593 }
13594 }
13595
13596 ArrayRef<Expr*> DeduceInits;
13597 if (Init)
13598 DeduceInits = Init;
13599
13600 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13601 if (DirectInit && PL)
13602 DeduceInits = PL->exprs();
13603
13604 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13605 assert(VDecl && "non-auto type for init capture deduction?");
13606 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13607 InitializationKind Kind = InitializationKind::CreateForInit(
13608 Loc: VDecl->getLocation(), DirectInit, Init);
13609 // FIXME: Initialization should not be taking a mutable list of inits.
13610 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13611 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13612 Init: InitsCopy);
13613 }
13614
13615 if (DirectInit) {
13616 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13617 DeduceInits = IL->inits();
13618 }
13619
13620 // Deduction only works if we have exactly one source expression.
13621 if (DeduceInits.empty()) {
13622 // It isn't possible to write this directly, but it is possible to
13623 // end up in this situation with "auto x(some_pack...);"
13624 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13625 ? diag::err_init_capture_no_expression
13626 : diag::err_auto_var_init_no_expression)
13627 << VN << Type << Range;
13628 return QualType();
13629 }
13630
13631 if (DeduceInits.size() > 1) {
13632 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13633 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13634 : diag::err_auto_var_init_multiple_expressions)
13635 << VN << Type << Range;
13636 return QualType();
13637 }
13638
13639 Expr *DeduceInit = DeduceInits[0];
13640 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13641 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13642 ? diag::err_init_capture_paren_braces
13643 : diag::err_auto_var_init_paren_braces)
13644 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13645 return QualType();
13646 }
13647
13648 // Expressions default to 'id' when we're in a debugger.
13649 bool DefaultedAnyToId = false;
13650 if (getLangOpts().DebuggerCastResultToId &&
13651 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13652 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13653 if (Result.isInvalid()) {
13654 return QualType();
13655 }
13656 Init = Result.get();
13657 DefaultedAnyToId = true;
13658 }
13659
13660 // C++ [dcl.decomp]p1:
13661 // If the assignment-expression [...] has array type A and no ref-qualifier
13662 // is present, e has type cv A
13663 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13664 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13665 DeduceInit->getType()->isConstantArrayType())
13666 return Context.getQualifiedType(T: DeduceInit->getType(),
13667 Qs: Type.getQualifiers());
13668
13669 QualType DeducedType;
13670 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13671 TemplateDeductionResult Result =
13672 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13673 if (Result != TemplateDeductionResult::Success &&
13674 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13675 if (!IsInitCapture)
13676 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13677 else if (isa<InitListExpr>(Val: Init))
13678 Diag(Loc: Range.getBegin(),
13679 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13680 << VN
13681 << (DeduceInit->getType().isNull() ? TSI->getType()
13682 : DeduceInit->getType())
13683 << DeduceInit->getSourceRange();
13684 else
13685 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13686 << VN << TSI->getType()
13687 << (DeduceInit->getType().isNull() ? TSI->getType()
13688 : DeduceInit->getType())
13689 << DeduceInit->getSourceRange();
13690 }
13691
13692 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13693 // 'id' instead of a specific object type prevents most of our usual
13694 // checks.
13695 // We only want to warn outside of template instantiations, though:
13696 // inside a template, the 'id' could have come from a parameter.
13697 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13698 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13699 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13700 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13701 }
13702
13703 return DeducedType;
13704}
13705
13706bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13707 Expr *Init) {
13708 assert(!Init || !Init->containsErrors());
13709 QualType DeducedType = deduceVarTypeFromInitializer(
13710 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13711 Range: VDecl->getSourceRange(), DirectInit, Init);
13712 if (DeducedType.isNull()) {
13713 VDecl->setInvalidDecl();
13714 return true;
13715 }
13716
13717 VDecl->setType(DeducedType);
13718 assert(VDecl->isLinkageValid());
13719
13720 // In ARC, infer lifetime.
13721 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13722 VDecl->setInvalidDecl();
13723
13724 if (getLangOpts().OpenCL)
13725 deduceOpenCLAddressSpace(Var: VDecl);
13726
13727 if (getLangOpts().HLSL)
13728 HLSL().deduceAddressSpace(Decl: VDecl);
13729
13730 // If this is a redeclaration, check that the type we just deduced matches
13731 // the previously declared type.
13732 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13733 // We never need to merge the type, because we cannot form an incomplete
13734 // array of auto, nor deduce such a type.
13735 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13736 }
13737
13738 // Check the deduced type is valid for a variable declaration.
13739 CheckVariableDeclarationType(NewVD: VDecl);
13740 return VDecl->isInvalidDecl();
13741}
13742
13743void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13744 SourceLocation Loc) {
13745 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13746 Init = EWC->getSubExpr();
13747
13748 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13749 Init = CE->getSubExpr();
13750
13751 QualType InitType = Init->getType();
13752 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13753 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13754 "shouldn't be called if type doesn't have a non-trivial C struct");
13755 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13756 for (auto *I : ILE->inits()) {
13757 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13758 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13759 continue;
13760 SourceLocation SL = I->getExprLoc();
13761 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13762 }
13763 return;
13764 }
13765
13766 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13767 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13768 checkNonTrivialCUnion(QT: InitType, Loc,
13769 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13770 NonTrivialKind: NTCUK_Init);
13771 } else {
13772 // Assume all other explicit initializers involving copying some existing
13773 // object.
13774 // TODO: ignore any explicit initializers where we can guarantee
13775 // copy-elision.
13776 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13777 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13778 NonTrivialKind: NTCUK_Copy);
13779 }
13780}
13781
13782namespace {
13783
13784bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13785 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13786 // in the source code or implicitly by the compiler if it is in a union
13787 // defined in a system header and has non-trivial ObjC ownership
13788 // qualifications. We don't want those fields to participate in determining
13789 // whether the containing union is non-trivial.
13790 return FD->hasAttr<UnavailableAttr>();
13791}
13792
13793struct DiagNonTrivalCUnionDefaultInitializeVisitor
13794 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13795 void> {
13796 using Super =
13797 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13798 void>;
13799
13800 DiagNonTrivalCUnionDefaultInitializeVisitor(
13801 QualType OrigTy, SourceLocation OrigLoc,
13802 NonTrivialCUnionContext UseContext, Sema &S)
13803 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13804
13805 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13806 const FieldDecl *FD, bool InNonTrivialUnion) {
13807 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13808 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13809 Args&: InNonTrivialUnion);
13810 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13811 }
13812
13813 void visitARCStrong(QualType QT, const FieldDecl *FD,
13814 bool InNonTrivialUnion) {
13815 if (InNonTrivialUnion)
13816 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13817 << 1 << 0 << QT << FD->getName();
13818 }
13819
13820 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13821 if (InNonTrivialUnion)
13822 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13823 << 1 << 0 << QT << FD->getName();
13824 }
13825
13826 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13827 const auto *RD = QT->castAsRecordDecl();
13828 if (RD->isUnion()) {
13829 if (OrigLoc.isValid()) {
13830 bool IsUnion = false;
13831 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13832 IsUnion = OrigRD->isUnion();
13833 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13834 << 0 << OrigTy << IsUnion << UseContext;
13835 // Reset OrigLoc so that this diagnostic is emitted only once.
13836 OrigLoc = SourceLocation();
13837 }
13838 InNonTrivialUnion = true;
13839 }
13840
13841 if (InNonTrivialUnion)
13842 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13843 << 0 << 0 << QT.getUnqualifiedType() << "";
13844
13845 for (const FieldDecl *FD : RD->fields())
13846 if (!shouldIgnoreForRecordTriviality(FD))
13847 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13848 }
13849
13850 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13851
13852 // The non-trivial C union type or the struct/union type that contains a
13853 // non-trivial C union.
13854 QualType OrigTy;
13855 SourceLocation OrigLoc;
13856 NonTrivialCUnionContext UseContext;
13857 Sema &S;
13858};
13859
13860struct DiagNonTrivalCUnionDestructedTypeVisitor
13861 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13862 using Super =
13863 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13864
13865 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13866 SourceLocation OrigLoc,
13867 NonTrivialCUnionContext UseContext,
13868 Sema &S)
13869 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13870
13871 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13872 const FieldDecl *FD, bool InNonTrivialUnion) {
13873 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13874 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13875 Args&: InNonTrivialUnion);
13876 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13877 }
13878
13879 void visitARCStrong(QualType QT, const FieldDecl *FD,
13880 bool InNonTrivialUnion) {
13881 if (InNonTrivialUnion)
13882 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13883 << 1 << 1 << QT << FD->getName();
13884 }
13885
13886 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13887 if (InNonTrivialUnion)
13888 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13889 << 1 << 1 << QT << FD->getName();
13890 }
13891
13892 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13893 const auto *RD = QT->castAsRecordDecl();
13894 if (RD->isUnion()) {
13895 if (OrigLoc.isValid()) {
13896 bool IsUnion = false;
13897 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13898 IsUnion = OrigRD->isUnion();
13899 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13900 << 1 << OrigTy << IsUnion << UseContext;
13901 // Reset OrigLoc so that this diagnostic is emitted only once.
13902 OrigLoc = SourceLocation();
13903 }
13904 InNonTrivialUnion = true;
13905 }
13906
13907 if (InNonTrivialUnion)
13908 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13909 << 0 << 1 << QT.getUnqualifiedType() << "";
13910
13911 for (const FieldDecl *FD : RD->fields())
13912 if (!shouldIgnoreForRecordTriviality(FD))
13913 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13914 }
13915
13916 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13917 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13918 bool InNonTrivialUnion) {}
13919
13920 // The non-trivial C union type or the struct/union type that contains a
13921 // non-trivial C union.
13922 QualType OrigTy;
13923 SourceLocation OrigLoc;
13924 NonTrivialCUnionContext UseContext;
13925 Sema &S;
13926};
13927
13928struct DiagNonTrivalCUnionCopyVisitor
13929 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13930 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13931
13932 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13933 NonTrivialCUnionContext UseContext, Sema &S)
13934 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13935
13936 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13937 const FieldDecl *FD, bool InNonTrivialUnion) {
13938 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13939 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13940 Args&: InNonTrivialUnion);
13941 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13942 }
13943
13944 void visitARCStrong(QualType QT, const FieldDecl *FD,
13945 bool InNonTrivialUnion) {
13946 if (InNonTrivialUnion)
13947 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13948 << 1 << 2 << QT << FD->getName();
13949 }
13950
13951 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13952 if (InNonTrivialUnion)
13953 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13954 << 1 << 2 << QT << FD->getName();
13955 }
13956
13957 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13958 const auto *RD = QT->castAsRecordDecl();
13959 if (RD->isUnion()) {
13960 if (OrigLoc.isValid()) {
13961 bool IsUnion = false;
13962 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13963 IsUnion = OrigRD->isUnion();
13964 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13965 << 2 << OrigTy << IsUnion << UseContext;
13966 // Reset OrigLoc so that this diagnostic is emitted only once.
13967 OrigLoc = SourceLocation();
13968 }
13969 InNonTrivialUnion = true;
13970 }
13971
13972 if (InNonTrivialUnion)
13973 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13974 << 0 << 2 << QT.getUnqualifiedType() << "";
13975
13976 for (const FieldDecl *FD : RD->fields())
13977 if (!shouldIgnoreForRecordTriviality(FD))
13978 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13979 }
13980
13981 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13982 if (InNonTrivialUnion)
13983 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13984 << 1 << 2 << QT << FD->getName();
13985 }
13986
13987 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13988 const FieldDecl *FD, bool InNonTrivialUnion) {}
13989 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13990 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13991 bool InNonTrivialUnion) {}
13992
13993 // The non-trivial C union type or the struct/union type that contains a
13994 // non-trivial C union.
13995 QualType OrigTy;
13996 SourceLocation OrigLoc;
13997 NonTrivialCUnionContext UseContext;
13998 Sema &S;
13999};
14000
14001} // namespace
14002
14003void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
14004 NonTrivialCUnionContext UseContext,
14005 unsigned NonTrivialKind) {
14006 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14007 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
14008 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
14009 "shouldn't be called if type doesn't have a non-trivial C union");
14010
14011 if ((NonTrivialKind & NTCUK_Init) &&
14012 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14013 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
14014 .visit(FT: QT, Args: nullptr, Args: false);
14015 if ((NonTrivialKind & NTCUK_Destruct) &&
14016 QT.hasNonTrivialToPrimitiveDestructCUnion())
14017 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
14018 .visit(FT: QT, Args: nullptr, Args: false);
14019 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
14020 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
14021 .visit(FT: QT, Args: nullptr, Args: false);
14022}
14023
14024bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
14025 const VarDecl *Dcl) {
14026 if (!getLangOpts().CPlusPlus)
14027 return false;
14028
14029 // We only need to warn if the definition is in a header file, so wait to
14030 // diagnose until we've seen the definition.
14031 if (!Dcl->isThisDeclarationADefinition())
14032 return false;
14033
14034 // If an object is defined in a source file, its definition can't get
14035 // duplicated since it will never appear in more than one TU.
14036 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
14037 return false;
14038
14039 // If the variable we're looking at is a static local, then we actually care
14040 // about the properties of the function containing it.
14041 const ValueDecl *Target = Dcl;
14042 // VarDecls and FunctionDecls have different functions for checking
14043 // inline-ness, and whether they were originally templated, so we have to
14044 // call the appropriate functions manually.
14045 bool TargetIsInline = Dcl->isInline();
14046 bool TargetWasTemplated =
14047 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
14048
14049 // Update the Target and TargetIsInline property if necessary
14050 if (Dcl->isStaticLocal()) {
14051 const DeclContext *Ctx = Dcl->getDeclContext();
14052 if (!Ctx)
14053 return false;
14054
14055 const FunctionDecl *FunDcl =
14056 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
14057 if (!FunDcl)
14058 return false;
14059
14060 Target = FunDcl;
14061 // IsInlined() checks for the C++ inline property
14062 TargetIsInline = FunDcl->isInlined();
14063 TargetWasTemplated =
14064 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
14065 }
14066
14067 // Non-inline functions/variables can only legally appear in one TU
14068 // unless they were part of a template. Unfortunately, making complex
14069 // template instantiations visible is infeasible in practice, since
14070 // everything the template depends on also has to be visible. To avoid
14071 // giving impractical-to-fix warnings, don't warn if we're inside
14072 // something that was templated, even on inline stuff.
14073 if (!TargetIsInline || TargetWasTemplated)
14074 return false;
14075
14076 // If the object isn't hidden, the dynamic linker will prevent duplication.
14077 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14078
14079 // The target is "hidden" (from the dynamic linker) if:
14080 // 1. On posix, it has hidden visibility, or
14081 // 2. On windows, it has no import/export annotation, and neither does the
14082 // class which directly contains it.
14083 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14084 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14085 return false;
14086
14087 // If the variable isn't directly annotated, check to see if it's a member
14088 // of an annotated class.
14089 const CXXRecordDecl *Ctx =
14090 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
14091 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14092 return false;
14093
14094 } else if (Lnk.getVisibility() != HiddenVisibility) {
14095 // Posix case
14096 return false;
14097 }
14098
14099 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14100 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
14101 return false;
14102
14103 return true;
14104}
14105
14106// Determine whether the object seems mutable for the purpose of diagnosing
14107// possible unique object duplication, i.e. non-const-qualified, and
14108// not an always-constant type like a function.
14109// Not perfect: doesn't account for mutable members, for example, or
14110// elements of container types.
14111// For nested pointers, any individual level being non-const is sufficient.
14112static bool looksMutable(QualType T, const ASTContext &Ctx) {
14113 T = T.getNonReferenceType();
14114 if (T->isFunctionType())
14115 return false;
14116 if (!T.isConstant(Ctx))
14117 return true;
14118 if (T->isPointerType())
14119 return looksMutable(T: T->getPointeeType(), Ctx);
14120 return false;
14121}
14122
14123void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
14124 // If this object has external linkage and hidden visibility, it might be
14125 // duplicated when built into a shared library, which causes problems if it's
14126 // mutable (since the copies won't be in sync) or its initialization has side
14127 // effects (since it will run once per copy instead of once globally).
14128
14129 // Don't diagnose if we're inside a template, because it's not practical to
14130 // fix the warning in most cases.
14131 if (!VD->isTemplated() &&
14132 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
14133
14134 QualType Type = VD->getType();
14135 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
14136 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
14137 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14138 }
14139
14140 // To keep false positives low, only warn if we're certain that the
14141 // initializer has side effects. Don't warn on operator new, since a mutable
14142 // pointer will trigger the previous warning, and an immutable pointer
14143 // getting duplicated just results in a little extra memory usage.
14144 const Expr *Init = VD->getAnyInitializer();
14145 if (Init &&
14146 Init->HasSideEffects(Ctx: VD->getASTContext(),
14147 /*IncludePossibleEffects=*/false) &&
14148 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
14149 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
14150 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14151 }
14152 }
14153}
14154
14155void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
14156 llvm::scope_exit ResetDeclForInitializer([this]() {
14157 if (!this->ExprEvalContexts.empty())
14158 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14159 });
14160
14161 // If there is no declaration, there was an error parsing it. Just ignore
14162 // the initializer.
14163 if (!RealDecl) {
14164 return;
14165 }
14166
14167 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
14168 if (!Method->isInvalidDecl()) {
14169 // Pure-specifiers are handled in ActOnPureSpecifier.
14170 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
14171 << Method->getDeclName() << Init->getSourceRange();
14172 Method->setInvalidDecl();
14173 }
14174 return;
14175 }
14176
14177 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
14178 if (!VDecl) {
14179 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14180 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
14181 RealDecl->setInvalidDecl();
14182 return;
14183 }
14184
14185 if (VDecl->isInvalidDecl()) {
14186 ExprResult Recovery =
14187 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
14188 if (Expr *E = Recovery.get())
14189 VDecl->setInit(E);
14190 return;
14191 }
14192
14193 // __amdgpu_feature_predicate_t cannot be initialised
14194 if (VDecl->getType().getDesugaredType(Context) ==
14195 Context.AMDGPUFeaturePredicateTy) {
14196 Diag(Loc: VDecl->getLocation(),
14197 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14198 << VDecl;
14199 VDecl->setInvalidDecl();
14200 return;
14201 }
14202
14203 // WebAssembly tables can't be used to initialise a variable.
14204 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14205 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
14206 VDecl->setInvalidDecl();
14207 return;
14208 }
14209
14210 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14211 if (VDecl->getType()->isUndeducedType()) {
14212 if (Init->containsErrors()) {
14213 // Invalidate the decl as we don't know the type for recovery-expr yet.
14214 RealDecl->setInvalidDecl();
14215 VDecl->setInit(Init);
14216 return;
14217 }
14218
14219 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
14220 assert(VDecl->isInvalidDecl() &&
14221 "decl should be invalidated when deduce fails");
14222 if (auto *RecoveryExpr =
14223 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
14224 .get())
14225 VDecl->setInit(RecoveryExpr);
14226 return;
14227 }
14228 }
14229
14230 this->CheckAttributesOnDeducedType(D: RealDecl);
14231
14232 // we don't initialize groupshared variables so warn and return
14233 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14234 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
14235 return;
14236 }
14237
14238 // dllimport cannot be used on variable definitions.
14239 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14240 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
14241 VDecl->setInvalidDecl();
14242 return;
14243 }
14244
14245 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14246 // the identifier has external or internal linkage, the declaration shall
14247 // have no initializer for the identifier.
14248 // C++14 [dcl.init]p5 is the same restriction for C++.
14249 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14250 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14251 VDecl->setInvalidDecl();
14252 return;
14253 }
14254
14255 if (!VDecl->getType()->isDependentType()) {
14256 // A definition must end up with a complete type, which means it must be
14257 // complete with the restriction that an array type might be completed by
14258 // the initializer; note that later code assumes this restriction.
14259 QualType BaseDeclType = VDecl->getType();
14260 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14261 BaseDeclType = Array->getElementType();
14262 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14263 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14264 RealDecl->setInvalidDecl();
14265 return;
14266 }
14267
14268 // The variable can not have an abstract class type.
14269 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14270 DiagID: diag::err_abstract_type_in_decl,
14271 Args: AbstractVariableType))
14272 VDecl->setInvalidDecl();
14273 }
14274
14275 // C++ [module.import/6]
14276 // ...
14277 // A header unit shall not contain a definition of a non-inline function or
14278 // variable whose name has external linkage.
14279 //
14280 // We choose to allow weak & selectany definitions, as they are common in
14281 // headers, and have semantics similar to inline definitions which are allowed
14282 // in header units.
14283 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14284 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14285 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14286 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14287 !VDecl->getInstantiatedFromStaticDataMember() &&
14288 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14289 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14290 VDecl->setInvalidDecl();
14291 }
14292
14293 // If adding the initializer will turn this declaration into a definition,
14294 // and we already have a definition for this variable, diagnose or otherwise
14295 // handle the situation.
14296 if (VarDecl *Def = VDecl->getDefinition())
14297 if (Def != VDecl &&
14298 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14299 !VDecl->isThisDeclarationADemotedDefinition() &&
14300 checkVarDeclRedefinition(Old: Def, New: VDecl))
14301 return;
14302
14303 if (getLangOpts().CPlusPlus) {
14304 // C++ [class.static.data]p4
14305 // If a static data member is of const integral or const
14306 // enumeration type, its declaration in the class definition can
14307 // specify a constant-initializer which shall be an integral
14308 // constant expression (5.19). In that case, the member can appear
14309 // in integral constant expressions. The member shall still be
14310 // defined in a namespace scope if it is used in the program and the
14311 // namespace scope definition shall not contain an initializer.
14312 //
14313 // We already performed a redefinition check above, but for static
14314 // data members we also need to check whether there was an in-class
14315 // declaration with an initializer.
14316 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14317 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14318 << VDecl->getDeclName();
14319 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14320 DiagID: diag::note_previous_initializer)
14321 << 0;
14322 return;
14323 }
14324
14325 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14326 VDecl->setInvalidDecl();
14327 return;
14328 }
14329 }
14330
14331 // If the variable has an initializer and local storage, check whether
14332 // anything jumps over the initialization.
14333 if (VDecl->hasLocalStorage())
14334 setFunctionHasBranchProtectedScope();
14335
14336 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14337 // a kernel function cannot be initialized."
14338 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14339 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14340 VDecl->setInvalidDecl();
14341 return;
14342 }
14343
14344 // The LoaderUninitialized attribute acts as a definition (of undef).
14345 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14346 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14347 VDecl->setInvalidDecl();
14348 return;
14349 }
14350
14351 if (getLangOpts().HLSL)
14352 if (!HLSL().handleInitialization(VDecl, Init))
14353 return;
14354
14355 if (Context.getTargetInfo().getTriple().isBPF())
14356 Init = BPF().checkLocalConstantInitializer(VD: VDecl, Init);
14357
14358 // Get the decls type and save a reference for later, since
14359 // CheckInitializerTypes may change it.
14360 QualType DclT = VDecl->getType(), SavT = DclT;
14361
14362 // Expressions default to 'id' when we're in a debugger
14363 // and we are assigning it to a variable of Objective-C pointer type.
14364 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14365 Init->getType() == Context.UnknownAnyTy) {
14366 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14367 if (!Result.isUsable()) {
14368 VDecl->setInvalidDecl();
14369 return;
14370 }
14371 Init = Result.get();
14372 }
14373
14374 // Perform the initialization.
14375 bool InitializedFromParenListExpr = false;
14376 bool IsParenListInit = false;
14377 if (!VDecl->isInvalidDecl()) {
14378 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14379 InitializationKind Kind = InitializationKind::CreateForInit(
14380 Loc: VDecl->getLocation(), DirectInit, Init);
14381
14382 MultiExprArg Args = Init;
14383 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14384 Args =
14385 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14386 InitializedFromParenListExpr = true;
14387 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14388 Args = CXXDirectInit->getInitExprs();
14389 InitializedFromParenListExpr = true;
14390 }
14391
14392 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14393 /*TopLevelOfInitList=*/false,
14394 /*TreatUnavailableAsInvalid=*/false);
14395 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14396 if (!Result.isUsable()) {
14397 // If the provided initializer fails to initialize the var decl,
14398 // we attach a recovery expr for better recovery.
14399 auto RecoveryExpr =
14400 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14401 if (RecoveryExpr.get())
14402 VDecl->setInit(RecoveryExpr.get());
14403 // In general, for error recovery purposes, the initializer doesn't play
14404 // part in the valid bit of the declaration. There are a few exceptions:
14405 // 1) if the var decl has a deduced auto type, and the type cannot be
14406 // deduced by an invalid initializer;
14407 // 2) if the var decl is a decomposition decl with a non-deduced type,
14408 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14409 // Case 1) was already handled elsewhere.
14410 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14411 VDecl->setInvalidDecl();
14412 return;
14413 }
14414
14415 Init = Result.getAs<Expr>();
14416 IsParenListInit = !InitSeq.steps().empty() &&
14417 InitSeq.step_begin()->Kind ==
14418 InitializationSequence::SK_ParenthesizedListInit;
14419 QualType VDeclType = VDecl->getType();
14420 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14421 !VDeclType->isDependentType() &&
14422 Context.getAsIncompleteArrayType(T: VDeclType) &&
14423 Context.getAsIncompleteArrayType(T: Init->getType())) {
14424 // Bail out if it is not possible to deduce array size from the
14425 // initializer.
14426 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14427 << VDeclType;
14428 VDecl->setInvalidDecl();
14429 return;
14430 }
14431 }
14432
14433 // Check for self-references within variable initializers.
14434 // Variables declared within a function/method body (except for references)
14435 // are handled by a dataflow analysis.
14436 // This is undefined behavior in C++, but valid in C.
14437 if (getLangOpts().CPlusPlus)
14438 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14439 VDecl->getType()->isReferenceType())
14440 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14441
14442 // If the type changed, it means we had an incomplete type that was
14443 // completed by the initializer. For example:
14444 // int ary[] = { 1, 3, 5 };
14445 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14446 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14447 VDecl->setType(DclT);
14448
14449 if (!VDecl->isInvalidDecl()) {
14450 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14451
14452 if (VDecl->hasAttr<BlocksAttr>())
14453 ObjC().checkRetainCycles(Var: VDecl, Init);
14454
14455 // It is safe to assign a weak reference into a strong variable.
14456 // Although this code can still have problems:
14457 // id x = self.weakProp;
14458 // id y = self.weakProp;
14459 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14460 // paths through the function. This should be revisited if
14461 // -Wrepeated-use-of-weak is made flow-sensitive.
14462 if (FunctionScopeInfo *FSI = getCurFunction())
14463 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14464 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14465 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14466 Loc: Init->getBeginLoc()))
14467 FSI->markSafeWeakUse(E: Init);
14468 }
14469
14470 // The initialization is usually a full-expression.
14471 //
14472 // FIXME: If this is a braced initialization of an aggregate, it is not
14473 // an expression, and each individual field initializer is a separate
14474 // full-expression. For instance, in:
14475 //
14476 // struct Temp { ~Temp(); };
14477 // struct S { S(Temp); };
14478 // struct T { S a, b; } t = { Temp(), Temp() }
14479 //
14480 // we should destroy the first Temp before constructing the second.
14481
14482 // Set context flag for OverflowBehaviorType initialization analysis
14483 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14484 true);
14485 ExprResult Result =
14486 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14487 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14488 if (!Result.isUsable()) {
14489 VDecl->setInvalidDecl();
14490 return;
14491 }
14492 Init = Result.get();
14493
14494 // Attach the initializer to the decl.
14495 VDecl->setInit(Init);
14496
14497 if (VDecl->isLocalVarDecl()) {
14498 // Don't check the initializer if the declaration is malformed.
14499 if (VDecl->isInvalidDecl()) {
14500 // do nothing
14501
14502 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14503 // This is true even in C++ for OpenCL.
14504 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14505 CheckForConstantInitializer(Init);
14506
14507 // Otherwise, C++ does not restrict the initializer.
14508 } else if (getLangOpts().CPlusPlus) {
14509 // do nothing
14510
14511 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14512 // static storage duration shall be constant expressions or string literals.
14513 } else if (VDecl->getStorageClass() == SC_Static) {
14514 // Avoid evaluating the initializer twice for constexpr variables. It will
14515 // be evaluated later.
14516 if (!VDecl->isConstexpr())
14517 CheckForConstantInitializer(Init);
14518
14519 // C89 is stricter than C99 for aggregate initializers.
14520 // C89 6.5.7p3: All the expressions [...] in an initializer list
14521 // for an object that has aggregate or union type shall be
14522 // constant expressions.
14523 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14524 isa<InitListExpr>(Val: Init)) {
14525 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14526 }
14527
14528 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14529 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14530 if (VDecl->hasLocalStorage())
14531 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14532 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14533 VDecl->getLexicalDeclContext()->isRecord()) {
14534 // This is an in-class initialization for a static data member, e.g.,
14535 //
14536 // struct S {
14537 // static const int value = 17;
14538 // };
14539
14540 // C++ [class.mem]p4:
14541 // A member-declarator can contain a constant-initializer only
14542 // if it declares a static member (9.4) of const integral or
14543 // const enumeration type, see 9.4.2.
14544 //
14545 // C++11 [class.static.data]p3:
14546 // If a non-volatile non-inline const static data member is of integral
14547 // or enumeration type, its declaration in the class definition can
14548 // specify a brace-or-equal-initializer in which every initializer-clause
14549 // that is an assignment-expression is a constant expression. A static
14550 // data member of literal type can be declared in the class definition
14551 // with the constexpr specifier; if so, its declaration shall specify a
14552 // brace-or-equal-initializer in which every initializer-clause that is
14553 // an assignment-expression is a constant expression.
14554
14555 // Do nothing on dependent types.
14556 if (DclT->isDependentType()) {
14557
14558 // Allow any 'static constexpr' members, whether or not they are of literal
14559 // type. We separately check that every constexpr variable is of literal
14560 // type.
14561 } else if (VDecl->isConstexpr()) {
14562
14563 // Require constness.
14564 } else if (!DclT.isConstQualified()) {
14565 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14566 << Init->getSourceRange();
14567 VDecl->setInvalidDecl();
14568
14569 // We allow integer constant expressions in all cases.
14570 } else if (DclT->isIntegralOrEnumerationType()) {
14571 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14572 // In C++11, a non-constexpr const static data member with an
14573 // in-class initializer cannot be volatile.
14574 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14575
14576 // We allow foldable floating-point constants as an extension.
14577 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14578 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14579 // it anyway and provide a fixit to add the 'constexpr'.
14580 if (getLangOpts().CPlusPlus11) {
14581 Diag(Loc: VDecl->getLocation(),
14582 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14583 << DclT << Init->getSourceRange();
14584 Diag(Loc: VDecl->getBeginLoc(),
14585 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14586 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14587 } else {
14588 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14589 << DclT << Init->getSourceRange();
14590
14591 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14592 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14593 << Init->getSourceRange();
14594 VDecl->setInvalidDecl();
14595 }
14596 }
14597
14598 // Suggest adding 'constexpr' in C++11 for literal types.
14599 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14600 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14601 << DclT << Init->getSourceRange()
14602 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14603 VDecl->setConstexpr(true);
14604
14605 } else {
14606 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14607 << DclT << Init->getSourceRange();
14608 VDecl->setInvalidDecl();
14609 }
14610 } else if (VDecl->isFileVarDecl()) {
14611 // In C, extern is typically used to avoid tentative definitions when
14612 // declaring variables in headers, but adding an initializer makes it a
14613 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14614 // In C++, extern is often used to give implicitly static const variables
14615 // external linkage, so don't warn in that case. If selectany is present,
14616 // this might be header code intended for C and C++ inclusion, so apply the
14617 // C++ rules.
14618 if (VDecl->getStorageClass() == SC_Extern &&
14619 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14620 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14621 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14622 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14623 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14624
14625 // In Microsoft C++ mode, a const variable defined in namespace scope has
14626 // external linkage by default if the variable is declared with
14627 // __declspec(dllexport).
14628 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14629 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14630 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14631 VDecl->setStorageClass(SC_Extern);
14632
14633 // C99 6.7.8p4. All file scoped initializers need to be constant.
14634 // Avoid duplicate diagnostics for constexpr variables.
14635 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14636 !VDecl->isConstexpr())
14637 CheckForConstantInitializer(Init);
14638 }
14639
14640 QualType InitType = Init->getType();
14641 if (!InitType.isNull() &&
14642 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14643 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14644 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14645
14646 // We will represent direct-initialization similarly to copy-initialization:
14647 // int x(1); -as-> int x = 1;
14648 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14649 //
14650 // Clients that want to distinguish between the two forms, can check for
14651 // direct initializer using VarDecl::getInitStyle().
14652 // A major benefit is that clients that don't particularly care about which
14653 // exactly form was it (like the CodeGen) can handle both cases without
14654 // special case code.
14655
14656 // C++ 8.5p11:
14657 // The form of initialization (using parentheses or '=') matters
14658 // when the entity being initialized has class type.
14659 if (InitializedFromParenListExpr) {
14660 assert(DirectInit && "Call-style initializer must be direct init.");
14661 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14662 : VarDecl::CallInit);
14663 } else if (DirectInit) {
14664 // This must be list-initialization. No other way is direct-initialization.
14665 VDecl->setInitStyle(VarDecl::ListInit);
14666 }
14667
14668 if (LangOpts.OpenMP &&
14669 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14670 VDecl->isFileVarDecl())
14671 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14672 CheckCompleteVariableDeclaration(VD: VDecl);
14673
14674 if (LangOpts.OpenACC && !InitType.isNull())
14675 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14676}
14677
14678void Sema::ActOnInitializerError(Decl *D) {
14679 // Our main concern here is re-establishing invariants like "a
14680 // variable's type is either dependent or complete".
14681 if (!D || D->isInvalidDecl()) return;
14682
14683 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14684 if (!VD) return;
14685
14686 // Bindings are not usable if we can't make sense of the initializer.
14687 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14688 for (auto *BD : DD->bindings())
14689 BD->setInvalidDecl();
14690
14691 // Auto types are meaningless if we can't make sense of the initializer.
14692 if (VD->getType()->isUndeducedType()) {
14693 D->setInvalidDecl();
14694 return;
14695 }
14696
14697 QualType Ty = VD->getType();
14698 if (Ty->isDependentType()) return;
14699
14700 // Require a complete type.
14701 if (RequireCompleteType(Loc: VD->getLocation(),
14702 T: Context.getBaseElementType(QT: Ty),
14703 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14704 VD->setInvalidDecl();
14705 return;
14706 }
14707
14708 // Require a non-abstract type.
14709 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14710 DiagID: diag::err_abstract_type_in_decl,
14711 Args: AbstractVariableType)) {
14712 VD->setInvalidDecl();
14713 return;
14714 }
14715
14716 // Don't bother complaining about constructors or destructors,
14717 // though.
14718}
14719
14720void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14721 // If there is no declaration, there was an error parsing it. Just ignore it.
14722 if (!RealDecl)
14723 return;
14724
14725 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14726 QualType Type = Var->getType();
14727
14728 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14729 Diag(Loc: Var->getLocation(),
14730 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14731 << Var;
14732 Var->setInvalidDecl();
14733 return;
14734 }
14735 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14736 if (isa<DecompositionDecl>(Val: RealDecl)) {
14737 // Point the caret to the token immediately after the closing bracket if
14738 // it can be found; otherwise fall back to the declaration's location.
14739 SourceLocation Loc = Var->getLocation();
14740 SourceLocation RSquareLoc =
14741 dyn_cast<DecompositionDecl>(Val: RealDecl)->getRSquareLoc();
14742 if (std::optional<Token> Next = Lexer::findNextToken(
14743 Loc: RSquareLoc, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()))
14744 Loc = Next->getLocation();
14745 Diag(Loc, DiagID: diag::err_decomp_decl_requires_init) << Var;
14746 Var->setInvalidDecl();
14747 return;
14748 }
14749
14750 if (Type->isUndeducedType() &&
14751 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14752 return;
14753
14754 this->CheckAttributesOnDeducedType(D: RealDecl);
14755
14756 // C++11 [class.static.data]p3: A static data member can be declared with
14757 // the constexpr specifier; if so, its declaration shall specify
14758 // a brace-or-equal-initializer.
14759 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14760 // the definition of a variable [...] or the declaration of a static data
14761 // member.
14762 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14763 !Var->isThisDeclarationADemotedDefinition()) {
14764 if (Var->isStaticDataMember()) {
14765 // C++1z removes the relevant rule; the in-class declaration is always
14766 // a definition there.
14767 if (!getLangOpts().CPlusPlus17 &&
14768 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14769 Diag(Loc: Var->getLocation(),
14770 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14771 << Var;
14772 Var->setInvalidDecl();
14773 return;
14774 }
14775 } else {
14776 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14777 Var->setInvalidDecl();
14778 return;
14779 }
14780 }
14781
14782 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14783 // be initialized.
14784 if (!Var->isInvalidDecl() &&
14785 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14786 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14787 bool HasConstExprDefaultConstructor = false;
14788 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14789 for (auto *Ctor : RD->ctors()) {
14790 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14791 Ctor->getMethodQualifiers().getAddressSpace() ==
14792 LangAS::opencl_constant) {
14793 HasConstExprDefaultConstructor = true;
14794 }
14795 }
14796 }
14797 if (!HasConstExprDefaultConstructor) {
14798 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14799 Var->setInvalidDecl();
14800 return;
14801 }
14802 }
14803
14804 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14805 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14806 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14807 Var->setInvalidDecl();
14808 return;
14809 }
14810
14811 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14812 if (Var->getStorageClass() == SC_Extern) {
14813 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14814 << Var;
14815 Var->setInvalidDecl();
14816 return;
14817 }
14818 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14819 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14820 Var->setInvalidDecl();
14821 return;
14822 }
14823 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14824 if (!RD->hasTrivialDefaultConstructor()) {
14825 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14826 Var->setInvalidDecl();
14827 return;
14828 }
14829 }
14830 // The declaration is uninitialized, no need for further checks.
14831 return;
14832 }
14833
14834 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14835 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14836 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14837 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14838 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14839 NonTrivialKind: NTCUK_Init);
14840
14841 switch (DefKind) {
14842 case VarDecl::Definition:
14843 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14844 break;
14845
14846 // We have an out-of-line definition of a static data member
14847 // that has an in-class initializer, so we type-check this like
14848 // a declaration.
14849 //
14850 [[fallthrough]];
14851
14852 case VarDecl::DeclarationOnly:
14853 // It's only a declaration.
14854
14855 // Block scope. C99 6.7p7: If an identifier for an object is
14856 // declared with no linkage (C99 6.2.2p6), the type for the
14857 // object shall be complete.
14858 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14859 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14860 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14861 DiagID: diag::err_typecheck_decl_incomplete_type))
14862 Var->setInvalidDecl();
14863
14864 // Make sure that the type is not abstract.
14865 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14866 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14867 DiagID: diag::err_abstract_type_in_decl,
14868 Args: AbstractVariableType))
14869 Var->setInvalidDecl();
14870 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14871 Var->getStorageClass() == SC_PrivateExtern) {
14872 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14873 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14874 }
14875
14876 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14877 !Var->isInvalidDecl())
14878 ExternalDeclarations.push_back(Elt: Var);
14879
14880 return;
14881
14882 case VarDecl::TentativeDefinition:
14883 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14884 // object that has file scope without an initializer, and without a
14885 // storage-class specifier or with the storage-class specifier "static",
14886 // constitutes a tentative definition. Note: A tentative definition with
14887 // external linkage is valid (C99 6.2.2p5).
14888 if (!Var->isInvalidDecl()) {
14889 if (const IncompleteArrayType *ArrayT
14890 = Context.getAsIncompleteArrayType(T: Type)) {
14891 if (RequireCompleteSizedType(
14892 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14893 DiagID: diag::err_array_incomplete_or_sizeless_type))
14894 Var->setInvalidDecl();
14895 }
14896 if (Var->getStorageClass() == SC_Static) {
14897 // C99 6.9.2p3: If the declaration of an identifier for an object is
14898 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14899 // declared type shall not be an incomplete type.
14900 // NOTE: code such as the following
14901 // static struct s;
14902 // struct s { int a; };
14903 // is accepted by gcc. Hence here we issue a warning instead of
14904 // an error and we do not invalidate the static declaration.
14905 // NOTE: to avoid multiple warnings, only check the first declaration.
14906 if (Var->isFirstDecl())
14907 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14908 DiagID: diag::ext_typecheck_decl_incomplete_type,
14909 Args: Type->isArrayType());
14910 }
14911 }
14912
14913 // Record the tentative definition; we're done.
14914 if (!Var->isInvalidDecl())
14915 TentativeDefinitions.push_back(LocalValue: Var);
14916 return;
14917 }
14918
14919 // Provide a specific diagnostic for uninitialized variable definitions
14920 // with incomplete array type, unless it is a global unbounded HLSL resource
14921 // array.
14922 if (Type->isIncompleteArrayType() &&
14923 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14924 Type->isHLSLResourceRecordArray())) {
14925 if (Var->isConstexpr())
14926 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14927 << Var;
14928 else
14929 Diag(Loc: Var->getLocation(),
14930 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14931 Var->setInvalidDecl();
14932 return;
14933 }
14934
14935 // Provide a specific diagnostic for uninitialized variable
14936 // definitions with reference type.
14937 if (Type->isReferenceType()) {
14938 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14939 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14940 return;
14941 }
14942
14943 // Do not attempt to type-check the default initializer for a
14944 // variable with dependent type.
14945 if (Type->isDependentType())
14946 return;
14947
14948 if (Var->isInvalidDecl())
14949 return;
14950
14951 if (!Var->hasAttr<AliasAttr>()) {
14952 if (RequireCompleteType(Loc: Var->getLocation(),
14953 T: Context.getBaseElementType(QT: Type),
14954 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14955 Var->setInvalidDecl();
14956 return;
14957 }
14958 } else {
14959 return;
14960 }
14961
14962 // The variable can not have an abstract class type.
14963 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14964 DiagID: diag::err_abstract_type_in_decl,
14965 Args: AbstractVariableType)) {
14966 Var->setInvalidDecl();
14967 return;
14968 }
14969
14970 // In C, if the definition is const-qualified and has no initializer, it
14971 // is left uninitialized unless it has static or thread storage duration.
14972 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14973 unsigned DiagID = diag::warn_default_init_const_unsafe;
14974 if (Var->getStorageDuration() == SD_Static ||
14975 Var->getStorageDuration() == SD_Thread)
14976 DiagID = diag::warn_default_init_const;
14977
14978 bool EmitCppCompat = !Diags.isIgnored(
14979 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14980 Loc: Var->getLocation());
14981
14982 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14983 }
14984
14985 // Check for jumps past the implicit initializer. C++0x
14986 // clarifies that this applies to a "variable with automatic
14987 // storage duration", not a "local variable".
14988 // C++11 [stmt.dcl]p3
14989 // A program that jumps from a point where a variable with automatic
14990 // storage duration is not in scope to a point where it is in scope is
14991 // ill-formed unless the variable has scalar type, class type with a
14992 // trivial default constructor and a trivial destructor, a cv-qualified
14993 // version of one of these types, or an array of one of the preceding
14994 // types and is declared without an initializer.
14995 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14996 if (const auto *CXXRecord =
14997 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14998 // Mark the function (if we're in one) for further checking even if the
14999 // looser rules of C++11 do not require such checks, so that we can
15000 // diagnose incompatibilities with C++98.
15001 if (!CXXRecord->isPOD())
15002 setFunctionHasBranchProtectedScope();
15003 }
15004 }
15005 // In OpenCL, we can't initialize objects in the __local address space,
15006 // even implicitly, so don't synthesize an implicit initializer.
15007 if (getLangOpts().OpenCL &&
15008 Var->getType().getAddressSpace() == LangAS::opencl_local)
15009 return;
15010
15011 // Handle HLSL uninitialized decls
15012 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
15013 return;
15014
15015 // HLSL input & push-constant variables are expected to be externally
15016 // initialized, even when marked `static`.
15017 if (getLangOpts().HLSL &&
15018 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
15019 return;
15020
15021 // C++03 [dcl.init]p9:
15022 // If no initializer is specified for an object, and the
15023 // object is of (possibly cv-qualified) non-POD class type (or
15024 // array thereof), the object shall be default-initialized; if
15025 // the object is of const-qualified type, the underlying class
15026 // type shall have a user-declared default
15027 // constructor. Otherwise, if no initializer is specified for
15028 // a non- static object, the object and its subobjects, if
15029 // any, have an indeterminate initial value); if the object
15030 // or any of its subobjects are of const-qualified type, the
15031 // program is ill-formed.
15032 // C++0x [dcl.init]p11:
15033 // If no initializer is specified for an object, the object is
15034 // default-initialized; [...].
15035 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
15036 InitializationKind Kind
15037 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
15038
15039 InitializationSequence InitSeq(*this, Entity, Kind, {});
15040 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
15041
15042 if (Init.get()) {
15043 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
15044 // This is important for template substitution.
15045 Var->setInitStyle(VarDecl::CallInit);
15046 } else if (Init.isInvalid()) {
15047 // If default-init fails, attach a recovery-expr initializer to track
15048 // that initialization was attempted and failed.
15049 auto RecoveryExpr =
15050 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
15051 if (RecoveryExpr.get())
15052 Var->setInit(RecoveryExpr.get());
15053 }
15054
15055 CheckCompleteVariableDeclaration(VD: Var);
15056 }
15057}
15058
15059void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15060 // If there is no declaration, there was an error parsing it. Ignore it.
15061 if (!D)
15062 return;
15063
15064 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
15065 if (!VD) {
15066 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var)
15067 << InExpansionStmt;
15068 D->setInvalidDecl();
15069 return;
15070 }
15071
15072 VD->setCXXForRangeDecl(true);
15073
15074 // for-range-declaration cannot be given a storage class specifier.
15075 int Error = -1;
15076 switch (VD->getStorageClass()) {
15077 case SC_None:
15078 break;
15079 case SC_Extern:
15080 Error = 0;
15081 break;
15082 case SC_Static:
15083 Error = 1;
15084 break;
15085 case SC_PrivateExtern:
15086 Error = 2;
15087 break;
15088 case SC_Auto:
15089 Error = 3;
15090 break;
15091 case SC_Register:
15092 Error = 4;
15093 break;
15094 }
15095
15096 // for-range-declaration cannot be given a storage class specifier con't.
15097 switch (VD->getTSCSpec()) {
15098 case TSCS_thread_local:
15099 Error = 6;
15100 break;
15101 case TSCS___thread:
15102 case TSCS__Thread_local:
15103 case TSCS_unspecified:
15104 break;
15105 }
15106
15107 if (Error != -1) {
15108 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
15109 << InExpansionStmt << VD << Error;
15110 D->setInvalidDecl();
15111 }
15112}
15113
15114StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
15115 IdentifierInfo *Ident,
15116 ParsedAttributes &Attrs) {
15117 // C++1y [stmt.iter]p1:
15118 // A range-based for statement of the form
15119 // for ( for-range-identifier : for-range-initializer ) statement
15120 // is equivalent to
15121 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15122 DeclSpec DS(Attrs.getPool().getFactory());
15123
15124 const char *PrevSpec;
15125 unsigned DiagID;
15126 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
15127 Policy: getPrintingPolicy());
15128
15129 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
15130 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
15131 D.takeAttributesAppending(attrs&: Attrs);
15132
15133 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
15134 EndLoc: IdentLoc);
15135 Decl *Var = ActOnDeclarator(S, D);
15136 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
15137 FinalizeDeclaration(D: Var);
15138 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
15139 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15140 : IdentLoc);
15141}
15142
15143void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
15144 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
15145 return;
15146 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
15147 QualType MethodType = MD->getType();
15148 QualType AttributedType =
15149 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
15150 TypeLocBuilder TLB;
15151 TypeSourceInfo *TSI = MD->getTypeSourceInfo();
15152 if (TSI && TSI->getTypeLoc().getType() == MethodType) {
15153 TLB.pushFullCopy(L: TSI->getTypeLoc());
15154 } else {
15155 // The written type-source info can disagree with the method's type. For
15156 // example, a deduced 'auto' return type keeps the 'auto' placeholder in its
15157 // TypeSourceInfo while the method's type has already been resolved to the
15158 // deduced type. Pushing the stale TypeLoc would make the wrapping
15159 // AttributedTypeLoc's inner type inconsistent with MethodType. Build a
15160 // trivial TypeLoc that matches MethodType instead.
15161 TLB.pushTrivial(Context, T: MethodType,
15162 Loc: TSI ? TSI->getTypeLoc().getBeginLoc() : MD->getLocation());
15163 }
15164 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
15165 TyLoc.setAttr(Attr);
15166 MD->setType(AttributedType);
15167 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
15168 // A trivial TypeLoc has no parameter decls, but AST visitors rely on them.
15169 if (FunctionTypeLoc FTL = MD->getFunctionTypeLoc())
15170 for (unsigned I = 0, E = MD->getNumParams(); I != E; ++I)
15171 FTL.setParam(i: I, VD: MD->getParamDecl(i: I));
15172}
15173
15174void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
15175 if (var->isInvalidDecl()) return;
15176
15177 CUDA().MaybeAddConstantAttr(VD: var);
15178
15179 if (getLangOpts().OpenCL) {
15180 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15181 // initialiser
15182 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15183 !var->hasInit()) {
15184 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
15185 << 1 /*Init*/;
15186 var->setInvalidDecl();
15187 return;
15188 }
15189 }
15190
15191 // In Objective-C, don't allow jumps past the implicit initialization of a
15192 // local retaining variable.
15193 if (getLangOpts().ObjC &&
15194 var->hasLocalStorage()) {
15195 switch (var->getType().getObjCLifetime()) {
15196 case Qualifiers::OCL_None:
15197 case Qualifiers::OCL_ExplicitNone:
15198 case Qualifiers::OCL_Autoreleasing:
15199 break;
15200
15201 case Qualifiers::OCL_Weak:
15202 case Qualifiers::OCL_Strong:
15203 setFunctionHasBranchProtectedScope();
15204 break;
15205 }
15206 }
15207
15208 if (var->hasLocalStorage() &&
15209 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15210 setFunctionHasBranchProtectedScope();
15211
15212 // Warn about externally-visible variables being defined without a
15213 // prior declaration. We only want to do this for global
15214 // declarations, but we also specifically need to avoid doing it for
15215 // class members because the linkage of an anonymous class can
15216 // change if it's later given a typedef name.
15217 if (var->isThisDeclarationADefinition() &&
15218 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15219 var->isExternallyVisible() && var->hasLinkage() &&
15220 !var->isInline() && !var->getDescribedVarTemplate() &&
15221 var->getStorageClass() != SC_Register &&
15222 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
15223 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
15224 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
15225 Loc: var->getLocation())) {
15226 // Find a previous declaration that's not a definition.
15227 VarDecl *prev = var->getPreviousDecl();
15228 while (prev && prev->isThisDeclarationADefinition())
15229 prev = prev->getPreviousDecl();
15230
15231 if (!prev) {
15232 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
15233 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
15234 << /* variable */ 0;
15235 }
15236 }
15237
15238 // Cache the result of checking for constant initialization.
15239 std::optional<bool> CacheHasConstInit;
15240 const Expr *CacheCulprit = nullptr;
15241 auto checkConstInit = [&]() mutable {
15242 const Expr *Init = var->getInit();
15243 if (Init->isInstantiationDependent())
15244 return true;
15245
15246 if (!CacheHasConstInit)
15247 CacheHasConstInit = var->getInit()->isConstantInitializer(
15248 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
15249 return *CacheHasConstInit;
15250 };
15251
15252 if (var->getTLSKind() == VarDecl::TLS_Static) {
15253 if (var->getType().isDestructedType()) {
15254 // GNU C++98 edits for __thread, [basic.start.term]p3:
15255 // The type of an object with thread storage duration shall not
15256 // have a non-trivial destructor.
15257 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
15258 if (getLangOpts().CPlusPlus11)
15259 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15260 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15261 if (!checkConstInit()) {
15262 // GNU C++98 edits for __thread, [basic.start.init]p4:
15263 // An object of thread storage duration shall not require dynamic
15264 // initialization.
15265 // FIXME: Need strict checking here.
15266 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
15267 << CacheCulprit->getSourceRange();
15268 if (getLangOpts().CPlusPlus11)
15269 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15270 }
15271 }
15272 }
15273
15274
15275 if (!var->getType()->isStructureType() && var->hasInit() &&
15276 isa<InitListExpr>(Val: var->getInit())) {
15277 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15278 unsigned NumInits = ILE->getNumInits();
15279 if (NumInits > 2)
15280 for (unsigned I = 0; I < NumInits; ++I) {
15281 const auto *Init = ILE->getInit(Init: I);
15282 if (!Init)
15283 break;
15284 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15285 if (!SL)
15286 break;
15287
15288 unsigned NumConcat = SL->getNumConcatenated();
15289 // Diagnose missing comma in string array initialization.
15290 // Do not warn when all the elements in the initializer are concatenated
15291 // together. Do not warn for macros too.
15292 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15293 bool OnlyOneMissingComma = true;
15294 for (unsigned J = I + 1; J < NumInits; ++J) {
15295 const auto *Init = ILE->getInit(Init: J);
15296 if (!Init)
15297 break;
15298 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15299 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15300 OnlyOneMissingComma = false;
15301 break;
15302 }
15303 }
15304
15305 if (OnlyOneMissingComma) {
15306 SmallVector<FixItHint, 1> Hints;
15307 for (unsigned i = 0; i < NumConcat - 1; ++i)
15308 Hints.push_back(Elt: FixItHint::CreateInsertion(
15309 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15310
15311 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15312 DiagID: diag::warn_concatenated_literal_array_init)
15313 << Hints;
15314 Diag(Loc: SL->getBeginLoc(),
15315 DiagID: diag::note_concatenated_string_literal_silence);
15316 }
15317 // In any case, stop now.
15318 break;
15319 }
15320 }
15321 }
15322
15323
15324 QualType type = var->getType();
15325
15326 if (var->hasAttr<BlocksAttr>())
15327 getCurFunction()->addByrefBlockVar(VD: var);
15328
15329 Expr *Init = var->getInit();
15330 bool GlobalStorage = var->hasGlobalStorage();
15331 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15332 QualType baseType = Context.getBaseElementType(QT: type);
15333 bool HasConstInit = true;
15334
15335 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15336 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15337 << var;
15338
15339 // Check whether the initializer is sufficiently constant.
15340 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15341 !type->isDependentType() && Init && !Init->isValueDependent() &&
15342 (GlobalStorage || var->isConstexpr() ||
15343 var->mightBeUsableInConstantExpressions(C: Context))) {
15344 // If this variable might have a constant initializer or might be usable in
15345 // constant expressions, check whether or not it actually is now. We can't
15346 // do this lazily, because the result might depend on things that change
15347 // later, such as which constexpr functions happen to be defined.
15348 SmallVector<PartialDiagnosticAt, 8> Notes;
15349 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15350 // Prior to C++11, in contexts where a constant initializer is required,
15351 // the set of valid constant initializers is described by syntactic rules
15352 // in [expr.const]p2-6.
15353 // FIXME: Stricter checking for these rules would be useful for constinit /
15354 // -Wglobal-constructors.
15355 HasConstInit = checkConstInit();
15356
15357 // Compute and cache the constant value, and remember that we have a
15358 // constant initializer.
15359 if (HasConstInit) {
15360 if (var->isStaticDataMember() && !var->isInline() &&
15361 var->getLexicalDeclContext()->isRecord() &&
15362 type->isIntegralOrEnumerationType()) {
15363 // In C++98, in-class initialization for a static data member must
15364 // be an integer constant expression.
15365 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15366 Diag(Loc: Init->getExprLoc(),
15367 DiagID: diag::ext_in_class_initializer_non_constant)
15368 << Init->getSourceRange();
15369 }
15370 }
15371 EvalProxy SProxy(*this);
15372 (void)var->checkForConstantInitialization(Notes, SProxy);
15373 Notes.clear();
15374 } else if (CacheCulprit) {
15375 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15376 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15377 Notes.back().second << CacheCulprit->getSourceRange();
15378 }
15379 } else {
15380 // Evaluate the initializer to see if it's a constant initializer.
15381 EvalProxy SProxy(*this);
15382 HasConstInit = var->checkForConstantInitialization(Notes, SProxy);
15383 }
15384
15385 if (HasConstInit) {
15386 // FIXME: Consider replacing the initializer with a ConstantExpr.
15387 } else if (var->isConstexpr()) {
15388 SourceLocation DiagLoc = var->getLocation();
15389 // If the note doesn't add any useful information other than a source
15390 // location, fold it into the primary diagnostic.
15391 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15392 diag::note_invalid_subexpr_in_const_expr) {
15393 DiagLoc = Notes[0].first;
15394 Notes.clear();
15395 }
15396 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15397 << var << Init->getSourceRange();
15398 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15399 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15400 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15401 auto *Attr = var->getAttr<ConstInitAttr>();
15402 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15403 << Init->getSourceRange();
15404 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15405 << Attr->getRange() << Attr->isConstinit();
15406 for (auto &it : Notes)
15407 Diag(Loc: it.first, PD: it.second);
15408 } else if (var->isStaticDataMember() && !var->isInline() &&
15409 var->getLexicalDeclContext()->isRecord()) {
15410 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15411 << Init->getSourceRange();
15412 for (auto &it : Notes)
15413 Diag(Loc: it.first, PD: it.second);
15414 var->setInvalidDecl();
15415 } else if (IsGlobal &&
15416 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15417 Loc: var->getLocation())) {
15418 // Warn about globals which don't have a constant initializer. Don't
15419 // warn about globals with a non-trivial destructor because we already
15420 // warned about them.
15421 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15422 if (!(RD && !RD->hasTrivialDestructor())) {
15423 // checkConstInit() here permits trivial default initialization even in
15424 // C++11 onwards, where such an initializer is not a constant initializer
15425 // but nonetheless doesn't require a global constructor.
15426 if (!checkConstInit())
15427 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15428 << Init->getSourceRange();
15429 }
15430 }
15431 }
15432
15433 // Apply section attributes and pragmas to global variables.
15434 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15435 !inTemplateInstantiation()) {
15436 PragmaStack<StringLiteral *> *Stack = nullptr;
15437 int SectionFlags = ASTContext::PSF_Read;
15438 bool MSVCEnv =
15439 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15440 std::optional<QualType::NonConstantStorageReason> Reason;
15441 if (HasConstInit &&
15442 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15443 Stack = &ConstSegStack;
15444 } else {
15445 SectionFlags |= ASTContext::PSF_Write;
15446 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15447 }
15448 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15449 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15450 SectionFlags |= ASTContext::PSF_Implicit;
15451 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15452 } else if (Stack->CurrentValue) {
15453 if (Stack != &ConstSegStack && MSVCEnv &&
15454 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15455 var->getType().isConstQualified()) {
15456 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15457 NonConstNonReferenceType) &&
15458 "This case should've already been handled elsewhere");
15459 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15460 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15461 ? QualType::NonConstantStorageReason::NonTrivialCtor
15462 : *Reason);
15463 }
15464 SectionFlags |= ASTContext::PSF_Implicit;
15465 auto SectionName = Stack->CurrentValue->getString();
15466 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15467 Range: Stack->CurrentPragmaLocation,
15468 S: SectionAttr::Declspec_allocate));
15469 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15470 var->dropAttr<SectionAttr>();
15471 }
15472
15473 // Apply the init_seg attribute if this has an initializer. If the
15474 // initializer turns out to not be dynamic, we'll end up ignoring this
15475 // attribute.
15476 if (CurInitSeg.Segment && var->getInit())
15477 var->addAttr(A: InitSegAttr::CreateImplicit(
15478 Ctx&: Context, Section: CurInitSeg.Segment->getString(), Func: CurInitSeg.Func,
15479 Range: CurInitSeg.PragmaLocation));
15480 }
15481
15482 // All the following checks are C++ only.
15483 if (!getLangOpts().CPlusPlus) {
15484 // If this variable must be emitted, add it as an initializer for the
15485 // current module.
15486 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15487 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15488 return;
15489 }
15490
15491 DiagnoseUniqueObjectDuplication(VD: var);
15492
15493 // Require the destructor.
15494 if (!type->isDependentType())
15495 if (auto *RD = baseType->getAsCXXRecordDecl())
15496 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15497
15498 // If this variable must be emitted, add it as an initializer for the current
15499 // module. For named modules, discardable inline variables may be deferred
15500 // until they are odr-used. Non-inline variables that must be emitted,
15501 // including those with side-effecting initialization, must still be emitted
15502 // even if they have internal linkage.
15503 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) {
15504 GVALinkage Linkage = Context.GetGVALinkageForVariable(VD: var);
15505 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15506 !isDiscardableGVALinkage(L: Linkage) ||
15507 (Linkage == GVA_Internal && !var->isInline()))
15508 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15509 }
15510
15511 // Build the bindings if this is a structured binding declaration.
15512 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15513 CheckCompleteDecompositionDeclaration(DD);
15514}
15515
15516void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15517 assert(VD->isStaticLocal());
15518
15519 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15520
15521 // Find outermost function when VD is in lambda function.
15522 while (FD && !getDLLAttr(D: FD) &&
15523 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15524 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15525 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15526 }
15527
15528 if (!FD)
15529 return;
15530
15531 // Static locals inherit dll attributes from their function.
15532 if (Attr *A = getDLLAttr(D: FD)) {
15533 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15534 NewAttr->setInherited(true);
15535 VD->addAttr(A: NewAttr);
15536 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15537 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15538 NewAttr->setInherited(true);
15539 VD->addAttr(A: NewAttr);
15540
15541 // Export this function to enforce exporting this static variable even
15542 // if it is not used in this compilation unit.
15543 if (!FD->hasAttr<DLLExportAttr>())
15544 FD->addAttr(A: NewAttr);
15545
15546 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15547 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15548 NewAttr->setInherited(true);
15549 VD->addAttr(A: NewAttr);
15550 }
15551}
15552
15553void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15554 assert(VD->getTLSKind());
15555
15556 // Perform TLS alignment check here after attributes attached to the variable
15557 // which may affect the alignment have been processed. Only perform the check
15558 // if the target has a maximum TLS alignment (zero means no constraints).
15559 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15560 // Protect the check so that it's not performed on dependent types and
15561 // dependent alignments (we can't determine the alignment in that case).
15562 if (!VD->hasDependentAlignment()) {
15563 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15564 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15565 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15566 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15567 << (unsigned)MaxAlignChars.getQuantity();
15568 }
15569 }
15570 }
15571}
15572
15573void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15574 // Note that we are no longer parsing the initializer for this declaration.
15575 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15576
15577 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15578 if (!VD)
15579 return;
15580
15581 // Emit any deferred warnings for the variable's initializer, even if the
15582 // variable is invalid
15583 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15584
15585 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15586 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15587 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15588 if (PragmaClangBSSSection.Valid)
15589 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15590 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15591 Range: PragmaClangBSSSection.PragmaLocation));
15592 if (PragmaClangDataSection.Valid)
15593 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15594 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15595 Range: PragmaClangDataSection.PragmaLocation));
15596 if (PragmaClangRodataSection.Valid)
15597 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15598 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15599 Range: PragmaClangRodataSection.PragmaLocation));
15600 if (PragmaClangRelroSection.Valid)
15601 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15602 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15603 Range: PragmaClangRelroSection.PragmaLocation));
15604 }
15605
15606 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15607 for (auto *BD : DD->bindings()) {
15608 FinalizeDeclaration(ThisDecl: BD);
15609 }
15610 }
15611
15612 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15613 K: BuiltinCountedByRefKind::Initializer);
15614
15615 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15616
15617 if (VD->isStaticLocal())
15618 CheckStaticLocalForDllExport(VD);
15619
15620 if (VD->getTLSKind())
15621 CheckThreadLocalForLargeAlignment(VD);
15622
15623 // Perform check for initializers of device-side global variables.
15624 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15625 // 7.5). We must also apply the same checks to all __shared__
15626 // variables whether they are local or not. CUDA also allows
15627 // constant initializers for __constant__ and __device__ variables.
15628 if (getLangOpts().CUDA)
15629 CUDA().checkAllowedInitializer(VD);
15630
15631 // Grab the dllimport or dllexport attribute off of the VarDecl.
15632 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15633
15634 // Imported static data members cannot be defined out-of-line.
15635 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15636 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15637 VD->isThisDeclarationADefinition()) {
15638 // We allow definitions of dllimport class template static data members
15639 // with a warning.
15640 CXXRecordDecl *Context =
15641 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15642 bool IsClassTemplateMember =
15643 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15644 Context->getDescribedClassTemplate();
15645
15646 Diag(Loc: VD->getLocation(),
15647 DiagID: IsClassTemplateMember
15648 ? diag::warn_attribute_dllimport_static_field_definition
15649 : diag::err_attribute_dllimport_static_field_definition);
15650 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15651 if (!IsClassTemplateMember)
15652 VD->setInvalidDecl();
15653 }
15654 }
15655
15656 // dllimport/dllexport variables cannot be thread local, their TLS index
15657 // isn't exported with the variable.
15658 if (DLLAttr && VD->getTLSKind()) {
15659 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15660 if (F && getDLLAttr(D: F)) {
15661 assert(VD->isStaticLocal());
15662 // But if this is a static local in a dlimport/dllexport function, the
15663 // function will never be inlined, which means the var would never be
15664 // imported, so having it marked import/export is safe.
15665 } else {
15666 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15667 << DLLAttr;
15668 VD->setInvalidDecl();
15669 }
15670 }
15671
15672 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15673 if (!Attr->isInherited() && !Attr->isImplicit() &&
15674 !VD->isThisDeclarationADefinition()) {
15675 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15676 << Attr;
15677 VD->dropAttr<UsedAttr>();
15678 }
15679 }
15680 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15681 if (!Attr->isInherited() && !Attr->isImplicit() &&
15682 !VD->isThisDeclarationADefinition()) {
15683 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15684 << Attr;
15685 VD->dropAttr<RetainAttr>();
15686 }
15687 }
15688
15689 const DeclContext *DC = VD->getDeclContext();
15690 // If there's a #pragma GCC visibility in scope, and this isn't a class
15691 // member, set the visibility of this variable.
15692 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15693 AddPushedVisibilityAttribute(RD: VD);
15694
15695 // FIXME: Warn on unused var template partial specializations.
15696 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15697 MarkUnusedFileScopedDecl(D: VD);
15698
15699 // Now we have parsed the initializer and can update the table of magic
15700 // tag values.
15701 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15702 !VD->getType()->isIntegralOrEnumerationType())
15703 return;
15704
15705 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15706 const Expr *MagicValueExpr = VD->getInit();
15707 if (!MagicValueExpr) {
15708 continue;
15709 }
15710 std::optional<llvm::APSInt> MagicValueInt;
15711 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15712 Diag(Loc: I->getRange().getBegin(),
15713 DiagID: diag::err_type_tag_for_datatype_not_ice)
15714 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15715 continue;
15716 }
15717 if (MagicValueInt->getActiveBits() > 64) {
15718 Diag(Loc: I->getRange().getBegin(),
15719 DiagID: diag::err_type_tag_for_datatype_too_large)
15720 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15721 continue;
15722 }
15723 uint64_t MagicValue = MagicValueInt->getZExtValue();
15724 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15725 MagicValue,
15726 Type: I->getMatchingCType(),
15727 LayoutCompatible: I->getLayoutCompatible(),
15728 MustBeNull: I->getMustBeNull());
15729 }
15730}
15731
15732static bool hasDeducedAuto(DeclaratorDecl *DD) {
15733 auto *VD = dyn_cast<VarDecl>(Val: DD);
15734 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15735}
15736
15737Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15738 ArrayRef<Decl *> Group) {
15739 SmallVector<Decl*, 8> Decls;
15740
15741 if (DS.isTypeSpecOwned())
15742 Decls.push_back(Elt: DS.getRepAsDecl());
15743
15744 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15745 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15746 bool DiagnosedMultipleDecomps = false;
15747 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15748 bool DiagnosedNonDeducedAuto = false;
15749
15750 for (Decl *D : Group) {
15751 if (!D)
15752 continue;
15753 // Check if the Decl has been declared in '#pragma omp declare target'
15754 // directive and has static storage duration.
15755 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15756 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15757 VD->hasGlobalStorage())
15758 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15759 // For declarators, there are some additional syntactic-ish checks we need
15760 // to perform.
15761 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15762 if (!FirstDeclaratorInGroup)
15763 FirstDeclaratorInGroup = DD;
15764 if (!FirstDecompDeclaratorInGroup)
15765 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15766 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15767 !hasDeducedAuto(DD))
15768 FirstNonDeducedAutoInGroup = DD;
15769
15770 if (FirstDeclaratorInGroup != DD) {
15771 // A decomposition declaration cannot be combined with any other
15772 // declaration in the same group.
15773 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15774 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15775 DiagID: diag::err_decomp_decl_not_alone)
15776 << FirstDeclaratorInGroup->getSourceRange()
15777 << DD->getSourceRange();
15778 DiagnosedMultipleDecomps = true;
15779 }
15780
15781 // A declarator that uses 'auto' in any way other than to declare a
15782 // variable with a deduced type cannot be combined with any other
15783 // declarator in the same group.
15784 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15785 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15786 DiagID: diag::err_auto_non_deduced_not_alone)
15787 << FirstNonDeducedAutoInGroup->getType()
15788 ->hasAutoForTrailingReturnType()
15789 << FirstDeclaratorInGroup->getSourceRange()
15790 << DD->getSourceRange();
15791 DiagnosedNonDeducedAuto = true;
15792 }
15793 }
15794 }
15795
15796 Decls.push_back(Elt: D);
15797 }
15798
15799 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15800 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15801 handleTagNumbering(Tag, TagScope: S);
15802 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15803 getLangOpts().CPlusPlus)
15804 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15805 }
15806 }
15807
15808 return BuildDeclaratorGroup(Group: Decls);
15809}
15810
15811Sema::DeclGroupPtrTy
15812Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15813 // C++14 [dcl.spec.auto]p7: (DR1347)
15814 // If the type that replaces the placeholder type is not the same in each
15815 // deduction, the program is ill-formed.
15816 if (Group.size() > 1) {
15817 QualType Deduced;
15818 VarDecl *DeducedDecl = nullptr;
15819 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15820 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15821 if (!D || D->isInvalidDecl())
15822 break;
15823 DeducedType *DT = D->getType()->getContainedDeducedType();
15824 if (!DT || DT->getDeducedType().isNull())
15825 continue;
15826 if (Deduced.isNull()) {
15827 Deduced = DT->getDeducedType();
15828 DeducedDecl = D;
15829 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15830 auto *AT = dyn_cast<AutoType>(Val: DT);
15831 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15832 DiagID: diag::err_auto_different_deductions)
15833 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15834 << DeducedDecl->getDeclName() << DT->getDeducedType()
15835 << D->getDeclName();
15836 if (DeducedDecl->hasInit())
15837 Dia << DeducedDecl->getInit()->getSourceRange();
15838 if (D->getInit())
15839 Dia << D->getInit()->getSourceRange();
15840 D->setInvalidDecl();
15841 break;
15842 }
15843 }
15844 }
15845
15846 ActOnDocumentableDecls(Group);
15847
15848 return DeclGroupPtrTy::make(
15849 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15850}
15851
15852void Sema::ActOnDocumentableDecl(Decl *D) {
15853 ActOnDocumentableDecls(Group: D);
15854}
15855
15856void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15857 // Don't parse the comment if Doxygen diagnostics are ignored.
15858 if (Group.empty() || !Group[0])
15859 return;
15860
15861 if (!areDocumentationDiagsEnabled(Loc: Group[0]->getLocation()))
15862 return;
15863
15864 if (Group.size() >= 2) {
15865 // This is a decl group. Normally it will contain only declarations
15866 // produced from declarator list. But in case we have any definitions or
15867 // additional declaration references:
15868 // 'typedef struct S {} S;'
15869 // 'typedef struct S *S;'
15870 // 'struct S *pS;'
15871 // FinalizeDeclaratorGroup adds these as separate declarations.
15872 Decl *MaybeTagDecl = Group[0];
15873 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15874 Group = Group.slice(N: 1);
15875 }
15876 }
15877
15878 // FIXME: We assume every Decl in the group is in the same file.
15879 // This is false when preprocessor constructs the group from decls in
15880 // different files (e. g. macros or #include).
15881 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15882}
15883
15884void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15885 // Check that there are no default arguments inside the type of this
15886 // parameter.
15887 if (getLangOpts().CPlusPlus)
15888 CheckExtraCXXDefaultArguments(D);
15889
15890 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15891 if (D.getCXXScopeSpec().isSet()) {
15892 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15893 << D.getCXXScopeSpec().getRange();
15894 }
15895
15896 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15897 // simple identifier except [...irrelevant cases...].
15898 switch (D.getName().getKind()) {
15899 case UnqualifiedIdKind::IK_Identifier:
15900 break;
15901
15902 case UnqualifiedIdKind::IK_OperatorFunctionId:
15903 case UnqualifiedIdKind::IK_ConversionFunctionId:
15904 case UnqualifiedIdKind::IK_LiteralOperatorId:
15905 case UnqualifiedIdKind::IK_ConstructorName:
15906 case UnqualifiedIdKind::IK_DestructorName:
15907 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15908 case UnqualifiedIdKind::IK_DeductionGuideName:
15909 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15910 << GetNameForDeclarator(D).getName();
15911 break;
15912
15913 case UnqualifiedIdKind::IK_TemplateId:
15914 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15915 // GetNameForDeclarator would not produce a useful name in this case.
15916 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15917 break;
15918 }
15919}
15920
15921void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15922 // This only matters in C.
15923 if (getLangOpts().CPlusPlus)
15924 return;
15925
15926 // This only matters if the declaration has a type.
15927 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15928 if (!VD)
15929 return;
15930
15931 // Get the type, this only matters for tag types.
15932 QualType QT = VD->getType();
15933 const auto *TD = QT->getAsTagDecl();
15934 if (!TD)
15935 return;
15936
15937 // Check if the tag declaration is lexically declared somewhere different
15938 // from the lexical declaration of the given object, then it will be hidden
15939 // in C++ and we should warn on it.
15940 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15941 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15942 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15943 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15944 }
15945}
15946
15947static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15948 SourceLocation ExplicitThisLoc) {
15949 if (!ExplicitThisLoc.isValid())
15950 return;
15951 assert(S.getLangOpts().CPlusPlus &&
15952 "explicit parameter in non-cplusplus mode");
15953 if (!S.getLangOpts().CPlusPlus23)
15954 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15955 << P->getSourceRange();
15956
15957 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15958 // parameter pack.
15959 if (P->isParameterPack()) {
15960 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15961 << P->getSourceRange();
15962 return;
15963 }
15964 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15965 if (LambdaScopeInfo *LSI = S.getCurLambda())
15966 LSI->ExplicitObjectParameter = P;
15967}
15968
15969Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15970 SourceLocation ExplicitThisLoc) {
15971 const DeclSpec &DS = D.getDeclSpec();
15972
15973 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15974 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15975 // except for the special case of a single unnamed parameter of type void
15976 // with no storage class specifier, no type qualifier, and no following
15977 // ellipsis terminator.
15978 // Clang applies the C2y rules for 'register void' in all C language modes,
15979 // same as GCC, because it's questionable what that could possibly mean.
15980
15981 // C++03 [dcl.stc]p2 also permits 'auto'.
15982 StorageClass SC = SC_None;
15983 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15984 SC = SC_Register;
15985 // In C++11, the 'register' storage class specifier is deprecated.
15986 // In C++17, it is not allowed, but we tolerate it as an extension.
15987 if (getLangOpts().CPlusPlus11) {
15988 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15989 ? diag::ext_register_storage_class
15990 : diag::warn_deprecated_register)
15991 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15992 } else if (!getLangOpts().CPlusPlus &&
15993 DS.getTypeSpecType() == DeclSpec::TST_void &&
15994 D.getNumTypeObjects() == 0) {
15995 Diag(Loc: DS.getStorageClassSpecLoc(),
15996 DiagID: diag::err_invalid_storage_class_in_func_decl)
15997 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15998 D.getMutableDeclSpec().ClearStorageClassSpecs();
15999 }
16000 } else if (getLangOpts().CPlusPlus &&
16001 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
16002 SC = SC_Auto;
16003 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
16004 Diag(Loc: DS.getStorageClassSpecLoc(),
16005 DiagID: diag::err_invalid_storage_class_in_func_decl);
16006 D.getMutableDeclSpec().ClearStorageClassSpecs();
16007 }
16008
16009 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
16010 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
16011 << DeclSpec::getSpecifierName(S: TSCS);
16012 if (DS.isInlineSpecified())
16013 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
16014 << getLangOpts().CPlusPlus17;
16015 if (DS.hasConstexprSpecifier())
16016 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
16017 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
16018
16019 DiagnoseFunctionSpecifiers(DS);
16020
16021 CheckFunctionOrTemplateParamDeclarator(S, D);
16022
16023 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
16024 QualType parmDeclType = TInfo->getType();
16025
16026 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
16027 const IdentifierInfo *II = D.getIdentifier();
16028 if (II) {
16029 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
16030 RedeclarationKind::ForVisibleRedeclaration);
16031 LookupName(R, S);
16032 if (!R.empty()) {
16033 NamedDecl *PrevDecl = *R.begin();
16034 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
16035 // Maybe we will complain about the shadowed template parameter.
16036 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
16037 // Just pretend that we didn't see the previous declaration.
16038 PrevDecl = nullptr;
16039 }
16040 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
16041 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
16042 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
16043 // Recover by removing the name
16044 II = nullptr;
16045 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
16046 D.setInvalidType(true);
16047 }
16048 }
16049 }
16050
16051 // Incomplete resource arrays are not allowed as function parameters in HLSL
16052 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
16053 QualType EltTy = Context.getBaseElementType(QT: parmDeclType);
16054 // `isCompleteType` forces completion of the element type so the resource
16055 // check is valid.
16056 if (!EltTy->isDependentType() &&
16057 isCompleteType(Loc: D.getIdentifierLoc(), T: EltTy) &&
16058 parmDeclType->isHLSLResourceRecordArray()) {
16059 Diag(Loc: D.getIdentifierLoc(),
16060 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
16061 D.setInvalidType(true);
16062 }
16063 }
16064
16065 // Temporarily put parameter variables in the translation unit, not
16066 // the enclosing context. This prevents them from accidentally
16067 // looking like class members in C++.
16068 ParmVarDecl *New =
16069 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
16070 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
16071
16072 if (D.isInvalidType())
16073 New->setInvalidDecl();
16074
16075 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
16076
16077 assert(S->isFunctionPrototypeScope());
16078 assert(S->getFunctionPrototypeDepth() >= 1);
16079 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
16080 parameterIndex: S->getNextFunctionPrototypeIndex());
16081
16082 warnOnCTypeHiddenInCPlusPlus(D: New);
16083
16084 // Add the parameter declaration into this scope.
16085 S->AddDecl(D: New);
16086 if (II)
16087 IdResolver.AddDecl(D: New);
16088
16089 ProcessDeclAttributes(S, D: New, PD: D);
16090
16091 if (D.getDeclSpec().isModulePrivateSpecified())
16092 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
16093 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16094 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
16095
16096 if (New->hasAttr<BlocksAttr>())
16097 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
16098 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16099
16100 New->deduceParmAddressSpace(Ctxt: Context);
16101
16102 return New;
16103}
16104
16105ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
16106 SourceLocation Loc,
16107 QualType T) {
16108 /* FIXME: setting StartLoc == Loc.
16109 Would it be worth to modify callers so as to provide proper source
16110 location for the unnamed parameters, embedding the parameter's type? */
16111 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
16112 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
16113 S: SC_None, DefArg: nullptr);
16114 Param->setImplicit();
16115 return Param;
16116}
16117
16118void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
16119 // Don't diagnose unused-parameter errors in template instantiations; we
16120 // will already have done so in the template itself.
16121 if (inTemplateInstantiation())
16122 return;
16123
16124 for (const ParmVarDecl *Parameter : Parameters) {
16125 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16126 !Parameter->hasAttr<UnusedAttr>() &&
16127 !Parameter->getIdentifier()->isPlaceholder()) {
16128 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
16129 << Parameter->getDeclName();
16130 }
16131 }
16132}
16133
16134void Sema::DiagnoseSizeOfParametersAndReturnValue(
16135 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16136 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16137 return;
16138
16139 // Warn if the return value is pass-by-value and larger than the specified
16140 // threshold.
16141 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16142 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
16143 if (Size > LangOpts.NumLargeByValueCopy)
16144 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
16145 }
16146
16147 // Warn if any parameter is pass-by-value and larger than the specified
16148 // threshold.
16149 for (const ParmVarDecl *Parameter : Parameters) {
16150 QualType T = Parameter->getType();
16151 if (T->isDependentType() || !T.isPODType(Context))
16152 continue;
16153 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16154 if (Size > LangOpts.NumLargeByValueCopy)
16155 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
16156 << Parameter << Size;
16157 }
16158}
16159
16160ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
16161 SourceLocation NameLoc,
16162 const IdentifierInfo *Name, QualType T,
16163 TypeSourceInfo *TSInfo, StorageClass SC) {
16164 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16165 if (getLangOpts().ObjCAutoRefCount &&
16166 T.getObjCLifetime() == Qualifiers::OCL_None &&
16167 T->isObjCLifetimeType()) {
16168
16169 Qualifiers::ObjCLifetime lifetime;
16170
16171 // Special cases for arrays:
16172 // - if it's const, use __unsafe_unretained
16173 // - otherwise, it's an error
16174 if (T->isArrayType()) {
16175 if (!T.isConstQualified()) {
16176 if (DelayedDiagnostics.shouldDelayDiagnostics())
16177 DelayedDiagnostics.add(
16178 diag: sema::DelayedDiagnostic::makeForbiddenType(
16179 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
16180 else
16181 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
16182 << TSInfo->getTypeLoc().getSourceRange();
16183 }
16184 lifetime = Qualifiers::OCL_ExplicitNone;
16185 } else {
16186 lifetime = T->getObjCARCImplicitLifetime();
16187 }
16188 T = Context.getLifetimeQualifiedType(type: T, lifetime);
16189 }
16190
16191 if (getLangOpts().OpenCL) {
16192 assert(!isa<DecayedType>(T));
16193 if (T->isArrayType() && !T.hasAddressSpace()) {
16194 QualType ET = Context.getAsArrayType(T)->getElementType();
16195 if (!ET.hasAddressSpace()) {
16196 // Add the private address space to the contents of the pointer when a
16197 // pointer parameter is declared as an array and not declared.
16198 LangAS ImplAS = LangAS::opencl_private;
16199 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
16200 T = QualType(Context.getAsArrayType(T), 0);
16201 }
16202 }
16203 }
16204
16205 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
16206 T: Context.getAdjustedParameterType(T),
16207 TInfo: TSInfo, S: SC, DefArg: nullptr);
16208
16209 SourceLocation VMLoc = TSInfo ? TSInfo->getTypeLoc().getBeginLoc() : NameLoc;
16210 if (!CheckVariablyModifiedTypeUse(T, Loc: VMLoc))
16211 New->setInvalidDecl();
16212
16213 // Make a note if we created a new pack in the scope of a lambda, so that
16214 // we know that references to that pack must also be expanded within the
16215 // lambda scope.
16216 if (New->isParameterPack())
16217 if (auto *CSI = getEnclosingLambdaOrBlock())
16218 CSI->LocalPacks.push_back(Elt: New);
16219
16220 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16221 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16222 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
16223 UseContext: NonTrivialCUnionContext::FunctionParam,
16224 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16225
16226 // Parameter declarators cannot be interface types. All ObjC objects are
16227 // passed by reference.
16228 if (T->isObjCObjectType()) {
16229 SourceLocation TypeEndLoc =
16230 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
16231 Diag(Loc: NameLoc,
16232 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16233 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
16234 T = Context.getObjCObjectPointerType(OIT: T);
16235 New->setType(T);
16236 }
16237
16238 // __ptrauth is forbidden on parameters.
16239 if (T.getPointerAuth()) {
16240 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
16241 New->setInvalidDecl();
16242 }
16243
16244 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16245 // duration shall not be qualified by an address-space qualifier."
16246 // Since all parameters have automatic store duration, they can not have
16247 // an address space.
16248 if (T.getAddressSpace() != LangAS::Default &&
16249 // OpenCL allows function arguments declared to be an array of a type
16250 // to be qualified with an address space.
16251 !(getLangOpts().OpenCL &&
16252 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16253 // WebAssembly allows reference types as parameters. Funcref in particular
16254 // lives in a different address space.
16255 !(T->isFunctionPointerType() &&
16256 T.getAddressSpace() == LangAS::wasm_funcref) &&
16257 // HLSL allows function arguments to be qualified with an address space
16258 // if the groupshared annotation is used.
16259 !(getLangOpts().HLSL &&
16260 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16261 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
16262 New->setInvalidDecl();
16263 }
16264
16265 // PPC MMA non-pointer types are not allowed as function argument types.
16266 if (Context.getTargetInfo().getTriple().isPPC64() &&
16267 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
16268 New->setInvalidDecl();
16269 }
16270
16271 return New;
16272}
16273
16274void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
16275 SourceLocation LocAfterDecls) {
16276 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
16277
16278 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16279 // in the declaration list shall have at least one declarator, those
16280 // declarators shall only declare identifiers from the identifier list, and
16281 // every identifier in the identifier list shall be declared.
16282 //
16283 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16284 // identifiers it names shall be declared in the declaration list."
16285 //
16286 // This is why we only diagnose in C99 and later. Note, the other conditions
16287 // listed are checked elsewhere.
16288 if (!FTI.hasPrototype) {
16289 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16290 --i;
16291 if (FTI.Params[i].Param == nullptr) {
16292 if (getLangOpts().C99) {
16293 SmallString<256> Code;
16294 llvm::raw_svector_ostream(Code)
16295 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16296 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16297 << FTI.Params[i].Ident
16298 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16299 }
16300
16301 // Implicitly declare the argument as type 'int' for lack of a better
16302 // type.
16303 AttributeFactory attrs;
16304 DeclSpec DS(attrs);
16305 const char* PrevSpec; // unused
16306 unsigned DiagID; // unused
16307 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16308 DiagID, Policy: Context.getPrintingPolicy());
16309 // Use the identifier location for the type source range.
16310 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16311 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16312 Declarator ParamD(DS, ParsedAttributesView::none(),
16313 DeclaratorContext::KNRTypeList);
16314 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16315 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16316 }
16317 }
16318 }
16319}
16320
16321Decl *
16322Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16323 MultiTemplateParamsArg TemplateParameterLists,
16324 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16325 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16326 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16327 Scope *ParentScope = FnBodyScope->getParent();
16328
16329 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16330 // we define a non-templated function definition, we will create a declaration
16331 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16332 // The base function declaration will have the equivalent of an `omp declare
16333 // variant` annotation which specifies the mangled definition as a
16334 // specialization function under the OpenMP context defined as part of the
16335 // `omp begin declare variant`.
16336 SmallVector<FunctionDecl *, 4> Bases;
16337 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16338 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16339 S: ParentScope, D, TemplateParameterLists, Bases);
16340
16341 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16342 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16343 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16344
16345 if (!Bases.empty())
16346 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16347 Bases);
16348
16349 return Dcl;
16350}
16351
16352void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16353 Consumer.HandleInlineFunctionDefinition(D);
16354}
16355
16356static bool FindPossiblePrototype(const FunctionDecl *FD,
16357 const FunctionDecl *&PossiblePrototype) {
16358 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16359 Prev = Prev->getPreviousDecl()) {
16360 // Ignore any declarations that occur in function or method
16361 // scope, because they aren't visible from the header.
16362 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16363 continue;
16364
16365 PossiblePrototype = Prev;
16366 return Prev->getType()->isFunctionProtoType();
16367 }
16368 return false;
16369}
16370
16371static bool
16372ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16373 const FunctionDecl *&PossiblePrototype) {
16374 // Don't warn about invalid declarations.
16375 if (FD->isInvalidDecl())
16376 return false;
16377
16378 // Or declarations that aren't global.
16379 if (!FD->isGlobal())
16380 return false;
16381
16382 // Don't warn about C++ member functions.
16383 if (isa<CXXMethodDecl>(Val: FD))
16384 return false;
16385
16386 // Don't warn about 'main'.
16387 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16388 if (IdentifierInfo *II = FD->getIdentifier())
16389 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16390 return false;
16391
16392 if (FD->isMSVCRTEntryPoint())
16393 return false;
16394
16395 // Don't warn about inline functions.
16396 if (FD->isInlined())
16397 return false;
16398
16399 // Don't warn about function templates.
16400 if (FD->getDescribedFunctionTemplate())
16401 return false;
16402
16403 // Don't warn about function template specializations.
16404 if (FD->isFunctionTemplateSpecialization())
16405 return false;
16406
16407 // Don't warn for OpenCL kernels.
16408 if (FD->hasAttr<DeviceKernelAttr>())
16409 return false;
16410
16411 // Don't warn on explicitly deleted functions.
16412 if (FD->isDeleted())
16413 return false;
16414
16415 // Don't warn on implicitly local functions (such as having local-typed
16416 // parameters).
16417 if (!FD->isExternallyVisible())
16418 return false;
16419
16420 // If we were able to find a potential prototype, don't warn.
16421 if (FindPossiblePrototype(FD, PossiblePrototype))
16422 return false;
16423
16424 return true;
16425}
16426
16427void
16428Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16429 const FunctionDecl *EffectiveDefinition,
16430 SkipBodyInfo *SkipBody) {
16431 const FunctionDecl *Definition = EffectiveDefinition;
16432 if (!Definition &&
16433 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16434 return;
16435
16436 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16437 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16438 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16439 // A merged copy of the same function, instantiated as a member of
16440 // the same class, is OK.
16441 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16442 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16443 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16444 return;
16445 }
16446 }
16447 }
16448
16449 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16450 return;
16451
16452 // Don't emit an error when this is redefinition of a typo-corrected
16453 // definition.
16454 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16455 return;
16456
16457 bool DefinitionVisible = false;
16458 if (SkipBody &&
16459 isRedefinitionAllowedFor(D: Definition, NewLoc: FD->getLocation(),
16460 Visible&: DefinitionVisible) &&
16461 (Definition->getFormalLinkage() == Linkage::Internal ||
16462 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16463 !Definition->getTemplateParameterLists().empty())) {
16464 SkipBody->ShouldSkip = true;
16465 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16466 if (!DefinitionVisible) {
16467 if (auto *TD = Definition->getDescribedFunctionTemplate())
16468 makeMergedDefinitionVisible(ND: TD);
16469 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16470 }
16471 return;
16472 }
16473
16474 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16475 Definition->getStorageClass() == SC_Extern)
16476 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16477 << FD << getLangOpts().CPlusPlus;
16478 else
16479 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16480
16481 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16482 FD->setInvalidDecl();
16483}
16484
16485LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16486 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16487
16488 LambdaScopeInfo *LSI = PushLambdaScope();
16489 LSI->CallOperator = CallOperator;
16490 LSI->Lambda = LambdaClass;
16491 LSI->ReturnType = CallOperator->getReturnType();
16492 // When this function is called in situation where the context of the call
16493 // operator is not entered, we set AfterParameterList to false, so that
16494 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16495 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16496 // where we would set the CurContext to the lambda operator before
16497 // substituting into it. In this case the flag needs to be true such that
16498 // tryCaptureVariable can correctly handle potential captures thereof.
16499 LSI->AfterParameterList = CurContext == CallOperator;
16500 LSI->BeforeCompoundStatement = false;
16501
16502 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16503 // used at the point of dealing with potential captures.
16504 //
16505 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16506 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16507 // associated. (Technically, we could recover that list from their
16508 // instantiation patterns, but for now, the GLTemplateParameterList seems
16509 // unnecessary in these cases.)
16510 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16511 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16512 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16513
16514 if (LCD == LCD_None)
16515 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16516 else if (LCD == LCD_ByCopy)
16517 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16518 else if (LCD == LCD_ByRef)
16519 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16520 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16521
16522 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16523 LSI->Mutable = !CallOperator->isConst();
16524 if (CallOperator->isExplicitObjectMemberFunction())
16525 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16526
16527 // Add the captures to the LSI so they can be noted as already
16528 // captured within tryCaptureVar.
16529 auto I = LambdaClass->field_begin();
16530 for (const auto &C : LambdaClass->captures()) {
16531 if (C.capturesVariable()) {
16532 ValueDecl *VD = C.getCapturedVar();
16533 if (VD->isInitCapture())
16534 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16535 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16536 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16537 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16538 /*EllipsisLoc*/C.isPackExpansion()
16539 ? C.getEllipsisLoc() : SourceLocation(),
16540 CaptureType: I->getType(), /*Invalid*/false);
16541
16542 } else if (C.capturesThis()) {
16543 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16544 ByCopy: C.getCaptureKind() == LCK_StarThis);
16545 } else {
16546 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16547 CaptureType: I->getType());
16548 }
16549 ++I;
16550 }
16551 return LSI;
16552}
16553
16554Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16555 SkipBodyInfo *SkipBody,
16556 FnBodyKind BodyKind) {
16557 if (!D) {
16558 // Parsing the function declaration failed in some way. Push on a fake scope
16559 // anyway so we can try to parse the function body.
16560 PushFunctionScope();
16561 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16562 return D;
16563 }
16564
16565 FunctionDecl *FD = nullptr;
16566
16567 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16568 FD = FunTmpl->getTemplatedDecl();
16569 else
16570 FD = cast<FunctionDecl>(Val: D);
16571
16572 // Do not push if it is a lambda because one is already pushed when building
16573 // the lambda in ActOnStartOfLambdaDefinition().
16574 if (!isLambdaCallOperator(DC: FD))
16575 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16576 FD);
16577
16578 // Check for defining attributes before the check for redefinition.
16579 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16580 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16581 FD->dropAttr<AliasAttr>();
16582 FD->setInvalidDecl();
16583 }
16584 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16585 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16586 FD->dropAttr<IFuncAttr>();
16587 FD->setInvalidDecl();
16588 }
16589 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16590 if (Context.getTargetInfo().getTriple().isAArch64() &&
16591 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16592 !Attr->isDefaultVersion()) {
16593 // If function multi versioning disabled skip parsing function body
16594 // defined with non-default target_version attribute
16595 if (SkipBody)
16596 SkipBody->ShouldSkip = true;
16597 return nullptr;
16598 }
16599 }
16600
16601 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16602 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16603 Ctor->isDefaultConstructor() &&
16604 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16605 // If this is an MS ABI dllexport default constructor, instantiate any
16606 // default arguments.
16607 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16608 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
16609 }
16610 }
16611
16612 // See if this is a redefinition. If 'will have body' (or similar) is already
16613 // set, then these checks were already performed when it was set.
16614 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16615 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16616 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16617
16618 // If we're skipping the body, we're done. Don't enter the scope.
16619 if (SkipBody && SkipBody->ShouldSkip)
16620 return D;
16621 }
16622
16623 // Mark this function as "will have a body eventually". This lets users to
16624 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16625 // this function.
16626 FD->setWillHaveBody();
16627
16628 // If we are instantiating a generic lambda call operator, push
16629 // a LambdaScopeInfo onto the function stack. But use the information
16630 // that's already been calculated (ActOnLambdaExpr) to prime the current
16631 // LambdaScopeInfo.
16632 // When the template operator is being specialized, the LambdaScopeInfo,
16633 // has to be properly restored so that tryCaptureVariable doesn't try
16634 // and capture any new variables. In addition when calculating potential
16635 // captures during transformation of nested lambdas, it is necessary to
16636 // have the LSI properly restored.
16637 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16638 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16639 // specialized.
16640 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16641 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16642 << /*specialization*/ 0;
16643 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16644 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16645
16646 FD->setInvalidDecl();
16647 PushFunctionScope();
16648 } else {
16649 assert(inTemplateInstantiation() &&
16650 "There should be an active template instantiation on the stack "
16651 "when instantiating a generic lambda!");
16652 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16653 }
16654 } else {
16655 // Enter a new function scope
16656 PushFunctionScope();
16657 }
16658
16659 // Builtin functions cannot be defined.
16660 if (unsigned BuiltinID = FD->getBuiltinID()) {
16661 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16662 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16663 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16664 FD->setInvalidDecl();
16665 }
16666 }
16667
16668 // The return type of a function definition must be complete (C99 6.9.1p3).
16669 // C++23 [dcl.fct.def.general]/p2
16670 // The type of [...] the return for a function definition
16671 // shall not be a (possibly cv-qualified) class type that is incomplete
16672 // or abstract within the function body unless the function is deleted.
16673 QualType ResultType = FD->getReturnType();
16674 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16675 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16676 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16677 DiagID: diag::err_func_def_incomplete_result) ||
16678 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16679 DiagID: diag::err_abstract_type_in_decl,
16680 Args: AbstractReturnType)))
16681 FD->setInvalidDecl();
16682
16683 if (FnBodyScope)
16684 PushDeclContext(S: FnBodyScope, DC: FD);
16685
16686 // Check the validity of our function parameters
16687 if (BodyKind != FnBodyKind::Delete)
16688 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16689 /*CheckParameterNames=*/true);
16690
16691 // Add non-parameter declarations already in the function to the current
16692 // scope.
16693 if (FnBodyScope) {
16694 for (Decl *NPD : FD->decls()) {
16695 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16696 if (!NonParmDecl)
16697 continue;
16698 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16699 "parameters should not be in newly created FD yet");
16700
16701 // If the decl has a name, make it accessible in the current scope.
16702 if (NonParmDecl->getDeclName())
16703 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16704
16705 // Similarly, dive into enums and fish their constants out, making them
16706 // accessible in this scope.
16707 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16708 for (auto *EI : ED->enumerators())
16709 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16710 }
16711 }
16712 }
16713
16714 // Introduce our parameters into the function scope
16715 for (auto *Param : FD->parameters()) {
16716 Param->setOwningFunction(FD);
16717
16718 // If this has an identifier, add it to the scope stack.
16719 if (Param->getIdentifier() && FnBodyScope) {
16720 CheckShadow(S: FnBodyScope, D: Param);
16721
16722 PushOnScopeChains(D: Param, S: FnBodyScope);
16723 }
16724 }
16725
16726 // C++ [module.import/6]
16727 // ...
16728 // A header unit shall not contain a definition of a non-inline function or
16729 // variable whose name has external linkage.
16730 //
16731 // Deleted and Defaulted functions are implicitly inline (but the
16732 // inline state is not set at this point, so check the BodyKind explicitly).
16733 // We choose to allow weak & selectany definitions, as they are common in
16734 // headers, and have semantics similar to inline definitions which are allowed
16735 // in header units.
16736 // FIXME: Consider an alternate location for the test where the inlined()
16737 // state is complete.
16738 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16739 !FD->isInvalidDecl() && !FD->isInlined() &&
16740 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16741 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16742 !FD->isTemplateInstantiation() &&
16743 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16744 assert(FD->isThisDeclarationADefinition());
16745 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16746 FD->setInvalidDecl();
16747 }
16748
16749 // Ensure that the function's exception specification is instantiated.
16750 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16751 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16752
16753 // dllimport cannot be applied to non-inline function definitions.
16754 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16755 !FD->isTemplateInstantiation()) {
16756 assert(!FD->hasAttr<DLLExportAttr>());
16757 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16758 FD->setInvalidDecl();
16759 return D;
16760 }
16761
16762 // Some function attributes (like OptimizeNoneAttr) need actions before
16763 // parsing body started.
16764 applyFunctionAttributesBeforeParsingBody(FD: D);
16765
16766 // We want to attach documentation to original Decl (which might be
16767 // a function template).
16768 ActOnDocumentableDecl(D);
16769 if (getCurLexicalContext()->isObjCContainer() &&
16770 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16771 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16772 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16773
16774 maybeAddDeclWithEffects(D: FD);
16775
16776 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16777 FnBodyScope) {
16778 // An implicit call expression is synthesized for functions declared with
16779 // the sycl_kernel_entry_point attribute. The call may resolve to a
16780 // function template, a member function template, or a call operator
16781 // of a variable template depending on the results of unqualified lookup
16782 // for 'sycl_kernel_launch' from the beginning of the function body.
16783 // Performing that lookup requires the stack of parsing scopes active
16784 // when the definition is parsed and is thus done here; the result is
16785 // cached in FunctionScopeInfo and used to synthesize the (possibly
16786 // unresolved) call expression after the function body has been parsed.
16787 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16788 if (!SKEPAttr->isInvalidAttr()) {
16789 ExprResult LaunchIdExpr =
16790 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16791 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16792 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16793 // treated as an error in the definition of 'FD'; treating it as an error
16794 // of the declaration would affect overload resolution which would
16795 // potentially result in additional errors. If construction of
16796 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16797 // a null pointer value below; that is expected.
16798 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16799 }
16800 }
16801
16802 return D;
16803}
16804
16805void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16806 if (!FD || FD->isInvalidDecl())
16807 return;
16808 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16809 FD = TD->getTemplatedDecl();
16810 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16811 FPOptionsOverride FPO;
16812 FPO.setDisallowOptimizations();
16813 CurFPFeatures.applyChanges(FPO);
16814 FpPragmaStack.CurrentValue =
16815 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16816 }
16817}
16818
16819void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16820 ReturnStmt **Returns = Scope->Returns.data();
16821
16822 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16823 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16824 if (!NRVOCandidate->isNRVOVariable()) {
16825 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16826 DiagID: diag::warn_not_eliding_copy_on_return);
16827 Returns[I]->setNRVOCandidate(nullptr);
16828 }
16829 }
16830 }
16831}
16832
16833bool Sema::canDelayFunctionBody(const Declarator &D) {
16834 // We can't delay parsing the body of a constexpr function template (yet).
16835 if (D.getDeclSpec().hasConstexprSpecifier())
16836 return false;
16837
16838 // We can't delay parsing the body of a function template with a deduced
16839 // return type (yet).
16840 if (D.getDeclSpec().hasAutoTypeSpec()) {
16841 // If the placeholder introduces a non-deduced trailing return type,
16842 // we can still delay parsing it.
16843 if (D.getNumTypeObjects()) {
16844 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16845 if (Outer.Kind == DeclaratorChunk::Function &&
16846 Outer.Fun.hasTrailingReturnType()) {
16847 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16848 return Ty.isNull() || !Ty->isUndeducedType();
16849 }
16850 }
16851 return false;
16852 }
16853
16854 return true;
16855}
16856
16857bool Sema::canSkipFunctionBody(Decl *D) {
16858 // We cannot skip the body of a function (or function template) which is
16859 // constexpr, since we may need to evaluate its body in order to parse the
16860 // rest of the file.
16861 // We cannot skip the body of a function with an undeduced return type,
16862 // because any callers of that function need to know the type.
16863 if (const FunctionDecl *FD = D->getAsFunction()) {
16864 if (FD->isConstexpr())
16865 return false;
16866 // We can't simply call Type::isUndeducedType here, because inside template
16867 // auto can be deduced to a dependent type, which is not considered
16868 // "undeduced".
16869 if (FD->getReturnType()->getContainedDeducedType())
16870 return false;
16871 }
16872 return Consumer.shouldSkipFunctionBody(D);
16873}
16874
16875Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16876 if (!Decl)
16877 return nullptr;
16878 if (FunctionDecl *FD = Decl->getAsFunction())
16879 FD->setHasSkippedBody();
16880 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16881 MD->setHasSkippedBody();
16882 return Decl;
16883}
16884
16885/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16886/// body.
16887class ExitFunctionBodyRAII {
16888public:
16889 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16890 ~ExitFunctionBodyRAII() {
16891 if (!IsLambda)
16892 S.PopExpressionEvaluationContext();
16893 }
16894
16895private:
16896 Sema &S;
16897 bool IsLambda = false;
16898};
16899
16900static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16901 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16902
16903 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16904 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16905 if (!Inserted)
16906 return It->second;
16907
16908 bool R = false;
16909 const BlockDecl *CurBD = BD;
16910
16911 do {
16912 R = !CurBD->doesNotEscape();
16913 if (R)
16914 break;
16915 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16916 } while (CurBD);
16917
16918 return It->second = R;
16919 };
16920
16921 // If the location where 'self' is implicitly retained is inside a escaping
16922 // block, emit a diagnostic.
16923 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16924 S.ImplicitlyRetainedSelfLocs)
16925 if (IsOrNestedInEscapingBlock(P.second))
16926 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16927 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16928}
16929
16930static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16931 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16932 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16933}
16934
16935bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16936 return methodHasName(FD, Name: "get_return_object");
16937}
16938
16939bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16940 return FD->isStatic() &&
16941 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16942}
16943
16944void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16945 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16946 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16947 return;
16948 // Allow some_promise_type::get_return_object().
16949 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16950 return;
16951 if (!FD->hasAttr<CoroWrapperAttr>())
16952 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16953}
16954
16955Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16956 bool RetainFunctionScopeInfo) {
16957 FunctionScopeInfo *FSI = getCurFunction();
16958 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16959
16960 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16961 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16962
16963 SourceLocation AnalysisLoc;
16964 if (Body)
16965 AnalysisLoc = Body->getEndLoc();
16966 else if (FD)
16967 AnalysisLoc = FD->getEndLoc();
16968 sema::AnalysisBasedWarnings::Policy WP =
16969 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16970 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16971
16972 // If we skip function body, we can't tell if a function is a coroutine.
16973 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16974 if (FSI->isCoroutine())
16975 CheckCompletedCoroutineBody(FD, Body);
16976 else
16977 CheckCoroutineWrapper(FD);
16978 }
16979
16980 // Diagnose invalid SYCL kernel entry point function declarations
16981 // and build SYCLKernelCallStmts for valid ones.
16982 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16983 SYCLKernelEntryPointAttr *SKEPAttr =
16984 FD->getAttr<SYCLKernelEntryPointAttr>();
16985 if (FD->isDefaulted()) {
16986 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16987 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16988 SKEPAttr->setInvalidAttr();
16989 } else if (FD->isDeleted()) {
16990 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16991 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16992 SKEPAttr->setInvalidAttr();
16993 } else if (FSI->isCoroutine()) {
16994 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16995 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16996 SKEPAttr->setInvalidAttr();
16997 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16998 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16999 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
17000 SKEPAttr->setInvalidAttr();
17001 }
17002
17003 // Build an unresolved SYCL kernel call statement for a function template,
17004 // validate that a SYCL kernel call statement was instantiated for an
17005 // (implicit or explicit) instantiation of a function template, or otherwise
17006 // build a (resolved) SYCL kernel call statement for a non-templated
17007 // function or an explicit specialization.
17008 if (Body && !SKEPAttr->isInvalidAttr()) {
17009 StmtResult SR;
17010 if (FD->isTemplateInstantiation()) {
17011 // The function body should already be a SYCLKernelCallStmt in this
17012 // case, but might not be if there were previous errors.
17013 SR = Body;
17014 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
17015 // If name lookup for a template named sycl_kernel_launch failed
17016 // earlier, don't try to build a SYCL kernel call statement as that
17017 // would cause additional errors to be issued; just proceed with the
17018 // original function body.
17019 SR = Body;
17020 } else if (FD->isTemplated()) {
17021 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
17022 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
17023 } else {
17024 SR = SYCL().BuildSYCLKernelCallStmt(
17025 FD, Body: cast<CompoundStmt>(Val: Body),
17026 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
17027 }
17028 // If construction of the replacement body fails, just continue with the
17029 // original function body. An early error return here is not valid; the
17030 // current declaration context and function scopes must be popped before
17031 // returning.
17032 if (SR.isUsable())
17033 Body = SR.get();
17034 }
17035 }
17036
17037 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
17038 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
17039 if (FD->isDeletedAsWritten())
17040 Diag(Loc: SEAttr->getLocation(),
17041 DiagID: diag::err_sycl_external_invalid_deleted_function)
17042 << SEAttr;
17043 }
17044
17045 {
17046 // Do not call PopExpressionEvaluationContext() if it is a lambda because
17047 // one is already popped when finishing the lambda in BuildLambdaExpr().
17048 // This is meant to pop the context added in ActOnStartOfFunctionDef().
17049 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
17050 if (FD) {
17051 // The function body and the DefaultedOrDeletedInfo, if present, use
17052 // the same storage; don't overwrite the latter if the former is null
17053 // (the body is initialised to null anyway, so even if the latter isn't
17054 // present, this would still be a no-op).
17055 if (Body)
17056 FD->setBody(Body);
17057 FD->setWillHaveBody(false);
17058
17059 if (getLangOpts().CPlusPlus14) {
17060 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
17061 FD->getReturnType()->isUndeducedType()) {
17062 // For a function with a deduced result type to return void,
17063 // the result type as written must be 'auto' or 'decltype(auto)',
17064 // possibly cv-qualified or constrained, but not ref-qualified.
17065 if (!FD->getReturnType()->getAs<AutoType>()) {
17066 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
17067 << FD->getReturnType();
17068 FD->setInvalidDecl();
17069 } else {
17070 // Falling off the end of the function is the same as 'return;'.
17071 Expr *Dummy = nullptr;
17072 if (DeduceFunctionTypeFromReturnExpr(
17073 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
17074 AT: FD->getReturnType()->getAs<AutoType>()))
17075 FD->setInvalidDecl();
17076 }
17077 }
17078 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
17079 // In C++11, we don't use 'auto' deduction rules for lambda call
17080 // operators because we don't support return type deduction.
17081 auto *LSI = getCurLambda();
17082 if (LSI->HasImplicitReturnType) {
17083 deduceClosureReturnType(CSI&: *LSI);
17084
17085 // C++11 [expr.prim.lambda]p4:
17086 // [...] if there are no return statements in the compound-statement
17087 // [the deduced type is] the type void
17088 QualType RetType =
17089 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17090
17091 // Update the return type to the deduced type.
17092 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17093 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
17094 EPI: Proto->getExtProtoInfo()));
17095 }
17096 }
17097
17098 // If the function implicitly returns zero (like 'main') or is naked,
17099 // don't complain about missing return statements.
17100 // Clang implicitly returns 0 in C89 mode, but that's considered an
17101 // extension. The check is necessary to ensure the expected extension
17102 // warning is emitted in C89 mode.
17103 if ((FD->hasImplicitReturnZero() &&
17104 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17105 FD->hasAttr<NakedAttr>())
17106 WP.disableCheckFallThrough();
17107
17108 // MSVC permits the use of pure specifier (=0) on function definition,
17109 // defined at class scope, warn about this non-standard construct.
17110 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17111 !FD->isOutOfLine())
17112 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
17113
17114 if (!FD->isInvalidDecl()) {
17115 // Don't diagnose unused parameters of defaulted, deleted or naked
17116 // functions.
17117 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17118 !FD->hasAttr<NakedAttr>())
17119 DiagnoseUnusedParameters(Parameters: FD->parameters());
17120 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
17121 ReturnTy: FD->getReturnType(), D: FD);
17122
17123 // If this is a structor, we need a vtable.
17124 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
17125 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
17126 else if (CXXDestructorDecl *Destructor =
17127 dyn_cast<CXXDestructorDecl>(Val: FD))
17128 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
17129
17130 // Try to apply the named return value optimization. We have to check
17131 // if we can do this here because lambdas keep return statements around
17132 // to deduce an implicit return type.
17133 if (FD->getReturnType()->isRecordType() &&
17134 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
17135 computeNRVO(Body, Scope: FSI);
17136 }
17137
17138 // GNU warning -Wmissing-prototypes:
17139 // Warn if a global function is defined without a previous
17140 // prototype declaration. This warning is issued even if the
17141 // definition itself provides a prototype. The aim is to detect
17142 // global functions that fail to be declared in header files.
17143 const FunctionDecl *PossiblePrototype = nullptr;
17144 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17145 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
17146
17147 if (PossiblePrototype) {
17148 // We found a declaration that is not a prototype,
17149 // but that could be a zero-parameter prototype
17150 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17151 TypeLoc TL = TI->getTypeLoc();
17152 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
17153 Diag(Loc: PossiblePrototype->getLocation(),
17154 DiagID: diag::note_declaration_not_a_prototype)
17155 << (FD->getNumParams() != 0)
17156 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
17157 InsertionLoc: FTL.getRParenLoc(), Code: "void")
17158 : FixItHint{});
17159 }
17160 } else {
17161 // Returns true if the token beginning at this Loc is `const`.
17162 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17163 const LangOptions &LangOpts) {
17164 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17165 if (LocInfo.first.isInvalid())
17166 return false;
17167
17168 bool Invalid = false;
17169 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
17170 if (Invalid)
17171 return false;
17172
17173 if (LocInfo.second > Buffer.size())
17174 return false;
17175
17176 const char *LexStart = Buffer.data() + LocInfo.second;
17177 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17178
17179 return StartTok.consume_front(Prefix: "const") &&
17180 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
17181 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
17182 };
17183
17184 auto findBeginLoc = [&]() {
17185 // If the return type has `const` qualifier, we want to insert
17186 // `static` before `const` (and not before the typename).
17187 if ((FD->getReturnType()->isAnyPointerType() &&
17188 FD->getReturnType()->getPointeeType().isConstQualified()) ||
17189 FD->getReturnType().isConstQualified()) {
17190 // But only do this if we can determine where the `const` is.
17191
17192 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17193 getLangOpts()))
17194
17195 return FD->getBeginLoc();
17196 }
17197 return FD->getTypeSpecStartLoc();
17198 };
17199 Diag(Loc: FD->getTypeSpecStartLoc(),
17200 DiagID: diag::note_static_for_internal_linkage)
17201 << /* function */ 1
17202 << (FD->getStorageClass() == SC_None
17203 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
17204 : FixItHint{});
17205 }
17206 }
17207
17208 // We might not have found a prototype because we didn't wish to warn on
17209 // the lack of a missing prototype. Try again without the checks for
17210 // whether we want to warn on the missing prototype.
17211 if (!PossiblePrototype)
17212 (void)FindPossiblePrototype(FD, PossiblePrototype);
17213
17214 // If the function being defined does not have a prototype, then we may
17215 // need to diagnose it as changing behavior in C23 because we now know
17216 // whether the function accepts arguments or not. This only handles the
17217 // case where the definition has no prototype but does have parameters
17218 // and either there is no previous potential prototype, or the previous
17219 // potential prototype also has no actual prototype. This handles cases
17220 // like:
17221 // void f(); void f(a) int a; {}
17222 // void g(a) int a; {}
17223 // See MergeFunctionDecl() for other cases of the behavior change
17224 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17225 // type without a prototype.
17226 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17227 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17228 !PossiblePrototype->isImplicit()))) {
17229 // The function definition has parameters, so this will change behavior
17230 // in C23. If there is a possible prototype, it comes before the
17231 // function definition.
17232 // FIXME: The declaration may have already been diagnosed as being
17233 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17234 // there's no way to test for the "changes behavior" condition in
17235 // SemaType.cpp when forming the declaration's function type. So, we do
17236 // this awkward dance instead.
17237 //
17238 // If we have a possible prototype and it declares a function with a
17239 // prototype, we don't want to diagnose it; if we have a possible
17240 // prototype and it has no prototype, it may have already been
17241 // diagnosed in SemaType.cpp as deprecated depending on whether
17242 // -Wstrict-prototypes is enabled. If we already warned about it being
17243 // deprecated, add a note that it also changes behavior. If we didn't
17244 // warn about it being deprecated (because the diagnostic is not
17245 // enabled), warn now that it is deprecated and changes behavior.
17246
17247 // This K&R C function definition definitely changes behavior in C23,
17248 // so diagnose it.
17249 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
17250 << /*definition*/ 1 << /* not supported in C23 */ 0;
17251
17252 // If we have a possible prototype for the function which is a user-
17253 // visible declaration, we already tested that it has no prototype.
17254 // This will change behavior in C23. This gets a warning rather than a
17255 // note because it's the same behavior-changing problem as with the
17256 // definition.
17257 if (PossiblePrototype)
17258 Diag(Loc: PossiblePrototype->getLocation(),
17259 DiagID: diag::warn_non_prototype_changes_behavior)
17260 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17261 << /*definition*/ 1;
17262 }
17263
17264 // Warn on CPUDispatch with an actual body.
17265 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17266 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
17267 if (!CmpndBody->body_empty())
17268 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
17269 DiagID: diag::warn_dispatch_body_ignored);
17270
17271 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
17272 const CXXMethodDecl *KeyFunction;
17273 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17274 MD->isVirtual() &&
17275 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
17276 MD == KeyFunction->getCanonicalDecl()) {
17277 // Update the key-function state if necessary for this ABI.
17278 if (FD->isInlined() &&
17279 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17280 Context.setNonKeyFunction(MD);
17281
17282 // If the newly-chosen key function is already defined, then we
17283 // need to mark the vtable as used retroactively.
17284 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
17285 const FunctionDecl *Definition;
17286 if (KeyFunction && KeyFunction->isDefined(Definition))
17287 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17288 } else {
17289 // We just defined they key function; mark the vtable as used.
17290 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17291 }
17292 }
17293 }
17294
17295 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17296 "Function parsing confused");
17297 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
17298 assert(MD == getCurMethodDecl() && "Method parsing confused");
17299 MD->setBody(Body);
17300 if (!MD->isInvalidDecl()) {
17301 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17302 ReturnTy: MD->getReturnType(), D: MD);
17303
17304 if (Body)
17305 computeNRVO(Body, Scope: FSI);
17306 }
17307 if (FSI->ObjCShouldCallSuper) {
17308 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17309 << MD->getSelector().getAsString();
17310 FSI->ObjCShouldCallSuper = false;
17311 }
17312 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17313 const ObjCMethodDecl *InitMethod = nullptr;
17314 bool isDesignated =
17315 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17316 assert(isDesignated && InitMethod);
17317 (void)isDesignated;
17318
17319 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17320 auto IFace = MD->getClassInterface();
17321 if (!IFace)
17322 return false;
17323 auto SuperD = IFace->getSuperClass();
17324 if (!SuperD)
17325 return false;
17326 return SuperD->getIdentifier() ==
17327 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17328 };
17329 // Don't issue this warning for unavailable inits or direct subclasses
17330 // of NSObject.
17331 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17332 Diag(Loc: MD->getLocation(),
17333 DiagID: diag::warn_objc_designated_init_missing_super_call);
17334 Diag(Loc: InitMethod->getLocation(),
17335 DiagID: diag::note_objc_designated_init_marked_here);
17336 }
17337 FSI->ObjCWarnForNoDesignatedInitChain = false;
17338 }
17339 if (FSI->ObjCWarnForNoInitDelegation) {
17340 // Don't issue this warning for unavailable inits.
17341 if (!MD->isUnavailable())
17342 Diag(Loc: MD->getLocation(),
17343 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17344 FSI->ObjCWarnForNoInitDelegation = false;
17345 }
17346
17347 diagnoseImplicitlyRetainedSelf(S&: *this);
17348 } else {
17349 // Parsing the function declaration failed in some way. Pop the fake scope
17350 // we pushed on.
17351 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17352 return nullptr;
17353 }
17354
17355 if (Body) {
17356 if (FSI->HasPotentialAvailabilityViolations)
17357 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17358 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17359 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17360 }
17361
17362 assert(!FSI->ObjCShouldCallSuper &&
17363 "This should only be set for ObjC methods, which should have been "
17364 "handled in the block above.");
17365
17366 // Verify and clean out per-function state.
17367 if (Body && (!FD || !FD->isDefaulted())) {
17368 // C++ constructors that have function-try-blocks can't have return
17369 // statements in the handlers of that block. (C++ [except.handle]p14)
17370 // Verify this.
17371 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17372 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17373
17374 // Verify that gotos and switch cases don't jump into scopes illegally.
17375 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17376 DiagnoseInvalidJumps(Body);
17377
17378 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17379 if (!Destructor->getParent()->isDependentType())
17380 CheckDestructor(Destructor);
17381
17382 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17383 Record: Destructor->getParent());
17384 }
17385
17386 // If any errors have occurred, clear out any temporaries that may have
17387 // been leftover. This ensures that these temporaries won't be picked up
17388 // for deletion in some later function.
17389 if (hasUncompilableErrorOccurred() ||
17390 hasAnyUnrecoverableErrorsInThisFunction() ||
17391 getDiagnostics().getSuppressAllDiagnostics()) {
17392 DiscardCleanupsInEvaluationContext();
17393 }
17394 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17395 // Since the body is valid, issue any analysis-based warnings that are
17396 // enabled.
17397 ActivePolicy = &WP;
17398 }
17399
17400 if (!IsInstantiation && FD &&
17401 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17402 !FD->isInvalidDecl() &&
17403 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17404 FD->setInvalidDecl();
17405
17406 if (FD && FD->hasAttr<NakedAttr>()) {
17407 for (const Stmt *S : Body->children()) {
17408 // Allow local register variables without initializer as they don't
17409 // require prologue.
17410 bool RegisterVariables = false;
17411 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17412 for (const auto *Decl : DS->decls()) {
17413 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17414 RegisterVariables =
17415 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17416 if (!RegisterVariables)
17417 break;
17418 }
17419 }
17420 }
17421 if (RegisterVariables)
17422 continue;
17423 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17424 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17425 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17426 FD->setInvalidDecl();
17427 break;
17428 }
17429 }
17430 }
17431
17432 assert(ExprCleanupObjects.size() ==
17433 ExprEvalContexts.back().NumCleanupObjects &&
17434 "Leftover temporaries in function");
17435 assert(!Cleanup.exprNeedsCleanups() &&
17436 "Unaccounted cleanups in function");
17437 assert(MaybeODRUseExprs.empty() &&
17438 "Leftover expressions for odr-use checking");
17439 }
17440 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17441 // the declaration context below. Otherwise, we're unable to transform
17442 // 'this' expressions when transforming immediate context functions.
17443
17444 if (FD)
17445 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17446
17447 if (!IsInstantiation)
17448 PopDeclContext();
17449
17450 if (!RetainFunctionScopeInfo)
17451 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17452 // If any errors have occurred, clear out any temporaries that may have
17453 // been leftover. This ensures that these temporaries won't be picked up for
17454 // deletion in some later function.
17455 if (hasUncompilableErrorOccurred()) {
17456 DiscardCleanupsInEvaluationContext();
17457 }
17458
17459 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17460 (LangOpts.OpenMP && !LangOpts.OpenMPSimd) ||
17461 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17462 auto ES = getEmissionStatus(Decl: FD);
17463 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17464 ES == Sema::FunctionEmissionStatus::Unknown)
17465 DeclsToCheckForDeferredDiags.insert(X: FD);
17466 }
17467
17468 if (FD && !FD->isDeleted())
17469 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17470
17471 return dcl;
17472}
17473
17474/// When we finish delayed parsing of an attribute, we must attach it to the
17475/// relevant Decl.
17476void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17477 ParsedAttributes &Attrs) {
17478 // Always attach attributes to the underlying decl.
17479 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17480 D = TD->getTemplatedDecl();
17481 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17482 ProcessAPINotes(D);
17483
17484 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17485 if (Method->isStatic())
17486 checkThisInStaticMemberFunctionAttributes(Method);
17487}
17488
17489NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17490 IdentifierInfo &II, Scope *S) {
17491 // It is not valid to implicitly define a function in C23.
17492 assert(LangOpts.implicitFunctionsAllowed() &&
17493 "Implicit function declarations aren't allowed in this language mode");
17494
17495 // Find the scope in which the identifier is injected and the corresponding
17496 // DeclContext.
17497 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17498 // In that case, we inject the declaration into the translation unit scope
17499 // instead.
17500 Scope *BlockScope = S;
17501 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17502 BlockScope = BlockScope->getParent();
17503
17504 // Loop until we find a DeclContext that is either a function/method or the
17505 // translation unit, which are the only two valid places to implicitly define
17506 // a function. This avoids accidentally defining the function within a tag
17507 // declaration, for example.
17508 Scope *ContextScope = BlockScope;
17509 while (!ContextScope->getEntity() ||
17510 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17511 !ContextScope->getEntity()->isTranslationUnit()))
17512 ContextScope = ContextScope->getParent();
17513 ContextRAII SavedContext(*this, ContextScope->getEntity());
17514
17515 // Before we produce a declaration for an implicitly defined
17516 // function, see whether there was a locally-scoped declaration of
17517 // this name as a function or variable. If so, use that
17518 // (non-visible) declaration, and complain about it.
17519 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17520 if (ExternCPrev) {
17521 // We still need to inject the function into the enclosing block scope so
17522 // that later (non-call) uses can see it.
17523 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17524
17525 // C89 footnote 38:
17526 // If in fact it is not defined as having type "function returning int",
17527 // the behavior is undefined.
17528 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17529 !Context.typesAreCompatible(
17530 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17531 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17532 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17533 << ExternCPrev << !getLangOpts().C99;
17534 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17535 return ExternCPrev;
17536 }
17537 }
17538
17539 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17540 unsigned diag_id;
17541 if (II.getName().starts_with(Prefix: "__builtin_"))
17542 diag_id = diag::warn_builtin_unknown;
17543 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17544 else if (getLangOpts().C99)
17545 diag_id = diag::ext_implicit_function_decl_c99;
17546 else
17547 diag_id = diag::warn_implicit_function_decl;
17548
17549 TypoCorrection Corrected;
17550 // Because typo correction is expensive, only do it if the implicit
17551 // function declaration is going to be treated as an error.
17552 //
17553 // Perform the correction before issuing the main diagnostic, as some
17554 // consumers use typo-correction callbacks to enhance the main diagnostic.
17555 if (S && !ExternCPrev &&
17556 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17557 DeclFilterCCC<FunctionDecl> CCC{};
17558 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17559 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17560 }
17561
17562 Diag(Loc, DiagID: diag_id) << &II;
17563 if (Corrected) {
17564 // If the correction is going to suggest an implicitly defined function,
17565 // skip the correction as not being a particularly good idea.
17566 bool Diagnose = true;
17567 if (const auto *D = Corrected.getCorrectionDecl())
17568 Diagnose = !D->isImplicit();
17569 if (Diagnose)
17570 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17571 /*ErrorRecovery*/ false);
17572 }
17573
17574 // If we found a prior declaration of this function, don't bother building
17575 // another one. We've already pushed that one into scope, so there's nothing
17576 // more to do.
17577 if (ExternCPrev)
17578 return ExternCPrev;
17579
17580 // Set a Declarator for the implicit definition: int foo();
17581 const char *Dummy;
17582 AttributeFactory attrFactory;
17583 DeclSpec DS(attrFactory);
17584 unsigned DiagID;
17585 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17586 Policy: Context.getPrintingPolicy());
17587 (void)Error; // Silence warning.
17588 assert(!Error && "Error setting up implicit decl!");
17589 SourceLocation NoLoc;
17590 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17591 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17592 /*IsAmbiguous=*/false,
17593 /*LParenLoc=*/NoLoc,
17594 /*Params=*/nullptr,
17595 /*NumParams=*/0,
17596 /*EllipsisLoc=*/NoLoc,
17597 /*RParenLoc=*/NoLoc,
17598 /*RefQualifierIsLvalueRef=*/true,
17599 /*RefQualifierLoc=*/NoLoc,
17600 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17601 /*ESpecRange=*/SourceRange(),
17602 /*Exceptions=*/nullptr,
17603 /*ExceptionRanges=*/nullptr,
17604 /*NumExceptions=*/0,
17605 /*NoexceptExpr=*/nullptr,
17606 /*ExceptionSpecTokens=*/nullptr,
17607 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17608 TheDeclarator&: D),
17609 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17610 D.SetIdentifier(Id: &II, IdLoc: Loc);
17611
17612 // Insert this function into the enclosing block scope.
17613 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17614 FD->setImplicit();
17615
17616 AddKnownFunctionAttributes(FD);
17617
17618 return FD;
17619}
17620
17621void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17622 FunctionDecl *FD) {
17623 if (FD->isInvalidDecl())
17624 return;
17625
17626 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17627 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17628 return;
17629
17630 UnsignedOrNone AlignmentParam = std::nullopt;
17631 bool IsNothrow = false;
17632 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17633 return;
17634
17635 // C++2a [basic.stc.dynamic.allocation]p4:
17636 // An allocation function that has a non-throwing exception specification
17637 // indicates failure by returning a null pointer value. Any other allocation
17638 // function never returns a null pointer value and indicates failure only by
17639 // throwing an exception [...]
17640 //
17641 // However, -fcheck-new invalidates this possible assumption, so don't add
17642 // NonNull when that is enabled.
17643 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17644 !getLangOpts().CheckNew)
17645 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17646
17647 // C++2a [basic.stc.dynamic.allocation]p2:
17648 // An allocation function attempts to allocate the requested amount of
17649 // storage. [...] If the request succeeds, the value returned by a
17650 // replaceable allocation function is a [...] pointer value p0 different
17651 // from any previously returned value p1 [...]
17652 //
17653 // However, this particular information is being added in codegen,
17654 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17655
17656 // C++2a [basic.stc.dynamic.allocation]p2:
17657 // An allocation function attempts to allocate the requested amount of
17658 // storage. If it is successful, it returns the address of the start of a
17659 // block of storage whose length in bytes is at least as large as the
17660 // requested size.
17661 if (!FD->hasAttr<AllocSizeAttr>()) {
17662 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17663 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17664 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17665 }
17666
17667 // C++2a [basic.stc.dynamic.allocation]p3:
17668 // For an allocation function [...], the pointer returned on a successful
17669 // call shall represent the address of storage that is aligned as follows:
17670 // (3.1) If the allocation function takes an argument of type
17671 // std​::​align_­val_­t, the storage will have the alignment
17672 // specified by the value of this argument.
17673 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17674 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17675 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17676 }
17677
17678 // FIXME:
17679 // C++2a [basic.stc.dynamic.allocation]p3:
17680 // For an allocation function [...], the pointer returned on a successful
17681 // call shall represent the address of storage that is aligned as follows:
17682 // (3.2) Otherwise, if the allocation function is named operator new[],
17683 // the storage is aligned for any object that does not have
17684 // new-extended alignment ([basic.align]) and is no larger than the
17685 // requested size.
17686 // (3.3) Otherwise, the storage is aligned for any object that does not
17687 // have new-extended alignment and is of the requested size.
17688}
17689
17690void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17691 if (FD->isInvalidDecl())
17692 return;
17693
17694 // Both format and format_arg attributes require a function prototype.
17695 const bool HasPrototype = FD->getType()->isFunctionProtoType();
17696
17697 // If this is a built-in function, map its builtin attributes to
17698 // actual attributes.
17699 if (unsigned BuiltinID = FD->getBuiltinID()) {
17700 // Handle printf-formatting attributes.
17701 unsigned FormatIdx;
17702 bool HasVAListArg;
17703 if (HasPrototype &&
17704 Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17705 if (!FD->hasAttr<FormatAttr>() && FormatIdx < FD->getNumParams()) {
17706 const char *fmt = "printf";
17707 if (FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17708 fmt = "NSString";
17709 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17710 Type: &Context.Idents.get(Name: fmt),
17711 FormatIdx: FormatIdx+1,
17712 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17713 Range: FD->getLocation()));
17714 }
17715 }
17716 if (HasPrototype &&
17717 Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17718 if (!FD->hasAttr<FormatAttr>() && FormatIdx < FD->getNumParams())
17719 FD->addAttr(A: FormatAttr::CreateImplicit(
17720 Ctx&: Context, Type: &Context.Idents.get(Name: "scanf"), FormatIdx: FormatIdx + 1,
17721 FirstArg: HasVAListArg ? 0 : FormatIdx + 2, Range: FD->getLocation()));
17722 }
17723
17724 // Handle automatically recognized callbacks.
17725 SmallVector<int, 4> Encoding;
17726 if (!FD->hasAttr<CallbackAttr>() &&
17727 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17728 FD->addAttr(A: CallbackAttr::CreateImplicit(
17729 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17730
17731 // Mark const if we don't care about errno and/or floating point exceptions
17732 // that are the only thing preventing the function from being const. This
17733 // allows IRgen to use LLVM intrinsics for such functions.
17734 bool NoExceptions =
17735 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17736 bool ConstWithoutErrnoAndExceptions =
17737 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17738 bool ConstWithoutExceptions =
17739 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17740 if (!FD->hasAttr<ConstAttr>() &&
17741 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17742 (!ConstWithoutErrnoAndExceptions ||
17743 (!getLangOpts().MathErrno && NoExceptions)) &&
17744 (!ConstWithoutExceptions || NoExceptions))
17745 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17746
17747 // We make "fma" on GNU or Windows const because we know it does not set
17748 // errno in those environments even though it could set errno based on the
17749 // C standard.
17750 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17751 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17752 !FD->hasAttr<ConstAttr>()) {
17753 switch (BuiltinID) {
17754 case Builtin::BI__builtin_fma:
17755 case Builtin::BI__builtin_fmaf:
17756 case Builtin::BI__builtin_fmal:
17757 case Builtin::BIfma:
17758 case Builtin::BIfmaf:
17759 case Builtin::BIfmal:
17760 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17761 break;
17762 default:
17763 break;
17764 }
17765 }
17766
17767 SmallVector<int, 4> Indxs;
17768 Builtin::Info::NonNullMode OptMode;
17769 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17770 !FD->hasAttr<NonNullAttr>()) {
17771 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17772 for (int I : Indxs) {
17773 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17774 QualType T = PVD->getType();
17775 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17776 PVD->setType(T);
17777 }
17778 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17779 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17780 for (int I : Indxs)
17781 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17782 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17783 ArgsSize: ParamIndxs.size()));
17784 }
17785 }
17786 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17787 !FD->hasAttr<ReturnsTwiceAttr>())
17788 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17789 Range: FD->getLocation()));
17790 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17791 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17792 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17793 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17794 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17795 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17796 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17797 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17798 // Add the appropriate attribute, depending on the CUDA compilation mode
17799 // and which target the builtin belongs to. For example, during host
17800 // compilation, aux builtins are __device__, while the rest are __host__.
17801 if (getLangOpts().CUDAIsDevice !=
17802 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17803 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17804 else
17805 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17806 }
17807
17808 // Add known guaranteed alignment for allocation functions.
17809 switch (BuiltinID) {
17810 case Builtin::BImemalign:
17811 case Builtin::BIaligned_alloc:
17812 if (!FD->hasAttr<AllocAlignAttr>())
17813 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17814 Range: FD->getLocation()));
17815 break;
17816 default:
17817 break;
17818 }
17819
17820 // Add allocsize attribute for allocation functions.
17821 switch (BuiltinID) {
17822 case Builtin::BIcalloc:
17823 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17824 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17825 break;
17826 case Builtin::BImemalign:
17827 case Builtin::BIaligned_alloc:
17828 case Builtin::BIrealloc:
17829 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17830 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17831 break;
17832 case Builtin::BImalloc:
17833 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17834 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17835 break;
17836 default:
17837 break;
17838 }
17839 }
17840
17841 LazyProcessLifetimeCaptureByParams(FD);
17842 inferLifetimeBoundAttribute(FD);
17843 inferLifetimeCaptureByAttribute(FD);
17844 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17845
17846 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17847 // throw, add an implicit nothrow attribute to any extern "C" function we come
17848 // across.
17849 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17850 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17851 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17852 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17853 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17854 }
17855
17856 IdentifierInfo *Name = FD->getIdentifier();
17857 if (!Name)
17858 return;
17859 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17860 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17861 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17862 LinkageSpecLanguageIDs::C)) {
17863 // Okay: this could be a libc/libm/Objective-C function we know
17864 // about.
17865 } else
17866 return;
17867
17868 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17869 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17870 // target-specific builtins, perhaps?
17871 if (HasPrototype && FD->getNumParams() >= 2 && !FD->hasAttr<FormatAttr>())
17872 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17873 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17874 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17875 Range: FD->getLocation()));
17876 }
17877
17878 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17879 // We already have a __builtin___CFStringMakeConstantString,
17880 // but builds that use -fno-constant-cfstrings don't go through that.
17881 if (HasPrototype && FD->getNumParams() >= 1 &&
17882 !FD->hasAttr<FormatArgAttr>())
17883 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17884 Range: FD->getLocation()));
17885 }
17886}
17887
17888TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17889 TypeSourceInfo *TInfo) {
17890 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17891 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17892
17893 if (!TInfo) {
17894 assert(D.isInvalidType() && "no declarator info for valid type");
17895 TInfo = Context.getTrivialTypeSourceInfo(T);
17896 }
17897
17898 // Scope manipulation handled by caller.
17899 TypedefDecl *NewTD =
17900 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17901 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17902
17903 // Bail out immediately if we have an invalid declaration.
17904 if (D.isInvalidType()) {
17905 NewTD->setInvalidDecl();
17906 return NewTD;
17907 }
17908
17909 if (D.getDeclSpec().isModulePrivateSpecified()) {
17910 if (CurContext->isFunctionOrMethod())
17911 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17912 << 2 << NewTD
17913 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17914 << FixItHint::CreateRemoval(
17915 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17916 else
17917 NewTD->setModulePrivate();
17918 }
17919
17920 // C++ [dcl.typedef]p8:
17921 // If the typedef declaration defines an unnamed class (or
17922 // enum), the first typedef-name declared by the declaration
17923 // to be that class type (or enum type) is used to denote the
17924 // class type (or enum type) for linkage purposes only.
17925 // We need to check whether the type was declared in the declaration.
17926 switch (D.getDeclSpec().getTypeSpecType()) {
17927 case TST_enum:
17928 case TST_struct:
17929 case TST_interface:
17930 case TST_union:
17931 case TST_class: {
17932 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17933 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17934 break;
17935 }
17936
17937 default:
17938 break;
17939 }
17940
17941 return NewTD;
17942}
17943
17944bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17945 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17946 QualType T = TI->getType();
17947
17948 if (T->isDependentType())
17949 return false;
17950
17951 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17952 // integral type; any cv-qualification is ignored.
17953 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17954 // non-atomic version of the type specified by the type specifiers in the
17955 // specifier qualifier list.
17956 // Because of how odd C's rule is, we'll let the user know that operations
17957 // involving the enumeration type will be non-atomic.
17958 if (T->isAtomicType())
17959 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17960
17961 Qualifiers Q = T.getQualifiers();
17962 std::optional<unsigned> QualSelect;
17963 if (Q.hasConst() && Q.hasVolatile())
17964 QualSelect = diag::CVQualList::Both;
17965 else if (Q.hasConst())
17966 QualSelect = diag::CVQualList::Const;
17967 else if (Q.hasVolatile())
17968 QualSelect = diag::CVQualList::Volatile;
17969
17970 if (QualSelect)
17971 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17972
17973 T = T.getAtomicUnqualifiedType();
17974
17975 // This doesn't use 'isIntegralType' despite the error message mentioning
17976 // integral type because isIntegralType would also allow enum types in C.
17977 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17978 if (BT->isInteger())
17979 return false;
17980
17981 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17982 << T << T->isBitIntType();
17983}
17984
17985bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17986 QualType EnumUnderlyingTy, bool IsFixed,
17987 const EnumDecl *Prev) {
17988 if (IsScoped != Prev->isScoped()) {
17989 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17990 << Prev->isScoped();
17991 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17992 return true;
17993 }
17994
17995 if (IsFixed && Prev->isFixed()) {
17996 if (!EnumUnderlyingTy->isDependentType() &&
17997 !Prev->getIntegerType()->isDependentType() &&
17998 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17999 T2: Prev->getIntegerType())) {
18000 // TODO: Highlight the underlying type of the redeclaration.
18001 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
18002 << EnumUnderlyingTy << Prev->getIntegerType();
18003 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
18004 << Prev->getIntegerTypeRange();
18005 return true;
18006 }
18007 } else if (IsFixed != Prev->isFixed()) {
18008 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
18009 << Prev->isFixed();
18010 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
18011 return true;
18012 }
18013
18014 return false;
18015}
18016
18017/// Get diagnostic %select index for tag kind for
18018/// redeclaration diagnostic message.
18019/// WARNING: Indexes apply to particular diagnostics only!
18020///
18021/// \returns diagnostic %select index.
18022static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
18023 switch (Tag) {
18024 case TagTypeKind::Struct:
18025 return 0;
18026 case TagTypeKind::Interface:
18027 return 1;
18028 case TagTypeKind::Class:
18029 return 2;
18030 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
18031 }
18032}
18033
18034/// Determine if tag kind is a class-key compatible with
18035/// class for redeclaration (class, struct, or __interface).
18036///
18037/// \returns true iff the tag kind is compatible.
18038static bool isClassCompatTagKind(TagTypeKind Tag)
18039{
18040 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
18041 Tag == TagTypeKind::Interface;
18042}
18043
18044NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
18045 if (isa<TypedefDecl>(Val: PrevDecl))
18046 return NonTagKind::Typedef;
18047 else if (isa<TypeAliasDecl>(Val: PrevDecl))
18048 return NonTagKind::TypeAlias;
18049 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
18050 return NonTagKind::Template;
18051 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
18052 return NonTagKind::TypeAliasTemplate;
18053 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
18054 return NonTagKind::TemplateTemplateArgument;
18055 switch (TTK) {
18056 case TagTypeKind::Struct:
18057 case TagTypeKind::Interface:
18058 case TagTypeKind::Class:
18059 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
18060 : NonTagKind::NonStruct;
18061 case TagTypeKind::Union:
18062 return NonTagKind::NonUnion;
18063 case TagTypeKind::Enum:
18064 return NonTagKind::NonEnum;
18065 }
18066 llvm_unreachable("invalid TTK");
18067}
18068
18069bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
18070 TagTypeKind NewTag, bool isDefinition,
18071 SourceLocation NewTagLoc,
18072 const IdentifierInfo *Name) {
18073 // C++ [dcl.type.elab]p3:
18074 // The class-key or enum keyword present in the
18075 // elaborated-type-specifier shall agree in kind with the
18076 // declaration to which the name in the elaborated-type-specifier
18077 // refers. This rule also applies to the form of
18078 // elaborated-type-specifier that declares a class-name or
18079 // friend class since it can be construed as referring to the
18080 // definition of the class. Thus, in any
18081 // elaborated-type-specifier, the enum keyword shall be used to
18082 // refer to an enumeration (7.2), the union class-key shall be
18083 // used to refer to a union (clause 9), and either the class or
18084 // struct class-key shall be used to refer to a class (clause 9)
18085 // declared using the class or struct class-key.
18086 TagTypeKind OldTag = Previous->getTagKind();
18087 if (OldTag != NewTag &&
18088 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
18089 return false;
18090
18091 // Tags are compatible, but we might still want to warn on mismatched tags.
18092 // Non-class tags can't be mismatched at this point.
18093 if (!isClassCompatTagKind(Tag: NewTag))
18094 return true;
18095
18096 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18097 // by our warning analysis. We don't want to warn about mismatches with (eg)
18098 // declarations in system headers that are designed to be specialized, but if
18099 // a user asks us to warn, we should warn if their code contains mismatched
18100 // declarations.
18101 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18102 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
18103 Loc);
18104 };
18105 if (IsIgnoredLoc(NewTagLoc))
18106 return true;
18107
18108 auto IsIgnored = [&](const TagDecl *Tag) {
18109 return IsIgnoredLoc(Tag->getLocation());
18110 };
18111 while (IsIgnored(Previous)) {
18112 Previous = Previous->getPreviousDecl();
18113 if (!Previous)
18114 return true;
18115 OldTag = Previous->getTagKind();
18116 }
18117
18118 bool isTemplate = false;
18119 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
18120 isTemplate = Record->getDescribedClassTemplate();
18121
18122 if (inTemplateInstantiation()) {
18123 if (OldTag != NewTag) {
18124 // In a template instantiation, do not offer fix-its for tag mismatches
18125 // since they usually mess up the template instead of fixing the problem.
18126 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18127 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18128 << getRedeclDiagFromTagKind(Tag: OldTag);
18129 // FIXME: Note previous location?
18130 }
18131 return true;
18132 }
18133
18134 if (isDefinition) {
18135 // On definitions, check all previous tags and issue a fix-it for each
18136 // one that doesn't match the current tag.
18137 if (Previous->getDefinition()) {
18138 // Don't suggest fix-its for redefinitions.
18139 return true;
18140 }
18141
18142 bool previousMismatch = false;
18143 for (const TagDecl *I : Previous->redecls()) {
18144 if (I->getTagKind() != NewTag) {
18145 // Ignore previous declarations for which the warning was disabled.
18146 if (IsIgnored(I))
18147 continue;
18148
18149 if (!previousMismatch) {
18150 previousMismatch = true;
18151 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
18152 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18153 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
18154 }
18155 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
18156 << getRedeclDiagFromTagKind(Tag: NewTag)
18157 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
18158 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
18159 }
18160 }
18161 return true;
18162 }
18163
18164 // Identify the prevailing tag kind: this is the kind of the definition (if
18165 // there is a non-ignored definition), or otherwise the kind of the prior
18166 // (non-ignored) declaration.
18167 const TagDecl *PrevDef = Previous->getDefinition();
18168 if (PrevDef && IsIgnored(PrevDef))
18169 PrevDef = nullptr;
18170 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18171 if (Redecl->getTagKind() != NewTag) {
18172 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18173 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18174 << getRedeclDiagFromTagKind(Tag: OldTag);
18175 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
18176
18177 // If there is a previous definition, suggest a fix-it.
18178 if (PrevDef) {
18179 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
18180 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
18181 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
18182 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
18183 }
18184 }
18185
18186 return true;
18187}
18188
18189/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18190/// from an outer enclosing namespace or file scope inside a friend declaration.
18191/// This should provide the commented out code in the following snippet:
18192/// namespace N {
18193/// struct X;
18194/// namespace M {
18195/// struct Y { friend struct /*N::*/ X; };
18196/// }
18197/// }
18198static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
18199 SourceLocation NameLoc) {
18200 // While the decl is in a namespace, do repeated lookup of that name and see
18201 // if we get the same namespace back. If we do not, continue until
18202 // translation unit scope, at which point we have a fully qualified NNS.
18203 SmallVector<IdentifierInfo *, 4> Namespaces;
18204 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18205 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18206 // This tag should be declared in a namespace, which can only be enclosed by
18207 // other namespaces. Bail if there's an anonymous namespace in the chain.
18208 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
18209 if (!Namespace || Namespace->isAnonymousNamespace())
18210 return FixItHint();
18211 IdentifierInfo *II = Namespace->getIdentifier();
18212 Namespaces.push_back(Elt: II);
18213 NamedDecl *Lookup = SemaRef.LookupSingleName(
18214 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
18215 if (Lookup == Namespace)
18216 break;
18217 }
18218
18219 // Once we have all the namespaces, reverse them to go outermost first, and
18220 // build an NNS.
18221 SmallString<64> Insertion;
18222 llvm::raw_svector_ostream OS(Insertion);
18223 if (DC->isTranslationUnit())
18224 OS << "::";
18225 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
18226 for (auto *II : Namespaces)
18227 OS << II->getName() << "::";
18228 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
18229}
18230
18231/// Determine whether a tag originally declared in context \p OldDC can
18232/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18233/// found a declaration in \p OldDC as a previous decl, perhaps through a
18234/// using-declaration).
18235static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
18236 DeclContext *NewDC) {
18237 OldDC = OldDC->getRedeclContext();
18238 NewDC = NewDC->getRedeclContext();
18239
18240 if (OldDC->Equals(DC: NewDC))
18241 return true;
18242
18243 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18244 // encloses the other).
18245 if (S.getLangOpts().MSVCCompat &&
18246 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
18247 return true;
18248
18249 return false;
18250}
18251
18252DeclResult
18253Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18254 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18255 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18256 SourceLocation ModulePrivateLoc,
18257 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18258 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18259 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18260 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18261 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18262 // If this is not a definition, it must have a name.
18263 IdentifierInfo *OrigName = Name;
18264 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18265 "Nameless record must be a definition!");
18266 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18267
18268 OwnedDecl = false;
18269 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18270 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18271
18272 // FIXME: Check member specializations more carefully.
18273 bool isMemberSpecialization = false;
18274 bool IsInjectedClassName = false;
18275 bool Invalid = false;
18276
18277 // We only need to do this matching if we have template parameters
18278 // or a scope specifier, which also conveniently avoids this work
18279 // for non-C++ cases.
18280 if (TemplateParameterLists.size() > 0 ||
18281 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18282 TemplateParameterList *TemplateParams =
18283 MatchTemplateParametersToScopeSpecifier(
18284 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
18285 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
18286
18287 // C++23 [dcl.type.elab] p2:
18288 // If an elaborated-type-specifier is the sole constituent of a
18289 // declaration, the declaration is ill-formed unless it is an explicit
18290 // specialization, an explicit instantiation or it has one of the
18291 // following forms: [...]
18292 // C++23 [dcl.enum] p1:
18293 // If the enum-head-name of an opaque-enum-declaration contains a
18294 // nested-name-specifier, the declaration shall be an explicit
18295 // specialization.
18296 //
18297 // FIXME: Class template partial specializations can be forward declared
18298 // per CWG2213, but the resolution failed to allow qualified forward
18299 // declarations. This is almost certainly unintentional, so we allow them.
18300 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18301 !isMemberSpecialization)
18302 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18303 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18304
18305 if (TemplateParams) {
18306 if (Kind == TagTypeKind::Enum) {
18307 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18308 return true;
18309 }
18310
18311 if (TemplateParams->size() > 0) {
18312 // This is a declaration or definition of a class template (which may
18313 // be a member of another template).
18314
18315 if (Invalid)
18316 return true;
18317
18318 OwnedDecl = false;
18319 DeclResult Result = CheckClassTemplate(
18320 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18321 AS, ModulePrivateLoc,
18322 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18323 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18324 return Result.get();
18325 } else {
18326 // The "template<>" header is extraneous.
18327 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18328 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18329 isMemberSpecialization = true;
18330 }
18331 }
18332
18333 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18334 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18335 return true;
18336 }
18337
18338 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18339 // C++23 [dcl.type.elab]p4:
18340 // If an elaborated-type-specifier appears with the friend specifier as
18341 // an entire member-declaration, the member-declaration shall have one
18342 // of the following forms:
18343 // friend class-key nested-name-specifier(opt) identifier ;
18344 // friend class-key simple-template-id ;
18345 // friend class-key nested-name-specifier template(opt)
18346 // simple-template-id ;
18347 //
18348 // Since enum is not a class-key, so declarations like "friend enum E;"
18349 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18350 // invalid, most implementations accept so we issue a pedantic warning.
18351 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18352 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18353 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18354 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18355 << (ScopedEnum + ScopedEnumUsesClassTag);
18356 }
18357
18358 // Figure out the underlying type if this a enum declaration. We need to do
18359 // this early, because it's needed to detect if this is an incompatible
18360 // redeclaration.
18361 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18362 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18363
18364 if (Kind == TagTypeKind::Enum) {
18365 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18366 Invalid) {
18367 // No underlying type explicitly specified, or we failed to parse the
18368 // type, default to int.
18369 EnumUnderlying = Context.IntTy.getTypePtr();
18370 } else if (UnderlyingType.get()) {
18371 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18372 // integral type; any cv-qualification is ignored.
18373 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18374 // unqualified, non-atomic version of the type specified by the type
18375 // specifiers in the specifier qualifier list.
18376 TypeSourceInfo *TI = nullptr;
18377 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18378 EnumUnderlying = TI;
18379
18380 if (CheckEnumUnderlyingType(TI))
18381 // Recover by falling back to int.
18382 EnumUnderlying = Context.IntTy.getTypePtr();
18383
18384 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18385 UPPC: UPPC_FixedUnderlyingType))
18386 EnumUnderlying = Context.IntTy.getTypePtr();
18387
18388 // If the underlying type is atomic, we need to adjust the type before
18389 // continuing. This only happens in the case we stored a TypeSourceInfo
18390 // into EnumUnderlying because the other cases are error recovery up to
18391 // this point. But because it's not possible to gin up a TypeSourceInfo
18392 // for a non-atomic type from an atomic one, we'll store into the Type
18393 // field instead. FIXME: it would be nice to have an easy way to get a
18394 // derived TypeSourceInfo which strips qualifiers including the weird
18395 // ones like _Atomic where it forms a different type.
18396 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18397 TI && TI->getType()->isAtomicType())
18398 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18399
18400 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18401 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18402 // of 'int'. However, if this is an unfixed forward declaration, don't set
18403 // the underlying type unless the user enables -fms-compatibility. This
18404 // makes unfixed forward declared enums incomplete and is more conforming.
18405 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18406 EnumUnderlying = Context.IntTy.getTypePtr();
18407 }
18408 }
18409
18410 DeclContext *SearchDC = CurContext;
18411 DeclContext *DC = CurContext;
18412 bool isStdBadAlloc = false;
18413 bool isStdAlignValT = false;
18414
18415 RedeclarationKind Redecl = forRedeclarationInCurContext();
18416 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18417 Redecl = RedeclarationKind::NotForRedeclaration;
18418
18419 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18420 /// implemented asks for structural equivalence checking, the returned decl
18421 /// here is passed back to the parser, allowing the tag body to be parsed.
18422 auto createTagFromNewDecl = [&]() -> TagDecl * {
18423 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18424 // If there is an identifier, use the location of the identifier as the
18425 // location of the decl, otherwise use the location of the struct/union
18426 // keyword.
18427 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18428 TagDecl *New = nullptr;
18429
18430 if (Kind == TagTypeKind::Enum) {
18431 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18432 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18433 // If this is an undefined enum, bail.
18434 if (TUK != TagUseKind::Definition && !Invalid)
18435 return nullptr;
18436 if (EnumUnderlying) {
18437 EnumDecl *ED = cast<EnumDecl>(Val: New);
18438 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18439 ED->setIntegerTypeSourceInfo(TI);
18440 else
18441 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18442 QualType EnumTy = ED->getIntegerType();
18443 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18444 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18445 : EnumTy);
18446 }
18447 } else { // struct/union
18448 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18449 PrevDecl: nullptr);
18450 }
18451
18452 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18453 // Add alignment attributes if necessary; these attributes are checked
18454 // when the ASTContext lays out the structure.
18455 //
18456 // It is important for implementing the correct semantics that this
18457 // happen here (in ActOnTag). The #pragma pack stack is
18458 // maintained as a result of parser callbacks which can occur at
18459 // many points during the parsing of a struct declaration (because
18460 // the #pragma tokens are effectively skipped over during the
18461 // parsing of the struct).
18462 if (TUK == TagUseKind::Definition &&
18463 (!SkipBody || !SkipBody->ShouldSkip)) {
18464 if (LangOpts.HLSL)
18465 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18466 AddAlignmentAttributesForRecord(RD);
18467 AddMsStructLayoutForRecord(RD);
18468 }
18469 }
18470 New->setLexicalDeclContext(CurContext);
18471 return New;
18472 };
18473
18474 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18475 if (Name && SS.isNotEmpty()) {
18476 // We have a nested-name tag ('struct foo::bar').
18477
18478 // Check for invalid 'foo::'.
18479 if (SS.isInvalid()) {
18480 Name = nullptr;
18481 goto CreateNewDecl;
18482 }
18483
18484 // If this is a friend or a reference to a class in a dependent
18485 // context, don't try to make a decl for it.
18486 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18487 DC = computeDeclContext(SS, EnteringContext: false);
18488 if (!DC) {
18489 IsDependent = true;
18490 return true;
18491 }
18492 } else {
18493 DC = computeDeclContext(SS, EnteringContext: true);
18494 if (!DC) {
18495 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18496 << SS.getRange();
18497 return true;
18498 }
18499 }
18500
18501 if (RequireCompleteDeclContext(SS, DC))
18502 return true;
18503
18504 SearchDC = DC;
18505 // Look-up name inside 'foo::'.
18506 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18507
18508 if (Previous.isAmbiguous())
18509 return true;
18510
18511 if (Previous.empty()) {
18512 // Name lookup did not find anything. However, if the
18513 // nested-name-specifier refers to the current instantiation,
18514 // and that current instantiation has any dependent base
18515 // classes, we might find something at instantiation time: treat
18516 // this as a dependent elaborated-type-specifier.
18517 // But this only makes any sense for reference-like lookups.
18518 if (Previous.wasNotFoundInCurrentInstantiation() &&
18519 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18520 IsDependent = true;
18521 return true;
18522 }
18523
18524 // A tag 'foo::bar' must already exist.
18525 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18526 << Kind << Name << DC << SS.getRange();
18527 Name = nullptr;
18528 Invalid = true;
18529 goto CreateNewDecl;
18530 }
18531 } else if (Name) {
18532 // C++14 [class.mem]p14:
18533 // If T is the name of a class, then each of the following shall have a
18534 // name different from T:
18535 // -- every member of class T that is itself a type
18536 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18537 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18538 return true;
18539
18540 // If this is a named struct, check to see if there was a previous forward
18541 // declaration or definition.
18542 // FIXME: We're looking into outer scopes here, even when we
18543 // shouldn't be. Doing so can result in ambiguities that we
18544 // shouldn't be diagnosing.
18545 LookupName(R&: Previous, S);
18546
18547 // When declaring or defining a tag, ignore ambiguities introduced
18548 // by types using'ed into this scope.
18549 if (Previous.isAmbiguous() &&
18550 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18551 LookupResult::Filter F = Previous.makeFilter();
18552 while (F.hasNext()) {
18553 NamedDecl *ND = F.next();
18554 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18555 DC: SearchDC->getRedeclContext()))
18556 F.erase();
18557 }
18558 F.done();
18559 }
18560
18561 // C++11 [namespace.memdef]p3:
18562 // If the name in a friend declaration is neither qualified nor
18563 // a template-id and the declaration is a function or an
18564 // elaborated-type-specifier, the lookup to determine whether
18565 // the entity has been previously declared shall not consider
18566 // any scopes outside the innermost enclosing namespace.
18567 //
18568 // MSVC doesn't implement the above rule for types, so a friend tag
18569 // declaration may be a redeclaration of a type declared in an enclosing
18570 // scope. They do implement this rule for friend functions.
18571 //
18572 // Does it matter that this should be by scope instead of by
18573 // semantic context?
18574 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18575 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18576 LookupResult::Filter F = Previous.makeFilter();
18577 bool FriendSawTagOutsideEnclosingNamespace = false;
18578 while (F.hasNext()) {
18579 NamedDecl *ND = F.next();
18580 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18581 if (DC->isFileContext() &&
18582 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18583 if (getLangOpts().MSVCCompat)
18584 FriendSawTagOutsideEnclosingNamespace = true;
18585 else
18586 F.erase();
18587 }
18588 }
18589 F.done();
18590
18591 // Diagnose this MSVC extension in the easy case where lookup would have
18592 // unambiguously found something outside the enclosing namespace.
18593 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18594 NamedDecl *ND = Previous.getFoundDecl();
18595 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18596 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18597 }
18598 }
18599
18600 // Note: there used to be some attempt at recovery here.
18601 if (Previous.isAmbiguous())
18602 return true;
18603
18604 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18605 // FIXME: This makes sure that we ignore the contexts associated
18606 // with C structs, unions, and enums when looking for a matching
18607 // tag declaration or definition. See the similar lookup tweak
18608 // in Sema::LookupName; is there a better way to deal with this?
18609 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18610 SearchDC = SearchDC->getParent();
18611 } else if (getLangOpts().CPlusPlus) {
18612 // Inside ObjCContainer want to keep it as a lexical decl context but go
18613 // past it (most often to TranslationUnit) to find the semantic decl
18614 // context.
18615 while (isa<ObjCContainerDecl>(Val: SearchDC))
18616 SearchDC = SearchDC->getParent();
18617 }
18618 } else if (getLangOpts().CPlusPlus) {
18619 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18620 // TagDecl the same way as we skip it for named TagDecl.
18621 while (isa<ObjCContainerDecl>(Val: SearchDC))
18622 SearchDC = SearchDC->getParent();
18623 }
18624
18625 if (Previous.isSingleResult() &&
18626 Previous.getFoundDecl()->isTemplateParameter()) {
18627 // Maybe we will complain about the shadowed template parameter.
18628 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18629 // Just pretend that we didn't see the previous declaration.
18630 Previous.clear();
18631 }
18632
18633 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18634 DC->getRedeclContext()->Equals(DC: getStdNamespace())) {
18635 if (Name->isStr(Str: "bad_alloc")) {
18636 // This is a declaration of or a reference to "std::bad_alloc".
18637 isStdBadAlloc = true;
18638
18639 // If std::bad_alloc has been implicitly declared (but made invisible to
18640 // name lookup), fill in this implicit declaration as the previous
18641 // declaration, so that the declarations get chained appropriately.
18642 if (Previous.empty() && StdBadAlloc)
18643 Previous.addDecl(D: getStdBadAlloc());
18644 } else if (Name->isStr(Str: "align_val_t")) {
18645 isStdAlignValT = true;
18646 if (Previous.empty() && StdAlignValT)
18647 Previous.addDecl(D: getStdAlignValT());
18648 }
18649 }
18650
18651 // If we didn't find a previous declaration, and this is a reference
18652 // (or friend reference), move to the correct scope. In C++, we
18653 // also need to do a redeclaration lookup there, just in case
18654 // there's a shadow friend decl.
18655 if (Name && Previous.empty() &&
18656 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18657 IsTemplateParamOrArg)) {
18658 if (Invalid) goto CreateNewDecl;
18659 assert(SS.isEmpty());
18660
18661 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18662 // C++ [basic.scope.pdecl]p5:
18663 // -- for an elaborated-type-specifier of the form
18664 //
18665 // class-key identifier
18666 //
18667 // if the elaborated-type-specifier is used in the
18668 // decl-specifier-seq or parameter-declaration-clause of a
18669 // function defined in namespace scope, the identifier is
18670 // declared as a class-name in the namespace that contains
18671 // the declaration; otherwise, except as a friend
18672 // declaration, the identifier is declared in the smallest
18673 // non-class, non-function-prototype scope that contains the
18674 // declaration.
18675 //
18676 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18677 // C structs and unions.
18678 //
18679 // It is an error in C++ to declare (rather than define) an enum
18680 // type, including via an elaborated type specifier. We'll
18681 // diagnose that later; for now, declare the enum in the same
18682 // scope as we would have picked for any other tag type.
18683 //
18684 // GNU C also supports this behavior as part of its incomplete
18685 // enum types extension, while GNU C++ does not.
18686 //
18687 // Find the context where we'll be declaring the tag.
18688 // FIXME: We would like to maintain the current DeclContext as the
18689 // lexical context,
18690 SearchDC = getTagInjectionContext(DC: SearchDC);
18691
18692 // Find the scope where we'll be declaring the tag.
18693 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18694 } else {
18695 assert(TUK == TagUseKind::Friend);
18696 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18697
18698 // C++ [namespace.memdef]p3:
18699 // If a friend declaration in a non-local class first declares a
18700 // class or function, the friend class or function is a member of
18701 // the innermost enclosing namespace.
18702 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18703 : SearchDC->getEnclosingNamespaceContext();
18704 }
18705
18706 // In C++, we need to do a redeclaration lookup to properly
18707 // diagnose some problems.
18708 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18709 // hidden declaration so that we don't get ambiguity errors when using a
18710 // type declared by an elaborated-type-specifier. In C that is not correct
18711 // and we should instead merge compatible types found by lookup.
18712 if (getLangOpts().CPlusPlus) {
18713 // FIXME: This can perform qualified lookups into function contexts,
18714 // which are meaningless.
18715 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18716 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18717 } else {
18718 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18719 LookupName(R&: Previous, S);
18720 }
18721 }
18722
18723 // If we have a known previous declaration to use, then use it.
18724 if (Previous.empty() && SkipBody && SkipBody->Previous)
18725 Previous.addDecl(D: SkipBody->Previous);
18726
18727 if (!Previous.empty()) {
18728 NamedDecl *PrevDecl = Previous.getFoundDecl();
18729 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18730
18731 // It's okay to have a tag decl in the same scope as a typedef
18732 // which hides a tag decl in the same scope. Finding this
18733 // with a redeclaration lookup can only actually happen in C++.
18734 //
18735 // This is also okay for elaborated-type-specifiers, which is
18736 // technically forbidden by the current standard but which is
18737 // okay according to the likely resolution of an open issue;
18738 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18739 if (getLangOpts().CPlusPlus) {
18740 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18741 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18742 if (Tag->getDeclName() == Name &&
18743 Tag->getDeclContext()->getRedeclContext()
18744 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18745 PrevDecl = Tag;
18746 Previous.clear();
18747 Previous.addDecl(D: Tag);
18748 Previous.resolveKind();
18749 }
18750 }
18751 }
18752 }
18753
18754 // If this is a redeclaration of a using shadow declaration, it must
18755 // declare a tag in the same context. In MSVC mode, we allow a
18756 // redefinition if either context is within the other.
18757 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18758 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18759 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18760 TUK != TagUseKind::Friend &&
18761 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18762 !(OldTag && isAcceptableTagRedeclContext(
18763 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18764 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18765 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18766 DiagID: diag::note_using_decl_target);
18767 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18768 << 0;
18769 // Recover by ignoring the old declaration.
18770 Previous.clear();
18771 goto CreateNewDecl;
18772 }
18773 }
18774
18775 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18776 // If this is a use of a previous tag, or if the tag is already declared
18777 // in the same scope (so that the definition/declaration completes or
18778 // rementions the tag), reuse the decl.
18779 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18780 isTagRedeclarationInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18781 AllowInlineNamespace: SS.isNotEmpty() ||
18782 isMemberSpecialization)) {
18783
18784 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18785 RD && RD->isInjectedClassName()) {
18786 // If lookup found the injected class name, the previous declaration
18787 // is the class being injected into.
18788 Previous.clear();
18789 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(Val: RD->getDeclContext());
18790 Previous.addDecl(D: PrevDecl);
18791 Previous.resolveKind();
18792 IsInjectedClassName = true;
18793 }
18794
18795 // Make sure that this wasn't declared as an enum and now used as a
18796 // struct or something similar.
18797 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18798 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18799 Name)) {
18800 bool SafeToContinue =
18801 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18802 Kind != TagTypeKind::Enum);
18803 if (SafeToContinue)
18804 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18805 << Name
18806 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18807 Code: PrevTagDecl->getKindName());
18808 else
18809 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18810 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18811
18812 if (SafeToContinue)
18813 Kind = PrevTagDecl->getTagKind();
18814 else {
18815 // Recover by making this an anonymous redefinition.
18816 Name = nullptr;
18817 Previous.clear();
18818 Invalid = true;
18819 }
18820 }
18821
18822 if (Kind == TagTypeKind::Enum &&
18823 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18824 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18825 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18826 return PrevTagDecl;
18827
18828 QualType EnumUnderlyingTy;
18829 if (TypeSourceInfo *TI =
18830 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18831 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18832 else if (const Type *T =
18833 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18834 EnumUnderlyingTy = QualType(T, 0);
18835
18836 // All conflicts with previous declarations are recovered by
18837 // returning the previous declaration, unless this is a definition,
18838 // in which case we want the caller to bail out.
18839 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18840 IsScoped: ScopedEnum, EnumUnderlyingTy,
18841 IsFixed, Prev: PrevEnum))
18842 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18843 }
18844
18845 // C++11 [class.mem]p1:
18846 // A member shall not be declared twice in the member-specification,
18847 // except that a nested class or member class template can be declared
18848 // and then later defined.
18849 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18850 S->isDeclScope(D: PrevDecl)) {
18851 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18852 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18853 }
18854
18855 // C++ [class.local]p3:
18856 // A class nested within a local class is a local class. A member of
18857 // a local class X shall be declared only in the definition of X or,
18858 // if the member is a nested class, in the nearest enclosing block
18859 // scope of X.
18860 if (TUK == TagUseKind::Definition && SS.isValid()) {
18861 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18862 while (const auto *ParentClass =
18863 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18864 OutermostClass = ParentClass;
18865
18866 if (OutermostClass->isLocalClass() &&
18867 !S->isDeclScope(D: OutermostClass)) {
18868 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18869 << Name << OutermostClass;
18870 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18871 << OutermostClass;
18872 }
18873 }
18874 }
18875
18876 if (!Invalid) {
18877 // If this is a use, just return the declaration we found, unless
18878 // we have attributes.
18879 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18880 if (!Attrs.empty()) {
18881 // FIXME: Diagnose these attributes. For now, we create a new
18882 // declaration to hold them.
18883 } else if (TUK == TagUseKind::Reference &&
18884 (PrevTagDecl->getFriendObjectKind() ==
18885 Decl::FOK_Undeclared ||
18886 PrevDecl->getOwningModule() != getCurrentModule()) &&
18887 SS.isEmpty()) {
18888 // This declaration is a reference to an existing entity, but
18889 // has different visibility from that entity: it either makes
18890 // a friend visible or it makes a type visible in a new module.
18891 // In either case, create a new declaration. We only do this if
18892 // the declaration would have meant the same thing if no prior
18893 // declaration were found, that is, if it was found in the same
18894 // scope where we would have injected a declaration.
18895 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18896 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18897 return PrevTagDecl;
18898 // This is in the injected scope, create a new declaration in
18899 // that scope.
18900 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18901 } else {
18902 return PrevTagDecl;
18903 }
18904 }
18905
18906 // Diagnose attempts to redefine a tag.
18907 if (TUK == TagUseKind::Definition) {
18908 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18909 // If the type is currently being defined, complain
18910 // about a nested redefinition.
18911 if (Def->isBeingDefined()) {
18912 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18913 Diag(Loc: PrevTagDecl->getLocation(),
18914 DiagID: diag::note_previous_definition);
18915 Name = nullptr;
18916 Previous.clear();
18917 Invalid = true;
18918 } else {
18919 // If we're defining a specialization and the previous
18920 // definition is from an implicit instantiation, don't emit an
18921 // error here; we'll catch this in the general case below.
18922 bool IsExplicitSpecializationAfterInstantiation = false;
18923 if (isMemberSpecialization) {
18924 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18925 IsExplicitSpecializationAfterInstantiation =
18926 RD->getTemplateSpecializationKind() !=
18927 TSK_ExplicitSpecialization;
18928 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18929 IsExplicitSpecializationAfterInstantiation =
18930 ED->getTemplateSpecializationKind() !=
18931 TSK_ExplicitSpecialization;
18932 }
18933
18934 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18935 // do not keep more that one definition around (merge them).
18936 // However, ensure the decl passes the structural compatibility
18937 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18938 NamedDecl *Hidden = nullptr;
18939 bool HiddenDefVisible = false;
18940 if (SkipBody && (isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: NameLoc, Suggested: &Hidden,
18941 Visible&: HiddenDefVisible) ||
18942 getLangOpts().C23)) {
18943 // There is a definition of this tag, but it is not visible.
18944 // We explicitly make use of C++'s one definition rule here,
18945 // and assume that this definition is identical to the hidden
18946 // one we already have. Make the existing definition visible
18947 // and use it in place of this one.
18948 if (!getLangOpts().CPlusPlus) {
18949 // Postpone making the old definition visible until after we
18950 // complete parsing the new one and do the structural
18951 // comparison.
18952 SkipBody->CheckSameAsPrevious = true;
18953 SkipBody->New = createTagFromNewDecl();
18954 SkipBody->Previous = Def;
18955
18956 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18957 return Def;
18958 }
18959
18960 SkipBody->ShouldSkip = true;
18961 SkipBody->Previous = Def;
18962 if (!HiddenDefVisible && Hidden)
18963 makeMergedDefinitionVisible(ND: Hidden);
18964 // Carry on and handle it like a normal definition. We'll
18965 // skip starting the definition later.
18966
18967 } else if (!IsExplicitSpecializationAfterInstantiation) {
18968 // A redeclaration in function prototype scope in C isn't
18969 // visible elsewhere, so merely issue a warning.
18970 if (!getLangOpts().CPlusPlus &&
18971 S->containedInPrototypeScope())
18972 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18973 << Name;
18974 else
18975 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18976 notePreviousDefinition(Old: Def,
18977 New: NameLoc.isValid() ? NameLoc : KWLoc);
18978 // If this is a redefinition, recover by making this
18979 // struct be anonymous, which will make any later
18980 // references get the previous definition.
18981 Name = nullptr;
18982 Previous.clear();
18983 Invalid = true;
18984 }
18985 }
18986 }
18987
18988 // Okay, this is definition of a previously declared or referenced
18989 // tag. We're going to create a new Decl for it.
18990 }
18991
18992 // Qualified lookup can find a tag in an inline namespace. Its
18993 // redeclaration belongs to that namespace, which need not be the
18994 // context named by the qualifier.
18995 if (SS.isNotEmpty())
18996 SearchDC = PrevTagDecl->getDeclContext();
18997
18998 // Okay, we're going to make a redeclaration. If this is some kind
18999 // of reference, make sure we build the redeclaration in the same DC
19000 // as the original, and ignore the current access specifier.
19001 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
19002 IsInjectedClassName) {
19003 SearchDC = PrevTagDecl->getDeclContext();
19004 AS = AS_none;
19005 }
19006 }
19007 // If we get here we have (another) forward declaration or we
19008 // have a definition. Just create a new decl.
19009
19010 } else {
19011 // If we get here, this is a definition of a new tag type in a nested
19012 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
19013 // new decl/type. We set PrevDecl to NULL so that the entities
19014 // have distinct types.
19015 Previous.clear();
19016 }
19017 // If we get here, we're going to create a new Decl. If PrevDecl
19018 // is non-NULL, it's a definition of the tag declared by
19019 // PrevDecl. If it's NULL, we have a new definition.
19020
19021 // Otherwise, PrevDecl is not a tag, but was found with tag
19022 // lookup. This is only actually possible in C++, where a few
19023 // things like templates still live in the tag namespace.
19024 } else {
19025 // Use a better diagnostic if an elaborated-type-specifier
19026 // found the wrong kind of type on the first
19027 // (non-redeclaration) lookup.
19028 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
19029 !Previous.isForRedeclaration()) {
19030 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
19031 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
19032 << PrevDecl << NTK << Kind;
19033 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
19034 Invalid = true;
19035
19036 // Otherwise, only diagnose if the declaration is in scope.
19037 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
19038 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
19039 // do nothing
19040
19041 // Diagnose implicit declarations introduced by elaborated types.
19042 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
19043 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
19044 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
19045 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
19046 Invalid = true;
19047
19048 // Otherwise it's a declaration. Call out a particularly common
19049 // case here.
19050 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
19051 unsigned Kind = 0;
19052 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
19053 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
19054 << Name << Kind << TND->getUnderlyingType();
19055 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
19056 Invalid = true;
19057
19058 // Otherwise, diagnose.
19059 } else {
19060 // The tag name clashes with something else in the target scope,
19061 // issue an error and recover by making this tag be anonymous.
19062 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
19063 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
19064 Name = nullptr;
19065 Invalid = true;
19066 }
19067
19068 // The existing declaration isn't relevant to us; we're in a
19069 // new scope, so clear out the previous declaration.
19070 Previous.clear();
19071 }
19072 }
19073
19074CreateNewDecl:
19075
19076 TagDecl *PrevDecl = nullptr;
19077 if (Previous.isSingleResult())
19078 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
19079
19080 // If there is an identifier, use the location of the identifier as the
19081 // location of the decl, otherwise use the location of the struct/union
19082 // keyword.
19083 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
19084
19085 // Otherwise, create a new declaration. If there is a previous
19086 // declaration of the same entity, the two will be linked via
19087 // PrevDecl.
19088 TagDecl *New;
19089
19090 if (Kind == TagTypeKind::Enum) {
19091 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19092 // enum X { A, B, C } D; D should chain to X.
19093 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19094 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
19095 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
19096
19097 EnumDecl *ED = cast<EnumDecl>(Val: New);
19098 ED->setEnumKeyRange(SourceRange(
19099 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19100
19101 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19102 StdAlignValT = cast<EnumDecl>(Val: New);
19103
19104 // If this is an undefined enum, warn.
19105 if (TUK != TagUseKind::Definition && !Invalid) {
19106 TagDecl *Def;
19107 if (IsFixed && ED->isFixed()) {
19108 // C++0x: 7.2p2: opaque-enum-declaration.
19109 // Conflicts are diagnosed above. Do nothing.
19110 } else if (PrevDecl &&
19111 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
19112 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
19113 << New;
19114 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
19115 } else {
19116 unsigned DiagID = diag::ext_forward_ref_enum;
19117 if (getLangOpts().MSVCCompat)
19118 DiagID = diag::ext_ms_forward_ref_enum;
19119 else if (getLangOpts().CPlusPlus)
19120 DiagID = diag::err_forward_ref_enum;
19121 Diag(Loc, DiagID);
19122 }
19123 }
19124
19125 if (EnumUnderlying) {
19126 EnumDecl *ED = cast<EnumDecl>(Val: New);
19127 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
19128 ED->setIntegerTypeSourceInfo(TI);
19129 else
19130 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
19131 QualType EnumTy = ED->getIntegerType();
19132 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
19133 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
19134 : EnumTy);
19135 assert(ED->isComplete() && "enum with type should be complete");
19136 }
19137 } else {
19138 // struct/union/class
19139
19140 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19141 // struct X { int A; } D; D should chain to X.
19142 if (getLangOpts().CPlusPlus) {
19143 // FIXME: Look for a way to use RecordDecl for simple structs.
19144 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19145 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
19146
19147 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19148 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
19149 } else
19150 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19151 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
19152 }
19153
19154 // Only C23 and later allow defining new types in 'offsetof()'.
19155 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19156 !getLangOpts().CPlusPlus && !getLangOpts().C23)
19157 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
19158 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19159
19160 // C++11 [dcl.type]p3:
19161 // A type-specifier-seq shall not define a class or enumeration [...].
19162 if (!Invalid && getLangOpts().CPlusPlus &&
19163 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19164 TUK == TagUseKind::Definition) {
19165 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
19166 << Context.getCanonicalTagType(TD: New);
19167 Invalid = true;
19168 }
19169
19170 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
19171 DC->getDeclKind() == Decl::Enum) {
19172 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
19173 << Context.getCanonicalTagType(TD: New);
19174 Invalid = true;
19175 }
19176
19177 // Maybe add qualifier info.
19178 if (SS.isNotEmpty()) {
19179 if (SS.isSet()) {
19180 // If this is either a declaration or a definition, check the
19181 // nested-name-specifier against the current context.
19182 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19183 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
19184 /*TemplateId=*/nullptr,
19185 IsMemberSpecialization: isMemberSpecialization))
19186 Invalid = true;
19187
19188 New->setQualifierInfo(SS.getWithLocInContext(Context));
19189 if (TemplateParameterLists.size() > 0) {
19190 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
19191 }
19192 }
19193 else
19194 Invalid = true;
19195 }
19196
19197 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
19198 // Add alignment attributes if necessary; these attributes are checked when
19199 // the ASTContext lays out the structure.
19200 //
19201 // It is important for implementing the correct semantics that this
19202 // happen here (in ActOnTag). The #pragma pack stack is
19203 // maintained as a result of parser callbacks which can occur at
19204 // many points during the parsing of a struct declaration (because
19205 // the #pragma tokens are effectively skipped over during the
19206 // parsing of the struct).
19207 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19208 if (LangOpts.HLSL)
19209 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
19210 AddAlignmentAttributesForRecord(RD);
19211 AddMsStructLayoutForRecord(RD);
19212 }
19213
19214 // The __interface tag implies __declspec(novtable) according to MSDN:
19215 // https://learn.microsoft.com/en-us/cpp/cpp/interface?view=msvc-170
19216 // so add the implicit attribute now.
19217 if (Kind == TagTypeKind::Interface)
19218 RD->addAttr(A: MSNoVTableAttr::CreateImplicit(Ctx&: Context));
19219 }
19220
19221 if (ModulePrivateLoc.isValid()) {
19222 if (isMemberSpecialization)
19223 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
19224 << 2
19225 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
19226 // __module_private__ does not apply to local classes. However, we only
19227 // diagnose this as an error when the declaration specifiers are
19228 // freestanding. Here, we just ignore the __module_private__.
19229 else if (!SearchDC->isFunctionOrMethod())
19230 New->setModulePrivate();
19231 }
19232
19233 // If this is a specialization of a member class (of a class template),
19234 // check the specialization.
19235 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
19236 Invalid = true;
19237
19238 // If we're declaring or defining a tag in function prototype scope in C,
19239 // note that this type can only be used within the function and add it to
19240 // the list of decls to inject into the function definition scope. However,
19241 // in C23 and later, while the type is only visible within the function, the
19242 // function can be called with a compatible type defined in the same TU, so
19243 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19244 if ((Name || Kind == TagTypeKind::Enum) &&
19245 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19246 if (getLangOpts().CPlusPlus) {
19247 // C++ [dcl.fct]p6:
19248 // Types shall not be defined in return or parameter types.
19249 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19250 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
19251 << Name;
19252 Invalid = true;
19253 }
19254 if (TUK == TagUseKind::Declaration)
19255 Invalid = true;
19256 } else if (!PrevDecl) {
19257 // In C23 mode, if the declaration is complete, we do not want to
19258 // diagnose.
19259 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19260 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
19261 << Context.getCanonicalTagType(TD: New);
19262 }
19263 }
19264
19265 if (Invalid)
19266 New->setInvalidDecl();
19267
19268 // Set the lexical context. If the tag has a C++ scope specifier, the
19269 // lexical context will be different from the semantic context.
19270 New->setLexicalDeclContext(CurContext);
19271
19272 // Mark this as a friend decl if applicable.
19273 // In Microsoft mode, a friend declaration also acts as a forward
19274 // declaration so we always pass true to setObjectOfFriendDecl to make
19275 // the tag name visible.
19276 if (TUK == TagUseKind::Friend)
19277 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19278
19279 // Set the access specifier.
19280 if (!Invalid && SearchDC->isRecord())
19281 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
19282
19283 // FIXME: An elaborated-type-specifier referring to an existing tag should
19284 // ideally not introduce a redeclaration. ActOnTag currently creates one, so
19285 // avoid diagnosing it as a redeclaration across module boundaries.
19286 //
19287 // See https://github.com/llvm/llvm-project/pull/194546 for full background.
19288 if (PrevDecl && TUK != TagUseKind::Reference)
19289 CheckRedeclarationInModule(New, Old: PrevDecl);
19290
19291 if (TUK == TagUseKind::Definition) {
19292 if (!SkipBody || !SkipBody->ShouldSkip) {
19293 New->startDefinition();
19294 } else {
19295 New->setCompleteDefinition();
19296 New->demoteThisDefinitionToDeclaration();
19297 }
19298 }
19299
19300 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
19301 AddPragmaAttributes(S, D: New);
19302
19303 // If this has an identifier, add it to the scope stack.
19304 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19305 // We might be replacing an existing declaration in the lookup tables;
19306 // if so, borrow its access specifier.
19307 if (PrevDecl)
19308 New->setAccess(PrevDecl->getAccess());
19309
19310 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19311 DC->makeDeclVisibleInContext(D: New);
19312 if (Name) // can be null along some error paths
19313 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19314 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
19315 } else if (Name) {
19316 S = getNonFieldDeclScope(S);
19317 PushOnScopeChains(D: New, S, AddToContext: true);
19318 } else {
19319 CurContext->addDecl(D: New);
19320 }
19321
19322 // If this is the C FILE type, notify the AST context.
19323 if (IdentifierInfo *II = New->getIdentifier())
19324 if (!New->isInvalidDecl() &&
19325 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19326 II->isStr(Str: "FILE"))
19327 Context.setFILEDecl(New);
19328
19329 if (PrevDecl)
19330 mergeDeclAttributes(New, Old: PrevDecl);
19331
19332 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19333 inferGslOwnerPointerAttribute(Record: CXXRD);
19334 inferNullableClassAttribute(CRD: CXXRD);
19335 }
19336
19337 // If there's a #pragma GCC visibility in scope, set the visibility of this
19338 // record.
19339 AddPushedVisibilityAttribute(RD: New);
19340
19341 // If this is not a definition, process API notes for it now.
19342 if (TUK != TagUseKind::Definition)
19343 ProcessAPINotes(D: New);
19344
19345 if (isMemberSpecialization && !New->isInvalidDecl())
19346 CompleteMemberSpecialization(Member: New, Previous);
19347
19348 OwnedDecl = true;
19349 // In C++, don't return an invalid declaration. We can't recover well from
19350 // the cases where we make the type anonymous.
19351 if (Invalid && getLangOpts().CPlusPlus) {
19352 if (New->isBeingDefined())
19353 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19354 RD->completeDefinition();
19355 return true;
19356 } else if (SkipBody && SkipBody->ShouldSkip) {
19357 return SkipBody->Previous;
19358 } else {
19359 return New;
19360 }
19361}
19362
19363void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19364 AdjustDeclIfTemplate(Decl&: TagD);
19365 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19366
19367 // Enter the tag context.
19368 PushDeclContext(S, DC: Tag);
19369
19370 ActOnDocumentableDecl(D: TagD);
19371
19372 // If there's a #pragma GCC visibility in scope, set the visibility of this
19373 // record.
19374 AddPushedVisibilityAttribute(RD: Tag);
19375}
19376
19377bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19378 SkipBodyInfo &SkipBody) {
19379 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19380 return false;
19381
19382 // Make the previous decl visible.
19383 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19384 CleanupMergedEnum(S, New: SkipBody.New);
19385 return true;
19386}
19387
19388void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19389 SourceLocation FinalLoc,
19390 bool IsFinalSpelledSealed,
19391 bool IsAbstract,
19392 SourceLocation LBraceLoc) {
19393 AdjustDeclIfTemplate(Decl&: TagD);
19394 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19395
19396 FieldCollector->StartClass();
19397
19398 if (!Record->getIdentifier())
19399 return;
19400
19401 if (IsAbstract)
19402 Record->markAbstract();
19403
19404 if (FinalLoc.isValid()) {
19405 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19406 S: IsFinalSpelledSealed
19407 ? FinalAttr::Keyword_sealed
19408 : FinalAttr::Keyword_final));
19409 }
19410
19411 // C++ [class]p2:
19412 // [...] The class-name is also inserted into the scope of the
19413 // class itself; this is known as the injected-class-name. For
19414 // purposes of access checking, the injected-class-name is treated
19415 // as if it were a public member name.
19416 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19417 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19418 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19419 InjectedClassName->setImplicit();
19420 InjectedClassName->setAccess(AS_public);
19421 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19422 InjectedClassName->setDescribedClassTemplate(Template);
19423
19424 PushOnScopeChains(D: InjectedClassName, S);
19425 assert(InjectedClassName->isInjectedClassName() &&
19426 "Broken injected-class-name");
19427}
19428
19429void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19430 SourceRange BraceRange) {
19431 AdjustDeclIfTemplate(Decl&: TagD);
19432 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19433 Tag->setBraceRange(BraceRange);
19434
19435 // Make sure we "complete" the definition even it is invalid.
19436 if (Tag->isBeingDefined()) {
19437 assert(Tag->isInvalidDecl() && "We should already have completed it");
19438 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19439 RD->completeDefinition();
19440 }
19441
19442 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19443 FieldCollector->FinishClass();
19444 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19445 auto *Def = RD->getDefinition();
19446 assert(Def && "The record is expected to have a completed definition");
19447 unsigned NumInitMethods = 0;
19448 for (auto *Method : Def->methods()) {
19449 if (!Method->getIdentifier())
19450 continue;
19451 if (Method->getName() == "__init")
19452 NumInitMethods++;
19453 }
19454 if (NumInitMethods > 1 || !Def->hasInitMethod())
19455 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19456 }
19457
19458 // If we're defining a dynamic class in a module interface unit, we always
19459 // need to produce the vtable for it, even if the vtable is not used in the
19460 // current TU.
19461 //
19462 // The case where the current class is not dynamic is handled in
19463 // MarkVTableUsed.
19464 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19465 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19466 }
19467
19468 // Exit this scope of this tag's definition.
19469 PopDeclContext();
19470
19471 if (getCurLexicalContext()->isObjCContainer() &&
19472 Tag->getDeclContext()->isFileContext())
19473 Tag->setTopLevelDeclInObjCContainer();
19474
19475 // Notify the consumer that we've defined a tag.
19476 if (!Tag->isInvalidDecl())
19477 Consumer.HandleTagDeclDefinition(D: Tag);
19478
19479 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19480 // from XLs and instead matches the XL #pragma pack(1) behavior.
19481 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19482 AlignPackStack.hasValue()) {
19483 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19484 // Only diagnose #pragma align(packed).
19485 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19486 return;
19487 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19488 if (!RD)
19489 return;
19490 // Only warn if there is at least 1 bitfield member.
19491 if (llvm::any_of(Range: RD->fields(),
19492 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19493 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19494 }
19495}
19496
19497void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19498 AdjustDeclIfTemplate(Decl&: TagD);
19499 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19500 Tag->setInvalidDecl();
19501
19502 // Make sure we "complete" the definition even it is invalid.
19503 if (Tag->isBeingDefined()) {
19504 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19505 RD->completeDefinition();
19506 }
19507
19508 // We're undoing ActOnTagStartDefinition here, not
19509 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19510 // the FieldCollector.
19511
19512 PopDeclContext();
19513}
19514
19515// Note that FieldName may be null for anonymous bitfields.
19516ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19517 const IdentifierInfo *FieldName,
19518 QualType FieldTy, bool IsMsStruct,
19519 Expr *BitWidth) {
19520 assert(BitWidth);
19521 if (BitWidth->containsErrors())
19522 return ExprError();
19523
19524 // C99 6.7.2.1p4 - verify the field type.
19525 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19526 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19527 // Handle incomplete and sizeless types with a specific error.
19528 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19529 DiagID: diag::err_field_incomplete_or_sizeless))
19530 return ExprError();
19531 if (FieldName)
19532 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19533 << FieldName << FieldTy << BitWidth->getSourceRange();
19534 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19535 << FieldTy << BitWidth->getSourceRange();
19536 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19537 return ExprError();
19538
19539 // If the bit-width is type- or value-dependent, don't try to check
19540 // it now.
19541 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19542 return BitWidth;
19543
19544 llvm::APSInt Value;
19545 ExprResult ICE =
19546 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19547 if (ICE.isInvalid())
19548 return ICE;
19549 BitWidth = ICE.get();
19550
19551 // Zero-width bitfield is ok for anonymous field.
19552 if (Value == 0 && FieldName)
19553 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19554 << FieldName << BitWidth->getSourceRange();
19555
19556 if (Value.isSigned() && Value.isNegative()) {
19557 if (FieldName)
19558 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19559 << FieldName << toString(I: Value, Radix: 10);
19560 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19561 << toString(I: Value, Radix: 10);
19562 }
19563
19564 // The size of the bit-field must not exceed our maximum permitted object
19565 // size.
19566 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19567 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19568 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19569 }
19570
19571 if (!FieldTy->isDependentType()) {
19572 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19573 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19574 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19575
19576 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19577 // ABI.
19578 bool CStdConstraintViolation =
19579 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19580 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19581 if (CStdConstraintViolation || MSBitfieldViolation) {
19582 unsigned DiagWidth =
19583 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19584 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19585 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19586 << !CStdConstraintViolation << DiagWidth;
19587 }
19588
19589 // Warn on types where the user might conceivably expect to get all
19590 // specified bits as value bits: that's all integral types other than
19591 // 'bool'.
19592 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19593 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19594 << FieldName << Value << (unsigned)TypeWidth;
19595 }
19596 }
19597
19598 if (isa<ConstantExpr>(Val: BitWidth))
19599 return BitWidth;
19600 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19601}
19602
19603Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19604 Declarator &D, Expr *BitfieldWidth) {
19605 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19606 D, BitfieldWidth,
19607 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19608 return Res;
19609}
19610
19611FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19612 SourceLocation DeclStart,
19613 Declarator &D, Expr *BitWidth,
19614 InClassInitStyle InitStyle,
19615 AccessSpecifier AS) {
19616 if (D.isDecompositionDeclarator()) {
19617 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19618 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19619 << Decomp.getSourceRange();
19620 return nullptr;
19621 }
19622
19623 const IdentifierInfo *II = D.getIdentifier();
19624 SourceLocation Loc = DeclStart;
19625 if (II) Loc = D.getIdentifierLoc();
19626
19627 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19628 QualType T = TInfo->getType();
19629 if (getLangOpts().CPlusPlus) {
19630 CheckExtraCXXDefaultArguments(D);
19631
19632 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19633 UPPC: UPPC_DataMemberType)) {
19634 D.setInvalidType();
19635 T = Context.IntTy;
19636 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19637 }
19638 }
19639
19640 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19641
19642 if (D.getDeclSpec().isInlineSpecified())
19643 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19644 << getLangOpts().CPlusPlus17;
19645 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19646 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19647 DiagID: diag::err_invalid_thread)
19648 << DeclSpec::getSpecifierName(S: TSCS);
19649
19650 // Check to see if this name was declared as a member previously
19651 NamedDecl *PrevDecl = nullptr;
19652 LookupResult Previous(*this, II, Loc, LookupMemberName,
19653 RedeclarationKind::ForVisibleRedeclaration);
19654 LookupName(R&: Previous, S);
19655 switch (Previous.getResultKind()) {
19656 case LookupResultKind::Found:
19657 case LookupResultKind::FoundUnresolvedValue:
19658 PrevDecl = Previous.getAsSingle<NamedDecl>();
19659 break;
19660
19661 case LookupResultKind::FoundOverloaded:
19662 PrevDecl = Previous.getRepresentativeDecl();
19663 break;
19664
19665 case LookupResultKind::NotFound:
19666 case LookupResultKind::NotFoundInCurrentInstantiation:
19667 case LookupResultKind::Ambiguous:
19668 break;
19669 }
19670 Previous.suppressDiagnostics();
19671
19672 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19673 // Maybe we will complain about the shadowed template parameter.
19674 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19675 // Just pretend that we didn't see the previous declaration.
19676 PrevDecl = nullptr;
19677 }
19678
19679 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19680 PrevDecl = nullptr;
19681
19682 bool Mutable
19683 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19684 SourceLocation TSSL = D.getBeginLoc();
19685 FieldDecl *NewFD
19686 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19687 TSSL, AS, PrevDecl, D: &D);
19688
19689 if (NewFD->isInvalidDecl())
19690 Record->setInvalidDecl();
19691
19692 if (D.getDeclSpec().isModulePrivateSpecified())
19693 NewFD->setModulePrivate();
19694
19695 if (NewFD->isInvalidDecl() && PrevDecl) {
19696 // Don't introduce NewFD into scope; there's already something
19697 // with the same name in the same scope.
19698 } else if (II) {
19699 PushOnScopeChains(D: NewFD, S);
19700 } else
19701 Record->addDecl(D: NewFD);
19702
19703 return NewFD;
19704}
19705
19706FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19707 TypeSourceInfo *TInfo,
19708 RecordDecl *Record, SourceLocation Loc,
19709 bool Mutable, Expr *BitWidth,
19710 InClassInitStyle InitStyle,
19711 SourceLocation TSSL,
19712 AccessSpecifier AS, NamedDecl *PrevDecl,
19713 Declarator *D) {
19714 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19715 bool InvalidDecl = false;
19716 if (D) InvalidDecl = D->isInvalidType();
19717
19718 // If we receive a broken type, recover by assuming 'int' and
19719 // marking this declaration as invalid.
19720 if (T.isNull() || T->containsErrors()) {
19721 InvalidDecl = true;
19722 T = Context.IntTy;
19723 }
19724
19725 QualType EltTy = Context.getBaseElementType(QT: T);
19726 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19727 bool isIncomplete =
19728 LangOpts.HLSL // HLSL allows sizeless builtin types
19729 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19730 : RequireCompleteSizedType(Loc, T: EltTy,
19731 DiagID: diag::err_field_incomplete_or_sizeless);
19732 if (isIncomplete) {
19733 // Fields of incomplete type force their record to be invalid.
19734 Record->setInvalidDecl();
19735 InvalidDecl = true;
19736 } else {
19737 NamedDecl *Def;
19738 EltTy->isIncompleteType(Def: &Def);
19739 if (Def && Def->isInvalidDecl()) {
19740 Record->setInvalidDecl();
19741 InvalidDecl = true;
19742 }
19743 }
19744 }
19745
19746 // TR 18037 does not allow fields to be declared with address space
19747 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19748 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19749 Diag(Loc, DiagID: diag::err_field_with_address_space);
19750 Record->setInvalidDecl();
19751 InvalidDecl = true;
19752 }
19753
19754 if (LangOpts.OpenCL) {
19755 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19756 // used as structure or union field: image, sampler, event or block types.
19757 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19758 T->isBlockPointerType()) {
19759 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19760 Record->setInvalidDecl();
19761 InvalidDecl = true;
19762 }
19763 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19764 // is enabled.
19765 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19766 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19767 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19768 InvalidDecl = true;
19769 }
19770 }
19771
19772 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19773 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19774 T.hasQualifiers()) {
19775 InvalidDecl = true;
19776 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19777 }
19778
19779 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19780 // than a variably modified type.
19781 if (!InvalidDecl && T->isVariablyModifiedType()) {
19782 if (!tryToFixVariablyModifiedVarType(
19783 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19784 InvalidDecl = true;
19785 }
19786
19787 // Fields can not have abstract class types
19788 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19789 DiagID: diag::err_abstract_type_in_decl,
19790 Args: AbstractFieldType))
19791 InvalidDecl = true;
19792
19793 if (InvalidDecl)
19794 BitWidth = nullptr;
19795 // If this is declared as a bit-field, check the bit-field.
19796 if (BitWidth) {
19797 BitWidth =
19798 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19799 if (!BitWidth) {
19800 InvalidDecl = true;
19801 BitWidth = nullptr;
19802 }
19803 }
19804
19805 // Check that 'mutable' is consistent with the type of the declaration.
19806 if (!InvalidDecl && Mutable) {
19807 unsigned DiagID = 0;
19808 if (T->isReferenceType())
19809 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19810 : diag::err_mutable_reference;
19811 else if (T.isConstQualified())
19812 DiagID = diag::err_mutable_const;
19813
19814 if (DiagID) {
19815 SourceLocation ErrLoc = Loc;
19816 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19817 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19818 Diag(Loc: ErrLoc, DiagID);
19819 if (DiagID != diag::ext_mutable_reference) {
19820 Mutable = false;
19821 InvalidDecl = true;
19822 }
19823 }
19824 }
19825
19826 // Aggregates with members of HLX types are not allowed.
19827 if (Hexagon().isHLXVectorType(T)) {
19828 Diag(Loc, DiagID: diag::err_hlx_invalid_field);
19829 InvalidDecl = true;
19830 }
19831
19832 // C++11 [class.union]p8 (DR1460):
19833 // At most one variant member of a union may have a
19834 // brace-or-equal-initializer.
19835 if (InitStyle != ICIS_NoInit)
19836 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19837
19838 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19839 BW: BitWidth, Mutable, InitStyle);
19840 if (InvalidDecl)
19841 NewFD->setInvalidDecl();
19842
19843 if (!InvalidDecl)
19844 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19845
19846 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19847 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19848 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19849 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19850 NewFD->setInvalidDecl();
19851 }
19852
19853 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19854 if (Record->isUnion()) {
19855 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19856 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19857
19858 // C++ [class.union]p1: An object of a class with a non-trivial
19859 // constructor, a non-trivial copy constructor, a non-trivial
19860 // destructor, or a non-trivial copy assignment operator
19861 // cannot be a member of a union, nor can an array of such
19862 // objects.
19863 if (CheckNontrivialField(FD: NewFD))
19864 NewFD->setInvalidDecl();
19865 }
19866
19867 // C++ [class.union]p1: If a union contains a member of reference type,
19868 // the program is ill-formed, except when compiling with MSVC extensions
19869 // enabled.
19870 if (EltTy->isReferenceType()) {
19871 const bool HaveMSExt =
19872 getLangOpts().MicrosoftExt &&
19873 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19874
19875 Diag(Loc: NewFD->getLocation(),
19876 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19877 : diag::err_union_member_of_reference_type)
19878 << NewFD->getDeclName() << EltTy;
19879 if (!HaveMSExt)
19880 NewFD->setInvalidDecl();
19881 }
19882 }
19883 }
19884
19885 // FIXME: We need to pass in the attributes given an AST
19886 // representation, not a parser representation.
19887 if (D) {
19888 // FIXME: The current scope is almost... but not entirely... correct here.
19889 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19890
19891 if (NewFD->hasAttrs())
19892 CheckAlignasUnderalignment(D: NewFD);
19893 }
19894
19895 // In auto-retain/release, infer strong retension for fields of
19896 // retainable type.
19897 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19898 NewFD->setInvalidDecl();
19899
19900 if (T.isObjCGCWeak())
19901 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19902
19903 // PPC MMA non-pointer types are not allowed as field types.
19904 if (Context.getTargetInfo().getTriple().isPPC64() &&
19905 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19906 NewFD->setInvalidDecl();
19907
19908 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19909 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewFD->getLocation()))
19910 NewFD->setInvalidDecl();
19911 }
19912
19913 NewFD->setAccess(AS);
19914 return NewFD;
19915}
19916
19917bool Sema::CheckNontrivialField(FieldDecl *FD) {
19918 assert(FD);
19919 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19920
19921 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19922 return false;
19923
19924 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19925 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19926 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19927 // We check for copy constructors before constructors
19928 // because otherwise we'll never get complaints about
19929 // copy constructors.
19930
19931 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19932 // We're required to check for any non-trivial constructors. Since the
19933 // implicit default constructor is suppressed if there are any
19934 // user-declared constructors, we just need to check that there is a
19935 // trivial default constructor and a trivial copy constructor. (We don't
19936 // worry about move constructors here, since this is a C++98 check.)
19937 if (RDecl->hasNonTrivialCopyConstructor())
19938 member = CXXSpecialMemberKind::CopyConstructor;
19939 else if (!RDecl->hasTrivialDefaultConstructor())
19940 member = CXXSpecialMemberKind::DefaultConstructor;
19941 else if (RDecl->hasNonTrivialCopyAssignment())
19942 member = CXXSpecialMemberKind::CopyAssignment;
19943 else if (RDecl->hasNonTrivialDestructor())
19944 member = CXXSpecialMemberKind::Destructor;
19945
19946 if (member != CXXSpecialMemberKind::Invalid) {
19947 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19948 RDecl->hasObjectMember()) {
19949 // Objective-C++ ARC: it is an error to have a non-trivial field of
19950 // a union. However, system headers in Objective-C programs
19951 // occasionally have Objective-C lifetime objects within unions,
19952 // and rather than cause the program to fail, we make those
19953 // members unavailable.
19954 SourceLocation Loc = FD->getLocation();
19955 if (getSourceManager().isInSystemHeader(Loc)) {
19956 if (!FD->hasAttr<UnavailableAttr>())
19957 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19958 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19959 return false;
19960 }
19961 }
19962
19963 Diag(Loc: FD->getLocation(),
19964 DiagID: getLangOpts().CPlusPlus11
19965 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19966 : diag::err_illegal_union_or_anon_struct_member)
19967 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19968 DiagnoseNontrivial(Record: RDecl, CSM: member);
19969 return !getLangOpts().CPlusPlus11;
19970 }
19971 }
19972
19973 return false;
19974}
19975
19976void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19977 SmallVectorImpl<Decl *> &AllIvarDecls) {
19978 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19979 return;
19980
19981 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19982 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19983
19984 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19985 return;
19986 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19987 if (!ID) {
19988 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19989 if (!CD->IsClassExtension())
19990 return;
19991 }
19992 // No need to add this to end of @implementation.
19993 else
19994 return;
19995 }
19996 // All conditions are met. Add a new bitfield to the tail end of ivars.
19997 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19998 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19999 Expr *BitWidth =
20000 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
20001
20002 Ivar = ObjCIvarDecl::Create(
20003 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
20004 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
20005 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
20006 AllIvarDecls.push_back(Elt: Ivar);
20007}
20008
20009/// [class.dtor]p4:
20010/// At the end of the definition of a class, overload resolution is
20011/// performed among the prospective destructors declared in that class with
20012/// an empty argument list to select the destructor for the class, also
20013/// known as the selected destructor.
20014///
20015/// We do the overload resolution here, then mark the selected constructor in the AST.
20016/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
20017static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
20018 if (!Record->hasUserDeclaredDestructor()) {
20019 return;
20020 }
20021
20022 SourceLocation Loc = Record->getLocation();
20023 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
20024
20025 for (auto *Decl : Record->decls()) {
20026 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
20027 if (DD->isInvalidDecl())
20028 continue;
20029 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
20030 CandidateSet&: OCS);
20031 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
20032 }
20033 }
20034
20035 if (OCS.empty()) {
20036 return;
20037 }
20038 OverloadCandidateSet::iterator Best;
20039 unsigned Msg = 0;
20040 OverloadCandidateDisplayKind DisplayKind;
20041
20042 switch (OCS.BestViableFunction(S, Loc, Best)) {
20043 case OR_Success:
20044 case OR_Deleted:
20045 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
20046 break;
20047
20048 case OR_Ambiguous:
20049 Msg = diag::err_ambiguous_destructor;
20050 DisplayKind = OCD_AmbiguousCandidates;
20051 break;
20052
20053 case OR_No_Viable_Function:
20054 Msg = diag::err_no_viable_destructor;
20055 DisplayKind = OCD_AllCandidates;
20056 break;
20057 }
20058
20059 if (Msg) {
20060 // OpenCL have got their own thing going with destructors. It's slightly broken,
20061 // but we allow it.
20062 if (!S.LangOpts.OpenCL) {
20063 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
20064 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
20065 Record->setInvalidDecl();
20066 }
20067 // It's a bit hacky: At this point we've raised an error but we want the
20068 // rest of the compiler to continue somehow working. However almost
20069 // everything we'll try to do with the class will depend on there being a
20070 // destructor. So let's pretend the first one is selected and hope for the
20071 // best.
20072 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
20073 }
20074}
20075
20076/// [class.mem.special]p5
20077/// Two special member functions are of the same kind if:
20078/// - they are both default constructors,
20079/// - they are both copy or move constructors with the same first parameter
20080/// type, or
20081/// - they are both copy or move assignment operators with the same first
20082/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
20083static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
20084 CXXMethodDecl *M1,
20085 CXXMethodDecl *M2,
20086 CXXSpecialMemberKind CSM) {
20087 // We don't want to compare templates to non-templates: See
20088 // https://github.com/llvm/llvm-project/issues/59206
20089 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
20090 return bool(M1->getDescribedFunctionTemplate()) ==
20091 bool(M2->getDescribedFunctionTemplate());
20092 // FIXME: better resolve CWG
20093 // https://cplusplus.github.io/CWG/issues/2787.html
20094 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
20095 T2: M2->getNonObjectParameter(I: 0)->getType()))
20096 return false;
20097 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
20098 T2: M2->getFunctionObjectParameterReferenceType()))
20099 return false;
20100
20101 return true;
20102}
20103
20104/// [class.mem.special]p6:
20105/// An eligible special member function is a special member function for which:
20106/// - the function is not deleted,
20107/// - the associated constraints, if any, are satisfied, and
20108/// - no special member function of the same kind whose associated constraints
20109/// [CWG2595], if any, are satisfied is more constrained.
20110static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
20111 ArrayRef<CXXMethodDecl *> Methods,
20112 CXXSpecialMemberKind CSM) {
20113 SmallVector<bool, 4> SatisfactionStatus;
20114
20115 for (CXXMethodDecl *Method : Methods) {
20116 if (!Method->getTrailingRequiresClause())
20117 SatisfactionStatus.push_back(Elt: true);
20118 else {
20119 ConstraintSatisfaction Satisfaction;
20120 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
20121 SatisfactionStatus.push_back(Elt: false);
20122 else
20123 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
20124 }
20125 }
20126
20127 for (size_t i = 0; i < Methods.size(); i++) {
20128 if (!SatisfactionStatus[i])
20129 continue;
20130 CXXMethodDecl *Method = Methods[i];
20131 CXXMethodDecl *OrigMethod = Method;
20132 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20133 OrigMethod = cast<CXXMethodDecl>(Val: MF);
20134
20135 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
20136 bool AnotherMethodIsMoreConstrained = false;
20137 for (size_t j = 0; j < Methods.size(); j++) {
20138 if (i == j || !SatisfactionStatus[j])
20139 continue;
20140 CXXMethodDecl *OtherMethod = Methods[j];
20141 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20142 OtherMethod = cast<CXXMethodDecl>(Val: MF);
20143
20144 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
20145 CSM))
20146 continue;
20147
20148 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
20149 if (!Other)
20150 continue;
20151 if (!Orig) {
20152 AnotherMethodIsMoreConstrained = true;
20153 break;
20154 }
20155 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
20156 Result&: AnotherMethodIsMoreConstrained)) {
20157 // There was an error with the constraints comparison. Exit the loop
20158 // and don't consider this function eligible.
20159 AnotherMethodIsMoreConstrained = true;
20160 }
20161 if (AnotherMethodIsMoreConstrained)
20162 break;
20163 }
20164 // FIXME: Do not consider deleted methods as eligible after implementing
20165 // DR1734 and DR1496.
20166 if (!AnotherMethodIsMoreConstrained) {
20167 Method->setIneligibleOrNotSelected(false);
20168 Record->addedEligibleSpecialMemberFunction(MD: Method,
20169 SMKind: 1 << llvm::to_underlying(E: CSM));
20170 }
20171 }
20172}
20173
20174static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
20175 CXXRecordDecl *Record) {
20176 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20177 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20178 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20179 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20180 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20181
20182 for (auto *Decl : Record->decls()) {
20183 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
20184 if (!MD) {
20185 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
20186 if (FTD)
20187 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
20188 }
20189 if (!MD)
20190 continue;
20191 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
20192 if (CD->isInvalidDecl())
20193 continue;
20194 if (CD->isDefaultConstructor())
20195 DefaultConstructors.push_back(Elt: MD);
20196 else if (CD->isCopyConstructor())
20197 CopyConstructors.push_back(Elt: MD);
20198 else if (CD->isMoveConstructor())
20199 MoveConstructors.push_back(Elt: MD);
20200 } else if (MD->isCopyAssignmentOperator()) {
20201 CopyAssignmentOperators.push_back(Elt: MD);
20202 } else if (MD->isMoveAssignmentOperator()) {
20203 MoveAssignmentOperators.push_back(Elt: MD);
20204 }
20205 }
20206
20207 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
20208 CSM: CXXSpecialMemberKind::DefaultConstructor);
20209 SetEligibleMethods(S, Record, Methods: CopyConstructors,
20210 CSM: CXXSpecialMemberKind::CopyConstructor);
20211 SetEligibleMethods(S, Record, Methods: MoveConstructors,
20212 CSM: CXXSpecialMemberKind::MoveConstructor);
20213 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
20214 CSM: CXXSpecialMemberKind::CopyAssignment);
20215 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
20216 CSM: CXXSpecialMemberKind::MoveAssignment);
20217}
20218
20219bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20220 // Check to see if a FieldDecl is a pointer to a function.
20221 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20222 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
20223 if (!FD) {
20224 // Check whether this is a forward declaration that was inserted by
20225 // Clang. This happens when a non-forward declared / defined type is
20226 // used, e.g.:
20227 //
20228 // struct foo {
20229 // struct bar *(*f)();
20230 // struct bar *(*g)();
20231 // };
20232 //
20233 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20234 // incomplete definition.
20235 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
20236 return !TD->isCompleteDefinition();
20237 return false;
20238 }
20239 QualType FieldType = FD->getType().getDesugaredType(Context);
20240 if (isa<PointerType>(Val: FieldType)) {
20241 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
20242 return PointeeType.getDesugaredType(Context)->isFunctionType();
20243 }
20244 // If a member is a struct entirely of function pointers, that counts too.
20245 if (const auto *Record = FieldType->getAsRecordDecl();
20246 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20247 return true;
20248 return false;
20249 };
20250
20251 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
20252}
20253
20254void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20255 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20256 SourceLocation RBrac,
20257 const ParsedAttributesView &Attrs) {
20258 assert(EnclosingDecl && "missing record or interface decl");
20259
20260 // If this is an Objective-C @implementation or category and we have
20261 // new fields here we should reset the layout of the interface since
20262 // it will now change.
20263 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
20264 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
20265 switch (DC->getKind()) {
20266 default: break;
20267 case Decl::ObjCCategory:
20268 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
20269 break;
20270 case Decl::ObjCImplementation:
20271 Context.
20272 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
20273 break;
20274 }
20275 }
20276
20277 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
20278 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
20279
20280 // Start counting up the number of named members; make sure to include
20281 // members of anonymous structs and unions in the total.
20282 unsigned NumNamedMembers = 0;
20283 if (Record) {
20284 for (const auto *I : Record->decls()) {
20285 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
20286 if (IFD->getDeclName())
20287 ++NumNamedMembers;
20288 }
20289 }
20290
20291 // Verify that all the fields are okay.
20292 SmallVector<FieldDecl*, 32> RecFields;
20293 const FieldDecl *PreviousField = nullptr;
20294 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20295 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
20296 FieldDecl *FD = cast<FieldDecl>(Val: *i);
20297
20298 // Get the type for the field.
20299 const Type *FDTy = FD->getType().getTypePtr();
20300
20301 if (!FD->isAnonymousStructOrUnion()) {
20302 // Remember all fields written by the user.
20303 RecFields.push_back(Elt: FD);
20304 }
20305
20306 // If the field is already invalid for some reason, don't emit more
20307 // diagnostics about it.
20308 if (FD->isInvalidDecl()) {
20309 EnclosingDecl->setInvalidDecl();
20310 continue;
20311 }
20312
20313 // C99 6.7.2.1p2:
20314 // A structure or union shall not contain a member with
20315 // incomplete or function type (hence, a structure shall not
20316 // contain an instance of itself, but may contain a pointer to
20317 // an instance of itself), except that the last member of a
20318 // structure with more than one named member may have incomplete
20319 // array type; such a structure (and any union containing,
20320 // possibly recursively, a member that is such a structure)
20321 // shall not be a member of a structure or an element of an
20322 // array.
20323 bool IsLastField = (i + 1 == Fields.end());
20324 if (FDTy->isFunctionType()) {
20325 // Field declared as a function.
20326 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
20327 << FD->getDeclName();
20328 FD->setInvalidDecl();
20329 EnclosingDecl->setInvalidDecl();
20330 continue;
20331 } else if (FDTy->isIncompleteArrayType() &&
20332 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20333 if (Record) {
20334 // Flexible array member.
20335 // Microsoft and g++ is more permissive regarding flexible array.
20336 // It will accept flexible array in union and also
20337 // as the sole element of a struct/class.
20338 unsigned DiagID = 0;
20339 if (!Record->isUnion() && !IsLastField) {
20340 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20341 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20342 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20343 FD->setInvalidDecl();
20344 EnclosingDecl->setInvalidDecl();
20345 continue;
20346 } else if (Record->isUnion())
20347 DiagID = getLangOpts().MicrosoftExt
20348 ? diag::ext_flexible_array_union_ms
20349 : diag::ext_flexible_array_union_gnu;
20350 else if (NumNamedMembers < 1)
20351 DiagID = getLangOpts().MicrosoftExt
20352 ? diag::ext_flexible_array_empty_aggregate_ms
20353 : diag::ext_flexible_array_empty_aggregate_gnu;
20354
20355 if (DiagID)
20356 Diag(Loc: FD->getLocation(), DiagID)
20357 << FD->getDeclName() << Record->getTagKind();
20358 // While the layout of types that contain virtual bases is not specified
20359 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20360 // virtual bases after the derived members. This would make a flexible
20361 // array member declared at the end of an object not adjacent to the end
20362 // of the type.
20363 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20364 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20365 << FD->getDeclName() << Record->getTagKind();
20366 if (!getLangOpts().C99)
20367 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20368 << FD->getDeclName() << Record->getTagKind();
20369
20370 // If the element type has a non-trivial destructor, we would not
20371 // implicitly destroy the elements, so disallow it for now.
20372 //
20373 // FIXME: GCC allows this. We should probably either implicitly delete
20374 // the destructor of the containing class, or just allow this.
20375 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20376 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20377 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20378 << FD->getDeclName() << FD->getType();
20379 FD->setInvalidDecl();
20380 EnclosingDecl->setInvalidDecl();
20381 continue;
20382 }
20383 // Okay, we have a legal flexible array member at the end of the struct.
20384 Record->setHasFlexibleArrayMember(true);
20385 } else {
20386 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20387 // unless they are followed by another ivar. That check is done
20388 // elsewhere, after synthesized ivars are known.
20389 }
20390 } else if (!FDTy->isDependentType() &&
20391 (LangOpts.HLSL // HLSL allows sizeless builtin types
20392 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20393 DiagID: diag::err_incomplete_type)
20394 : RequireCompleteSizedType(
20395 Loc: FD->getLocation(), T: FD->getType(),
20396 DiagID: diag::err_field_incomplete_or_sizeless))) {
20397 // Incomplete type
20398 FD->setInvalidDecl();
20399 EnclosingDecl->setInvalidDecl();
20400 continue;
20401 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20402 if (Record && RD->hasFlexibleArrayMember()) {
20403 // A type which contains a flexible array member is considered to be a
20404 // flexible array member.
20405 Record->setHasFlexibleArrayMember(true);
20406 if (!Record->isUnion()) {
20407 // If this is a struct/class and this is not the last element, reject
20408 // it. Note that GCC supports variable sized arrays in the middle of
20409 // structures.
20410 if (!IsLastField)
20411 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20412 << FD->getDeclName() << FD->getType();
20413 else {
20414 // We support flexible arrays at the end of structs in
20415 // other structs as an extension.
20416 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20417 << FD->getDeclName();
20418 }
20419 }
20420 }
20421 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20422 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20423 DiagID: diag::err_abstract_type_in_decl,
20424 Args: AbstractIvarType)) {
20425 // Ivars can not have abstract class types
20426 FD->setInvalidDecl();
20427 }
20428 if (Record && RD->hasObjectMember())
20429 Record->setHasObjectMember(true);
20430 if (Record && RD->hasVolatileMember())
20431 Record->setHasVolatileMember(true);
20432 } else if (FDTy->isObjCObjectType()) {
20433 /// A field cannot be an Objective-c object
20434 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20435 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20436 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20437 FD->setType(T);
20438 } else if (Record && Record->isUnion() &&
20439 FD->getType().hasNonTrivialObjCLifetime() &&
20440 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20441 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20442 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20443 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20444 // For backward compatibility, fields of C unions declared in system
20445 // headers that have non-trivial ObjC ownership qualifications are marked
20446 // as unavailable unless the qualifier is explicit and __strong. This can
20447 // break ABI compatibility between programs compiled with ARC and MRR, but
20448 // is a better option than rejecting programs using those unions under
20449 // ARC.
20450 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20451 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20452 Range: FD->getLocation()));
20453 } else if (getLangOpts().ObjC &&
20454 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20455 !Record->hasObjectMember()) {
20456 if (FD->getType()->isObjCObjectPointerType() ||
20457 FD->getType().isObjCGCStrong())
20458 Record->setHasObjectMember(true);
20459 else if (Context.getAsArrayType(T: FD->getType())) {
20460 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20461 if (const auto *RD = BaseType->getAsRecordDecl();
20462 RD && RD->hasObjectMember())
20463 Record->setHasObjectMember(true);
20464 else if (BaseType->isObjCObjectPointerType() ||
20465 BaseType.isObjCGCStrong())
20466 Record->setHasObjectMember(true);
20467 }
20468 }
20469
20470 if (Record && !getLangOpts().CPlusPlus &&
20471 !shouldIgnoreForRecordTriviality(FD)) {
20472 QualType FT = FD->getType();
20473 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20474 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20475 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20476 Record->isUnion())
20477 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20478 }
20479 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20480 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20481 Record->setNonTrivialToPrimitiveCopy(true);
20482 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20483 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20484 }
20485 if (FD->hasAttr<ExplicitInitAttr>())
20486 Record->setHasUninitializedExplicitInitFields(true);
20487 if (FT.isDestructedType()) {
20488 Record->setNonTrivialToPrimitiveDestroy(true);
20489 Record->setParamDestroyedInCallee(true);
20490 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20491 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20492 }
20493
20494 if (const auto *RD = FT->getAsRecordDecl()) {
20495 if (RD->getArgPassingRestrictions() ==
20496 RecordArgPassingKind::CanNeverPassInRegs)
20497 Record->setArgPassingRestrictions(
20498 RecordArgPassingKind::CanNeverPassInRegs);
20499 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20500 Record->setArgPassingRestrictions(
20501 RecordArgPassingKind::CanNeverPassInRegs);
20502 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20503 Q && Q.isAddressDiscriminated()) {
20504 Record->setArgPassingRestrictions(
20505 RecordArgPassingKind::CanNeverPassInRegs);
20506 Record->setNonTrivialToPrimitiveCopy(true);
20507 }
20508 }
20509
20510 if (Record && FD->getType().isVolatileQualified())
20511 Record->setHasVolatileMember(true);
20512 bool ReportMSBitfieldStoragePacking =
20513 Record && PreviousField &&
20514 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20515 Loc: Record->getLocation());
20516 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20517 return FD->isBitField() && !FD->getType()->isDependentType();
20518 };
20519
20520 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20521 IsNonDependentBitField(PreviousField)) {
20522 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20523 CharUnits PreviousFieldStorageSize =
20524 Context.getTypeSizeInChars(T: PreviousField->getType());
20525 if (FDStorageSize != PreviousFieldStorageSize) {
20526 Diag(Loc: FD->getLocation(),
20527 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20528 << FD << FD->getType() << FDStorageSize.getQuantity()
20529 << PreviousFieldStorageSize.getQuantity();
20530 Diag(Loc: PreviousField->getLocation(),
20531 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20532 << PreviousField << PreviousField->getType();
20533 }
20534 }
20535 // Keep track of the number of named members.
20536 if (FD->getIdentifier())
20537 ++NumNamedMembers;
20538 }
20539
20540 // Okay, we successfully defined 'Record'.
20541 if (Record) {
20542 bool Completed = false;
20543 if (S) {
20544 Scope *Parent = S->getParent();
20545 if (Parent && Parent->isTypeAliasScope() &&
20546 Parent->isTemplateParamScope())
20547 Record->setInvalidDecl();
20548 }
20549
20550 if (CXXRecord) {
20551 if (!CXXRecord->isInvalidDecl()) {
20552 // Set access bits correctly on the directly-declared conversions.
20553 for (CXXRecordDecl::conversion_iterator
20554 I = CXXRecord->conversion_begin(),
20555 E = CXXRecord->conversion_end(); I != E; ++I)
20556 I.setAccess((*I)->getAccess());
20557 }
20558
20559 // Add any implicitly-declared members to this class.
20560 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20561
20562 if (!CXXRecord->isDependentType()) {
20563 if (!CXXRecord->isInvalidDecl()) {
20564 // If we have virtual base classes, we may end up finding multiple
20565 // final overriders for a given virtual function. Check for this
20566 // problem now.
20567 if (CXXRecord->getNumVBases()) {
20568 CXXFinalOverriderMap FinalOverriders;
20569 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20570
20571 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20572 MEnd = FinalOverriders.end();
20573 M != MEnd; ++M) {
20574 for (OverridingMethods::iterator SO = M->second.begin(),
20575 SOEnd = M->second.end();
20576 SO != SOEnd; ++SO) {
20577 assert(SO->second.size() > 0 &&
20578 "Virtual function without overriding functions?");
20579 if (SO->second.size() == 1)
20580 continue;
20581
20582 // C++ [class.virtual]p2:
20583 // In a derived class, if a virtual member function of a base
20584 // class subobject has more than one final overrider the
20585 // program is ill-formed.
20586 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20587 << (const NamedDecl *)M->first << Record;
20588 Diag(Loc: M->first->getLocation(),
20589 DiagID: diag::note_overridden_virtual_function);
20590 for (OverridingMethods::overriding_iterator
20591 OM = SO->second.begin(),
20592 OMEnd = SO->second.end();
20593 OM != OMEnd; ++OM)
20594 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20595 << (const NamedDecl *)M->first << OM->Method->getParent();
20596
20597 Record->setInvalidDecl();
20598 }
20599 }
20600 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20601 Completed = true;
20602 }
20603 }
20604 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20605 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20606 }
20607 }
20608
20609 if (!Completed)
20610 Record->completeDefinition();
20611
20612 // Handle attributes before checking the layout.
20613 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20614
20615 // Maybe randomize the record's decls. We automatically randomize a record
20616 // of function pointers, unless it has the "no_randomize_layout" attribute.
20617 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20618 !Record->isRandomized() && !Record->isUnion() &&
20619 (Record->hasAttr<RandomizeLayoutAttr>() ||
20620 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20621 EntirelyFunctionPointers(Record)))) {
20622 SmallVector<Decl *, 32> NewDeclOrdering;
20623 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20624 FinalOrdering&: NewDeclOrdering))
20625 Record->reorderDecls(Decls: NewDeclOrdering);
20626 }
20627
20628 // We may have deferred checking for a deleted destructor. Check now.
20629 if (CXXRecord) {
20630 auto *Dtor = CXXRecord->getDestructor();
20631 if (Dtor && Dtor->isImplicit() &&
20632 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20633 CXXRecord->setImplicitDestructorIsDeleted();
20634 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20635 }
20636 }
20637
20638 if (Record->hasAttrs()) {
20639 CheckAlignasUnderalignment(D: Record);
20640
20641 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20642 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20643 Range: IA->getRange(), BestCase: IA->getBestCase(),
20644 SemanticSpelling: IA->getInheritanceModel());
20645 }
20646
20647 // Check if the structure/union declaration is a type that can have zero
20648 // size in C. For C this is a language extension, for C++ it may cause
20649 // compatibility problems.
20650 bool CheckForZeroSize;
20651 if (!getLangOpts().CPlusPlus) {
20652 CheckForZeroSize = true;
20653 } else {
20654 // For C++ filter out types that cannot be referenced in C code.
20655 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20656 CheckForZeroSize =
20657 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20658 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20659 CXXRecord->isCLike();
20660 }
20661 if (CheckForZeroSize) {
20662 bool ZeroSize = true;
20663 bool IsEmpty = true;
20664 unsigned NonBitFields = 0;
20665 for (RecordDecl::field_iterator I = Record->field_begin(),
20666 E = Record->field_end();
20667 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20668 IsEmpty = false;
20669 if (I->isUnnamedBitField()) {
20670 if (!I->isZeroLengthBitField())
20671 ZeroSize = false;
20672 } else {
20673 ++NonBitFields;
20674 QualType FieldType = I->getType();
20675 if (FieldType->isIncompleteType() ||
20676 !Context.getTypeSizeInChars(T: FieldType).isZero())
20677 ZeroSize = false;
20678 }
20679 }
20680
20681 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20682 // allowed in C++, but warn if its declaration is inside
20683 // extern "C" block.
20684 if (ZeroSize) {
20685 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20686 diag::warn_zero_size_struct_union_in_extern_c :
20687 diag::warn_zero_size_struct_union_compat)
20688 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20689 }
20690
20691 // Structs without named members are extension in C (C99 6.7.2.1p7),
20692 // but are accepted by GCC. In C2y, this became implementation-defined
20693 // (C2y 6.7.3.2p10).
20694 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20695 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20696 : diag::ext_no_named_members_in_struct_union)
20697 << Record->isUnion();
20698 }
20699 }
20700 } else {
20701 ObjCIvarDecl **ClsFields =
20702 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20703 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20704 ID->setEndOfDefinitionLoc(RBrac);
20705 // Add ivar's to class's DeclContext.
20706 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20707 ClsFields[i]->setLexicalDeclContext(ID);
20708 ID->addDecl(D: ClsFields[i]);
20709 }
20710 // Must enforce the rule that ivars in the base classes may not be
20711 // duplicates.
20712 if (ID->getSuperClass())
20713 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20714 } else if (ObjCImplementationDecl *IMPDecl =
20715 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20716 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20717 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20718 // Ivar declared in @implementation never belongs to the implementation.
20719 // Only it is in implementation's lexical context.
20720 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20721 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20722 Loc: RBrac);
20723 IMPDecl->setIvarLBraceLoc(LBrac);
20724 IMPDecl->setIvarRBraceLoc(RBrac);
20725 } else if (ObjCCategoryDecl *CDecl =
20726 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20727 // case of ivars in class extension; all other cases have been
20728 // reported as errors elsewhere.
20729 // FIXME. Class extension does not have a LocEnd field.
20730 // CDecl->setLocEnd(RBrac);
20731 // Add ivar's to class extension's DeclContext.
20732 // Diagnose redeclaration of private ivars.
20733 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20734 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20735 if (IDecl) {
20736 if (const ObjCIvarDecl *ClsIvar =
20737 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20738 Diag(Loc: ClsFields[i]->getLocation(),
20739 DiagID: diag::err_duplicate_ivar_declaration);
20740 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20741 continue;
20742 }
20743 for (const auto *Ext : IDecl->known_extensions()) {
20744 if (const ObjCIvarDecl *ClsExtIvar
20745 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20746 Diag(Loc: ClsFields[i]->getLocation(),
20747 DiagID: diag::err_duplicate_ivar_declaration);
20748 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20749 continue;
20750 }
20751 }
20752 }
20753 ClsFields[i]->setLexicalDeclContext(CDecl);
20754 CDecl->addDecl(D: ClsFields[i]);
20755 }
20756 CDecl->setIvarLBraceLoc(LBrac);
20757 CDecl->setIvarRBraceLoc(RBrac);
20758 }
20759 }
20760
20761 if (Record)
20762 AMDGPU().checkNamedBarrierWrapper(R: Record);
20763
20764 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20765 ProcessAPINotes(D: Record);
20766}
20767
20768// Given an integral type, return the next larger integral type
20769// (or a NULL type of no such type exists).
20770static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20771 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20772 // enum checking below.
20773 assert((T->isIntegralType(Context) ||
20774 T->isEnumeralType()) && "Integral type required!");
20775 const unsigned NumTypes = 4;
20776 QualType SignedIntegralTypes[NumTypes] = {
20777 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20778 };
20779 QualType UnsignedIntegralTypes[NumTypes] = {
20780 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20781 Context.UnsignedLongLongTy
20782 };
20783
20784 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20785 // bits but a 64-bit standard type can still represent its incremented
20786 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20787 // bit-precise type either.
20788 unsigned BitWidth = Context.getIntWidth(T);
20789 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20790 : UnsignedIntegralTypes;
20791 for (unsigned I = 0; I != NumTypes; ++I)
20792 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20793 return Types[I];
20794
20795 return QualType();
20796}
20797
20798EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20799 EnumConstantDecl *LastEnumConst,
20800 SourceLocation IdLoc,
20801 IdentifierInfo *Id,
20802 Expr *Val) {
20803 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20804 llvm::APSInt EnumVal(IntWidth);
20805 QualType EltTy;
20806
20807 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20808 Val = nullptr;
20809
20810 if (Val)
20811 Val = DefaultLvalueConversion(E: Val).get();
20812
20813 if (Val) {
20814 if (Enum->isDependentType() || Val->isTypeDependent() ||
20815 Val->containsErrors())
20816 EltTy = Context.DependentTy;
20817 else {
20818 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20819 // underlying type, but do allow it in all other contexts.
20820 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20821 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20822 // constant-expression in the enumerator-definition shall be a converted
20823 // constant expression of the underlying type.
20824 EltTy = Enum->getIntegerType();
20825 ExprResult Converted = CheckConvertedConstantExpression(
20826 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20827 if (Converted.isInvalid())
20828 Val = nullptr;
20829 else
20830 Val = Converted.get();
20831 } else if (!Val->isValueDependent() &&
20832 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20833 CanFold: AllowFoldKind::Allow)
20834 .get())) {
20835 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20836 } else {
20837 if (Enum->isComplete()) {
20838 EltTy = Enum->getIntegerType();
20839
20840 // In Obj-C and Microsoft mode, require the enumeration value to be
20841 // representable in the underlying type of the enumeration. In C++11,
20842 // we perform a non-narrowing conversion as part of converted constant
20843 // expression checking.
20844 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20845 if (Context.getTargetInfo()
20846 .getTriple()
20847 .isWindowsMSVCEnvironment()) {
20848 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20849 } else {
20850 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20851 }
20852 }
20853
20854 // Cast to the underlying type.
20855 Val = ImpCastExprToType(E: Val, Type: EltTy,
20856 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20857 : CK_IntegralCast)
20858 .get();
20859 } else if (getLangOpts().CPlusPlus) {
20860 // C++11 [dcl.enum]p5:
20861 // If the underlying type is not fixed, the type of each enumerator
20862 // is the type of its initializing value:
20863 // - If an initializer is specified for an enumerator, the
20864 // initializing value has the same type as the expression.
20865 EltTy = Val->getType();
20866 } else {
20867 // C99 6.7.2.2p2:
20868 // The expression that defines the value of an enumeration constant
20869 // shall be an integer constant expression that has a value
20870 // representable as an int.
20871
20872 // Complain if the value is not representable in an int.
20873 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20874 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20875 ? diag::warn_c17_compat_enum_value_not_int
20876 : diag::ext_c23_enum_value_not_int)
20877 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20878 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20879 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20880 // Force the type of the expression to 'int'.
20881 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20882 }
20883 EltTy = Val->getType();
20884 }
20885 }
20886 }
20887 }
20888
20889 if (!Val) {
20890 if (Enum->isDependentType())
20891 EltTy = Context.DependentTy;
20892 else if (!LastEnumConst) {
20893 // C++0x [dcl.enum]p5:
20894 // If the underlying type is not fixed, the type of each enumerator
20895 // is the type of its initializing value:
20896 // - If no initializer is specified for the first enumerator, the
20897 // initializing value has an unspecified integral type.
20898 //
20899 // GCC uses 'int' for its unspecified integral type, as does
20900 // C99 6.7.2.2p3.
20901 if (Enum->isFixed()) {
20902 EltTy = Enum->getIntegerType();
20903 }
20904 else {
20905 EltTy = Context.IntTy;
20906 }
20907 } else {
20908 // Assign the last value + 1.
20909 EnumVal = LastEnumConst->getInitVal();
20910 ++EnumVal;
20911 EltTy = LastEnumConst->getType();
20912
20913 // Check for overflow on increment.
20914 if (EnumVal < LastEnumConst->getInitVal()) {
20915 // C++0x [dcl.enum]p5:
20916 // If the underlying type is not fixed, the type of each enumerator
20917 // is the type of its initializing value:
20918 //
20919 // - Otherwise the type of the initializing value is the same as
20920 // the type of the initializing value of the preceding enumerator
20921 // unless the incremented value is not representable in that type,
20922 // in which case the type is an unspecified integral type
20923 // sufficient to contain the incremented value. If no such type
20924 // exists, the program is ill-formed.
20925 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20926 if (T.isNull() || Enum->isFixed()) {
20927 // There is no integral type larger enough to represent this
20928 // value. Complain, then allow the value to wrap around.
20929 EnumVal = LastEnumConst->getInitVal();
20930 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20931 ++EnumVal;
20932 if (Enum->isFixed())
20933 // When the underlying type is fixed, this is ill-formed.
20934 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20935 << toString(I: EnumVal, Radix: 10)
20936 << EltTy;
20937 else
20938 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20939 << toString(I: EnumVal, Radix: 10);
20940 } else {
20941 EltTy = T;
20942 }
20943
20944 // Retrieve the last enumerator's value, extent that type to the
20945 // type that is supposed to be large enough to represent the incremented
20946 // value, then increment.
20947 EnumVal = LastEnumConst->getInitVal();
20948 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20949 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20950 ++EnumVal;
20951
20952 // If we're not in C++, diagnose the overflow of enumerator values,
20953 // which in C99 means that the enumerator value is not representable in
20954 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20955 // are representable in some larger integral type and we allow it in
20956 // older language modes as an extension.
20957 // Exclude fixed enumerators since they are diagnosed with an error for
20958 // this case.
20959 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20960 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20961 ? diag::warn_c17_compat_enum_value_not_int
20962 : diag::ext_c23_enum_value_not_int)
20963 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20964 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20965 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20966 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20967 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20968 : diag::ext_c23_enum_value_not_int)
20969 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20970 }
20971 }
20972 }
20973
20974 if (!EltTy->isDependentType()) {
20975 // Make the enumerator value match the signedness and size of the
20976 // enumerator's type.
20977 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20978 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20979 }
20980
20981 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20982 E: Val, V: EnumVal);
20983}
20984
20985SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20986 SourceLocation IILoc) {
20987 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20988 !getLangOpts().CPlusPlus)
20989 return SkipBodyInfo();
20990
20991 // We have an anonymous enum definition. Look up the first enumerator to
20992 // determine if we should merge the definition with an existing one and
20993 // skip the body.
20994 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20995 Redecl: forRedeclarationInCurContext());
20996 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20997 if (!PrevECD)
20998 return SkipBodyInfo();
20999
21000 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
21001 NamedDecl *Hidden;
21002 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
21003 SkipBodyInfo Skip;
21004 Skip.Previous = Hidden;
21005 return Skip;
21006 }
21007
21008 return SkipBodyInfo();
21009}
21010
21011Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
21012 SourceLocation IdLoc, IdentifierInfo *Id,
21013 const ParsedAttributesView &Attrs,
21014 SourceLocation EqualLoc, Expr *Val,
21015 SkipBodyInfo *SkipBody) {
21016 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
21017 EnumConstantDecl *LastEnumConst =
21018 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
21019
21020 // The scope passed in may not be a decl scope. Zip up the scope tree until
21021 // we find one that is.
21022 S = getNonFieldDeclScope(S);
21023
21024 // Verify that there isn't already something declared with this name in this
21025 // scope.
21026 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
21027 RedeclarationKind::ForVisibleRedeclaration);
21028 LookupName(R, S);
21029 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
21030
21031 if (PrevDecl && PrevDecl->isTemplateParameter()) {
21032 // Maybe we will complain about the shadowed template parameter.
21033 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
21034 // Just pretend that we didn't see the previous declaration.
21035 PrevDecl = nullptr;
21036 }
21037
21038 // C++ [class.mem]p15:
21039 // If T is the name of a class, then each of the following shall have a name
21040 // different from T:
21041 // - every enumerator of every member of class T that is an unscoped
21042 // enumerated type
21043 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
21044 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
21045 NameInfo: DeclarationNameInfo(Id, IdLoc)))
21046 return nullptr;
21047
21048 EnumConstantDecl *New =
21049 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
21050 if (!New)
21051 return nullptr;
21052
21053 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
21054 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
21055 // Check for other kinds of shadowing not already handled.
21056 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
21057 }
21058
21059 // When in C++, we may get a TagDecl with the same name; in this case the
21060 // enum constant will 'hide' the tag.
21061 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
21062 "Received TagDecl when not in C++!");
21063 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
21064 if (isa<EnumConstantDecl>(Val: PrevDecl))
21065 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
21066 else
21067 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
21068 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
21069 return nullptr;
21070 }
21071 }
21072
21073 // Process attributes.
21074 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
21075 AddPragmaAttributes(S, D: New);
21076 ProcessAPINotes(D: New);
21077
21078 // Register this decl in the current scope stack.
21079 New->setAccess(TheEnumDecl->getAccess());
21080 PushOnScopeChains(D: New, S);
21081
21082 ActOnDocumentableDecl(D: New);
21083
21084 return New;
21085}
21086
21087// Returns true when the enum initial expression does not trigger the
21088// duplicate enum warning. A few common cases are exempted as follows:
21089// Element2 = Element1
21090// Element2 = Element1 + 1
21091// Element2 = Element1 - 1
21092// Where Element2 and Element1 are from the same enum.
21093static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
21094 Expr *InitExpr = ECD->getInitExpr();
21095 if (!InitExpr)
21096 return true;
21097 InitExpr = InitExpr->IgnoreImpCasts();
21098
21099 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
21100 if (!BO->isAdditiveOp())
21101 return true;
21102 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
21103 if (!IL)
21104 return true;
21105 if (IL->getValue() != 1)
21106 return true;
21107
21108 InitExpr = BO->getLHS();
21109 }
21110
21111 // This checks if the elements are from the same enum.
21112 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
21113 if (!DRE)
21114 return true;
21115
21116 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
21117 if (!EnumConstant)
21118 return true;
21119
21120 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
21121 Enum)
21122 return true;
21123
21124 return false;
21125}
21126
21127// Emits a warning when an element is implicitly set a value that
21128// a previous element has already been set to.
21129static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
21130 EnumDecl *Enum, QualType EnumType) {
21131 // Avoid anonymous enums
21132 if (!Enum->getIdentifier())
21133 return;
21134
21135 // Only check for small enums.
21136 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21137 return;
21138
21139 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
21140 return;
21141
21142 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21143 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21144
21145 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21146
21147 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21148 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21149
21150 // Use int64_t as a key to avoid needing special handling for map keys.
21151 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21152 llvm::APSInt Val = D->getInitVal();
21153 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21154 };
21155
21156 DuplicatesVector DupVector;
21157 ValueToVectorMap EnumMap;
21158
21159 // Populate the EnumMap with all values represented by enum constants without
21160 // an initializer.
21161 for (auto *Element : Elements) {
21162 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
21163
21164 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21165 // this constant. Skip this enum since it may be ill-formed.
21166 if (!ECD) {
21167 return;
21168 }
21169
21170 // Constants with initializers are handled in the next loop.
21171 if (ECD->getInitExpr())
21172 continue;
21173
21174 // Duplicate values are handled in the next loop.
21175 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
21176 }
21177
21178 if (EnumMap.size() == 0)
21179 return;
21180
21181 // Create vectors for any values that has duplicates.
21182 for (auto *Element : Elements) {
21183 // The last loop returned if any constant was null.
21184 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
21185 if (!ValidDuplicateEnum(ECD, Enum))
21186 continue;
21187
21188 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
21189 if (Iter == EnumMap.end())
21190 continue;
21191
21192 DeclOrVector& Entry = Iter->second;
21193 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
21194 // Ensure constants are different.
21195 if (D == ECD)
21196 continue;
21197
21198 // Create new vector and push values onto it.
21199 auto Vec = std::make_unique<ECDVector>();
21200 Vec->push_back(Elt: D);
21201 Vec->push_back(Elt: ECD);
21202
21203 // Update entry to point to the duplicates vector.
21204 Entry = Vec.get();
21205
21206 // Store the vector somewhere we can consult later for quick emission of
21207 // diagnostics.
21208 DupVector.emplace_back(Args: std::move(Vec));
21209 continue;
21210 }
21211
21212 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
21213 // Make sure constants are not added more than once.
21214 if (*Vec->begin() == ECD)
21215 continue;
21216
21217 Vec->push_back(Elt: ECD);
21218 }
21219
21220 // Emit diagnostics.
21221 for (const auto &Vec : DupVector) {
21222 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21223
21224 // Emit warning for one enum constant.
21225 auto *FirstECD = Vec->front();
21226 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
21227 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
21228 << FirstECD->getSourceRange();
21229
21230 // Emit one note for each of the remaining enum constants with
21231 // the same value.
21232 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
21233 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
21234 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
21235 << ECD->getSourceRange();
21236 }
21237}
21238
21239bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21240 bool AllowMask) const {
21241 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21242 assert(ED->isCompleteDefinition() && "expected enum definition");
21243
21244 auto R = FlagBitsCache.try_emplace(Key: ED);
21245 llvm::APInt &FlagBits = R.first->second;
21246
21247 if (R.second) {
21248 for (auto *E : ED->enumerators()) {
21249 const auto &EVal = E->getInitVal();
21250 // Only single-bit enumerators introduce new flag values.
21251 if (EVal.isPowerOf2())
21252 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
21253 }
21254 }
21255
21256 // A value is in a flag enum if either its bits are a subset of the enum's
21257 // flag bits (the first condition) or we are allowing masks and the same is
21258 // true of its complement (the second condition). When masks are allowed, we
21259 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21260 //
21261 // While it's true that any value could be used as a mask, the assumption is
21262 // that a mask will have all of the insignificant bits set. Anything else is
21263 // likely a logic error.
21264 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
21265 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21266}
21267
21268// Emits a warning when a suspicious comparison operator is used along side
21269// binary operators in enum initializers.
21270static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
21271 const EnumDecl *Enum) {
21272 bool HasBitwiseOp = false;
21273 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21274
21275 // Iterate over all the enum values, gather suspisious comparison ops and
21276 // whether any enum initialisers contain a binary operator.
21277 for (const auto *ECD : Enum->enumerators()) {
21278 const Expr *InitExpr = ECD->getInitExpr();
21279 if (!InitExpr)
21280 continue;
21281
21282 const Expr *E = InitExpr->IgnoreParenImpCasts();
21283
21284 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
21285 BinaryOperatorKind Op = BinOp->getOpcode();
21286
21287 // Check for bitwise ops (<<, >>, &, |)
21288 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21289 HasBitwiseOp = true;
21290 } else if (Op == BO_LT || Op == BO_GT) {
21291 // Check for the typo pattern (Comparison < or >)
21292 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21293 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
21294 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21295 if (IntLiteral->getValue() == 1)
21296 SuspiciousCompares.push_back(Elt: BinOp);
21297 }
21298 }
21299 }
21300 }
21301
21302 // If we found a bitwise op and some sus compares, iterate over the compares
21303 // and warn.
21304 if (HasBitwiseOp) {
21305 for (const auto *BinOp : SuspiciousCompares) {
21306 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21307 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
21308 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
21309 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21310
21311 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
21312 << BinOp->getOpcodeStr() << SuggestedOp;
21313
21314 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
21315 << SuggestedOp
21316 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
21317 }
21318 }
21319}
21320
21321void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
21322 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21323 const ParsedAttributesView &Attrs) {
21324 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
21325 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
21326
21327 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
21328 ProcessAPINotes(D: Enum);
21329
21330 if (Enum->isDependentType()) {
21331 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21332 EnumConstantDecl *ECD =
21333 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
21334 if (!ECD) continue;
21335
21336 ECD->setType(EnumType);
21337 }
21338
21339 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
21340 return;
21341 }
21342
21343 // Verify that all the values are okay, compute the size of the values, and
21344 // reverse the list.
21345 unsigned NumNegativeBits = 0;
21346 unsigned NumPositiveBits = 0;
21347 bool MembersRepresentableByInt =
21348 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21349
21350 // Figure out the type that should be used for this enum.
21351 QualType BestType;
21352 unsigned BestWidth;
21353
21354 // C++0x N3000 [conv.prom]p3:
21355 // An rvalue of an unscoped enumeration type whose underlying
21356 // type is not fixed can be converted to an rvalue of the first
21357 // of the following types that can represent all the values of
21358 // the enumeration: int, unsigned int, long int, unsigned long
21359 // int, long long int, or unsigned long long int.
21360 // C99 6.4.4.3p2:
21361 // An identifier declared as an enumeration constant has type int.
21362 // The C99 rule is modified by C23.
21363 QualType BestPromotionType;
21364
21365 bool Packed = Enum->hasAttr<PackedAttr>();
21366 // -fshort-enums is the equivalent to specifying the packed attribute on all
21367 // enum definitions.
21368 if (LangOpts.ShortEnums)
21369 Packed = true;
21370
21371 // If the enum already has a type because it is fixed or dictated by the
21372 // target, promote that type instead of analyzing the enumerators.
21373 if (Enum->isComplete()) {
21374 BestType = Enum->getIntegerType();
21375 if (Context.isPromotableIntegerType(T: BestType))
21376 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21377 else
21378 BestPromotionType = BestType;
21379
21380 BestWidth = Context.getIntWidth(T: BestType);
21381 } else {
21382 bool EnumTooLarge = Context.computeBestEnumTypes(
21383 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21384 BestWidth = Context.getIntWidth(T: BestType);
21385 if (EnumTooLarge)
21386 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21387 }
21388
21389 // Loop over all of the enumerator constants, changing their types to match
21390 // the type of the enum if needed.
21391 for (auto *D : Elements) {
21392 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21393 if (!ECD) continue; // Already issued a diagnostic.
21394
21395 // C99 says the enumerators have int type, but we allow, as an
21396 // extension, the enumerators to be larger than int size. If each
21397 // enumerator value fits in an int, type it as an int, otherwise type it the
21398 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21399 // that X has type 'int', not 'unsigned'.
21400
21401 // Determine whether the value fits into an int.
21402 llvm::APSInt InitVal = ECD->getInitVal();
21403
21404 // If it fits into an integer type, force it. Otherwise force it to match
21405 // the enum decl type.
21406 QualType NewTy;
21407 unsigned NewWidth;
21408 bool NewSign;
21409 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21410 MembersRepresentableByInt) {
21411 // C23 6.7.3.3.3p15:
21412 // The enumeration member type for an enumerated type without fixed
21413 // underlying type upon completion is:
21414 // - int if all the values of the enumeration are representable as an
21415 // int; or,
21416 // - the enumerated type
21417 NewTy = Context.IntTy;
21418 NewWidth = Context.getTargetInfo().getIntWidth();
21419 NewSign = true;
21420 } else if (ECD->getType() == BestType) {
21421 // Already the right type!
21422 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21423 // C++ [dcl.enum]p4: Following the closing brace of an
21424 // enum-specifier, each enumerator has the type of its
21425 // enumeration.
21426 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21427 // with fixed underlying type is the enumerated type.
21428 ECD->setType(EnumType);
21429 continue;
21430 } else {
21431 NewTy = BestType;
21432 NewWidth = BestWidth;
21433 NewSign = BestType->isSignedIntegerOrEnumerationType();
21434 }
21435
21436 // Adjust the APSInt value.
21437 InitVal = InitVal.extOrTrunc(width: NewWidth);
21438 InitVal.setIsSigned(NewSign);
21439 ECD->setInitVal(C: Context, V: InitVal);
21440
21441 // Adjust the Expr initializer and type.
21442 if (ECD->getInitExpr() &&
21443 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21444 ECD->setInitExpr(ImplicitCastExpr::Create(
21445 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21446 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21447 if (getLangOpts().CPlusPlus ||
21448 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21449 // C++ [dcl.enum]p4: Following the closing brace of an
21450 // enum-specifier, each enumerator has the type of its
21451 // enumeration.
21452 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21453 // with fixed underlying type is the enumerated type.
21454 ECD->setType(EnumType);
21455 else
21456 ECD->setType(NewTy);
21457 }
21458
21459 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21460 NumPositiveBits, NumNegativeBits);
21461
21462 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21463 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21464
21465 if (Enum->isClosedFlag()) {
21466 for (Decl *D : Elements) {
21467 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21468 if (!ECD) continue; // Already issued a diagnostic.
21469
21470 llvm::APSInt InitVal = ECD->getInitVal();
21471 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21472 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21473 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21474 << ECD << Enum;
21475 }
21476 }
21477
21478 // Now that the enum type is defined, ensure it's not been underaligned.
21479 if (Enum->hasAttrs())
21480 CheckAlignasUnderalignment(D: Enum);
21481}
21482
21483Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21484 SourceLocation EndLoc) {
21485
21486 FileScopeAsmDecl *New =
21487 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21488 CurContext->addDecl(D: New);
21489 return New;
21490}
21491
21492TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21493 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21494 CurContext->addDecl(D: New);
21495 PushDeclContext(S, DC: New);
21496 PushFunctionScope();
21497 PushCompoundScope(IsStmtExpr: false);
21498 return New;
21499}
21500
21501void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21502 if (Statement)
21503 D->setStmt(Statement);
21504 PopCompoundScope();
21505 PopFunctionScopeInfo();
21506 PopDeclContext();
21507}
21508
21509void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21510 IdentifierInfo* AliasName,
21511 SourceLocation PragmaLoc,
21512 SourceLocation NameLoc,
21513 SourceLocation AliasNameLoc) {
21514 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21515 NameKind: LookupOrdinaryName);
21516 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21517 AttributeCommonInfo::Form::Pragma());
21518 AsmLabelAttr *Attr =
21519 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21520
21521 // If a declaration that:
21522 // 1) declares a function or a variable
21523 // 2) has external linkage
21524 // already exists, add a label attribute to it.
21525 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21526 if (isDeclExternC(D: PrevDecl))
21527 PrevDecl->addAttr(A: Attr);
21528 else
21529 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21530 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21531 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21532 } else
21533 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21534}
21535
21536void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21537 SourceLocation PragmaLoc,
21538 SourceLocation NameLoc) {
21539 NamedDecl *PrevDecl =
21540 LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21541
21542 if (PrevDecl) {
21543 auto *Attr = WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc);
21544 if (checkWeakAttrCompatibility(S&: *this, ND: *PrevDecl, Attr: *Attr))
21545 PrevDecl->addAttr(A: Attr);
21546 } else {
21547 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21548 }
21549}
21550
21551void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21552 IdentifierInfo* AliasName,
21553 SourceLocation PragmaLoc,
21554 SourceLocation NameLoc,
21555 SourceLocation AliasNameLoc) {
21556 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21557 NameKind: LookupOrdinaryName);
21558 WeakInfo W = WeakInfo(Name, NameLoc);
21559
21560 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21561 if (!PrevDecl->hasAttr<AliasAttr>())
21562 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21563 DeclApplyPragmaWeak(S: TUScope, ND, W);
21564 } else {
21565 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21566 }
21567}
21568
21569/// Whether the definition \p FD is only handed to the ASTConsumer, and thus to
21570/// CodeGen, once it is used, so that it is never emitted unless it is used.
21571static bool isEmittedOnlyIfUsed(const FunctionDecl *FD) {
21572 // Lambda call operators are defined by their lambda expressions, which are
21573 // not top-level declarations. Implicit functions and functions defaulted on
21574 // their first declaration are defined when they are used.
21575 return isLambdaMethod(DC: FD) || FD->isImplicit() ||
21576 FD->getCanonicalDecl()->isDefaulted();
21577}
21578
21579/// Whether CodeGen emits \p FD regardless of whether it is used.
21580static bool isEmittedRegardlessOfUses(const Sema &S, const FunctionDecl *FD,
21581 bool Final) {
21582 const FunctionDecl *Def = FD->getDefinition();
21583 if (!Def || Def->hasSkippedBody())
21584 return false;
21585 // Immediate functions are never emitted. Whether an immediate-escalating
21586 // function is immediate is only known once its body is complete, so leave
21587 // that to the check at the end of the translation unit.
21588 const LangOptions &LangOpts = S.getLangOpts();
21589 if (Def->isImmediateFunction() ||
21590 (!Final && LangOpts.CPlusPlus20 && Def->isImmediateEscalating()))
21591 return false;
21592 if (isEmittedOnlyIfUsed(FD: Def))
21593 return false;
21594 // An available externally definition is only emitted to be inlined into its
21595 // callers.
21596 ASTContext &Ctx = S.getASTContext();
21597 if (Ctx.GetGVALinkageForFunction(FD: Def) == GVA_AvailableExternally)
21598 return false;
21599 return Ctx.shouldEmitCUDADecl(D: Def) &&
21600 (LangOpts.EmitAllDecls || Ctx.DeclMustBeEmitted(D: Def));
21601}
21602
21603Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21604 bool Final) {
21605 assert(FD && "Expected non-null FunctionDecl");
21606
21607 // Templates are emitted when they're instantiated.
21608 if (FD->isDependentContext())
21609 return FunctionEmissionStatus::TemplateDiscarded;
21610
21611 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21612 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21613 FD->hasAttr<SYCLExternalAttr>()))
21614 return FunctionEmissionStatus::Emitted;
21615
21616 // Check whether this function is an externally visible definition.
21617 auto IsEmittedForExternalSymbol = [this, FD]() {
21618 // We have to check the GVA linkage of the function's *definition* -- if we
21619 // only have a declaration, we don't know whether or not the function will
21620 // be emitted, because (say) the definition could include "inline".
21621 const FunctionDecl *Def = FD->getDefinition();
21622
21623 // We can't compute linkage when we skip function bodies.
21624 return Def && !Def->hasSkippedBody() &&
21625 !isDiscardableGVALinkage(
21626 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21627 };
21628
21629 if (LangOpts.OpenMPIsTargetDevice) {
21630 // In OpenMP device mode we will not emit host only functions, or functions
21631 // we don't need due to their linkage.
21632 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21633 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21634 // DevTy may be changed later by
21635 // #pragma omp declare target to(*) device_type(*).
21636 // Therefore DevTy having no value does not imply host. The emission status
21637 // will be checked again at the end of compilation unit with Final = true.
21638 if (DevTy)
21639 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21640 return FunctionEmissionStatus::OMPDiscarded;
21641 // If we have an explicit value for the device type, or we are in a target
21642 // declare context, we need to emit all extern and used symbols.
21643 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21644 if (IsEmittedForExternalSymbol())
21645 return FunctionEmissionStatus::Emitted;
21646 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21647 // we'll omit it.
21648 if (Final)
21649 return FunctionEmissionStatus::OMPDiscarded;
21650 } else if (LangOpts.OpenMP > 45) {
21651 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21652 // function. In 5.0, no_host was introduced which might cause a function to
21653 // be omitted.
21654 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21655 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21656 if (DevTy)
21657 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21658 return FunctionEmissionStatus::OMPDiscarded;
21659 }
21660
21661 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21662 return FunctionEmissionStatus::Emitted;
21663
21664 if (LangOpts.CUDA) {
21665 // When compiling for device, host functions are never emitted. Similarly,
21666 // when compiling for host, device and global functions are never emitted.
21667 // (Technically, we do emit a host-side stub for global functions, but this
21668 // doesn't count for our purposes here.)
21669 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21670 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21671 return FunctionEmissionStatus::CUDADiscarded;
21672 if (!LangOpts.CUDAIsDevice &&
21673 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21674 return FunctionEmissionStatus::CUDADiscarded;
21675
21676 if (IsEmittedForExternalSymbol() ||
21677 isEmittedRegardlessOfUses(S: *this, FD, Final))
21678 return FunctionEmissionStatus::Emitted;
21679 }
21680
21681 // Otherwise, the function is known-emitted if it's in our set of
21682 // known-emitted functions.
21683 return FunctionEmissionStatus::Unknown;
21684}
21685
21686bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21687 // Host-side references to a __global__ function refer to the stub, so the
21688 // function itself is never emitted and therefore should not be marked.
21689 // If we have host fn calls kernel fn calls host+device, the HD function
21690 // does not get instantiated on the host. We model this by omitting at the
21691 // call to the kernel from the callgraph. This ensures that, when compiling
21692 // for host, only HD functions actually called from the host get marked as
21693 // known-emitted.
21694 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21695 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21696}
21697
21698bool Sema::isRedefinitionAllowedFor(NamedDecl *D,
21699 SourceLocation NewDefinitionLoc,
21700 NamedDecl **Suggested, bool &Visible) {
21701 Visible = hasVisibleDefinition(D, Suggested);
21702 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21703 // for declaratins which is attached to named modules.
21704 // We only did this if the current module is named module as we have better
21705 // diagnostics for declarations in global module and named modules.
21706 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21707 D->isInNamedModule())
21708 return false;
21709 // The redefinition of D in the **current** TU is allowed if D is invisible or
21710 // D is defined in the global module of other module units or D is defined in
21711 // the same header in a different module.
21712 return D->isInAnotherModuleUnit() || !Visible ||
21713 isFromSameSingleIncludeHeader(PrevD: D, NewLoc: NewDefinitionLoc);
21714}
21715