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/CommentDiagnostic.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/NonTrivialTypeVisitor.h"
28#include "clang/AST/Randstruct.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/HLSLRuntime.h"
33#include "clang/Basic/PartialDiagnostic.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40#include "clang/Sema/CXXFieldCollector.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/DelayedDiagnostic.h"
43#include "clang/Sema/Initialization.h"
44#include "clang/Sema/Lookup.h"
45#include "clang/Sema/ParsedTemplate.h"
46#include "clang/Sema/Scope.h"
47#include "clang/Sema/ScopeInfo.h"
48#include "clang/Sema/SemaInternal.h"
49#include "clang/Sema/Template.h"
50#include "llvm/ADT/SmallString.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/TargetParser/Triple.h"
53#include <algorithm>
54#include <cstring>
55#include <functional>
56#include <optional>
57#include <unordered_map>
58
59using namespace clang;
60using namespace sema;
61
62Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
63 if (OwnedType) {
64 Decl *Group[2] = { OwnedType, Ptr };
65 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
66 }
67
68 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
69}
70
71namespace {
72
73class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
74 public:
75 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
76 bool AllowTemplates = false,
77 bool AllowNonTemplates = true)
78 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
79 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
80 WantExpressionKeywords = false;
81 WantCXXNamedCasts = false;
82 WantRemainingKeywords = false;
83 }
84
85 bool ValidateCandidate(const TypoCorrection &candidate) override {
86 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
87 if (!AllowInvalidDecl && ND->isInvalidDecl())
88 return false;
89
90 if (getAsTypeTemplateDecl(ND))
91 return AllowTemplates;
92
93 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
94 if (!IsType)
95 return false;
96
97 if (AllowNonTemplates)
98 return true;
99
100 // An injected-class-name of a class template (specialization) is valid
101 // as a template or as a non-template.
102 if (AllowTemplates) {
103 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
104 if (!RD || !RD->isInjectedClassName())
105 return false;
106 RD = cast<CXXRecordDecl>(RD->getDeclContext());
107 return RD->getDescribedClassTemplate() ||
108 isa<ClassTemplateSpecializationDecl>(Val: RD);
109 }
110
111 return false;
112 }
113
114 return !WantClassName && candidate.isKeyword();
115 }
116
117 std::unique_ptr<CorrectionCandidateCallback> clone() override {
118 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
119 }
120
121 private:
122 bool AllowInvalidDecl;
123 bool WantClassName;
124 bool AllowTemplates;
125 bool AllowNonTemplates;
126};
127
128} // end anonymous namespace
129
130namespace {
131enum class UnqualifiedTypeNameLookupResult {
132 NotFound,
133 FoundNonType,
134 FoundType
135};
136} // end anonymous namespace
137
138/// Tries to perform unqualified lookup of the type decls in bases for
139/// dependent class.
140/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
141/// type decl, \a FoundType if only type decls are found.
142static UnqualifiedTypeNameLookupResult
143lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
144 SourceLocation NameLoc,
145 const CXXRecordDecl *RD) {
146 if (!RD->hasDefinition())
147 return UnqualifiedTypeNameLookupResult::NotFound;
148 // Look for type decls in base classes.
149 UnqualifiedTypeNameLookupResult FoundTypeDecl =
150 UnqualifiedTypeNameLookupResult::NotFound;
151 for (const auto &Base : RD->bases()) {
152 const CXXRecordDecl *BaseRD = nullptr;
153 if (auto *BaseTT = Base.getType()->getAs<TagType>())
154 BaseRD = BaseTT->getAsCXXRecordDecl();
155 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
156 // Look for type decls in dependent base classes that have known primary
157 // templates.
158 if (!TST || !TST->isDependentType())
159 continue;
160 auto *TD = TST->getTemplateName().getAsTemplateDecl();
161 if (!TD)
162 continue;
163 if (auto *BasePrimaryTemplate =
164 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
165 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
166 BaseRD = BasePrimaryTemplate;
167 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
168 if (const ClassTemplatePartialSpecializationDecl *PS =
169 CTD->findPartialSpecialization(T: Base.getType()))
170 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
171 BaseRD = PS;
172 }
173 }
174 }
175 if (BaseRD) {
176 for (NamedDecl *ND : BaseRD->lookup(&II)) {
177 if (!isa<TypeDecl>(ND))
178 return UnqualifiedTypeNameLookupResult::FoundNonType;
179 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
180 }
181 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
182 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
183 case UnqualifiedTypeNameLookupResult::FoundNonType:
184 return UnqualifiedTypeNameLookupResult::FoundNonType;
185 case UnqualifiedTypeNameLookupResult::FoundType:
186 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
187 break;
188 case UnqualifiedTypeNameLookupResult::NotFound:
189 break;
190 }
191 }
192 }
193 }
194
195 return FoundTypeDecl;
196}
197
198static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
199 const IdentifierInfo &II,
200 SourceLocation NameLoc) {
201 // Lookup in the parent class template context, if any.
202 const CXXRecordDecl *RD = nullptr;
203 UnqualifiedTypeNameLookupResult FoundTypeDecl =
204 UnqualifiedTypeNameLookupResult::NotFound;
205 for (DeclContext *DC = S.CurContext;
206 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
207 DC = DC->getParent()) {
208 // Look for type decls in dependent base classes that have known primary
209 // templates.
210 RD = dyn_cast<CXXRecordDecl>(Val: DC);
211 if (RD && RD->getDescribedClassTemplate())
212 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
213 }
214 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
215 return nullptr;
216
217 // We found some types in dependent base classes. Recover as if the user
218 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
219 // lookup during template instantiation.
220 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
221
222 ASTContext &Context = S.Context;
223 auto *NNS = NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: false,
224 T: cast<Type>(Val: Context.getRecordType(RD)));
225 QualType T =
226 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::Typename, NNS: NNS, Name: &II);
227
228 CXXScopeSpec SS;
229 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
230
231 TypeLocBuilder Builder;
232 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
233 DepTL.setNameLoc(NameLoc);
234 DepTL.setElaboratedKeywordLoc(SourceLocation());
235 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
236 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
237}
238
239/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
240static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
241 SourceLocation NameLoc,
242 bool WantNontrivialTypeSourceInfo = true) {
243 switch (T->getTypeClass()) {
244 case Type::DeducedTemplateSpecialization:
245 case Type::Enum:
246 case Type::InjectedClassName:
247 case Type::Record:
248 case Type::Typedef:
249 case Type::UnresolvedUsing:
250 case Type::Using:
251 break;
252 // These can never be qualified so an ElaboratedType node
253 // would carry no additional meaning.
254 case Type::ObjCInterface:
255 case Type::ObjCTypeParam:
256 case Type::TemplateTypeParm:
257 return ParsedType::make(P: T);
258 default:
259 llvm_unreachable("Unexpected Type Class");
260 }
261
262 if (!SS || SS->isEmpty())
263 return ParsedType::make(P: S.Context.getElaboratedType(
264 Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T, OwnedTagDecl: nullptr));
265
266 QualType ElTy = S.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS: *SS, T);
267 if (!WantNontrivialTypeSourceInfo)
268 return ParsedType::make(P: ElTy);
269
270 TypeLocBuilder Builder;
271 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
272 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T: ElTy);
273 ElabTL.setElaboratedKeywordLoc(SourceLocation());
274 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context&: S.Context));
275 return S.CreateParsedType(T: ElTy, TInfo: Builder.getTypeSourceInfo(Context&: S.Context, T: ElTy));
276}
277
278/// If the identifier refers to a type name within this scope,
279/// return the declaration of that type.
280///
281/// This routine performs ordinary name lookup of the identifier II
282/// within the given scope, with optional C++ scope specifier SS, to
283/// determine whether the name refers to a type. If so, returns an
284/// opaque pointer (actually a QualType) corresponding to that
285/// type. Otherwise, returns NULL.
286ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
287 Scope *S, CXXScopeSpec *SS, bool isClassName,
288 bool HasTrailingDot, ParsedType ObjectTypePtr,
289 bool IsCtorOrDtorName,
290 bool WantNontrivialTypeSourceInfo,
291 bool IsClassTemplateDeductionContext,
292 ImplicitTypenameContext AllowImplicitTypename,
293 IdentifierInfo **CorrectedII) {
294 // FIXME: Consider allowing this outside C++1z mode as an extension.
295 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297 !isClassName && !HasTrailingDot;
298
299 // Determine where we will perform name lookup.
300 DeclContext *LookupCtx = nullptr;
301 if (ObjectTypePtr) {
302 QualType ObjectType = ObjectTypePtr.get();
303 if (ObjectType->isRecordType())
304 LookupCtx = computeDeclContext(T: ObjectType);
305 } else if (SS && SS->isNotEmpty()) {
306 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
307
308 if (!LookupCtx) {
309 if (isDependentScopeSpecifier(SS: *SS)) {
310 // C++ [temp.res]p3:
311 // A qualified-id that refers to a type and in which the
312 // nested-name-specifier depends on a template-parameter (14.6.2)
313 // shall be prefixed by the keyword typename to indicate that the
314 // qualified-id denotes a type, forming an
315 // elaborated-type-specifier (7.1.5.3).
316 //
317 // We therefore do not perform any name lookup if the result would
318 // refer to a member of an unknown specialization.
319 // In C++2a, in several contexts a 'typename' is not required. Also
320 // allow this as an extension.
321 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
322 !isClassName && !IsCtorOrDtorName)
323 return nullptr;
324 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
325 if (IsImplicitTypename) {
326 SourceLocation QualifiedLoc = SS->getRange().getBegin();
327 if (getLangOpts().CPlusPlus20)
328 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
329 else
330 Diag(QualifiedLoc, diag::ext_implicit_typename)
331 << SS->getScopeRep() << II.getName()
332 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
333 }
334
335 // We know from the grammar that this name refers to a type,
336 // so build a dependent node to describe the type.
337 if (WantNontrivialTypeSourceInfo)
338 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
339 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
340 .get();
341
342 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
343 QualType T = CheckTypenameType(
344 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
345 : ElaboratedTypeKeyword::None,
346 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
347 return ParsedType::make(P: T);
348 }
349
350 return nullptr;
351 }
352
353 if (!LookupCtx->isDependentContext() &&
354 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
355 return nullptr;
356 }
357
358 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
359 // lookup for class-names.
360 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
361 LookupOrdinaryName;
362 LookupResult Result(*this, &II, NameLoc, Kind);
363 if (LookupCtx) {
364 // Perform "qualified" name lookup into the declaration context we
365 // computed, which is either the type of the base of a member access
366 // expression or the declaration context associated with a prior
367 // nested-name-specifier.
368 LookupQualifiedName(R&: Result, LookupCtx);
369
370 if (ObjectTypePtr && Result.empty()) {
371 // C++ [basic.lookup.classref]p3:
372 // If the unqualified-id is ~type-name, the type-name is looked up
373 // in the context of the entire postfix-expression. If the type T of
374 // the object expression is of a class type C, the type-name is also
375 // looked up in the scope of class C. At least one of the lookups shall
376 // find a name that refers to (possibly cv-qualified) T.
377 LookupName(R&: Result, S);
378 }
379 } else {
380 // Perform unqualified name lookup.
381 LookupName(R&: Result, S);
382
383 // For unqualified lookup in a class template in MSVC mode, look into
384 // dependent base classes where the primary class template is known.
385 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
386 if (ParsedType TypeInBase =
387 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
388 return TypeInBase;
389 }
390 }
391
392 NamedDecl *IIDecl = nullptr;
393 UsingShadowDecl *FoundUsingShadow = nullptr;
394 switch (Result.getResultKind()) {
395 case LookupResult::NotFound:
396 if (CorrectedII) {
397 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
398 AllowDeducedTemplate);
399 TypoCorrection Correction = CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind,
400 S, SS, CCC, Mode: CTK_ErrorRecovery);
401 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
402 TemplateTy Template;
403 bool MemberOfUnknownSpecialization;
404 UnqualifiedId TemplateName;
405 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
406 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
407 CXXScopeSpec NewSS, *NewSSPtr = SS;
408 if (SS && NNS) {
409 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
410 NewSSPtr = &NewSS;
411 }
412 if (Correction && (NNS || NewII != &II) &&
413 // Ignore a correction to a template type as the to-be-corrected
414 // identifier is not a template (typo correction for template names
415 // is handled elsewhere).
416 !(getLangOpts().CPlusPlus && NewSSPtr &&
417 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
418 Template, MemberOfUnknownSpecialization))) {
419 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
420 isClassName, HasTrailingDot, ObjectTypePtr,
421 IsCtorOrDtorName,
422 WantNontrivialTypeSourceInfo,
423 IsClassTemplateDeductionContext);
424 if (Ty) {
425 diagnoseTypo(Correction,
426 PDiag(diag::err_unknown_type_or_class_name_suggest)
427 << Result.getLookupName() << isClassName);
428 if (SS && NNS)
429 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
430 *CorrectedII = NewII;
431 return Ty;
432 }
433 }
434 }
435 Result.suppressDiagnostics();
436 return nullptr;
437 case LookupResult::NotFoundInCurrentInstantiation:
438 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
439 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
440 NNS: SS->getScopeRep(), Name: &II);
441 TypeLocBuilder TLB;
442 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
443 TL.setElaboratedKeywordLoc(SourceLocation());
444 TL.setQualifierLoc(SS->getWithLocInContext(Context));
445 TL.setNameLoc(NameLoc);
446 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
447 }
448 [[fallthrough]];
449 case LookupResult::FoundOverloaded:
450 case LookupResult::FoundUnresolvedValue:
451 Result.suppressDiagnostics();
452 return nullptr;
453
454 case LookupResult::Ambiguous:
455 // Recover from type-hiding ambiguities by hiding the type. We'll
456 // do the lookup again when looking for an object, and we can
457 // diagnose the error then. If we don't do this, then the error
458 // about hiding the type will be immediately followed by an error
459 // that only makes sense if the identifier was treated like a type.
460 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
461 Result.suppressDiagnostics();
462 return nullptr;
463 }
464
465 // Look to see if we have a type anywhere in the list of results.
466 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
467 Res != ResEnd; ++Res) {
468 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
469 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
470 Val: RealRes) ||
471 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
472 if (!IIDecl ||
473 // Make the selection of the recovery decl deterministic.
474 RealRes->getLocation() < IIDecl->getLocation()) {
475 IIDecl = RealRes;
476 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
477 }
478 }
479 }
480
481 if (!IIDecl) {
482 // None of the entities we found is a type, so there is no way
483 // to even assume that the result is a type. In this case, don't
484 // complain about the ambiguity. The parser will either try to
485 // perform this lookup again (e.g., as an object name), which
486 // will produce the ambiguity, or will complain that it expected
487 // a type name.
488 Result.suppressDiagnostics();
489 return nullptr;
490 }
491
492 // We found a type within the ambiguous lookup; diagnose the
493 // ambiguity and then return that type. This might be the right
494 // answer, or it might not be, but it suppresses any attempt to
495 // perform the name lookup again.
496 break;
497
498 case LookupResult::Found:
499 IIDecl = Result.getFoundDecl();
500 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
501 break;
502 }
503
504 assert(IIDecl && "Didn't find decl");
505
506 QualType T;
507 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
508 // C++ [class.qual]p2: A lookup that would find the injected-class-name
509 // instead names the constructors of the class, except when naming a class.
510 // This is ill-formed when we're not actually forming a ctor or dtor name.
511 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
512 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
513 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
514 FoundRD->isInjectedClassName() &&
515 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
516 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
517 << &II << /*Type*/1;
518
519 DiagnoseUseOfDecl(D: IIDecl, Locs: NameLoc);
520
521 T = Context.getTypeDeclType(Decl: TD);
522 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
523 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
524 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
525 if (!HasTrailingDot)
526 T = Context.getObjCInterfaceType(Decl: IDecl);
527 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
528 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
529 (void)DiagnoseUseOfDecl(UD, NameLoc);
530 // Recover with 'int'
531 return ParsedType::make(P: Context.IntTy);
532 } else if (AllowDeducedTemplate) {
533 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
534 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
535 TemplateName Template =
536 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
537 T = Context.getDeducedTemplateSpecializationType(Template, DeducedType: QualType(),
538 IsDependent: false);
539 // Don't wrap in a further UsingType.
540 FoundUsingShadow = nullptr;
541 }
542 }
543
544 if (T.isNull()) {
545 // If it's not plausibly a type, suppress diagnostics.
546 Result.suppressDiagnostics();
547 return nullptr;
548 }
549
550 if (FoundUsingShadow)
551 T = Context.getUsingType(Found: FoundUsingShadow, Underlying: T);
552
553 return buildNamedType(S&: *this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
554}
555
556// Builds a fake NNS for the given decl context.
557static NestedNameSpecifier *
558synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
559 for (;; DC = DC->getLookupParent()) {
560 DC = DC->getPrimaryContext();
561 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
562 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
563 return NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: ND);
564 else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
565 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
566 RD->getTypeForDecl());
567 else if (isa<TranslationUnitDecl>(Val: DC))
568 return NestedNameSpecifier::GlobalSpecifier(Context);
569 }
570 llvm_unreachable("something isn't in TU scope?");
571}
572
573/// Find the parent class with dependent bases of the innermost enclosing method
574/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
575/// up allowing unqualified dependent type names at class-level, which MSVC
576/// correctly rejects.
577static const CXXRecordDecl *
578findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
579 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
580 DC = DC->getPrimaryContext();
581 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
582 if (MD->getParent()->hasAnyDependentBases())
583 return MD->getParent();
584 }
585 return nullptr;
586}
587
588ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
589 SourceLocation NameLoc,
590 bool IsTemplateTypeArg) {
591 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
592
593 NestedNameSpecifier *NNS = nullptr;
594 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
595 // If we weren't able to parse a default template argument, delay lookup
596 // until instantiation time by making a non-dependent DependentTypeName. We
597 // pretend we saw a NestedNameSpecifier referring to the current scope, and
598 // lookup is retried.
599 // FIXME: This hurts our diagnostic quality, since we get errors like "no
600 // type named 'Foo' in 'current_namespace'" when the user didn't write any
601 // name specifiers.
602 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
603 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
604 } else if (const CXXRecordDecl *RD =
605 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
606 // Build a DependentNameType that will perform lookup into RD at
607 // instantiation time.
608 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
609 RD->getTypeForDecl());
610
611 // Diagnose that this identifier was undeclared, and retry the lookup during
612 // template instantiation.
613 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
614 << RD;
615 } else {
616 // This is not a situation that we should recover from.
617 return ParsedType();
618 }
619
620 QualType T =
621 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
622
623 // Build type location information. We synthesized the qualifier, so we have
624 // to build a fake NestedNameSpecifierLoc.
625 NestedNameSpecifierLocBuilder NNSLocBuilder;
626 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
627 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
628
629 TypeLocBuilder Builder;
630 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
631 DepTL.setNameLoc(NameLoc);
632 DepTL.setElaboratedKeywordLoc(SourceLocation());
633 DepTL.setQualifierLoc(QualifierLoc);
634 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
635}
636
637/// isTagName() - This method is called *for error recovery purposes only*
638/// to determine if the specified name is a valid tag name ("struct foo"). If
639/// so, this returns the TST for the tag corresponding to it (TST_enum,
640/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
641/// cases in C where the user forgot to specify the tag.
642DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
643 // Do a tag name lookup in this scope.
644 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
645 LookupName(R, S, AllowBuiltinCreation: false);
646 R.suppressDiagnostics();
647 if (R.getResultKind() == LookupResult::Found)
648 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
649 switch (TD->getTagKind()) {
650 case TagTypeKind::Struct:
651 return DeclSpec::TST_struct;
652 case TagTypeKind::Interface:
653 return DeclSpec::TST_interface;
654 case TagTypeKind::Union:
655 return DeclSpec::TST_union;
656 case TagTypeKind::Class:
657 return DeclSpec::TST_class;
658 case TagTypeKind::Enum:
659 return DeclSpec::TST_enum;
660 }
661 }
662
663 return DeclSpec::TST_unspecified;
664}
665
666/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
667/// if a CXXScopeSpec's type is equal to the type of one of the base classes
668/// then downgrade the missing typename error to a warning.
669/// This is needed for MSVC compatibility; Example:
670/// @code
671/// template<class T> class A {
672/// public:
673/// typedef int TYPE;
674/// };
675/// template<class T> class B : public A<T> {
676/// public:
677/// A<T>::TYPE a; // no typename required because A<T> is a base class.
678/// };
679/// @endcode
680bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
681 if (CurContext->isRecord()) {
682 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
683 return true;
684
685 const Type *Ty = SS->getScopeRep()->getAsType();
686
687 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: CurContext);
688 for (const auto &Base : RD->bases())
689 if (Ty && Context.hasSameUnqualifiedType(T1: QualType(Ty, 1), T2: Base.getType()))
690 return true;
691 return S->isFunctionPrototypeScope();
692 }
693 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
694}
695
696void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
697 SourceLocation IILoc,
698 Scope *S,
699 CXXScopeSpec *SS,
700 ParsedType &SuggestedType,
701 bool IsTemplateName) {
702 // Don't report typename errors for editor placeholders.
703 if (II->isEditorPlaceholder())
704 return;
705 // We don't have anything to suggest (yet).
706 SuggestedType = nullptr;
707
708 // There may have been a typo in the name of the type. Look up typo
709 // results, in case we have something that we can suggest.
710 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
711 /*AllowTemplates=*/IsTemplateName,
712 /*AllowNonTemplates=*/!IsTemplateName);
713 if (TypoCorrection Corrected =
714 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
715 CCC, Mode: CTK_ErrorRecovery)) {
716 // FIXME: Support error recovery for the template-name case.
717 bool CanRecover = !IsTemplateName;
718 if (Corrected.isKeyword()) {
719 // We corrected to a keyword.
720 diagnoseTypo(Corrected,
721 PDiag(IsTemplateName ? diag::err_no_template_suggest
722 : diag::err_unknown_typename_suggest)
723 << II);
724 II = Corrected.getCorrectionAsIdentifierInfo();
725 } else {
726 // We found a similarly-named type or interface; suggest that.
727 if (!SS || !SS->isSet()) {
728 diagnoseTypo(Corrected,
729 PDiag(IsTemplateName ? diag::err_no_template_suggest
730 : diag::err_unknown_typename_suggest)
731 << II, CanRecover);
732 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
733 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
734 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
735 II->getName().equals(RHS: CorrectedStr);
736 diagnoseTypo(Corrected,
737 PDiag(IsTemplateName
738 ? diag::err_no_member_template_suggest
739 : diag::err_unknown_nested_typename_suggest)
740 << II << DC << DroppedSpecifier << SS->getRange(),
741 CanRecover);
742 } else {
743 llvm_unreachable("could not have corrected a typo here");
744 }
745
746 if (!CanRecover)
747 return;
748
749 CXXScopeSpec tmpSS;
750 if (Corrected.getCorrectionSpecifier())
751 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
752 R: SourceRange(IILoc));
753 // FIXME: Support class template argument deduction here.
754 SuggestedType =
755 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
756 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
757 /*IsCtorOrDtorName=*/false,
758 /*WantNontrivialTypeSourceInfo=*/true);
759 }
760 return;
761 }
762
763 if (getLangOpts().CPlusPlus && !IsTemplateName) {
764 // See if II is a class template that the user forgot to pass arguments to.
765 UnqualifiedId Name;
766 Name.setIdentifier(Id: II, IdLoc: IILoc);
767 CXXScopeSpec EmptySS;
768 TemplateTy TemplateResult;
769 bool MemberOfUnknownSpecialization;
770 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
771 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
772 MemberOfUnknownSpecialization) == TNK_Type_template) {
773 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
774 return;
775 }
776 }
777
778 // FIXME: Should we move the logic that tries to recover from a missing tag
779 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
780
781 if (!SS || (!SS->isSet() && !SS->isInvalid()))
782 Diag(IILoc, IsTemplateName ? diag::err_no_template
783 : diag::err_unknown_typename)
784 << II;
785 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
786 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
787 : diag::err_typename_nested_not_found)
788 << II << DC << SS->getRange();
789 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
790 SuggestedType =
791 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
792 } else if (isDependentScopeSpecifier(SS: *SS)) {
793 unsigned DiagID = diag::err_typename_missing;
794 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
795 DiagID = diag::ext_typename_missing;
796
797 Diag(Loc: SS->getRange().getBegin(), DiagID)
798 << SS->getScopeRep() << II->getName()
799 << SourceRange(SS->getRange().getBegin(), IILoc)
800 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
801 SuggestedType = ActOnTypenameType(S, TypenameLoc: SourceLocation(),
802 SS: *SS, II: *II, IdLoc: IILoc).get();
803 } else {
804 assert(SS && SS->isInvalid() &&
805 "Invalid scope specifier has already been diagnosed");
806 }
807}
808
809/// Determine whether the given result set contains either a type name
810/// or
811static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
812 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
813 NextToken.is(K: tok::less);
814
815 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
816 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
817 return true;
818
819 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
820 return true;
821 }
822
823 return false;
824}
825
826static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
827 Scope *S, CXXScopeSpec &SS,
828 IdentifierInfo *&Name,
829 SourceLocation NameLoc) {
830 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
831 SemaRef.LookupParsedName(R, S, SS: &SS);
832 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
833 StringRef FixItTagName;
834 switch (Tag->getTagKind()) {
835 case TagTypeKind::Class:
836 FixItTagName = "class ";
837 break;
838
839 case TagTypeKind::Enum:
840 FixItTagName = "enum ";
841 break;
842
843 case TagTypeKind::Struct:
844 FixItTagName = "struct ";
845 break;
846
847 case TagTypeKind::Interface:
848 FixItTagName = "__interface ";
849 break;
850
851 case TagTypeKind::Union:
852 FixItTagName = "union ";
853 break;
854 }
855
856 StringRef TagName = FixItTagName.drop_back();
857 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
858 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
859 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
860
861 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
862 I != IEnd; ++I)
863 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
864 << Name << TagName;
865
866 // Replace lookup results with just the tag decl.
867 Result.clear(Kind: Sema::LookupTagName);
868 SemaRef.LookupParsedName(R&: Result, S, SS: &SS);
869 return true;
870 }
871
872 return false;
873}
874
875Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
876 IdentifierInfo *&Name,
877 SourceLocation NameLoc,
878 const Token &NextToken,
879 CorrectionCandidateCallback *CCC) {
880 DeclarationNameInfo NameInfo(Name, NameLoc);
881 ObjCMethodDecl *CurMethod = getCurMethodDecl();
882
883 assert(NextToken.isNot(tok::coloncolon) &&
884 "parse nested name specifiers before calling ClassifyName");
885 if (getLangOpts().CPlusPlus && SS.isSet() &&
886 isCurrentClassName(II: *Name, S, SS: &SS)) {
887 // Per [class.qual]p2, this names the constructors of SS, not the
888 // injected-class-name. We don't have a classification for that.
889 // There's not much point caching this result, since the parser
890 // will reject it later.
891 return NameClassification::Unknown();
892 }
893
894 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
895 LookupParsedName(R&: Result, S, SS: &SS, AllowBuiltinCreation: !CurMethod);
896
897 if (SS.isInvalid())
898 return NameClassification::Error();
899
900 // For unqualified lookup in a class template in MSVC mode, look into
901 // dependent base classes where the primary class template is known.
902 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
903 if (ParsedType TypeInBase =
904 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
905 return TypeInBase;
906 }
907
908 // Perform lookup for Objective-C instance variables (including automatically
909 // synthesized instance variables), if we're in an Objective-C method.
910 // FIXME: This lookup really, really needs to be folded in to the normal
911 // unqualified lookup mechanism.
912 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
913 DeclResult Ivar = LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
914 if (Ivar.isInvalid())
915 return NameClassification::Error();
916 if (Ivar.isUsable())
917 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
918
919 // We defer builtin creation until after ivar lookup inside ObjC methods.
920 if (Result.empty())
921 LookupBuiltin(R&: Result);
922 }
923
924 bool SecondTry = false;
925 bool IsFilteredTemplateName = false;
926
927Corrected:
928 switch (Result.getResultKind()) {
929 case LookupResult::NotFound:
930 // If an unqualified-id is followed by a '(', then we have a function
931 // call.
932 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
933 // In C++, this is an ADL-only call.
934 // FIXME: Reference?
935 if (getLangOpts().CPlusPlus)
936 return NameClassification::UndeclaredNonType();
937
938 // C90 6.3.2.2:
939 // If the expression that precedes the parenthesized argument list in a
940 // function call consists solely of an identifier, and if no
941 // declaration is visible for this identifier, the identifier is
942 // implicitly declared exactly as if, in the innermost block containing
943 // the function call, the declaration
944 //
945 // extern int identifier ();
946 //
947 // appeared.
948 //
949 // We also allow this in C99 as an extension. However, this is not
950 // allowed in all language modes as functions without prototypes may not
951 // be supported.
952 if (getLangOpts().implicitFunctionsAllowed()) {
953 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
954 return NameClassification::NonType(D);
955 }
956 }
957
958 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
959 // In C++20 onwards, this could be an ADL-only call to a function
960 // template, and we're required to assume that this is a template name.
961 //
962 // FIXME: Find a way to still do typo correction in this case.
963 TemplateName Template =
964 Context.getAssumedTemplateName(Name: NameInfo.getName());
965 return NameClassification::UndeclaredTemplate(Name: Template);
966 }
967
968 // In C, we first see whether there is a tag type by the same name, in
969 // which case it's likely that the user just forgot to write "enum",
970 // "struct", or "union".
971 if (!getLangOpts().CPlusPlus && !SecondTry &&
972 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
973 break;
974 }
975
976 // Perform typo correction to determine if there is another name that is
977 // close to this name.
978 if (!SecondTry && CCC) {
979 SecondTry = true;
980 if (TypoCorrection Corrected =
981 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
982 SS: &SS, CCC&: *CCC, Mode: CTK_ErrorRecovery)) {
983 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
984 unsigned QualifiedDiag = diag::err_no_member_suggest;
985
986 NamedDecl *FirstDecl = Corrected.getFoundDecl();
987 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
988 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
989 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
990 UnqualifiedDiag = diag::err_no_template_suggest;
991 QualifiedDiag = diag::err_no_member_template_suggest;
992 } else if (UnderlyingFirstDecl &&
993 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
994 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
995 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
996 UnqualifiedDiag = diag::err_unknown_typename_suggest;
997 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
998 }
999
1000 if (SS.isEmpty()) {
1001 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1002 } else {// FIXME: is this even reachable? Test it.
1003 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1004 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1005 Name->getName().equals(RHS: CorrectedStr);
1006 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1007 << Name << computeDeclContext(SS, EnteringContext: false)
1008 << DroppedSpecifier << SS.getRange());
1009 }
1010
1011 // Update the name, so that the caller has the new name.
1012 Name = Corrected.getCorrectionAsIdentifierInfo();
1013
1014 // Typo correction corrected to a keyword.
1015 if (Corrected.isKeyword())
1016 return Name;
1017
1018 // Also update the LookupResult...
1019 // FIXME: This should probably go away at some point
1020 Result.clear();
1021 Result.setLookupName(Corrected.getCorrection());
1022 if (FirstDecl)
1023 Result.addDecl(D: FirstDecl);
1024
1025 // If we found an Objective-C instance variable, let
1026 // LookupInObjCMethod build the appropriate expression to
1027 // reference the ivar.
1028 // FIXME: This is a gross hack.
1029 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1030 DeclResult R =
1031 LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1032 if (R.isInvalid())
1033 return NameClassification::Error();
1034 if (R.isUsable())
1035 return NameClassification::NonType(Ivar);
1036 }
1037
1038 goto Corrected;
1039 }
1040 }
1041
1042 // We failed to correct; just fall through and let the parser deal with it.
1043 Result.suppressDiagnostics();
1044 return NameClassification::Unknown();
1045
1046 case LookupResult::NotFoundInCurrentInstantiation: {
1047 // We performed name lookup into the current instantiation, and there were
1048 // dependent bases, so we treat this result the same way as any other
1049 // dependent nested-name-specifier.
1050
1051 // C++ [temp.res]p2:
1052 // A name used in a template declaration or definition and that is
1053 // dependent on a template-parameter is assumed not to name a type
1054 // unless the applicable name lookup finds a type name or the name is
1055 // qualified by the keyword typename.
1056 //
1057 // FIXME: If the next token is '<', we might want to ask the parser to
1058 // perform some heroics to see if we actually have a
1059 // template-argument-list, which would indicate a missing 'template'
1060 // keyword here.
1061 return NameClassification::DependentNonType();
1062 }
1063
1064 case LookupResult::Found:
1065 case LookupResult::FoundOverloaded:
1066 case LookupResult::FoundUnresolvedValue:
1067 break;
1068
1069 case LookupResult::Ambiguous:
1070 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1071 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1072 /*AllowDependent=*/false)) {
1073 // C++ [temp.local]p3:
1074 // A lookup that finds an injected-class-name (10.2) can result in an
1075 // ambiguity in certain cases (for example, if it is found in more than
1076 // one base class). If all of the injected-class-names that are found
1077 // refer to specializations of the same class template, and if the name
1078 // is followed by a template-argument-list, the reference refers to the
1079 // class template itself and not a specialization thereof, and is not
1080 // ambiguous.
1081 //
1082 // This filtering can make an ambiguous result into an unambiguous one,
1083 // so try again after filtering out template names.
1084 FilterAcceptableTemplateNames(R&: Result);
1085 if (!Result.isAmbiguous()) {
1086 IsFilteredTemplateName = true;
1087 break;
1088 }
1089 }
1090
1091 // Diagnose the ambiguity and return an error.
1092 return NameClassification::Error();
1093 }
1094
1095 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1096 (IsFilteredTemplateName ||
1097 hasAnyAcceptableTemplateNames(
1098 R&: Result, /*AllowFunctionTemplates=*/true,
1099 /*AllowDependent=*/false,
1100 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1101 getLangOpts().CPlusPlus20))) {
1102 // C++ [temp.names]p3:
1103 // After name lookup (3.4) finds that a name is a template-name or that
1104 // an operator-function-id or a literal- operator-id refers to a set of
1105 // overloaded functions any member of which is a function template if
1106 // this is followed by a <, the < is always taken as the delimiter of a
1107 // template-argument-list and never as the less-than operator.
1108 // C++2a [temp.names]p2:
1109 // A name is also considered to refer to a template if it is an
1110 // unqualified-id followed by a < and name lookup finds either one
1111 // or more functions or finds nothing.
1112 if (!IsFilteredTemplateName)
1113 FilterAcceptableTemplateNames(R&: Result);
1114
1115 bool IsFunctionTemplate;
1116 bool IsVarTemplate;
1117 TemplateName Template;
1118 if (Result.end() - Result.begin() > 1) {
1119 IsFunctionTemplate = true;
1120 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1121 End: Result.end());
1122 } else if (!Result.empty()) {
1123 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1124 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1125 /*AllowDependent=*/false));
1126 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1127 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1128
1129 UsingShadowDecl *FoundUsingShadow =
1130 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1131 assert(!FoundUsingShadow ||
1132 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1133 Template =
1134 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1135 if (SS.isNotEmpty())
1136 Template = Context.getQualifiedTemplateName(NNS: SS.getScopeRep(),
1137 /*TemplateKeyword=*/false,
1138 Template);
1139 } else {
1140 // All results were non-template functions. This is a function template
1141 // name.
1142 IsFunctionTemplate = true;
1143 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1144 }
1145
1146 if (IsFunctionTemplate) {
1147 // Function templates always go through overload resolution, at which
1148 // point we'll perform the various checks (e.g., accessibility) we need
1149 // to based on which function we selected.
1150 Result.suppressDiagnostics();
1151
1152 return NameClassification::FunctionTemplate(Name: Template);
1153 }
1154
1155 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1156 : NameClassification::TypeTemplate(Name: Template);
1157 }
1158
1159 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1160 QualType T = Context.getTypeDeclType(Decl: Type);
1161 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found))
1162 T = Context.getUsingType(Found: USD, Underlying: T);
1163 return buildNamedType(S&: *this, SS: &SS, T, NameLoc);
1164 };
1165
1166 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1167 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1168 DiagnoseUseOfDecl(Type, NameLoc);
1169 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1170 return BuildTypeFor(Type, *Result.begin());
1171 }
1172
1173 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1174 if (!Class) {
1175 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1176 if (ObjCCompatibleAliasDecl *Alias =
1177 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1178 Class = Alias->getClassInterface();
1179 }
1180
1181 if (Class) {
1182 DiagnoseUseOfDecl(Class, NameLoc);
1183
1184 if (NextToken.is(K: tok::period)) {
1185 // Interface. <something> is parsed as a property reference expression.
1186 // Just return "unknown" as a fall-through for now.
1187 Result.suppressDiagnostics();
1188 return NameClassification::Unknown();
1189 }
1190
1191 QualType T = Context.getObjCInterfaceType(Decl: Class);
1192 return ParsedType::make(P: T);
1193 }
1194
1195 if (isa<ConceptDecl>(Val: FirstDecl))
1196 return NameClassification::Concept(
1197 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1198
1199 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1200 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1201 return NameClassification::Error();
1202 }
1203
1204 // We can have a type template here if we're classifying a template argument.
1205 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1206 !isa<VarTemplateDecl>(Val: FirstDecl))
1207 return NameClassification::TypeTemplate(
1208 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1209
1210 // Check for a tag type hidden by a non-type decl in a few cases where it
1211 // seems likely a type is wanted instead of the non-type that was found.
1212 bool NextIsOp = NextToken.isOneOf(K1: tok::amp, K2: tok::star);
1213 if ((NextToken.is(K: tok::identifier) ||
1214 (NextIsOp &&
1215 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1216 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1217 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1218 DiagnoseUseOfDecl(Type, NameLoc);
1219 return BuildTypeFor(Type, *Result.begin());
1220 }
1221
1222 // If we already know which single declaration is referenced, just annotate
1223 // that declaration directly. Defer resolving even non-overloaded class
1224 // member accesses, as we need to defer certain access checks until we know
1225 // the context.
1226 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1227 if (Result.isSingleResult() && !ADL &&
1228 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1229 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1230
1231 // Otherwise, this is an overload set that we will need to resolve later.
1232 Result.suppressDiagnostics();
1233 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1234 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1235 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Overloaded: Result.isOverloadedResult(),
1236 Begin: Result.begin(), End: Result.end()));
1237}
1238
1239ExprResult
1240Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1241 SourceLocation NameLoc) {
1242 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1243 CXXScopeSpec SS;
1244 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1245 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1246}
1247
1248ExprResult
1249Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1250 IdentifierInfo *Name,
1251 SourceLocation NameLoc,
1252 bool IsAddressOfOperand) {
1253 DeclarationNameInfo NameInfo(Name, NameLoc);
1254 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1255 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1256 /*TemplateArgs=*/nullptr);
1257}
1258
1259ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1260 NamedDecl *Found,
1261 SourceLocation NameLoc,
1262 const Token &NextToken) {
1263 if (getCurMethodDecl() && SS.isEmpty())
1264 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1265 return BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1266
1267 // Reconstruct the lookup result.
1268 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1269 Result.addDecl(D: Found);
1270 Result.resolveKind();
1271
1272 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1273 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1274}
1275
1276ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1277 // For an implicit class member access, transform the result into a member
1278 // access expression if necessary.
1279 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1280 if ((*ULE->decls_begin())->isCXXClassMember()) {
1281 CXXScopeSpec SS;
1282 SS.Adopt(Other: ULE->getQualifierLoc());
1283
1284 // Reconstruct the lookup result.
1285 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1286 LookupOrdinaryName);
1287 Result.setNamingClass(ULE->getNamingClass());
1288 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1289 Result.addDecl(*I, I.getAccess());
1290 Result.resolveKind();
1291 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1292 TemplateArgs: nullptr, S);
1293 }
1294
1295 // Otherwise, this is already in the form we needed, and no further checks
1296 // are necessary.
1297 return ULE;
1298}
1299
1300Sema::TemplateNameKindForDiagnostics
1301Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1302 auto *TD = Name.getAsTemplateDecl();
1303 if (!TD)
1304 return TemplateNameKindForDiagnostics::DependentTemplate;
1305 if (isa<ClassTemplateDecl>(Val: TD))
1306 return TemplateNameKindForDiagnostics::ClassTemplate;
1307 if (isa<FunctionTemplateDecl>(Val: TD))
1308 return TemplateNameKindForDiagnostics::FunctionTemplate;
1309 if (isa<VarTemplateDecl>(Val: TD))
1310 return TemplateNameKindForDiagnostics::VarTemplate;
1311 if (isa<TypeAliasTemplateDecl>(Val: TD))
1312 return TemplateNameKindForDiagnostics::AliasTemplate;
1313 if (isa<TemplateTemplateParmDecl>(Val: TD))
1314 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1315 if (isa<ConceptDecl>(Val: TD))
1316 return TemplateNameKindForDiagnostics::Concept;
1317 return TemplateNameKindForDiagnostics::DependentTemplate;
1318}
1319
1320void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1321 assert(DC->getLexicalParent() == CurContext &&
1322 "The next DeclContext should be lexically contained in the current one.");
1323 CurContext = DC;
1324 S->setEntity(DC);
1325}
1326
1327void Sema::PopDeclContext() {
1328 assert(CurContext && "DeclContext imbalance!");
1329
1330 CurContext = CurContext->getLexicalParent();
1331 assert(CurContext && "Popped translation unit!");
1332}
1333
1334Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1335 Decl *D) {
1336 // Unlike PushDeclContext, the context to which we return is not necessarily
1337 // the containing DC of TD, because the new context will be some pre-existing
1338 // TagDecl definition instead of a fresh one.
1339 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1340 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1341 assert(CurContext && "skipping definition of undefined tag");
1342 // Start lookups from the parent of the current context; we don't want to look
1343 // into the pre-existing complete definition.
1344 S->setEntity(CurContext->getLookupParent());
1345 return Result;
1346}
1347
1348void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1349 CurContext = static_cast<decltype(CurContext)>(Context);
1350}
1351
1352/// EnterDeclaratorContext - Used when we must lookup names in the context
1353/// of a declarator's nested name specifier.
1354///
1355void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1356 // C++0x [basic.lookup.unqual]p13:
1357 // A name used in the definition of a static data member of class
1358 // X (after the qualified-id of the static member) is looked up as
1359 // if the name was used in a member function of X.
1360 // C++0x [basic.lookup.unqual]p14:
1361 // If a variable member of a namespace is defined outside of the
1362 // scope of its namespace then any name used in the definition of
1363 // the variable member (after the declarator-id) is looked up as
1364 // if the definition of the variable member occurred in its
1365 // namespace.
1366 // Both of these imply that we should push a scope whose context
1367 // is the semantic context of the declaration. We can't use
1368 // PushDeclContext here because that context is not necessarily
1369 // lexically contained in the current context. Fortunately,
1370 // the containing scope should have the appropriate information.
1371
1372 assert(!S->getEntity() && "scope already has entity");
1373
1374#ifndef NDEBUG
1375 Scope *Ancestor = S->getParent();
1376 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1377 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1378#endif
1379
1380 CurContext = DC;
1381 S->setEntity(DC);
1382
1383 if (S->getParent()->isTemplateParamScope()) {
1384 // Also set the corresponding entities for all immediately-enclosing
1385 // template parameter scopes.
1386 EnterTemplatedContext(S: S->getParent(), DC);
1387 }
1388}
1389
1390void Sema::ExitDeclaratorContext(Scope *S) {
1391 assert(S->getEntity() == CurContext && "Context imbalance!");
1392
1393 // Switch back to the lexical context. The safety of this is
1394 // enforced by an assert in EnterDeclaratorContext.
1395 Scope *Ancestor = S->getParent();
1396 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1397 CurContext = Ancestor->getEntity();
1398
1399 // We don't need to do anything with the scope, which is going to
1400 // disappear.
1401}
1402
1403void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1404 assert(S->isTemplateParamScope() &&
1405 "expected to be initializing a template parameter scope");
1406
1407 // C++20 [temp.local]p7:
1408 // In the definition of a member of a class template that appears outside
1409 // of the class template definition, the name of a member of the class
1410 // template hides the name of a template-parameter of any enclosing class
1411 // templates (but not a template-parameter of the member if the member is a
1412 // class or function template).
1413 // C++20 [temp.local]p9:
1414 // In the definition of a class template or in the definition of a member
1415 // of such a template that appears outside of the template definition, for
1416 // each non-dependent base class (13.8.2.1), if the name of the base class
1417 // or the name of a member of the base class is the same as the name of a
1418 // template-parameter, the base class name or member name hides the
1419 // template-parameter name (6.4.10).
1420 //
1421 // This means that a template parameter scope should be searched immediately
1422 // after searching the DeclContext for which it is a template parameter
1423 // scope. For example, for
1424 // template<typename T> template<typename U> template<typename V>
1425 // void N::A<T>::B<U>::f(...)
1426 // we search V then B<U> (and base classes) then U then A<T> (and base
1427 // classes) then T then N then ::.
1428 unsigned ScopeDepth = getTemplateDepth(S);
1429 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1430 DeclContext *SearchDCAfterScope = DC;
1431 for (; DC; DC = DC->getLookupParent()) {
1432 if (const TemplateParameterList *TPL =
1433 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1434 unsigned DCDepth = TPL->getDepth() + 1;
1435 if (DCDepth > ScopeDepth)
1436 continue;
1437 if (ScopeDepth == DCDepth)
1438 SearchDCAfterScope = DC = DC->getLookupParent();
1439 break;
1440 }
1441 }
1442 S->setLookupEntity(SearchDCAfterScope);
1443 }
1444}
1445
1446void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1447 // We assume that the caller has already called
1448 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1449 FunctionDecl *FD = D->getAsFunction();
1450 if (!FD)
1451 return;
1452
1453 // Same implementation as PushDeclContext, but enters the context
1454 // from the lexical parent, rather than the top-level class.
1455 assert(CurContext == FD->getLexicalParent() &&
1456 "The next DeclContext should be lexically contained in the current one.");
1457 CurContext = FD;
1458 S->setEntity(CurContext);
1459
1460 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1461 ParmVarDecl *Param = FD->getParamDecl(i: P);
1462 // If the parameter has an identifier, then add it to the scope
1463 if (Param->getIdentifier()) {
1464 S->AddDecl(Param);
1465 IdResolver.AddDecl(Param);
1466 }
1467 }
1468}
1469
1470void Sema::ActOnExitFunctionContext() {
1471 // Same implementation as PopDeclContext, but returns to the lexical parent,
1472 // rather than the top-level class.
1473 assert(CurContext && "DeclContext imbalance!");
1474 CurContext = CurContext->getLexicalParent();
1475 assert(CurContext && "Popped translation unit!");
1476}
1477
1478/// Determine whether overloading is allowed for a new function
1479/// declaration considering prior declarations of the same name.
1480///
1481/// This routine determines whether overloading is possible, not
1482/// whether a new declaration actually overloads a previous one.
1483/// It will return true in C++ (where overloads are alway permitted)
1484/// or, as a C extension, when either the new declaration or a
1485/// previous one is declared with the 'overloadable' attribute.
1486static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1487 ASTContext &Context,
1488 const FunctionDecl *New) {
1489 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1490 return true;
1491
1492 // Multiversion function declarations are not overloads in the
1493 // usual sense of that term, but lookup will report that an
1494 // overload set was found if more than one multiversion function
1495 // declaration is present for the same name. It is therefore
1496 // inadequate to assume that some prior declaration(s) had
1497 // the overloadable attribute; checking is required. Since one
1498 // declaration is permitted to omit the attribute, it is necessary
1499 // to check at least two; hence the 'any_of' check below. Note that
1500 // the overloadable attribute is implicitly added to declarations
1501 // that were required to have it but did not.
1502 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1503 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1504 return ND->hasAttr<OverloadableAttr>();
1505 });
1506 } else if (Previous.getResultKind() == LookupResult::Found)
1507 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1508
1509 return false;
1510}
1511
1512/// Add this decl to the scope shadowed decl chains.
1513void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1514 // Move up the scope chain until we find the nearest enclosing
1515 // non-transparent context. The declaration will be introduced into this
1516 // scope.
1517 while (S->getEntity() && S->getEntity()->isTransparentContext())
1518 S = S->getParent();
1519
1520 // Add scoped declarations into their context, so that they can be
1521 // found later. Declarations without a context won't be inserted
1522 // into any context.
1523 if (AddToContext)
1524 CurContext->addDecl(D);
1525
1526 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1527 // are function-local declarations.
1528 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1529 return;
1530
1531 // Template instantiations should also not be pushed into scope.
1532 if (isa<FunctionDecl>(Val: D) &&
1533 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1534 return;
1535
1536 // If this replaces anything in the current scope,
1537 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1538 IEnd = IdResolver.end();
1539 for (; I != IEnd; ++I) {
1540 if (S->isDeclScope(*I) && D->declarationReplaces(OldD: *I)) {
1541 S->RemoveDecl(*I);
1542 IdResolver.RemoveDecl(D: *I);
1543
1544 // Should only need to replace one decl.
1545 break;
1546 }
1547 }
1548
1549 S->AddDecl(D);
1550
1551 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1552 // Implicitly-generated labels may end up getting generated in an order that
1553 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1554 // the label at the appropriate place in the identifier chain.
1555 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1556 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1557 if (IDC == CurContext) {
1558 if (!S->isDeclScope(*I))
1559 continue;
1560 } else if (IDC->Encloses(DC: CurContext))
1561 break;
1562 }
1563
1564 IdResolver.InsertDeclAfter(Pos: I, D);
1565 } else {
1566 IdResolver.AddDecl(D);
1567 }
1568 warnOnReservedIdentifier(D);
1569}
1570
1571bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1572 bool AllowInlineNamespace) const {
1573 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1574}
1575
1576Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1577 DeclContext *TargetDC = DC->getPrimaryContext();
1578 do {
1579 if (DeclContext *ScopeDC = S->getEntity())
1580 if (ScopeDC->getPrimaryContext() == TargetDC)
1581 return S;
1582 } while ((S = S->getParent()));
1583
1584 return nullptr;
1585}
1586
1587static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1588 DeclContext*,
1589 ASTContext&);
1590
1591/// Filters out lookup results that don't fall within the given scope
1592/// as determined by isDeclInScope.
1593void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1594 bool ConsiderLinkage,
1595 bool AllowInlineNamespace) {
1596 LookupResult::Filter F = R.makeFilter();
1597 while (F.hasNext()) {
1598 NamedDecl *D = F.next();
1599
1600 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1601 continue;
1602
1603 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1604 continue;
1605
1606 F.erase();
1607 }
1608
1609 F.done();
1610}
1611
1612/// We've determined that \p New is a redeclaration of \p Old. Check that they
1613/// have compatible owning modules.
1614bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1615 // [module.interface]p7:
1616 // A declaration is attached to a module as follows:
1617 // - If the declaration is a non-dependent friend declaration that nominates a
1618 // function with a declarator-id that is a qualified-id or template-id or that
1619 // nominates a class other than with an elaborated-type-specifier with neither
1620 // a nested-name-specifier nor a simple-template-id, it is attached to the
1621 // module to which the friend is attached ([basic.link]).
1622 if (New->getFriendObjectKind() &&
1623 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1624 New->setLocalOwningModule(Old->getOwningModule());
1625 makeMergedDefinitionVisible(ND: New);
1626 return false;
1627 }
1628
1629 Module *NewM = New->getOwningModule();
1630 Module *OldM = Old->getOwningModule();
1631
1632 if (NewM && NewM->isPrivateModule())
1633 NewM = NewM->Parent;
1634 if (OldM && OldM->isPrivateModule())
1635 OldM = OldM->Parent;
1636
1637 if (NewM == OldM)
1638 return false;
1639
1640 if (NewM && OldM) {
1641 // A module implementation unit has visibility of the decls in its
1642 // implicitly imported interface.
1643 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1644 return false;
1645
1646 // Partitions are part of the module, but a partition could import another
1647 // module, so verify that the PMIs agree.
1648 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1649 NewM->getPrimaryModuleInterfaceName() ==
1650 OldM->getPrimaryModuleInterfaceName())
1651 return false;
1652 }
1653
1654 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1655 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1656 if (NewIsModuleInterface || OldIsModuleInterface) {
1657 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1658 // if a declaration of D [...] appears in the purview of a module, all
1659 // other such declarations shall appear in the purview of the same module
1660 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1661 << New
1662 << NewIsModuleInterface
1663 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1664 << OldIsModuleInterface
1665 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1666 Diag(Old->getLocation(), diag::note_previous_declaration);
1667 New->setInvalidDecl();
1668 return true;
1669 }
1670
1671 return false;
1672}
1673
1674// [module.interface]p6:
1675// A redeclaration of an entity X is implicitly exported if X was introduced by
1676// an exported declaration; otherwise it shall not be exported.
1677bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1678 // [module.interface]p1:
1679 // An export-declaration shall inhabit a namespace scope.
1680 //
1681 // So it is meaningless to talk about redeclaration which is not at namespace
1682 // scope.
1683 if (!New->getLexicalDeclContext()
1684 ->getNonTransparentContext()
1685 ->isFileContext() ||
1686 !Old->getLexicalDeclContext()
1687 ->getNonTransparentContext()
1688 ->isFileContext())
1689 return false;
1690
1691 bool IsNewExported = New->isInExportDeclContext();
1692 bool IsOldExported = Old->isInExportDeclContext();
1693
1694 // It should be irrevelant if both of them are not exported.
1695 if (!IsNewExported && !IsOldExported)
1696 return false;
1697
1698 if (IsOldExported)
1699 return false;
1700
1701 assert(IsNewExported);
1702
1703 auto Lk = Old->getFormalLinkage();
1704 int S = 0;
1705 if (Lk == Linkage::Internal)
1706 S = 1;
1707 else if (Lk == Linkage::Module)
1708 S = 2;
1709 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1710 Diag(Old->getLocation(), diag::note_previous_declaration);
1711 return true;
1712}
1713
1714// A wrapper function for checking the semantic restrictions of
1715// a redeclaration within a module.
1716bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1717 if (CheckRedeclarationModuleOwnership(New, Old))
1718 return true;
1719
1720 if (CheckRedeclarationExported(New, Old))
1721 return true;
1722
1723 return false;
1724}
1725
1726// Check the redefinition in C++20 Modules.
1727//
1728// [basic.def.odr]p14:
1729// For any definable item D with definitions in multiple translation units,
1730// - if D is a non-inline non-templated function or variable, or
1731// - if the definitions in different translation units do not satisfy the
1732// following requirements,
1733// the program is ill-formed; a diagnostic is required only if the definable
1734// item is attached to a named module and a prior definition is reachable at
1735// the point where a later definition occurs.
1736// - Each such definition shall not be attached to a named module
1737// ([module.unit]).
1738// - Each such definition shall consist of the same sequence of tokens, ...
1739// ...
1740//
1741// Return true if the redefinition is not allowed. Return false otherwise.
1742bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1743 const NamedDecl *Old) const {
1744 assert(getASTContext().isSameEntity(New, Old) &&
1745 "New and Old are not the same definition, we should diagnostic it "
1746 "immediately instead of checking it.");
1747 assert(const_cast<Sema *>(this)->isReachable(New) &&
1748 const_cast<Sema *>(this)->isReachable(Old) &&
1749 "We shouldn't see unreachable definitions here.");
1750
1751 Module *NewM = New->getOwningModule();
1752 Module *OldM = Old->getOwningModule();
1753
1754 // We only checks for named modules here. The header like modules is skipped.
1755 // FIXME: This is not right if we import the header like modules in the module
1756 // purview.
1757 //
1758 // For example, assuming "header.h" provides definition for `D`.
1759 // ```C++
1760 // //--- M.cppm
1761 // export module M;
1762 // import "header.h"; // or #include "header.h" but import it by clang modules
1763 // actually.
1764 //
1765 // //--- Use.cpp
1766 // import M;
1767 // import "header.h"; // or uses clang modules.
1768 // ```
1769 //
1770 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1771 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1772 // reject it. But the current implementation couldn't detect the case since we
1773 // don't record the information about the importee modules.
1774 //
1775 // But this might not be painful in practice. Since the design of C++20 Named
1776 // Modules suggests us to use headers in global module fragment instead of
1777 // module purview.
1778 if (NewM && NewM->isHeaderLikeModule())
1779 NewM = nullptr;
1780 if (OldM && OldM->isHeaderLikeModule())
1781 OldM = nullptr;
1782
1783 if (!NewM && !OldM)
1784 return true;
1785
1786 // [basic.def.odr]p14.3
1787 // Each such definition shall not be attached to a named module
1788 // ([module.unit]).
1789 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1790 return true;
1791
1792 // Then New and Old lives in the same TU if their share one same module unit.
1793 if (NewM)
1794 NewM = NewM->getTopLevelModule();
1795 if (OldM)
1796 OldM = OldM->getTopLevelModule();
1797 return OldM == NewM;
1798}
1799
1800static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1801 if (D->getDeclContext()->isFileContext())
1802 return false;
1803
1804 return isa<UsingShadowDecl>(Val: D) ||
1805 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1806 isa<UnresolvedUsingValueDecl>(Val: D);
1807}
1808
1809/// Removes using shadow declarations not at class scope from the lookup
1810/// results.
1811static void RemoveUsingDecls(LookupResult &R) {
1812 LookupResult::Filter F = R.makeFilter();
1813 while (F.hasNext())
1814 if (isUsingDeclNotAtClassScope(D: F.next()))
1815 F.erase();
1816
1817 F.done();
1818}
1819
1820/// Check for this common pattern:
1821/// @code
1822/// class S {
1823/// S(const S&); // DO NOT IMPLEMENT
1824/// void operator=(const S&); // DO NOT IMPLEMENT
1825/// };
1826/// @endcode
1827static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1828 // FIXME: Should check for private access too but access is set after we get
1829 // the decl here.
1830 if (D->doesThisDeclarationHaveABody())
1831 return false;
1832
1833 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1834 return CD->isCopyConstructor();
1835 return D->isCopyAssignmentOperator();
1836}
1837
1838// We need this to handle
1839//
1840// typedef struct {
1841// void *foo() { return 0; }
1842// } A;
1843//
1844// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1845// for example. If 'A', foo will have external linkage. If we have '*A',
1846// foo will have no linkage. Since we can't know until we get to the end
1847// of the typedef, this function finds out if D might have non-external linkage.
1848// Callers should verify at the end of the TU if it D has external linkage or
1849// not.
1850bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1851 const DeclContext *DC = D->getDeclContext();
1852 while (!DC->isTranslationUnit()) {
1853 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1854 if (!RD->hasNameForLinkage())
1855 return true;
1856 }
1857 DC = DC->getParent();
1858 }
1859
1860 return !D->isExternallyVisible();
1861}
1862
1863// FIXME: This needs to be refactored; some other isInMainFile users want
1864// these semantics.
1865static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1866 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1867 return false;
1868 return S.SourceMgr.isInMainFile(Loc);
1869}
1870
1871bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1872 assert(D);
1873
1874 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1875 return false;
1876
1877 // Ignore all entities declared within templates, and out-of-line definitions
1878 // of members of class templates.
1879 if (D->getDeclContext()->isDependentContext() ||
1880 D->getLexicalDeclContext()->isDependentContext())
1881 return false;
1882
1883 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1884 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1885 return false;
1886 // A non-out-of-line declaration of a member specialization was implicitly
1887 // instantiated; it's the out-of-line declaration that we're interested in.
1888 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1889 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1890 return false;
1891
1892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1893 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1894 return false;
1895 } else {
1896 // 'static inline' functions are defined in headers; don't warn.
1897 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1898 return false;
1899 }
1900
1901 if (FD->doesThisDeclarationHaveABody() &&
1902 Context.DeclMustBeEmitted(FD))
1903 return false;
1904 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1905 // Constants and utility variables are defined in headers with internal
1906 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1907 // like "inline".)
1908 if (!isMainFileLoc(*this, VD->getLocation()))
1909 return false;
1910
1911 if (Context.DeclMustBeEmitted(VD))
1912 return false;
1913
1914 if (VD->isStaticDataMember() &&
1915 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1916 return false;
1917 if (VD->isStaticDataMember() &&
1918 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1919 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1920 return false;
1921
1922 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1923 return false;
1924 } else {
1925 return false;
1926 }
1927
1928 // Only warn for unused decls internal to the translation unit.
1929 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1930 // for inline functions defined in the main source file, for instance.
1931 return mightHaveNonExternalLinkage(D);
1932}
1933
1934void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1935 if (!D)
1936 return;
1937
1938 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1939 const FunctionDecl *First = FD->getFirstDecl();
1940 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1941 return; // First should already be in the vector.
1942 }
1943
1944 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1945 const VarDecl *First = VD->getFirstDecl();
1946 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1947 return; // First should already be in the vector.
1948 }
1949
1950 if (ShouldWarnIfUnusedFileScopedDecl(D))
1951 UnusedFileScopedDecls.push_back(LocalValue: D);
1952}
1953
1954static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1955 const NamedDecl *D) {
1956 if (D->isInvalidDecl())
1957 return false;
1958
1959 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
1960 // For a decomposition declaration, warn if none of the bindings are
1961 // referenced, instead of if the variable itself is referenced (which
1962 // it is, by the bindings' expressions).
1963 bool IsAllPlaceholders = true;
1964 for (const auto *BD : DD->bindings()) {
1965 if (BD->isReferenced())
1966 return false;
1967 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1968 }
1969 if (IsAllPlaceholders)
1970 return false;
1971 } else if (!D->getDeclName()) {
1972 return false;
1973 } else if (D->isReferenced() || D->isUsed()) {
1974 return false;
1975 }
1976
1977 if (D->isPlaceholderVar(LangOpts))
1978 return false;
1979
1980 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1981 D->hasAttr<CleanupAttr>())
1982 return false;
1983
1984 if (isa<LabelDecl>(Val: D))
1985 return true;
1986
1987 // Except for labels, we only care about unused decls that are local to
1988 // functions.
1989 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1990 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1991 // For dependent types, the diagnostic is deferred.
1992 WithinFunction =
1993 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1994 if (!WithinFunction)
1995 return false;
1996
1997 if (isa<TypedefNameDecl>(Val: D))
1998 return true;
1999
2000 // White-list anything that isn't a local variable.
2001 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2002 return false;
2003
2004 // Types of valid local variables should be complete, so this should succeed.
2005 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2006
2007 const Expr *Init = VD->getInit();
2008 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2009 Init = Cleanups->getSubExpr();
2010
2011 const auto *Ty = VD->getType().getTypePtr();
2012
2013 // Only look at the outermost level of typedef.
2014 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2015 // Allow anything marked with __attribute__((unused)).
2016 if (TT->getDecl()->hasAttr<UnusedAttr>())
2017 return false;
2018 }
2019
2020 // Warn for reference variables whose initializtion performs lifetime
2021 // extension.
2022 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2023 MTE && MTE->getExtendingDecl()) {
2024 Ty = VD->getType().getNonReferenceType().getTypePtr();
2025 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2026 }
2027
2028 // If we failed to complete the type for some reason, or if the type is
2029 // dependent, don't diagnose the variable.
2030 if (Ty->isIncompleteType() || Ty->isDependentType())
2031 return false;
2032
2033 // Look at the element type to ensure that the warning behaviour is
2034 // consistent for both scalars and arrays.
2035 Ty = Ty->getBaseElementTypeUnsafe();
2036
2037 if (const TagType *TT = Ty->getAs<TagType>()) {
2038 const TagDecl *Tag = TT->getDecl();
2039 if (Tag->hasAttr<UnusedAttr>())
2040 return false;
2041
2042 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2043 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2044 return false;
2045
2046 if (Init) {
2047 const auto *Construct = dyn_cast<CXXConstructExpr>(Val: Init);
2048 if (Construct && !Construct->isElidable()) {
2049 const CXXConstructorDecl *CD = Construct->getConstructor();
2050 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2051 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2052 return false;
2053 }
2054
2055 // Suppress the warning if we don't know how this is constructed, and
2056 // it could possibly be non-trivial constructor.
2057 if (Init->isTypeDependent()) {
2058 for (const CXXConstructorDecl *Ctor : RD->ctors())
2059 if (!Ctor->isTrivial())
2060 return false;
2061 }
2062
2063 // Suppress the warning if the constructor is unresolved because
2064 // its arguments are dependent.
2065 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2066 return false;
2067 }
2068 }
2069 }
2070
2071 // TODO: __attribute__((unused)) templates?
2072 }
2073
2074 return true;
2075}
2076
2077static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2078 FixItHint &Hint) {
2079 if (isa<LabelDecl>(Val: D)) {
2080 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2081 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2082 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2083 if (AfterColon.isInvalid())
2084 return;
2085 Hint = FixItHint::CreateRemoval(
2086 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2087 }
2088}
2089
2090void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2091 DiagnoseUnusedNestedTypedefs(
2092 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2093}
2094
2095void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2096 DiagReceiverTy DiagReceiver) {
2097 if (D->getTypeForDecl()->isDependentType())
2098 return;
2099
2100 for (auto *TmpD : D->decls()) {
2101 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2102 DiagnoseUnusedDecl(T, DiagReceiver);
2103 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2104 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2105 }
2106}
2107
2108void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2109 DiagnoseUnusedDecl(
2110 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2111}
2112
2113/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2114/// unless they are marked attr(unused).
2115void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2116 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2117 return;
2118
2119 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2120 // typedefs can be referenced later on, so the diagnostics are emitted
2121 // at end-of-translation-unit.
2122 UnusedLocalTypedefNameCandidates.insert(X: TD);
2123 return;
2124 }
2125
2126 FixItHint Hint;
2127 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2128
2129 unsigned DiagID;
2130 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2131 DiagID = diag::warn_unused_exception_param;
2132 else if (isa<LabelDecl>(D))
2133 DiagID = diag::warn_unused_label;
2134 else
2135 DiagID = diag::warn_unused_variable;
2136
2137 SourceLocation DiagLoc = D->getLocation();
2138 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2139}
2140
2141void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2142 DiagReceiverTy DiagReceiver) {
2143 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2144 // it's not really unused.
2145 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2146 return;
2147
2148 // In C++, `_` variables behave as if they were maybe_unused
2149 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2150 return;
2151
2152 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2153
2154 if (Ty->isReferenceType() || Ty->isDependentType())
2155 return;
2156
2157 if (const TagType *TT = Ty->getAs<TagType>()) {
2158 const TagDecl *Tag = TT->getDecl();
2159 if (Tag->hasAttr<UnusedAttr>())
2160 return;
2161 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2162 // mimic gcc's behavior.
2163 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2164 RD && !RD->hasAttr<WarnUnusedAttr>())
2165 return;
2166 }
2167
2168 // Don't warn about __block Objective-C pointer variables, as they might
2169 // be assigned in the block but not used elsewhere for the purpose of lifetime
2170 // extension.
2171 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2172 return;
2173
2174 // Don't warn about Objective-C pointer variables with precise lifetime
2175 // semantics; they can be used to ensure ARC releases the object at a known
2176 // time, which may mean assignment but no other references.
2177 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2178 return;
2179
2180 auto iter = RefsMinusAssignments.find(Val: VD);
2181 if (iter == RefsMinusAssignments.end())
2182 return;
2183
2184 assert(iter->getSecond() >= 0 &&
2185 "Found a negative number of references to a VarDecl");
2186 if (iter->getSecond() != 0)
2187 return;
2188 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2189 : diag::warn_unused_but_set_variable;
2190 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2191}
2192
2193static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2194 Sema::DiagReceiverTy DiagReceiver) {
2195 // Verify that we have no forward references left. If so, there was a goto
2196 // or address of a label taken, but no definition of it. Label fwd
2197 // definitions are indicated with a null substmt which is also not a resolved
2198 // MS inline assembly label name.
2199 bool Diagnose = false;
2200 if (L->isMSAsmLabel())
2201 Diagnose = !L->isResolvedMSAsmLabel();
2202 else
2203 Diagnose = L->getStmt() == nullptr;
2204 if (Diagnose)
2205 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2206 << L);
2207}
2208
2209void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2210 S->applyNRVO();
2211
2212 if (S->decl_empty()) return;
2213 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2214 "Scope shouldn't contain decls!");
2215
2216 /// We visit the decls in non-deterministic order, but we want diagnostics
2217 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2218 /// and sort the diagnostics before emitting them, after we visited all decls.
2219 struct LocAndDiag {
2220 SourceLocation Loc;
2221 std::optional<SourceLocation> PreviousDeclLoc;
2222 PartialDiagnostic PD;
2223 };
2224 SmallVector<LocAndDiag, 16> DeclDiags;
2225 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2226 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2227 };
2228 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2229 SourceLocation PreviousDeclLoc,
2230 PartialDiagnostic PD) {
2231 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2232 };
2233
2234 for (auto *TmpD : S->decls()) {
2235 assert(TmpD && "This decl didn't get pushed??");
2236
2237 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2238 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2239
2240 // Diagnose unused variables in this scope.
2241 if (!S->hasUnrecoverableErrorOccurred()) {
2242 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2243 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2244 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2245 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2246 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2247 RefsMinusAssignments.erase(Val: VD);
2248 }
2249 }
2250
2251 if (!D->getDeclName()) continue;
2252
2253 // If this was a forward reference to a label, verify it was defined.
2254 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2255 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2256
2257 // Remove this name from our lexical scope, and warn on it if we haven't
2258 // already.
2259 IdResolver.RemoveDecl(D);
2260 auto ShadowI = ShadowingDecls.find(Val: D);
2261 if (ShadowI != ShadowingDecls.end()) {
2262 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2263 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2264 PDiag(diag::warn_ctor_parm_shadows_field)
2265 << D << FD << FD->getParent());
2266 }
2267 ShadowingDecls.erase(I: ShadowI);
2268 }
2269
2270 if (!getLangOpts().CPlusPlus && S->isClassScope()) {
2271 if (auto *FD = dyn_cast<FieldDecl>(Val: TmpD);
2272 FD && FD->hasAttr<CountedByAttr>())
2273 CheckCountedByAttr(Scope: S, FD);
2274 }
2275 }
2276
2277 llvm::sort(C&: DeclDiags,
2278 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2279 // The particular order for diagnostics is not important, as long
2280 // as the order is deterministic. Using the raw location is going
2281 // to generally be in source order unless there are macro
2282 // expansions involved.
2283 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2284 });
2285 for (const LocAndDiag &D : DeclDiags) {
2286 Diag(Loc: D.Loc, PD: D.PD);
2287 if (D.PreviousDeclLoc)
2288 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2289 }
2290}
2291
2292/// Look for an Objective-C class in the translation unit.
2293///
2294/// \param Id The name of the Objective-C class we're looking for. If
2295/// typo-correction fixes this name, the Id will be updated
2296/// to the fixed name.
2297///
2298/// \param IdLoc The location of the name in the translation unit.
2299///
2300/// \param DoTypoCorrection If true, this routine will attempt typo correction
2301/// if there is no class with the given name.
2302///
2303/// \returns The declaration of the named Objective-C class, or NULL if the
2304/// class could not be found.
2305ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2306 SourceLocation IdLoc,
2307 bool DoTypoCorrection) {
2308 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2309 // creation from this context.
2310 NamedDecl *IDecl = LookupSingleName(S: TUScope, Name: Id, Loc: IdLoc, NameKind: LookupOrdinaryName);
2311
2312 if (!IDecl && DoTypoCorrection) {
2313 // Perform typo correction at the given location, but only if we
2314 // find an Objective-C class name.
2315 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2316 if (TypoCorrection C =
2317 CorrectTypo(Typo: DeclarationNameInfo(Id, IdLoc), LookupKind: LookupOrdinaryName,
2318 S: TUScope, SS: nullptr, CCC, Mode: CTK_ErrorRecovery)) {
2319 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2320 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2321 Id = IDecl->getIdentifier();
2322 }
2323 }
2324 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(Val: IDecl);
2325 // This routine must always return a class definition, if any.
2326 if (Def && Def->getDefinition())
2327 Def = Def->getDefinition();
2328 return Def;
2329}
2330
2331/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2332/// from S, where a non-field would be declared. This routine copes
2333/// with the difference between C and C++ scoping rules in structs and
2334/// unions. For example, the following code is well-formed in C but
2335/// ill-formed in C++:
2336/// @code
2337/// struct S6 {
2338/// enum { BAR } e;
2339/// };
2340///
2341/// void test_S6() {
2342/// struct S6 a;
2343/// a.e = BAR;
2344/// }
2345/// @endcode
2346/// For the declaration of BAR, this routine will return a different
2347/// scope. The scope S will be the scope of the unnamed enumeration
2348/// within S6. In C++, this routine will return the scope associated
2349/// with S6, because the enumeration's scope is a transparent
2350/// context but structures can contain non-field names. In C, this
2351/// routine will return the translation unit scope, since the
2352/// enumeration's scope is a transparent context and structures cannot
2353/// contain non-field names.
2354Scope *Sema::getNonFieldDeclScope(Scope *S) {
2355 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2356 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2357 (S->isClassScope() && !getLangOpts().CPlusPlus))
2358 S = S->getParent();
2359 return S;
2360}
2361
2362static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2363 ASTContext::GetBuiltinTypeError Error) {
2364 switch (Error) {
2365 case ASTContext::GE_None:
2366 return "";
2367 case ASTContext::GE_Missing_type:
2368 return BuiltinInfo.getHeaderName(ID);
2369 case ASTContext::GE_Missing_stdio:
2370 return "stdio.h";
2371 case ASTContext::GE_Missing_setjmp:
2372 return "setjmp.h";
2373 case ASTContext::GE_Missing_ucontext:
2374 return "ucontext.h";
2375 }
2376 llvm_unreachable("unhandled error kind");
2377}
2378
2379FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2380 unsigned ID, SourceLocation Loc) {
2381 DeclContext *Parent = Context.getTranslationUnitDecl();
2382
2383 if (getLangOpts().CPlusPlus) {
2384 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2385 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2386 CLinkageDecl->setImplicit();
2387 Parent->addDecl(CLinkageDecl);
2388 Parent = CLinkageDecl;
2389 }
2390
2391 FunctionDecl *New = FunctionDecl::Create(C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type,
2392 /*TInfo=*/nullptr, SC: SC_Extern,
2393 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
2394 isInlineSpecified: false, hasWrittenPrototype: Type->isFunctionProtoType());
2395 New->setImplicit();
2396 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2397
2398 // Create Decl objects for each parameter, adding them to the
2399 // FunctionDecl.
2400 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2401 SmallVector<ParmVarDecl *, 16> Params;
2402 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2403 ParmVarDecl *parm = ParmVarDecl::Create(
2404 Context, New, SourceLocation(), SourceLocation(), nullptr,
2405 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2406 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2407 Params.push_back(Elt: parm);
2408 }
2409 New->setParams(Params);
2410 }
2411
2412 AddKnownFunctionAttributes(FD: New);
2413 return New;
2414}
2415
2416/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2417/// file scope. lazily create a decl for it. ForRedeclaration is true
2418/// if we're creating this built-in in anticipation of redeclaring the
2419/// built-in.
2420NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2421 Scope *S, bool ForRedeclaration,
2422 SourceLocation Loc) {
2423 LookupNecessaryTypesForBuiltin(S, ID);
2424
2425 ASTContext::GetBuiltinTypeError Error;
2426 QualType R = Context.GetBuiltinType(ID, Error);
2427 if (Error) {
2428 if (!ForRedeclaration)
2429 return nullptr;
2430
2431 // If we have a builtin without an associated type we should not emit a
2432 // warning when we were not able to find a type for it.
2433 if (Error == ASTContext::GE_Missing_type ||
2434 Context.BuiltinInfo.allowTypeMismatch(ID))
2435 return nullptr;
2436
2437 // If we could not find a type for setjmp it is because the jmp_buf type was
2438 // not defined prior to the setjmp declaration.
2439 if (Error == ASTContext::GE_Missing_setjmp) {
2440 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2441 << Context.BuiltinInfo.getName(ID);
2442 return nullptr;
2443 }
2444
2445 // Generally, we emit a warning that the declaration requires the
2446 // appropriate header.
2447 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2448 << getHeaderName(Context.BuiltinInfo, ID, Error)
2449 << Context.BuiltinInfo.getName(ID);
2450 return nullptr;
2451 }
2452
2453 if (!ForRedeclaration &&
2454 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2455 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2456 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2457 : diag::ext_implicit_lib_function_decl)
2458 << Context.BuiltinInfo.getName(ID) << R;
2459 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2460 Diag(Loc, diag::note_include_header_or_declare)
2461 << Header << Context.BuiltinInfo.getName(ID);
2462 }
2463
2464 if (R.isNull())
2465 return nullptr;
2466
2467 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2468 RegisterLocallyScopedExternCDecl(New, S);
2469
2470 // TUScope is the translation-unit scope to insert this function into.
2471 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2472 // relate Scopes to DeclContexts, and probably eliminate CurContext
2473 // entirely, but we're not there yet.
2474 DeclContext *SavedContext = CurContext;
2475 CurContext = New->getDeclContext();
2476 PushOnScopeChains(New, TUScope);
2477 CurContext = SavedContext;
2478 return New;
2479}
2480
2481/// Typedef declarations don't have linkage, but they still denote the same
2482/// entity if their types are the same.
2483/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2484/// isSameEntity.
2485static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2486 TypedefNameDecl *Decl,
2487 LookupResult &Previous) {
2488 // This is only interesting when modules are enabled.
2489 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2490 return;
2491
2492 // Empty sets are uninteresting.
2493 if (Previous.empty())
2494 return;
2495
2496 LookupResult::Filter Filter = Previous.makeFilter();
2497 while (Filter.hasNext()) {
2498 NamedDecl *Old = Filter.next();
2499
2500 // Non-hidden declarations are never ignored.
2501 if (S.isVisible(D: Old))
2502 continue;
2503
2504 // Declarations of the same entity are not ignored, even if they have
2505 // different linkages.
2506 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2507 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2508 T2: Decl->getUnderlyingType()))
2509 continue;
2510
2511 // If both declarations give a tag declaration a typedef name for linkage
2512 // purposes, then they declare the same entity.
2513 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2514 Decl->getAnonDeclWithTypedefName())
2515 continue;
2516 }
2517
2518 Filter.erase();
2519 }
2520
2521 Filter.done();
2522}
2523
2524bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2525 QualType OldType;
2526 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2527 OldType = OldTypedef->getUnderlyingType();
2528 else
2529 OldType = Context.getTypeDeclType(Decl: Old);
2530 QualType NewType = New->getUnderlyingType();
2531
2532 if (NewType->isVariablyModifiedType()) {
2533 // Must not redefine a typedef with a variably-modified type.
2534 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2535 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2536 << Kind << NewType;
2537 if (Old->getLocation().isValid())
2538 notePreviousDefinition(Old, New: New->getLocation());
2539 New->setInvalidDecl();
2540 return true;
2541 }
2542
2543 if (OldType != NewType &&
2544 !OldType->isDependentType() &&
2545 !NewType->isDependentType() &&
2546 !Context.hasSameType(T1: OldType, T2: NewType)) {
2547 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2548 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2549 << Kind << NewType << OldType;
2550 if (Old->getLocation().isValid())
2551 notePreviousDefinition(Old, New: New->getLocation());
2552 New->setInvalidDecl();
2553 return true;
2554 }
2555 return false;
2556}
2557
2558/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2559/// same name and scope as a previous declaration 'Old'. Figure out
2560/// how to resolve this situation, merging decls or emitting
2561/// diagnostics as appropriate. If there was an error, set New to be invalid.
2562///
2563void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2564 LookupResult &OldDecls) {
2565 // If the new decl is known invalid already, don't bother doing any
2566 // merging checks.
2567 if (New->isInvalidDecl()) return;
2568
2569 // Allow multiple definitions for ObjC built-in typedefs.
2570 // FIXME: Verify the underlying types are equivalent!
2571 if (getLangOpts().ObjC) {
2572 const IdentifierInfo *TypeID = New->getIdentifier();
2573 switch (TypeID->getLength()) {
2574 default: break;
2575 case 2:
2576 {
2577 if (!TypeID->isStr(Str: "id"))
2578 break;
2579 QualType T = New->getUnderlyingType();
2580 if (!T->isPointerType())
2581 break;
2582 if (!T->isVoidPointerType()) {
2583 QualType PT = T->castAs<PointerType>()->getPointeeType();
2584 if (!PT->isStructureType())
2585 break;
2586 }
2587 Context.setObjCIdRedefinitionType(T);
2588 // Install the built-in type for 'id', ignoring the current definition.
2589 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2590 return;
2591 }
2592 case 5:
2593 if (!TypeID->isStr(Str: "Class"))
2594 break;
2595 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2596 // Install the built-in type for 'Class', ignoring the current definition.
2597 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2598 return;
2599 case 3:
2600 if (!TypeID->isStr(Str: "SEL"))
2601 break;
2602 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2603 // Install the built-in type for 'SEL', ignoring the current definition.
2604 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2605 return;
2606 }
2607 // Fall through - the typedef name was not a builtin type.
2608 }
2609
2610 // Verify the old decl was also a type.
2611 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2612 if (!Old) {
2613 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2614 << New->getDeclName();
2615
2616 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2617 if (OldD->getLocation().isValid())
2618 notePreviousDefinition(Old: OldD, New: New->getLocation());
2619
2620 return New->setInvalidDecl();
2621 }
2622
2623 // If the old declaration is invalid, just give up here.
2624 if (Old->isInvalidDecl())
2625 return New->setInvalidDecl();
2626
2627 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2628 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2629 auto *NewTag = New->getAnonDeclWithTypedefName();
2630 NamedDecl *Hidden = nullptr;
2631 if (OldTag && NewTag &&
2632 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2633 !hasVisibleDefinition(OldTag, &Hidden)) {
2634 // There is a definition of this tag, but it is not visible. Use it
2635 // instead of our tag.
2636 New->setTypeForDecl(OldTD->getTypeForDecl());
2637 if (OldTD->isModed())
2638 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2639 modedTy: OldTD->getUnderlyingType());
2640 else
2641 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2642
2643 // Make the old tag definition visible.
2644 makeMergedDefinitionVisible(ND: Hidden);
2645
2646 // If this was an unscoped enumeration, yank all of its enumerators
2647 // out of the scope.
2648 if (isa<EnumDecl>(Val: NewTag)) {
2649 Scope *EnumScope = getNonFieldDeclScope(S);
2650 for (auto *D : NewTag->decls()) {
2651 auto *ED = cast<EnumConstantDecl>(D);
2652 assert(EnumScope->isDeclScope(ED));
2653 EnumScope->RemoveDecl(ED);
2654 IdResolver.RemoveDecl(ED);
2655 ED->getLexicalDeclContext()->removeDecl(ED);
2656 }
2657 }
2658 }
2659 }
2660
2661 // If the typedef types are not identical, reject them in all languages and
2662 // with any extensions enabled.
2663 if (isIncompatibleTypedef(Old, New))
2664 return;
2665
2666 // The types match. Link up the redeclaration chain and merge attributes if
2667 // the old declaration was a typedef.
2668 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2669 New->setPreviousDecl(Typedef);
2670 mergeDeclAttributes(New, Old);
2671 }
2672
2673 if (getLangOpts().MicrosoftExt)
2674 return;
2675
2676 if (getLangOpts().CPlusPlus) {
2677 // C++ [dcl.typedef]p2:
2678 // In a given non-class scope, a typedef specifier can be used to
2679 // redefine the name of any type declared in that scope to refer
2680 // to the type to which it already refers.
2681 if (!isa<CXXRecordDecl>(Val: CurContext))
2682 return;
2683
2684 // C++0x [dcl.typedef]p4:
2685 // In a given class scope, a typedef specifier can be used to redefine
2686 // any class-name declared in that scope that is not also a typedef-name
2687 // to refer to the type to which it already refers.
2688 //
2689 // This wording came in via DR424, which was a correction to the
2690 // wording in DR56, which accidentally banned code like:
2691 //
2692 // struct S {
2693 // typedef struct A { } A;
2694 // };
2695 //
2696 // in the C++03 standard. We implement the C++0x semantics, which
2697 // allow the above but disallow
2698 //
2699 // struct S {
2700 // typedef int I;
2701 // typedef int I;
2702 // };
2703 //
2704 // since that was the intent of DR56.
2705 if (!isa<TypedefNameDecl>(Val: Old))
2706 return;
2707
2708 Diag(New->getLocation(), diag::err_redefinition)
2709 << New->getDeclName();
2710 notePreviousDefinition(Old, New: New->getLocation());
2711 return New->setInvalidDecl();
2712 }
2713
2714 // Modules always permit redefinition of typedefs, as does C11.
2715 if (getLangOpts().Modules || getLangOpts().C11)
2716 return;
2717
2718 // If we have a redefinition of a typedef in C, emit a warning. This warning
2719 // is normally mapped to an error, but can be controlled with
2720 // -Wtypedef-redefinition. If either the original or the redefinition is
2721 // in a system header, don't emit this for compatibility with GCC.
2722 if (getDiagnostics().getSuppressSystemWarnings() &&
2723 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2724 (Old->isImplicit() ||
2725 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2726 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2727 return;
2728
2729 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2730 << New->getDeclName();
2731 notePreviousDefinition(Old, New: New->getLocation());
2732}
2733
2734/// DeclhasAttr - returns true if decl Declaration already has the target
2735/// attribute.
2736static bool DeclHasAttr(const Decl *D, const Attr *A) {
2737 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2738 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2739 for (const auto *i : D->attrs())
2740 if (i->getKind() == A->getKind()) {
2741 if (Ann) {
2742 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2743 return true;
2744 continue;
2745 }
2746 // FIXME: Don't hardcode this check
2747 if (OA && isa<OwnershipAttr>(i))
2748 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2749 return true;
2750 }
2751
2752 return false;
2753}
2754
2755static bool isAttributeTargetADefinition(Decl *D) {
2756 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2757 return VD->isThisDeclarationADefinition();
2758 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2759 return TD->isCompleteDefinition() || TD->isBeingDefined();
2760 return true;
2761}
2762
2763/// Merge alignment attributes from \p Old to \p New, taking into account the
2764/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2765///
2766/// \return \c true if any attributes were added to \p New.
2767static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2768 // Look for alignas attributes on Old, and pick out whichever attribute
2769 // specifies the strictest alignment requirement.
2770 AlignedAttr *OldAlignasAttr = nullptr;
2771 AlignedAttr *OldStrictestAlignAttr = nullptr;
2772 unsigned OldAlign = 0;
2773 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2774 // FIXME: We have no way of representing inherited dependent alignments
2775 // in a case like:
2776 // template<int A, int B> struct alignas(A) X;
2777 // template<int A, int B> struct alignas(B) X {};
2778 // For now, we just ignore any alignas attributes which are not on the
2779 // definition in such a case.
2780 if (I->isAlignmentDependent())
2781 return false;
2782
2783 if (I->isAlignas())
2784 OldAlignasAttr = I;
2785
2786 unsigned Align = I->getAlignment(S.Context);
2787 if (Align > OldAlign) {
2788 OldAlign = Align;
2789 OldStrictestAlignAttr = I;
2790 }
2791 }
2792
2793 // Look for alignas attributes on New.
2794 AlignedAttr *NewAlignasAttr = nullptr;
2795 unsigned NewAlign = 0;
2796 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2797 if (I->isAlignmentDependent())
2798 return false;
2799
2800 if (I->isAlignas())
2801 NewAlignasAttr = I;
2802
2803 unsigned Align = I->getAlignment(S.Context);
2804 if (Align > NewAlign)
2805 NewAlign = Align;
2806 }
2807
2808 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2809 // Both declarations have 'alignas' attributes. We require them to match.
2810 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2811 // fall short. (If two declarations both have alignas, they must both match
2812 // every definition, and so must match each other if there is a definition.)
2813
2814 // If either declaration only contains 'alignas(0)' specifiers, then it
2815 // specifies the natural alignment for the type.
2816 if (OldAlign == 0 || NewAlign == 0) {
2817 QualType Ty;
2818 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2819 Ty = VD->getType();
2820 else
2821 Ty = S.Context.getTagDeclType(Decl: cast<TagDecl>(Val: New));
2822
2823 if (OldAlign == 0)
2824 OldAlign = S.Context.getTypeAlign(T: Ty);
2825 if (NewAlign == 0)
2826 NewAlign = S.Context.getTypeAlign(T: Ty);
2827 }
2828
2829 if (OldAlign != NewAlign) {
2830 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2831 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2832 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2833 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2834 }
2835 }
2836
2837 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2838 // C++11 [dcl.align]p6:
2839 // if any declaration of an entity has an alignment-specifier,
2840 // every defining declaration of that entity shall specify an
2841 // equivalent alignment.
2842 // C11 6.7.5/7:
2843 // If the definition of an object does not have an alignment
2844 // specifier, any other declaration of that object shall also
2845 // have no alignment specifier.
2846 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2847 << OldAlignasAttr;
2848 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2849 << OldAlignasAttr;
2850 }
2851
2852 bool AnyAdded = false;
2853
2854 // Ensure we have an attribute representing the strictest alignment.
2855 if (OldAlign > NewAlign) {
2856 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2857 Clone->setInherited(true);
2858 New->addAttr(A: Clone);
2859 AnyAdded = true;
2860 }
2861
2862 // Ensure we have an alignas attribute if the old declaration had one.
2863 if (OldAlignasAttr && !NewAlignasAttr &&
2864 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2865 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2866 Clone->setInherited(true);
2867 New->addAttr(A: Clone);
2868 AnyAdded = true;
2869 }
2870
2871 return AnyAdded;
2872}
2873
2874#define WANT_DECL_MERGE_LOGIC
2875#include "clang/Sema/AttrParsedAttrImpl.inc"
2876#undef WANT_DECL_MERGE_LOGIC
2877
2878static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2879 const InheritableAttr *Attr,
2880 Sema::AvailabilityMergeKind AMK) {
2881 // Diagnose any mutual exclusions between the attribute that we want to add
2882 // and attributes that already exist on the declaration.
2883 if (!DiagnoseMutualExclusions(S, D, Attr))
2884 return false;
2885
2886 // This function copies an attribute Attr from a previous declaration to the
2887 // new declaration D if the new declaration doesn't itself have that attribute
2888 // yet or if that attribute allows duplicates.
2889 // If you're adding a new attribute that requires logic different from
2890 // "use explicit attribute on decl if present, else use attribute from
2891 // previous decl", for example if the attribute needs to be consistent
2892 // between redeclarations, you need to call a custom merge function here.
2893 InheritableAttr *NewAttr = nullptr;
2894 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2895 NewAttr = S.mergeAvailabilityAttr(
2896 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2897 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2898 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2899 AA->getPriority());
2900 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2901 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2902 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2903 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2904 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2905 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2906 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2907 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2908 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2909 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2910 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2911 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2912 FirstArg: FA->getFirstArg());
2913 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2914 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2915 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2916 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2917 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2918 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2919 IA->getInheritanceModel());
2920 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2921 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2922 &S.Context.Idents.get(AA->getSpelling()));
2923 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2924 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2925 isa<CUDAGlobalAttr>(Attr))) {
2926 // CUDA target attributes are part of function signature for
2927 // overloading purposes and must not be merged.
2928 return false;
2929 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2930 NewAttr = S.mergeMinSizeAttr(D, *MA);
2931 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2932 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2933 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2934 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2935 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2936 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2937 else if (isa<AlignedAttr>(Attr))
2938 // AlignedAttrs are handled separately, because we need to handle all
2939 // such attributes on a declaration at the same time.
2940 NewAttr = nullptr;
2941 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2942 (AMK == Sema::AMK_Override ||
2943 AMK == Sema::AMK_ProtocolImplementation ||
2944 AMK == Sema::AMK_OptionalProtocolImplementation))
2945 NewAttr = nullptr;
2946 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2947 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2948 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2949 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2950 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2951 NewAttr = S.mergeImportNameAttr(D, *INA);
2952 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2953 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2954 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2955 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2956 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2957 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2958 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2959 NewAttr =
2960 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2961 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2962 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2963 else if (const auto *SupA = dyn_cast<SuppressAttr>(Attr))
2964 // Do nothing. Each redeclaration should be suppressed separately.
2965 NewAttr = nullptr;
2966 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2967 NewAttr = cast<InheritableAttr>(Attr->clone(C&: S.Context));
2968
2969 if (NewAttr) {
2970 NewAttr->setInherited(true);
2971 D->addAttr(NewAttr);
2972 if (isa<MSInheritanceAttr>(NewAttr))
2973 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(D));
2974 return true;
2975 }
2976
2977 return false;
2978}
2979
2980static const NamedDecl *getDefinition(const Decl *D) {
2981 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2982 return TD->getDefinition();
2983 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2984 const VarDecl *Def = VD->getDefinition();
2985 if (Def)
2986 return Def;
2987 return VD->getActingDefinition();
2988 }
2989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2990 const FunctionDecl *Def = nullptr;
2991 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
2992 return Def;
2993 }
2994 return nullptr;
2995}
2996
2997static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2998 for (const auto *Attribute : D->attrs())
2999 if (Attribute->getKind() == Kind)
3000 return true;
3001 return false;
3002}
3003
3004/// checkNewAttributesAfterDef - If we already have a definition, check that
3005/// there are no new attributes in this declaration.
3006static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3007 if (!New->hasAttrs())
3008 return;
3009
3010 const NamedDecl *Def = getDefinition(D: Old);
3011 if (!Def || Def == New)
3012 return;
3013
3014 AttrVec &NewAttributes = New->getAttrs();
3015 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3016 const Attr *NewAttribute = NewAttributes[I];
3017
3018 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3020 Sema::SkipBodyInfo SkipBody;
3021 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3022
3023 // If we're skipping this definition, drop the "alias" attribute.
3024 if (SkipBody.ShouldSkip) {
3025 NewAttributes.erase(CI: NewAttributes.begin() + I);
3026 --E;
3027 continue;
3028 }
3029 } else {
3030 VarDecl *VD = cast<VarDecl>(Val: New);
3031 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3032 VarDecl::TentativeDefinition
3033 ? diag::err_alias_after_tentative
3034 : diag::err_redefinition;
3035 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3036 if (Diag == diag::err_redefinition)
3037 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3038 else
3039 S.Diag(Def->getLocation(), diag::note_previous_definition);
3040 VD->setInvalidDecl();
3041 }
3042 ++I;
3043 continue;
3044 }
3045
3046 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3047 // Tentative definitions are only interesting for the alias check above.
3048 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3049 ++I;
3050 continue;
3051 }
3052 }
3053
3054 if (hasAttribute(Def, NewAttribute->getKind())) {
3055 ++I;
3056 continue; // regular attr merging will take care of validating this.
3057 }
3058
3059 if (isa<C11NoReturnAttr>(NewAttribute)) {
3060 // C's _Noreturn is allowed to be added to a function after it is defined.
3061 ++I;
3062 continue;
3063 } else if (isa<UuidAttr>(NewAttribute)) {
3064 // msvc will allow a subsequent definition to add an uuid to a class
3065 ++I;
3066 continue;
3067 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3068 if (AA->isAlignas()) {
3069 // C++11 [dcl.align]p6:
3070 // if any declaration of an entity has an alignment-specifier,
3071 // every defining declaration of that entity shall specify an
3072 // equivalent alignment.
3073 // C11 6.7.5/7:
3074 // If the definition of an object does not have an alignment
3075 // specifier, any other declaration of that object shall also
3076 // have no alignment specifier.
3077 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3078 << AA;
3079 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3080 << AA;
3081 NewAttributes.erase(CI: NewAttributes.begin() + I);
3082 --E;
3083 continue;
3084 }
3085 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3086 // If there is a C definition followed by a redeclaration with this
3087 // attribute then there are two different definitions. In C++, prefer the
3088 // standard diagnostics.
3089 if (!S.getLangOpts().CPlusPlus) {
3090 S.Diag(NewAttribute->getLocation(),
3091 diag::err_loader_uninitialized_redeclaration);
3092 S.Diag(Def->getLocation(), diag::note_previous_definition);
3093 NewAttributes.erase(CI: NewAttributes.begin() + I);
3094 --E;
3095 continue;
3096 }
3097 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3098 cast<VarDecl>(New)->isInline() &&
3099 !cast<VarDecl>(New)->isInlineSpecified()) {
3100 // Don't warn about applying selectany to implicitly inline variables.
3101 // Older compilers and language modes would require the use of selectany
3102 // to make such variables inline, and it would have no effect if we
3103 // honored it.
3104 ++I;
3105 continue;
3106 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3107 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3108 // declarations after definitions.
3109 ++I;
3110 continue;
3111 }
3112
3113 S.Diag(NewAttribute->getLocation(),
3114 diag::warn_attribute_precede_definition);
3115 S.Diag(Def->getLocation(), diag::note_previous_definition);
3116 NewAttributes.erase(CI: NewAttributes.begin() + I);
3117 --E;
3118 }
3119}
3120
3121static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3122 const ConstInitAttr *CIAttr,
3123 bool AttrBeforeInit) {
3124 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3125
3126 // Figure out a good way to write this specifier on the old declaration.
3127 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3128 // enough of the attribute list spelling information to extract that without
3129 // heroics.
3130 std::string SuitableSpelling;
3131 if (S.getLangOpts().CPlusPlus20)
3132 SuitableSpelling = std::string(
3133 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3134 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3135 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3136 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3137 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3138 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3139 tok::r_square, tok::r_square}));
3140 if (SuitableSpelling.empty())
3141 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3142 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3143 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3144 tok::r_paren, tok::r_paren}));
3145 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3146 SuitableSpelling = "constinit";
3147 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3148 SuitableSpelling = "[[clang::require_constant_initialization]]";
3149 if (SuitableSpelling.empty())
3150 SuitableSpelling = "__attribute__((require_constant_initialization))";
3151 SuitableSpelling += " ";
3152
3153 if (AttrBeforeInit) {
3154 // extern constinit int a;
3155 // int a = 0; // error (missing 'constinit'), accepted as extension
3156 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3157 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3158 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3159 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3160 } else {
3161 // int a = 0;
3162 // constinit extern int a; // error (missing 'constinit')
3163 S.Diag(CIAttr->getLocation(),
3164 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3165 : diag::warn_require_const_init_added_too_late)
3166 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3167 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3168 << CIAttr->isConstinit()
3169 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3170 }
3171}
3172
3173/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3174void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3175 AvailabilityMergeKind AMK) {
3176 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3177 UsedAttr *NewAttr = OldAttr->clone(Context);
3178 NewAttr->setInherited(true);
3179 New->addAttr(A: NewAttr);
3180 }
3181 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3182 RetainAttr *NewAttr = OldAttr->clone(Context);
3183 NewAttr->setInherited(true);
3184 New->addAttr(A: NewAttr);
3185 }
3186
3187 if (!Old->hasAttrs() && !New->hasAttrs())
3188 return;
3189
3190 // [dcl.constinit]p1:
3191 // If the [constinit] specifier is applied to any declaration of a
3192 // variable, it shall be applied to the initializing declaration.
3193 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3194 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3195 if (bool(OldConstInit) != bool(NewConstInit)) {
3196 const auto *OldVD = cast<VarDecl>(Val: Old);
3197 auto *NewVD = cast<VarDecl>(Val: New);
3198
3199 // Find the initializing declaration. Note that we might not have linked
3200 // the new declaration into the redeclaration chain yet.
3201 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3202 if (!InitDecl &&
3203 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3204 InitDecl = NewVD;
3205
3206 if (InitDecl == NewVD) {
3207 // This is the initializing declaration. If it would inherit 'constinit',
3208 // that's ill-formed. (Note that we do not apply this to the attribute
3209 // form).
3210 if (OldConstInit && OldConstInit->isConstinit())
3211 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3212 /*AttrBeforeInit=*/true);
3213 } else if (NewConstInit) {
3214 // This is the first time we've been told that this declaration should
3215 // have a constant initializer. If we already saw the initializing
3216 // declaration, this is too late.
3217 if (InitDecl && InitDecl != NewVD) {
3218 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3219 /*AttrBeforeInit=*/false);
3220 NewVD->dropAttr<ConstInitAttr>();
3221 }
3222 }
3223 }
3224
3225 // Attributes declared post-definition are currently ignored.
3226 checkNewAttributesAfterDef(*this, New, Old);
3227
3228 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3229 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3230 if (!OldA->isEquivalent(NewA)) {
3231 // This redeclaration changes __asm__ label.
3232 Diag(New->getLocation(), diag::err_different_asm_label);
3233 Diag(OldA->getLocation(), diag::note_previous_declaration);
3234 }
3235 } else if (Old->isUsed()) {
3236 // This redeclaration adds an __asm__ label to a declaration that has
3237 // already been ODR-used.
3238 Diag(New->getLocation(), diag::err_late_asm_label_name)
3239 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3240 }
3241 }
3242
3243 // Re-declaration cannot add abi_tag's.
3244 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3245 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3246 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3247 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3248 Diag(NewAbiTagAttr->getLocation(),
3249 diag::err_new_abi_tag_on_redeclaration)
3250 << NewTag;
3251 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3252 }
3253 }
3254 } else {
3255 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3256 Diag(Old->getLocation(), diag::note_previous_declaration);
3257 }
3258 }
3259
3260 // This redeclaration adds a section attribute.
3261 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3262 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3263 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3264 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3265 Diag(Old->getLocation(), diag::note_previous_declaration);
3266 }
3267 }
3268 }
3269
3270 // Redeclaration adds code-seg attribute.
3271 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3272 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3273 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3274 Diag(New->getLocation(), diag::warn_mismatched_section)
3275 << 0 /*codeseg*/;
3276 Diag(Old->getLocation(), diag::note_previous_declaration);
3277 }
3278
3279 if (!Old->hasAttrs())
3280 return;
3281
3282 bool foundAny = New->hasAttrs();
3283
3284 // Ensure that any moving of objects within the allocated map is done before
3285 // we process them.
3286 if (!foundAny) New->setAttrs(AttrVec());
3287
3288 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3289 // Ignore deprecated/unavailable/availability attributes if requested.
3290 AvailabilityMergeKind LocalAMK = AMK_None;
3291 if (isa<DeprecatedAttr>(I) ||
3292 isa<UnavailableAttr>(I) ||
3293 isa<AvailabilityAttr>(I)) {
3294 switch (AMK) {
3295 case AMK_None:
3296 continue;
3297
3298 case AMK_Redeclaration:
3299 case AMK_Override:
3300 case AMK_ProtocolImplementation:
3301 case AMK_OptionalProtocolImplementation:
3302 LocalAMK = AMK;
3303 break;
3304 }
3305 }
3306
3307 // Already handled.
3308 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3309 continue;
3310
3311 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3312 foundAny = true;
3313 }
3314
3315 if (mergeAlignedAttrs(S&: *this, New, Old))
3316 foundAny = true;
3317
3318 if (!foundAny) New->dropAttrs();
3319}
3320
3321/// mergeParamDeclAttributes - Copy attributes from the old parameter
3322/// to the new one.
3323static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3324 const ParmVarDecl *oldDecl,
3325 Sema &S) {
3326 // C++11 [dcl.attr.depend]p2:
3327 // The first declaration of a function shall specify the
3328 // carries_dependency attribute for its declarator-id if any declaration
3329 // of the function specifies the carries_dependency attribute.
3330 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3331 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3332 S.Diag(CDA->getLocation(),
3333 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3334 // Find the first declaration of the parameter.
3335 // FIXME: Should we build redeclaration chains for function parameters?
3336 const FunctionDecl *FirstFD =
3337 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3338 const ParmVarDecl *FirstVD =
3339 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3340 S.Diag(FirstVD->getLocation(),
3341 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3342 }
3343
3344 // HLSL parameter declarations for inout and out must match between
3345 // declarations. In HLSL inout and out are ambiguous at the call site, but
3346 // have different calling behavior, so you cannot overload a method based on a
3347 // difference between inout and out annotations.
3348 if (S.getLangOpts().HLSL) {
3349 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3350 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3351 // We don't need to cover the case where one declaration doesn't have an
3352 // attribute. The only possible case there is if one declaration has an `in`
3353 // attribute and the other declaration has no attribute. This case is
3354 // allowed since parameters are `in` by default.
3355 if (NDAttr && ODAttr &&
3356 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3357 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3358 << NDAttr << newDecl;
3359 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3360 << ODAttr;
3361 }
3362 }
3363
3364 if (!oldDecl->hasAttrs())
3365 return;
3366
3367 bool foundAny = newDecl->hasAttrs();
3368
3369 // Ensure that any moving of objects within the allocated map is
3370 // done before we process them.
3371 if (!foundAny) newDecl->setAttrs(AttrVec());
3372
3373 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3374 if (!DeclHasAttr(newDecl, I)) {
3375 InheritableAttr *newAttr =
3376 cast<InheritableParamAttr>(I->clone(S.Context));
3377 newAttr->setInherited(true);
3378 newDecl->addAttr(newAttr);
3379 foundAny = true;
3380 }
3381 }
3382
3383 if (!foundAny) newDecl->dropAttrs();
3384}
3385
3386static bool EquivalentArrayTypes(QualType Old, QualType New,
3387 const ASTContext &Ctx) {
3388
3389 auto NoSizeInfo = [&Ctx](QualType Ty) {
3390 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3391 return true;
3392 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3393 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3394 return false;
3395 };
3396
3397 // `type[]` is equivalent to `type *` and `type[*]`.
3398 if (NoSizeInfo(Old) && NoSizeInfo(New))
3399 return true;
3400
3401 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3402 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3403 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3404 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3405 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3406 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3407 return false;
3408 return true;
3409 }
3410
3411 // Only compare size, ignore Size modifiers and CVR.
3412 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3413 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3414 Ctx.getAsConstantArrayType(T: New)->getSize();
3415 }
3416
3417 // Don't try to compare dependent sized array
3418 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3419 return true;
3420 }
3421
3422 return Old == New;
3423}
3424
3425static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3426 const ParmVarDecl *OldParam,
3427 Sema &S) {
3428 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3429 if (auto Newnullability = NewParam->getType()->getNullability()) {
3430 if (*Oldnullability != *Newnullability) {
3431 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3432 << DiagNullabilityKind(
3433 *Newnullability,
3434 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3435 != 0))
3436 << DiagNullabilityKind(
3437 *Oldnullability,
3438 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3439 != 0));
3440 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3441 }
3442 } else {
3443 QualType NewT = NewParam->getType();
3444 NewT = S.Context.getAttributedType(
3445 attrKind: AttributedType::getNullabilityAttrKind(kind: *Oldnullability),
3446 modifiedType: NewT, equivalentType: NewT);
3447 NewParam->setType(NewT);
3448 }
3449 }
3450 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3451 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3452 if (OldParamDT && NewParamDT &&
3453 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3454 QualType OldParamOT = OldParamDT->getOriginalType();
3455 QualType NewParamOT = NewParamDT->getOriginalType();
3456 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3457 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3458 << NewParam << NewParamOT;
3459 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3460 << OldParamOT;
3461 }
3462 }
3463}
3464
3465namespace {
3466
3467/// Used in MergeFunctionDecl to keep track of function parameters in
3468/// C.
3469struct GNUCompatibleParamWarning {
3470 ParmVarDecl *OldParm;
3471 ParmVarDecl *NewParm;
3472 QualType PromotedType;
3473};
3474
3475} // end anonymous namespace
3476
3477// Determine whether the previous declaration was a definition, implicit
3478// declaration, or a declaration.
3479template <typename T>
3480static std::pair<diag::kind, SourceLocation>
3481getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3482 diag::kind PrevDiag;
3483 SourceLocation OldLocation = Old->getLocation();
3484 if (Old->isThisDeclarationADefinition())
3485 PrevDiag = diag::note_previous_definition;
3486 else if (Old->isImplicit()) {
3487 PrevDiag = diag::note_previous_implicit_declaration;
3488 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3489 if (FD->getBuiltinID())
3490 PrevDiag = diag::note_previous_builtin_declaration;
3491 }
3492 if (OldLocation.isInvalid())
3493 OldLocation = New->getLocation();
3494 } else
3495 PrevDiag = diag::note_previous_declaration;
3496 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3497}
3498
3499/// canRedefineFunction - checks if a function can be redefined. Currently,
3500/// only extern inline functions can be redefined, and even then only in
3501/// GNU89 mode.
3502static bool canRedefineFunction(const FunctionDecl *FD,
3503 const LangOptions& LangOpts) {
3504 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3505 !LangOpts.CPlusPlus &&
3506 FD->isInlineSpecified() &&
3507 FD->getStorageClass() == SC_Extern);
3508}
3509
3510const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3511 const AttributedType *AT = T->getAs<AttributedType>();
3512 while (AT && !AT->isCallingConv())
3513 AT = AT->getModifiedType()->getAs<AttributedType>();
3514 return AT;
3515}
3516
3517template <typename T>
3518static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3519 const DeclContext *DC = Old->getDeclContext();
3520 if (DC->isRecord())
3521 return false;
3522
3523 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3524 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3525 return true;
3526 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3527 return true;
3528 return false;
3529}
3530
3531template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3532static bool isExternC(VarTemplateDecl *) { return false; }
3533static bool isExternC(FunctionTemplateDecl *) { return false; }
3534
3535/// Check whether a redeclaration of an entity introduced by a
3536/// using-declaration is valid, given that we know it's not an overload
3537/// (nor a hidden tag declaration).
3538template<typename ExpectedDecl>
3539static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3540 ExpectedDecl *New) {
3541 // C++11 [basic.scope.declarative]p4:
3542 // Given a set of declarations in a single declarative region, each of
3543 // which specifies the same unqualified name,
3544 // -- they shall all refer to the same entity, or all refer to functions
3545 // and function templates; or
3546 // -- exactly one declaration shall declare a class name or enumeration
3547 // name that is not a typedef name and the other declarations shall all
3548 // refer to the same variable or enumerator, or all refer to functions
3549 // and function templates; in this case the class name or enumeration
3550 // name is hidden (3.3.10).
3551
3552 // C++11 [namespace.udecl]p14:
3553 // If a function declaration in namespace scope or block scope has the
3554 // same name and the same parameter-type-list as a function introduced
3555 // by a using-declaration, and the declarations do not declare the same
3556 // function, the program is ill-formed.
3557
3558 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3559 if (Old &&
3560 !Old->getDeclContext()->getRedeclContext()->Equals(
3561 New->getDeclContext()->getRedeclContext()) &&
3562 !(isExternC(Old) && isExternC(New)))
3563 Old = nullptr;
3564
3565 if (!Old) {
3566 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3567 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3568 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3569 return true;
3570 }
3571 return false;
3572}
3573
3574static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3575 const FunctionDecl *B) {
3576 assert(A->getNumParams() == B->getNumParams());
3577
3578 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3579 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3580 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3581 if (AttrA == AttrB)
3582 return true;
3583 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3584 AttrA->isDynamic() == AttrB->isDynamic();
3585 };
3586
3587 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3588}
3589
3590/// If necessary, adjust the semantic declaration context for a qualified
3591/// declaration to name the correct inline namespace within the qualifier.
3592static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3593 DeclaratorDecl *OldD) {
3594 // The only case where we need to update the DeclContext is when
3595 // redeclaration lookup for a qualified name finds a declaration
3596 // in an inline namespace within the context named by the qualifier:
3597 //
3598 // inline namespace N { int f(); }
3599 // int ::f(); // Sema DC needs adjusting from :: to N::.
3600 //
3601 // For unqualified declarations, the semantic context *can* change
3602 // along the redeclaration chain (for local extern declarations,
3603 // extern "C" declarations, and friend declarations in particular).
3604 if (!NewD->getQualifier())
3605 return;
3606
3607 // NewD is probably already in the right context.
3608 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3609 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3610 if (NamedDC->Equals(SemaDC))
3611 return;
3612
3613 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3614 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3615 "unexpected context for redeclaration");
3616
3617 auto *LexDC = NewD->getLexicalDeclContext();
3618 auto FixSemaDC = [=](NamedDecl *D) {
3619 if (!D)
3620 return;
3621 D->setDeclContext(SemaDC);
3622 D->setLexicalDeclContext(LexDC);
3623 };
3624
3625 FixSemaDC(NewD);
3626 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3627 FixSemaDC(FD->getDescribedFunctionTemplate());
3628 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3629 FixSemaDC(VD->getDescribedVarTemplate());
3630}
3631
3632/// MergeFunctionDecl - We just parsed a function 'New' from
3633/// declarator D which has the same name and scope as a previous
3634/// declaration 'Old'. Figure out how to resolve this situation,
3635/// merging decls or emitting diagnostics as appropriate.
3636///
3637/// In C++, New and Old must be declarations that are not
3638/// overloaded. Use IsOverload to determine whether New and Old are
3639/// overloaded, and to select the Old declaration that New should be
3640/// merged with.
3641///
3642/// Returns true if there was an error, false otherwise.
3643bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3644 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3645 // Verify the old decl was also a function.
3646 FunctionDecl *Old = OldD->getAsFunction();
3647 if (!Old) {
3648 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3649 if (New->getFriendObjectKind()) {
3650 Diag(New->getLocation(), diag::err_using_decl_friend);
3651 Diag(Shadow->getTargetDecl()->getLocation(),
3652 diag::note_using_decl_target);
3653 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3654 << 0;
3655 return true;
3656 }
3657
3658 // Check whether the two declarations might declare the same function or
3659 // function template.
3660 if (FunctionTemplateDecl *NewTemplate =
3661 New->getDescribedFunctionTemplate()) {
3662 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3663 New: NewTemplate))
3664 return true;
3665 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3666 ->getAsFunction();
3667 } else {
3668 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3669 return true;
3670 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3671 }
3672 } else {
3673 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3674 << New->getDeclName();
3675 notePreviousDefinition(Old: OldD, New: New->getLocation());
3676 return true;
3677 }
3678 }
3679
3680 // If the old declaration was found in an inline namespace and the new
3681 // declaration was qualified, update the DeclContext to match.
3682 adjustDeclContextForDeclaratorDecl(New, Old);
3683
3684 // If the old declaration is invalid, just give up here.
3685 if (Old->isInvalidDecl())
3686 return true;
3687
3688 // Disallow redeclaration of some builtins.
3689 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3690 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3691 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3692 << Old << Old->getType();
3693 return true;
3694 }
3695
3696 diag::kind PrevDiag;
3697 SourceLocation OldLocation;
3698 std::tie(args&: PrevDiag, args&: OldLocation) =
3699 getNoteDiagForInvalidRedeclaration(Old, New);
3700
3701 // Don't complain about this if we're in GNU89 mode and the old function
3702 // is an extern inline function.
3703 // Don't complain about specializations. They are not supposed to have
3704 // storage classes.
3705 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3706 New->getStorageClass() == SC_Static &&
3707 Old->hasExternalFormalLinkage() &&
3708 !New->getTemplateSpecializationInfo() &&
3709 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3710 if (getLangOpts().MicrosoftExt) {
3711 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3712 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3713 } else {
3714 Diag(New->getLocation(), diag::err_static_non_static) << New;
3715 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3716 return true;
3717 }
3718 }
3719
3720 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3721 if (!Old->hasAttr<InternalLinkageAttr>()) {
3722 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3723 << ILA;
3724 Diag(Old->getLocation(), diag::note_previous_declaration);
3725 New->dropAttr<InternalLinkageAttr>();
3726 }
3727
3728 if (auto *EA = New->getAttr<ErrorAttr>()) {
3729 if (!Old->hasAttr<ErrorAttr>()) {
3730 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3731 Diag(Old->getLocation(), diag::note_previous_declaration);
3732 New->dropAttr<ErrorAttr>();
3733 }
3734 }
3735
3736 if (CheckRedeclarationInModule(New, Old))
3737 return true;
3738
3739 if (!getLangOpts().CPlusPlus) {
3740 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3741 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3742 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3743 << New << OldOvl;
3744
3745 // Try our best to find a decl that actually has the overloadable
3746 // attribute for the note. In most cases (e.g. programs with only one
3747 // broken declaration/definition), this won't matter.
3748 //
3749 // FIXME: We could do this if we juggled some extra state in
3750 // OverloadableAttr, rather than just removing it.
3751 const Decl *DiagOld = Old;
3752 if (OldOvl) {
3753 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3754 const auto *A = D->getAttr<OverloadableAttr>();
3755 return A && !A->isImplicit();
3756 });
3757 // If we've implicitly added *all* of the overloadable attrs to this
3758 // chain, emitting a "previous redecl" note is pointless.
3759 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3760 }
3761
3762 if (DiagOld)
3763 Diag(DiagOld->getLocation(),
3764 diag::note_attribute_overloadable_prev_overload)
3765 << OldOvl;
3766
3767 if (OldOvl)
3768 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3769 else
3770 New->dropAttr<OverloadableAttr>();
3771 }
3772 }
3773
3774 // It is not permitted to redeclare an SME function with different SME
3775 // attributes.
3776 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3777 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3778 << New->getType() << Old->getType();
3779 Diag(OldLocation, diag::note_previous_declaration);
3780 return true;
3781 }
3782
3783 // If a function is first declared with a calling convention, but is later
3784 // declared or defined without one, all following decls assume the calling
3785 // convention of the first.
3786 //
3787 // It's OK if a function is first declared without a calling convention,
3788 // but is later declared or defined with the default calling convention.
3789 //
3790 // To test if either decl has an explicit calling convention, we look for
3791 // AttributedType sugar nodes on the type as written. If they are missing or
3792 // were canonicalized away, we assume the calling convention was implicit.
3793 //
3794 // Note also that we DO NOT return at this point, because we still have
3795 // other tests to run.
3796 QualType OldQType = Context.getCanonicalType(Old->getType());
3797 QualType NewQType = Context.getCanonicalType(New->getType());
3798 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3799 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3800 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3801 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3802 bool RequiresAdjustment = false;
3803
3804 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3805 FunctionDecl *First = Old->getFirstDecl();
3806 const FunctionType *FT =
3807 First->getType().getCanonicalType()->castAs<FunctionType>();
3808 FunctionType::ExtInfo FI = FT->getExtInfo();
3809 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3810 if (!NewCCExplicit) {
3811 // Inherit the CC from the previous declaration if it was specified
3812 // there but not here.
3813 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3814 RequiresAdjustment = true;
3815 } else if (Old->getBuiltinID()) {
3816 // Builtin attribute isn't propagated to the new one yet at this point,
3817 // so we check if the old one is a builtin.
3818
3819 // Calling Conventions on a Builtin aren't really useful and setting a
3820 // default calling convention and cdecl'ing some builtin redeclarations is
3821 // common, so warn and ignore the calling convention on the redeclaration.
3822 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3823 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3824 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3825 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3826 RequiresAdjustment = true;
3827 } else {
3828 // Calling conventions aren't compatible, so complain.
3829 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3830 Diag(New->getLocation(), diag::err_cconv_change)
3831 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3832 << !FirstCCExplicit
3833 << (!FirstCCExplicit ? "" :
3834 FunctionType::getNameForCallConv(FI.getCC()));
3835
3836 // Put the note on the first decl, since it is the one that matters.
3837 Diag(First->getLocation(), diag::note_previous_declaration);
3838 return true;
3839 }
3840 }
3841
3842 // FIXME: diagnose the other way around?
3843 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3844 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3845 RequiresAdjustment = true;
3846 }
3847
3848 // Merge regparm attribute.
3849 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3850 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3851 if (NewTypeInfo.getHasRegParm()) {
3852 Diag(New->getLocation(), diag::err_regparm_mismatch)
3853 << NewType->getRegParmType()
3854 << OldType->getRegParmType();
3855 Diag(OldLocation, diag::note_previous_declaration);
3856 return true;
3857 }
3858
3859 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3860 RequiresAdjustment = true;
3861 }
3862
3863 // Merge ns_returns_retained attribute.
3864 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3865 if (NewTypeInfo.getProducesResult()) {
3866 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3867 << "'ns_returns_retained'";
3868 Diag(OldLocation, diag::note_previous_declaration);
3869 return true;
3870 }
3871
3872 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3873 RequiresAdjustment = true;
3874 }
3875
3876 if (OldTypeInfo.getNoCallerSavedRegs() !=
3877 NewTypeInfo.getNoCallerSavedRegs()) {
3878 if (NewTypeInfo.getNoCallerSavedRegs()) {
3879 AnyX86NoCallerSavedRegistersAttr *Attr =
3880 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3881 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3882 Diag(OldLocation, diag::note_previous_declaration);
3883 return true;
3884 }
3885
3886 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3887 RequiresAdjustment = true;
3888 }
3889
3890 if (RequiresAdjustment) {
3891 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3892 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3893 New->setType(QualType(AdjustedType, 0));
3894 NewQType = Context.getCanonicalType(New->getType());
3895 }
3896
3897 // If this redeclaration makes the function inline, we may need to add it to
3898 // UndefinedButUsed.
3899 if (!Old->isInlined() && New->isInlined() &&
3900 !New->hasAttr<GNUInlineAttr>() &&
3901 !getLangOpts().GNUInline &&
3902 Old->isUsed(false) &&
3903 !Old->isDefined() && !New->isThisDeclarationADefinition())
3904 UndefinedButUsed.insert(std::make_pair(x: Old->getCanonicalDecl(),
3905 y: SourceLocation()));
3906
3907 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3908 // about it.
3909 if (New->hasAttr<GNUInlineAttr>() &&
3910 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3911 UndefinedButUsed.erase(Old->getCanonicalDecl());
3912 }
3913
3914 // If pass_object_size params don't match up perfectly, this isn't a valid
3915 // redeclaration.
3916 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3917 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3918 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3919 << New->getDeclName();
3920 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3921 return true;
3922 }
3923
3924 if (getLangOpts().CPlusPlus) {
3925 OldQType = Context.getCanonicalType(Old->getType());
3926 NewQType = Context.getCanonicalType(New->getType());
3927
3928 // Go back to the type source info to compare the declared return types,
3929 // per C++1y [dcl.type.auto]p13:
3930 // Redeclarations or specializations of a function or function template
3931 // with a declared return type that uses a placeholder type shall also
3932 // use that placeholder, not a deduced type.
3933 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3934 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3935 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
3936 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3937 OldDeclaredReturnType)) {
3938 QualType ResQT;
3939 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3940 OldDeclaredReturnType->isObjCObjectPointerType())
3941 // FIXME: This does the wrong thing for a deduced return type.
3942 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3943 if (ResQT.isNull()) {
3944 if (New->isCXXClassMember() && New->isOutOfLine())
3945 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3946 << New << New->getReturnTypeSourceRange();
3947 else
3948 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3949 << New->getReturnTypeSourceRange();
3950 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
3951 << Old->getReturnTypeSourceRange();
3952 return true;
3953 }
3954 else
3955 NewQType = ResQT;
3956 }
3957
3958 QualType OldReturnType = OldType->getReturnType();
3959 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
3960 if (OldReturnType != NewReturnType) {
3961 // If this function has a deduced return type and has already been
3962 // defined, copy the deduced value from the old declaration.
3963 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3964 if (OldAT && OldAT->isDeduced()) {
3965 QualType DT = OldAT->getDeducedType();
3966 if (DT.isNull()) {
3967 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
3968 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
3969 } else {
3970 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
3971 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
3972 }
3973 }
3974 }
3975
3976 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
3977 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
3978 if (OldMethod && NewMethod) {
3979 // Preserve triviality.
3980 NewMethod->setTrivial(OldMethod->isTrivial());
3981
3982 // MSVC allows explicit template specialization at class scope:
3983 // 2 CXXMethodDecls referring to the same function will be injected.
3984 // We don't want a redeclaration error.
3985 bool IsClassScopeExplicitSpecialization =
3986 OldMethod->isFunctionTemplateSpecialization() &&
3987 NewMethod->isFunctionTemplateSpecialization();
3988 bool isFriend = NewMethod->getFriendObjectKind();
3989
3990 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3991 !IsClassScopeExplicitSpecialization) {
3992 // -- Member function declarations with the same name and the
3993 // same parameter types cannot be overloaded if any of them
3994 // is a static member function declaration.
3995 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3996 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3997 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3998 return true;
3999 }
4000
4001 // C++ [class.mem]p1:
4002 // [...] A member shall not be declared twice in the
4003 // member-specification, except that a nested class or member
4004 // class template can be declared and then later defined.
4005 if (!inTemplateInstantiation()) {
4006 unsigned NewDiag;
4007 if (isa<CXXConstructorDecl>(OldMethod))
4008 NewDiag = diag::err_constructor_redeclared;
4009 else if (isa<CXXDestructorDecl>(NewMethod))
4010 NewDiag = diag::err_destructor_redeclared;
4011 else if (isa<CXXConversionDecl>(NewMethod))
4012 NewDiag = diag::err_conv_function_redeclared;
4013 else
4014 NewDiag = diag::err_member_redeclared;
4015
4016 Diag(New->getLocation(), NewDiag);
4017 } else {
4018 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4019 << New << New->getType();
4020 }
4021 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4022 return true;
4023
4024 // Complain if this is an explicit declaration of a special
4025 // member that was initially declared implicitly.
4026 //
4027 // As an exception, it's okay to befriend such methods in order
4028 // to permit the implicit constructor/destructor/operator calls.
4029 } else if (OldMethod->isImplicit()) {
4030 if (isFriend) {
4031 NewMethod->setImplicit();
4032 } else {
4033 Diag(NewMethod->getLocation(),
4034 diag::err_definition_of_implicitly_declared_member)
4035 << New << getSpecialMember(OldMethod);
4036 return true;
4037 }
4038 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4039 Diag(NewMethod->getLocation(),
4040 diag::err_definition_of_explicitly_defaulted_member)
4041 << getSpecialMember(OldMethod);
4042 return true;
4043 }
4044 }
4045
4046 // C++1z [over.load]p2
4047 // Certain function declarations cannot be overloaded:
4048 // -- Function declarations that differ only in the return type,
4049 // the exception specification, or both cannot be overloaded.
4050
4051 // Check the exception specifications match. This may recompute the type of
4052 // both Old and New if it resolved exception specifications, so grab the
4053 // types again after this. Because this updates the type, we do this before
4054 // any of the other checks below, which may update the "de facto" NewQType
4055 // but do not necessarily update the type of New.
4056 if (CheckEquivalentExceptionSpec(Old, New))
4057 return true;
4058
4059 // C++11 [dcl.attr.noreturn]p1:
4060 // The first declaration of a function shall specify the noreturn
4061 // attribute if any declaration of that function specifies the noreturn
4062 // attribute.
4063 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4064 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4065 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4066 << NRA;
4067 Diag(Old->getLocation(), diag::note_previous_declaration);
4068 }
4069
4070 // C++11 [dcl.attr.depend]p2:
4071 // The first declaration of a function shall specify the
4072 // carries_dependency attribute for its declarator-id if any declaration
4073 // of the function specifies the carries_dependency attribute.
4074 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4075 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4076 Diag(CDA->getLocation(),
4077 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4078 Diag(Old->getFirstDecl()->getLocation(),
4079 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4080 }
4081
4082 // (C++98 8.3.5p3):
4083 // All declarations for a function shall agree exactly in both the
4084 // return type and the parameter-type-list.
4085 // We also want to respect all the extended bits except noreturn.
4086
4087 // noreturn should now match unless the old type info didn't have it.
4088 QualType OldQTypeForComparison = OldQType;
4089 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4090 auto *OldType = OldQType->castAs<FunctionProtoType>();
4091 const FunctionType *OldTypeForComparison
4092 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4093 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4094 assert(OldQTypeForComparison.isCanonical());
4095 }
4096
4097 if (haveIncompatibleLanguageLinkages(Old, New)) {
4098 // As a special case, retain the language linkage from previous
4099 // declarations of a friend function as an extension.
4100 //
4101 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4102 // and is useful because there's otherwise no way to specify language
4103 // linkage within class scope.
4104 //
4105 // Check cautiously as the friend object kind isn't yet complete.
4106 if (New->getFriendObjectKind() != Decl::FOK_None) {
4107 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4108 Diag(Loc: OldLocation, DiagID: PrevDiag);
4109 } else {
4110 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4111 Diag(Loc: OldLocation, DiagID: PrevDiag);
4112 return true;
4113 }
4114 }
4115
4116 // If the function types are compatible, merge the declarations. Ignore the
4117 // exception specifier because it was already checked above in
4118 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4119 // about incompatible types under -fms-compatibility.
4120 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4121 U: NewQType))
4122 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4123
4124 // If the types are imprecise (due to dependent constructs in friends or
4125 // local extern declarations), it's OK if they differ. We'll check again
4126 // during instantiation.
4127 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4128 return false;
4129
4130 // Fall through for conflicting redeclarations and redefinitions.
4131 }
4132
4133 // C: Function types need to be compatible, not identical. This handles
4134 // duplicate function decls like "void f(int); void f(enum X);" properly.
4135 if (!getLangOpts().CPlusPlus) {
4136 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4137 // type is specified by a function definition that contains a (possibly
4138 // empty) identifier list, both shall agree in the number of parameters
4139 // and the type of each parameter shall be compatible with the type that
4140 // results from the application of default argument promotions to the
4141 // type of the corresponding identifier. ...
4142 // This cannot be handled by ASTContext::typesAreCompatible() because that
4143 // doesn't know whether the function type is for a definition or not when
4144 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4145 // we need to cover here is that the number of arguments agree as the
4146 // default argument promotion rules were already checked by
4147 // ASTContext::typesAreCompatible().
4148 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4149 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4150 if (Old->hasInheritedPrototype())
4151 Old = Old->getCanonicalDecl();
4152 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4153 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4154 return true;
4155 }
4156
4157 // If we are merging two functions where only one of them has a prototype,
4158 // we may have enough information to decide to issue a diagnostic that the
4159 // function without a protoype will change behavior in C23. This handles
4160 // cases like:
4161 // void i(); void i(int j);
4162 // void i(int j); void i();
4163 // void i(); void i(int j) {}
4164 // See ActOnFinishFunctionBody() for other cases of the behavior change
4165 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4166 // type without a prototype.
4167 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4168 !New->isImplicit() && !Old->isImplicit()) {
4169 const FunctionDecl *WithProto, *WithoutProto;
4170 if (New->hasWrittenPrototype()) {
4171 WithProto = New;
4172 WithoutProto = Old;
4173 } else {
4174 WithProto = Old;
4175 WithoutProto = New;
4176 }
4177
4178 if (WithProto->getNumParams() != 0) {
4179 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4180 // The one without the prototype will be changing behavior in C23, so
4181 // warn about that one so long as it's a user-visible declaration.
4182 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4183 if (WithoutProto == New)
4184 IsWithoutProtoADef = NewDeclIsDefn;
4185 else
4186 IsWithProtoADef = NewDeclIsDefn;
4187 Diag(WithoutProto->getLocation(),
4188 diag::warn_non_prototype_changes_behavior)
4189 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4190 << (WithoutProto == Old) << IsWithProtoADef;
4191
4192 // The reason the one without the prototype will be changing behavior
4193 // is because of the one with the prototype, so note that so long as
4194 // it's a user-visible declaration. There is one exception to this:
4195 // when the new declaration is a definition without a prototype, the
4196 // old declaration with a prototype is not the cause of the issue,
4197 // and that does not need to be noted because the one with a
4198 // prototype will not change behavior in C23.
4199 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4200 !IsWithoutProtoADef)
4201 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4202 }
4203 }
4204 }
4205
4206 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4207 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4208 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4209 const FunctionProtoType *OldProto = nullptr;
4210 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4211 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4212 // The old declaration provided a function prototype, but the
4213 // new declaration does not. Merge in the prototype.
4214 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4215 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4216 Args: OldProto->getParamTypes(),
4217 EPI: OldProto->getExtProtoInfo());
4218 New->setType(NewQType);
4219 New->setHasInheritedPrototype();
4220
4221 // Synthesize parameters with the same types.
4222 SmallVector<ParmVarDecl *, 16> Params;
4223 for (const auto &ParamType : OldProto->param_types()) {
4224 ParmVarDecl *Param = ParmVarDecl::Create(
4225 Context, New, SourceLocation(), SourceLocation(), nullptr,
4226 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4227 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4228 Param->setImplicit();
4229 Params.push_back(Elt: Param);
4230 }
4231
4232 New->setParams(Params);
4233 }
4234
4235 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4236 }
4237 }
4238
4239 // Check if the function types are compatible when pointer size address
4240 // spaces are ignored.
4241 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4242 return false;
4243
4244 // GNU C permits a K&R definition to follow a prototype declaration
4245 // if the declared types of the parameters in the K&R definition
4246 // match the types in the prototype declaration, even when the
4247 // promoted types of the parameters from the K&R definition differ
4248 // from the types in the prototype. GCC then keeps the types from
4249 // the prototype.
4250 //
4251 // If a variadic prototype is followed by a non-variadic K&R definition,
4252 // the K&R definition becomes variadic. This is sort of an edge case, but
4253 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4254 // C99 6.9.1p8.
4255 if (!getLangOpts().CPlusPlus &&
4256 Old->hasPrototype() && !New->hasPrototype() &&
4257 New->getType()->getAs<FunctionProtoType>() &&
4258 Old->getNumParams() == New->getNumParams()) {
4259 SmallVector<QualType, 16> ArgTypes;
4260 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4261 const FunctionProtoType *OldProto
4262 = Old->getType()->getAs<FunctionProtoType>();
4263 const FunctionProtoType *NewProto
4264 = New->getType()->getAs<FunctionProtoType>();
4265
4266 // Determine whether this is the GNU C extension.
4267 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4268 NewProto->getReturnType());
4269 bool LooseCompatible = !MergedReturn.isNull();
4270 for (unsigned Idx = 0, End = Old->getNumParams();
4271 LooseCompatible && Idx != End; ++Idx) {
4272 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4273 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4274 if (Context.typesAreCompatible(T1: OldParm->getType(),
4275 T2: NewProto->getParamType(i: Idx))) {
4276 ArgTypes.push_back(Elt: NewParm->getType());
4277 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4278 T2: NewParm->getType(),
4279 /*CompareUnqualified=*/true)) {
4280 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4281 NewProto->getParamType(i: Idx) };
4282 Warnings.push_back(Elt: Warn);
4283 ArgTypes.push_back(Elt: NewParm->getType());
4284 } else
4285 LooseCompatible = false;
4286 }
4287
4288 if (LooseCompatible) {
4289 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4290 Diag(Warnings[Warn].NewParm->getLocation(),
4291 diag::ext_param_promoted_not_compatible_with_prototype)
4292 << Warnings[Warn].PromotedType
4293 << Warnings[Warn].OldParm->getType();
4294 if (Warnings[Warn].OldParm->getLocation().isValid())
4295 Diag(Warnings[Warn].OldParm->getLocation(),
4296 diag::note_previous_declaration);
4297 }
4298
4299 if (MergeTypeWithOld)
4300 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4301 EPI: OldProto->getExtProtoInfo()));
4302 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4303 }
4304
4305 // Fall through to diagnose conflicting types.
4306 }
4307
4308 // A function that has already been declared has been redeclared or
4309 // defined with a different type; show an appropriate diagnostic.
4310
4311 // If the previous declaration was an implicitly-generated builtin
4312 // declaration, then at the very least we should use a specialized note.
4313 unsigned BuiltinID;
4314 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4315 // If it's actually a library-defined builtin function like 'malloc'
4316 // or 'printf', just warn about the incompatible redeclaration.
4317 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4318 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4319 Diag(OldLocation, diag::note_previous_builtin_declaration)
4320 << Old << Old->getType();
4321 return false;
4322 }
4323
4324 PrevDiag = diag::note_previous_builtin_declaration;
4325 }
4326
4327 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4328 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4329 return true;
4330}
4331
4332/// Completes the merge of two function declarations that are
4333/// known to be compatible.
4334///
4335/// This routine handles the merging of attributes and other
4336/// properties of function declarations from the old declaration to
4337/// the new declaration, once we know that New is in fact a
4338/// redeclaration of Old.
4339///
4340/// \returns false
4341bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4342 Scope *S, bool MergeTypeWithOld) {
4343 // Merge the attributes
4344 mergeDeclAttributes(New, Old);
4345
4346 // Merge "pure" flag.
4347 if (Old->isPureVirtual())
4348 New->setIsPureVirtual();
4349
4350 // Merge "used" flag.
4351 if (Old->getMostRecentDecl()->isUsed(false))
4352 New->setIsUsed();
4353
4354 // Merge attributes from the parameters. These can mismatch with K&R
4355 // declarations.
4356 if (New->getNumParams() == Old->getNumParams())
4357 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4358 ParmVarDecl *NewParam = New->getParamDecl(i);
4359 ParmVarDecl *OldParam = Old->getParamDecl(i);
4360 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4361 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4362 }
4363
4364 if (getLangOpts().CPlusPlus)
4365 return MergeCXXFunctionDecl(New, Old, S);
4366
4367 // Merge the function types so the we get the composite types for the return
4368 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4369 // was visible.
4370 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4371 if (!Merged.isNull() && MergeTypeWithOld)
4372 New->setType(Merged);
4373
4374 return false;
4375}
4376
4377void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4378 ObjCMethodDecl *oldMethod) {
4379 // Merge the attributes, including deprecated/unavailable
4380 AvailabilityMergeKind MergeKind =
4381 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4382 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4383 : AMK_ProtocolImplementation)
4384 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4385 : AMK_Override;
4386
4387 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4388
4389 // Merge attributes from the parameters.
4390 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4391 oe = oldMethod->param_end();
4392 for (ObjCMethodDecl::param_iterator
4393 ni = newMethod->param_begin(), ne = newMethod->param_end();
4394 ni != ne && oi != oe; ++ni, ++oi)
4395 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4396
4397 CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4398}
4399
4400static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4401 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4402
4403 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4404 ? diag::err_redefinition_different_type
4405 : diag::err_redeclaration_different_type)
4406 << New->getDeclName() << New->getType() << Old->getType();
4407
4408 diag::kind PrevDiag;
4409 SourceLocation OldLocation;
4410 std::tie(args&: PrevDiag, args&: OldLocation)
4411 = getNoteDiagForInvalidRedeclaration(Old, New);
4412 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4413 New->setInvalidDecl();
4414}
4415
4416/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4417/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4418/// emitting diagnostics as appropriate.
4419///
4420/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4421/// to here in AddInitializerToDecl. We can't check them before the initializer
4422/// is attached.
4423void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4424 bool MergeTypeWithOld) {
4425 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4426 return;
4427
4428 QualType MergedT;
4429 if (getLangOpts().CPlusPlus) {
4430 if (New->getType()->isUndeducedType()) {
4431 // We don't know what the new type is until the initializer is attached.
4432 return;
4433 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4434 // These could still be something that needs exception specs checked.
4435 return MergeVarDeclExceptionSpecs(New, Old);
4436 }
4437 // C++ [basic.link]p10:
4438 // [...] the types specified by all declarations referring to a given
4439 // object or function shall be identical, except that declarations for an
4440 // array object can specify array types that differ by the presence or
4441 // absence of a major array bound (8.3.4).
4442 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4443 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4444 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4445
4446 // We are merging a variable declaration New into Old. If it has an array
4447 // bound, and that bound differs from Old's bound, we should diagnose the
4448 // mismatch.
4449 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4450 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4451 PrevVD = PrevVD->getPreviousDecl()) {
4452 QualType PrevVDTy = PrevVD->getType();
4453 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4454 continue;
4455
4456 if (!Context.hasSameType(New->getType(), PrevVDTy))
4457 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4458 }
4459 }
4460
4461 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4462 if (Context.hasSameType(T1: OldArray->getElementType(),
4463 T2: NewArray->getElementType()))
4464 MergedT = New->getType();
4465 }
4466 // FIXME: Check visibility. New is hidden but has a complete type. If New
4467 // has no array bound, it should not inherit one from Old, if Old is not
4468 // visible.
4469 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4470 if (Context.hasSameType(T1: OldArray->getElementType(),
4471 T2: NewArray->getElementType()))
4472 MergedT = Old->getType();
4473 }
4474 }
4475 else if (New->getType()->isObjCObjectPointerType() &&
4476 Old->getType()->isObjCObjectPointerType()) {
4477 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4478 Old->getType());
4479 }
4480 } else {
4481 // C 6.2.7p2:
4482 // All declarations that refer to the same object or function shall have
4483 // compatible type.
4484 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4485 }
4486 if (MergedT.isNull()) {
4487 // It's OK if we couldn't merge types if either type is dependent, for a
4488 // block-scope variable. In other cases (static data members of class
4489 // templates, variable templates, ...), we require the types to be
4490 // equivalent.
4491 // FIXME: The C++ standard doesn't say anything about this.
4492 if ((New->getType()->isDependentType() ||
4493 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4494 // If the old type was dependent, we can't merge with it, so the new type
4495 // becomes dependent for now. We'll reproduce the original type when we
4496 // instantiate the TypeSourceInfo for the variable.
4497 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4498 New->setType(Context.DependentTy);
4499 return;
4500 }
4501 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4502 }
4503
4504 // Don't actually update the type on the new declaration if the old
4505 // declaration was an extern declaration in a different scope.
4506 if (MergeTypeWithOld)
4507 New->setType(MergedT);
4508}
4509
4510static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4511 LookupResult &Previous) {
4512 // C11 6.2.7p4:
4513 // For an identifier with internal or external linkage declared
4514 // in a scope in which a prior declaration of that identifier is
4515 // visible, if the prior declaration specifies internal or
4516 // external linkage, the type of the identifier at the later
4517 // declaration becomes the composite type.
4518 //
4519 // If the variable isn't visible, we do not merge with its type.
4520 if (Previous.isShadowed())
4521 return false;
4522
4523 if (S.getLangOpts().CPlusPlus) {
4524 // C++11 [dcl.array]p3:
4525 // If there is a preceding declaration of the entity in the same
4526 // scope in which the bound was specified, an omitted array bound
4527 // is taken to be the same as in that earlier declaration.
4528 return NewVD->isPreviousDeclInSameBlockScope() ||
4529 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4530 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4531 } else {
4532 // If the old declaration was function-local, don't merge with its
4533 // type unless we're in the same function.
4534 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4535 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4536 }
4537}
4538
4539/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4540/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4541/// situation, merging decls or emitting diagnostics as appropriate.
4542///
4543/// Tentative definition rules (C99 6.9.2p2) are checked by
4544/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4545/// definitions here, since the initializer hasn't been attached.
4546///
4547void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4548 // If the new decl is already invalid, don't do any other checking.
4549 if (New->isInvalidDecl())
4550 return;
4551
4552 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4553 return;
4554
4555 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4556
4557 // Verify the old decl was also a variable or variable template.
4558 VarDecl *Old = nullptr;
4559 VarTemplateDecl *OldTemplate = nullptr;
4560 if (Previous.isSingleResult()) {
4561 if (NewTemplate) {
4562 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4563 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4564
4565 if (auto *Shadow =
4566 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4567 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4568 return New->setInvalidDecl();
4569 } else {
4570 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4571
4572 if (auto *Shadow =
4573 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4574 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4575 return New->setInvalidDecl();
4576 }
4577 }
4578 if (!Old) {
4579 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4580 << New->getDeclName();
4581 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4582 New: New->getLocation());
4583 return New->setInvalidDecl();
4584 }
4585
4586 // If the old declaration was found in an inline namespace and the new
4587 // declaration was qualified, update the DeclContext to match.
4588 adjustDeclContextForDeclaratorDecl(New, Old);
4589
4590 // Ensure the template parameters are compatible.
4591 if (NewTemplate &&
4592 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4593 OldTemplate->getTemplateParameters(),
4594 /*Complain=*/true, TPL_TemplateMatch))
4595 return New->setInvalidDecl();
4596
4597 // C++ [class.mem]p1:
4598 // A member shall not be declared twice in the member-specification [...]
4599 //
4600 // Here, we need only consider static data members.
4601 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4602 Diag(New->getLocation(), diag::err_duplicate_member)
4603 << New->getIdentifier();
4604 Diag(Old->getLocation(), diag::note_previous_declaration);
4605 New->setInvalidDecl();
4606 }
4607
4608 mergeDeclAttributes(New, Old);
4609 // Warn if an already-declared variable is made a weak_import in a subsequent
4610 // declaration
4611 if (New->hasAttr<WeakImportAttr>() &&
4612 Old->getStorageClass() == SC_None &&
4613 !Old->hasAttr<WeakImportAttr>()) {
4614 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4615 Diag(Old->getLocation(), diag::note_previous_declaration);
4616 // Remove weak_import attribute on new declaration.
4617 New->dropAttr<WeakImportAttr>();
4618 }
4619
4620 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4621 if (!Old->hasAttr<InternalLinkageAttr>()) {
4622 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4623 << ILA;
4624 Diag(Old->getLocation(), diag::note_previous_declaration);
4625 New->dropAttr<InternalLinkageAttr>();
4626 }
4627
4628 // Merge the types.
4629 VarDecl *MostRecent = Old->getMostRecentDecl();
4630 if (MostRecent != Old) {
4631 MergeVarDeclTypes(New, Old: MostRecent,
4632 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4633 if (New->isInvalidDecl())
4634 return;
4635 }
4636
4637 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4638 if (New->isInvalidDecl())
4639 return;
4640
4641 diag::kind PrevDiag;
4642 SourceLocation OldLocation;
4643 std::tie(args&: PrevDiag, args&: OldLocation) =
4644 getNoteDiagForInvalidRedeclaration(Old, New);
4645
4646 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4647 if (New->getStorageClass() == SC_Static &&
4648 !New->isStaticDataMember() &&
4649 Old->hasExternalFormalLinkage()) {
4650 if (getLangOpts().MicrosoftExt) {
4651 Diag(New->getLocation(), diag::ext_static_non_static)
4652 << New->getDeclName();
4653 Diag(Loc: OldLocation, DiagID: PrevDiag);
4654 } else {
4655 Diag(New->getLocation(), diag::err_static_non_static)
4656 << New->getDeclName();
4657 Diag(Loc: OldLocation, DiagID: PrevDiag);
4658 return New->setInvalidDecl();
4659 }
4660 }
4661 // C99 6.2.2p4:
4662 // For an identifier declared with the storage-class specifier
4663 // extern in a scope in which a prior declaration of that
4664 // identifier is visible,23) if the prior declaration specifies
4665 // internal or external linkage, the linkage of the identifier at
4666 // the later declaration is the same as the linkage specified at
4667 // the prior declaration. If no prior declaration is visible, or
4668 // if the prior declaration specifies no linkage, then the
4669 // identifier has external linkage.
4670 if (New->hasExternalStorage() && Old->hasLinkage())
4671 /* Okay */;
4672 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4673 !New->isStaticDataMember() &&
4674 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4675 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4676 Diag(Loc: OldLocation, DiagID: PrevDiag);
4677 return New->setInvalidDecl();
4678 }
4679
4680 // Check if extern is followed by non-extern and vice-versa.
4681 if (New->hasExternalStorage() &&
4682 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4683 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4684 Diag(Loc: OldLocation, DiagID: PrevDiag);
4685 return New->setInvalidDecl();
4686 }
4687 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4688 !New->hasExternalStorage()) {
4689 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4690 Diag(Loc: OldLocation, DiagID: PrevDiag);
4691 return New->setInvalidDecl();
4692 }
4693
4694 if (CheckRedeclarationInModule(New, Old))
4695 return;
4696
4697 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4698
4699 // FIXME: The test for external storage here seems wrong? We still
4700 // need to check for mismatches.
4701 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4702 // Don't complain about out-of-line definitions of static members.
4703 !(Old->getLexicalDeclContext()->isRecord() &&
4704 !New->getLexicalDeclContext()->isRecord())) {
4705 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4706 Diag(Loc: OldLocation, DiagID: PrevDiag);
4707 return New->setInvalidDecl();
4708 }
4709
4710 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4711 if (VarDecl *Def = Old->getDefinition()) {
4712 // C++1z [dcl.fcn.spec]p4:
4713 // If the definition of a variable appears in a translation unit before
4714 // its first declaration as inline, the program is ill-formed.
4715 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4716 Diag(Def->getLocation(), diag::note_previous_definition);
4717 }
4718 }
4719
4720 // If this redeclaration makes the variable inline, we may need to add it to
4721 // UndefinedButUsed.
4722 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4723 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4724 UndefinedButUsed.insert(std::make_pair(x: Old->getCanonicalDecl(),
4725 y: SourceLocation()));
4726
4727 if (New->getTLSKind() != Old->getTLSKind()) {
4728 if (!Old->getTLSKind()) {
4729 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4730 Diag(Loc: OldLocation, DiagID: PrevDiag);
4731 } else if (!New->getTLSKind()) {
4732 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4733 Diag(Loc: OldLocation, DiagID: PrevDiag);
4734 } else {
4735 // Do not allow redeclaration to change the variable between requiring
4736 // static and dynamic initialization.
4737 // FIXME: GCC allows this, but uses the TLS keyword on the first
4738 // declaration to determine the kind. Do we need to be compatible here?
4739 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4740 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4741 Diag(Loc: OldLocation, DiagID: PrevDiag);
4742 }
4743 }
4744
4745 // C++ doesn't have tentative definitions, so go right ahead and check here.
4746 if (getLangOpts().CPlusPlus) {
4747 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4748 Old->getCanonicalDecl()->isConstexpr()) {
4749 // This definition won't be a definition any more once it's been merged.
4750 Diag(New->getLocation(),
4751 diag::warn_deprecated_redundant_constexpr_static_def);
4752 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4753 VarDecl *Def = Old->getDefinition();
4754 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4755 return;
4756 }
4757 }
4758
4759 if (haveIncompatibleLanguageLinkages(Old, New)) {
4760 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4761 Diag(Loc: OldLocation, DiagID: PrevDiag);
4762 New->setInvalidDecl();
4763 return;
4764 }
4765
4766 // Merge "used" flag.
4767 if (Old->getMostRecentDecl()->isUsed(false))
4768 New->setIsUsed();
4769
4770 // Keep a chain of previous declarations.
4771 New->setPreviousDecl(Old);
4772 if (NewTemplate)
4773 NewTemplate->setPreviousDecl(OldTemplate);
4774
4775 // Inherit access appropriately.
4776 New->setAccess(Old->getAccess());
4777 if (NewTemplate)
4778 NewTemplate->setAccess(New->getAccess());
4779
4780 if (Old->isInline())
4781 New->setImplicitlyInline();
4782}
4783
4784void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4785 SourceManager &SrcMgr = getSourceManager();
4786 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4787 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4788 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4789 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4790 auto &HSI = PP.getHeaderSearchInfo();
4791 StringRef HdrFilename =
4792 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4793
4794 auto noteFromModuleOrInclude = [&](Module *Mod,
4795 SourceLocation IncLoc) -> bool {
4796 // Redefinition errors with modules are common with non modular mapped
4797 // headers, example: a non-modular header H in module A that also gets
4798 // included directly in a TU. Pointing twice to the same header/definition
4799 // is confusing, try to get better diagnostics when modules is on.
4800 if (IncLoc.isValid()) {
4801 if (Mod) {
4802 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4803 << HdrFilename.str() << Mod->getFullModuleName();
4804 if (!Mod->DefinitionLoc.isInvalid())
4805 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4806 << Mod->getFullModuleName();
4807 } else {
4808 Diag(IncLoc, diag::note_redefinition_include_same_file)
4809 << HdrFilename.str();
4810 }
4811 return true;
4812 }
4813
4814 return false;
4815 };
4816
4817 // Is it the same file and same offset? Provide more information on why
4818 // this leads to a redefinition error.
4819 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4820 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4821 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4822 bool EmittedDiag =
4823 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4824 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4825
4826 // If the header has no guards, emit a note suggesting one.
4827 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4828 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4829
4830 if (EmittedDiag)
4831 return;
4832 }
4833
4834 // Redefinition coming from different files or couldn't do better above.
4835 if (Old->getLocation().isValid())
4836 Diag(Old->getLocation(), diag::note_previous_definition);
4837}
4838
4839/// We've just determined that \p Old and \p New both appear to be definitions
4840/// of the same variable. Either diagnose or fix the problem.
4841bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4842 if (!hasVisibleDefinition(Old) &&
4843 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4844 isa<VarTemplateSpecializationDecl>(Val: New) ||
4845 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4846 New->getDeclContext()->isDependentContext())) {
4847 // The previous definition is hidden, and multiple definitions are
4848 // permitted (in separate TUs). Demote this to a declaration.
4849 New->demoteThisDefinitionToDeclaration();
4850
4851 // Make the canonical definition visible.
4852 if (auto *OldTD = Old->getDescribedVarTemplate())
4853 makeMergedDefinitionVisible(OldTD);
4854 makeMergedDefinitionVisible(Old);
4855 return false;
4856 } else {
4857 Diag(New->getLocation(), diag::err_redefinition) << New;
4858 notePreviousDefinition(Old, New: New->getLocation());
4859 New->setInvalidDecl();
4860 return true;
4861 }
4862}
4863
4864/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4865/// no declarator (e.g. "struct foo;") is parsed.
4866Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4867 DeclSpec &DS,
4868 const ParsedAttributesView &DeclAttrs,
4869 RecordDecl *&AnonRecord) {
4870 return ParsedFreeStandingDeclSpec(
4871 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
4872}
4873
4874// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4875// disambiguate entities defined in different scopes.
4876// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4877// compatibility.
4878// We will pick our mangling number depending on which version of MSVC is being
4879// targeted.
4880static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4881 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
4882 ? S->getMSCurManglingNumber()
4883 : S->getMSLastManglingNumber();
4884}
4885
4886void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4887 if (!Context.getLangOpts().CPlusPlus)
4888 return;
4889
4890 if (isa<CXXRecordDecl>(Tag->getParent())) {
4891 // If this tag is the direct child of a class, number it if
4892 // it is anonymous.
4893 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4894 return;
4895 MangleNumberingContext &MCtx =
4896 Context.getManglingNumberContext(Tag->getParent());
4897 Context.setManglingNumber(
4898 Tag, MCtx.getManglingNumber(
4899 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4900 return;
4901 }
4902
4903 // If this tag isn't a direct child of a class, number it if it is local.
4904 MangleNumberingContext *MCtx;
4905 Decl *ManglingContextDecl;
4906 std::tie(args&: MCtx, args&: ManglingContextDecl) =
4907 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
4908 if (MCtx) {
4909 Context.setManglingNumber(
4910 Tag, MCtx->getManglingNumber(
4911 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4912 }
4913}
4914
4915namespace {
4916struct NonCLikeKind {
4917 enum {
4918 None,
4919 BaseClass,
4920 DefaultMemberInit,
4921 Lambda,
4922 Friend,
4923 OtherMember,
4924 Invalid,
4925 } Kind = None;
4926 SourceRange Range;
4927
4928 explicit operator bool() { return Kind != None; }
4929};
4930}
4931
4932/// Determine whether a class is C-like, according to the rules of C++
4933/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4934static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4935 if (RD->isInvalidDecl())
4936 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
4937
4938 // C++ [dcl.typedef]p9: [P1766R1]
4939 // An unnamed class with a typedef name for linkage purposes shall not
4940 //
4941 // -- have any base classes
4942 if (RD->getNumBases())
4943 return {.Kind: NonCLikeKind::BaseClass,
4944 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
4945 RD->bases_end()[-1].getEndLoc())};
4946 bool Invalid = false;
4947 for (Decl *D : RD->decls()) {
4948 // Don't complain about things we already diagnosed.
4949 if (D->isInvalidDecl()) {
4950 Invalid = true;
4951 continue;
4952 }
4953
4954 // -- have any [...] default member initializers
4955 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4956 if (FD->hasInClassInitializer()) {
4957 auto *Init = FD->getInClassInitializer();
4958 return {NonCLikeKind::DefaultMemberInit,
4959 Init ? Init->getSourceRange() : D->getSourceRange()};
4960 }
4961 continue;
4962 }
4963
4964 // FIXME: We don't allow friend declarations. This violates the wording of
4965 // P1766, but not the intent.
4966 if (isa<FriendDecl>(D))
4967 return {NonCLikeKind::Friend, D->getSourceRange()};
4968
4969 // -- declare any members other than non-static data members, member
4970 // enumerations, or member classes,
4971 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4972 isa<EnumDecl>(D))
4973 continue;
4974 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4975 if (!MemberRD) {
4976 if (D->isImplicit())
4977 continue;
4978 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4979 }
4980
4981 // -- contain a lambda-expression,
4982 if (MemberRD->isLambda())
4983 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4984
4985 // and all member classes shall also satisfy these requirements
4986 // (recursively).
4987 if (MemberRD->isThisDeclarationADefinition()) {
4988 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4989 return Kind;
4990 }
4991 }
4992
4993 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
4994}
4995
4996void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4997 TypedefNameDecl *NewTD) {
4998 if (TagFromDeclSpec->isInvalidDecl())
4999 return;
5000
5001 // Do nothing if the tag already has a name for linkage purposes.
5002 if (TagFromDeclSpec->hasNameForLinkage())
5003 return;
5004
5005 // A well-formed anonymous tag must always be a TUK_Definition.
5006 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5007
5008 // The type must match the tag exactly; no qualifiers allowed.
5009 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5010 T2: Context.getTagDeclType(Decl: TagFromDeclSpec))) {
5011 if (getLangOpts().CPlusPlus)
5012 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5013 return;
5014 }
5015
5016 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5017 // An unnamed class with a typedef name for linkage purposes shall [be
5018 // C-like].
5019 //
5020 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5021 // shouldn't happen, but there are constructs that the language rule doesn't
5022 // disallow for which we can't reasonably avoid computing linkage early.
5023 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5024 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5025 : NonCLikeKind();
5026 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5027 if (NonCLike || ChangesLinkage) {
5028 if (NonCLike.Kind == NonCLikeKind::Invalid)
5029 return;
5030
5031 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5032 if (ChangesLinkage) {
5033 // If the linkage changes, we can't accept this as an extension.
5034 if (NonCLike.Kind == NonCLikeKind::None)
5035 DiagID = diag::err_typedef_changes_linkage;
5036 else
5037 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5038 }
5039
5040 SourceLocation FixitLoc =
5041 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5042 llvm::SmallString<40> TextToInsert;
5043 TextToInsert += ' ';
5044 TextToInsert += NewTD->getIdentifier()->getName();
5045
5046 Diag(Loc: FixitLoc, DiagID)
5047 << isa<TypeAliasDecl>(Val: NewTD)
5048 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5049 if (NonCLike.Kind != NonCLikeKind::None) {
5050 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5051 << NonCLike.Kind - 1 << NonCLike.Range;
5052 }
5053 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5054 << NewTD << isa<TypeAliasDecl>(NewTD);
5055
5056 if (ChangesLinkage)
5057 return;
5058 }
5059
5060 // Otherwise, set this as the anon-decl typedef for the tag.
5061 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5062}
5063
5064static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5065 DeclSpec::TST T = DS.getTypeSpecType();
5066 switch (T) {
5067 case DeclSpec::TST_class:
5068 return 0;
5069 case DeclSpec::TST_struct:
5070 return 1;
5071 case DeclSpec::TST_interface:
5072 return 2;
5073 case DeclSpec::TST_union:
5074 return 3;
5075 case DeclSpec::TST_enum:
5076 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5077 if (ED->isScopedUsingClassTag())
5078 return 5;
5079 if (ED->isScoped())
5080 return 6;
5081 }
5082 return 4;
5083 default:
5084 llvm_unreachable("unexpected type specifier");
5085 }
5086}
5087/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5088/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5089/// parameters to cope with template friend declarations.
5090Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5091 DeclSpec &DS,
5092 const ParsedAttributesView &DeclAttrs,
5093 MultiTemplateParamsArg TemplateParams,
5094 bool IsExplicitInstantiation,
5095 RecordDecl *&AnonRecord) {
5096 Decl *TagD = nullptr;
5097 TagDecl *Tag = nullptr;
5098 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5099 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5100 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5101 DS.getTypeSpecType() == DeclSpec::TST_union ||
5102 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5103 TagD = DS.getRepAsDecl();
5104
5105 if (!TagD) // We probably had an error
5106 return nullptr;
5107
5108 // Note that the above type specs guarantee that the
5109 // type rep is a Decl, whereas in many of the others
5110 // it's a Type.
5111 if (isa<TagDecl>(Val: TagD))
5112 Tag = cast<TagDecl>(Val: TagD);
5113 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5114 Tag = CTD->getTemplatedDecl();
5115 }
5116
5117 if (Tag) {
5118 handleTagNumbering(Tag, TagScope: S);
5119 Tag->setFreeStanding();
5120 if (Tag->isInvalidDecl())
5121 return Tag;
5122 }
5123
5124 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5125 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5126 // or incomplete types shall not be restrict-qualified."
5127 if (TypeQuals & DeclSpec::TQ_restrict)
5128 Diag(DS.getRestrictSpecLoc(),
5129 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5130 << DS.getSourceRange();
5131 }
5132
5133 if (DS.isInlineSpecified())
5134 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5135 << getLangOpts().CPlusPlus17;
5136
5137 if (DS.hasConstexprSpecifier()) {
5138 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5139 // and definitions of functions and variables.
5140 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5141 // the declaration of a function or function template
5142 if (Tag)
5143 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5144 << GetDiagnosticTypeSpecifierID(DS)
5145 << static_cast<int>(DS.getConstexprSpecifier());
5146 else
5147 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5148 << static_cast<int>(DS.getConstexprSpecifier());
5149 // Don't emit warnings after this error.
5150 return TagD;
5151 }
5152
5153 DiagnoseFunctionSpecifiers(DS);
5154
5155 if (DS.isFriendSpecified()) {
5156 // If we're dealing with a decl but not a TagDecl, assume that
5157 // whatever routines created it handled the friendship aspect.
5158 if (TagD && !Tag)
5159 return nullptr;
5160 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5161 }
5162
5163 // Track whether this decl-specifier declares anything.
5164 bool DeclaresAnything = true;
5165
5166 // Handle anonymous struct definitions.
5167 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5168 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5169 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5170 if (getLangOpts().CPlusPlus ||
5171 Record->getDeclContext()->isRecord()) {
5172 // If CurContext is a DeclContext that can contain statements,
5173 // RecursiveASTVisitor won't visit the decls that
5174 // BuildAnonymousStructOrUnion() will put into CurContext.
5175 // Also store them here so that they can be part of the
5176 // DeclStmt that gets created in this case.
5177 // FIXME: Also return the IndirectFieldDecls created by
5178 // BuildAnonymousStructOr union, for the same reason?
5179 if (CurContext->isFunctionOrMethod())
5180 AnonRecord = Record;
5181 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5182 Policy: Context.getPrintingPolicy());
5183 }
5184
5185 DeclaresAnything = false;
5186 }
5187 }
5188
5189 // C11 6.7.2.1p2:
5190 // A struct-declaration that does not declare an anonymous structure or
5191 // anonymous union shall contain a struct-declarator-list.
5192 //
5193 // This rule also existed in C89 and C99; the grammar for struct-declaration
5194 // did not permit a struct-declaration without a struct-declarator-list.
5195 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5196 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5197 // Check for Microsoft C extension: anonymous struct/union member.
5198 // Handle 2 kinds of anonymous struct/union:
5199 // struct STRUCT;
5200 // union UNION;
5201 // and
5202 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5203 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5204 if ((Tag && Tag->getDeclName()) ||
5205 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5206 RecordDecl *Record = nullptr;
5207 if (Tag)
5208 Record = dyn_cast<RecordDecl>(Val: Tag);
5209 else if (const RecordType *RT =
5210 DS.getRepAsType().get()->getAsStructureType())
5211 Record = RT->getDecl();
5212 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5213 Record = UT->getDecl();
5214
5215 if (Record && getLangOpts().MicrosoftExt) {
5216 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5217 << Record->isUnion() << DS.getSourceRange();
5218 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5219 }
5220
5221 DeclaresAnything = false;
5222 }
5223 }
5224
5225 // Skip all the checks below if we have a type error.
5226 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5227 (TagD && TagD->isInvalidDecl()))
5228 return TagD;
5229
5230 if (getLangOpts().CPlusPlus &&
5231 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5232 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5233 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5234 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5235 DeclaresAnything = false;
5236
5237 if (!DS.isMissingDeclaratorOk()) {
5238 // Customize diagnostic for a typedef missing a name.
5239 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5240 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5241 << DS.getSourceRange();
5242 else
5243 DeclaresAnything = false;
5244 }
5245
5246 if (DS.isModulePrivateSpecified() &&
5247 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5248 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5249 << llvm::to_underlying(Tag->getTagKind())
5250 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5251
5252 ActOnDocumentableDecl(D: TagD);
5253
5254 // C 6.7/2:
5255 // A declaration [...] shall declare at least a declarator [...], a tag,
5256 // or the members of an enumeration.
5257 // C++ [dcl.dcl]p3:
5258 // [If there are no declarators], and except for the declaration of an
5259 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5260 // names into the program, or shall redeclare a name introduced by a
5261 // previous declaration.
5262 if (!DeclaresAnything) {
5263 // In C, we allow this as a (popular) extension / bug. Don't bother
5264 // producing further diagnostics for redundant qualifiers after this.
5265 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5266 ? diag::err_no_declarators
5267 : diag::ext_no_declarators)
5268 << DS.getSourceRange();
5269 return TagD;
5270 }
5271
5272 // C++ [dcl.stc]p1:
5273 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5274 // init-declarator-list of the declaration shall not be empty.
5275 // C++ [dcl.fct.spec]p1:
5276 // If a cv-qualifier appears in a decl-specifier-seq, the
5277 // init-declarator-list of the declaration shall not be empty.
5278 //
5279 // Spurious qualifiers here appear to be valid in C.
5280 unsigned DiagID = diag::warn_standalone_specifier;
5281 if (getLangOpts().CPlusPlus)
5282 DiagID = diag::ext_standalone_specifier;
5283
5284 // Note that a linkage-specification sets a storage class, but
5285 // 'extern "C" struct foo;' is actually valid and not theoretically
5286 // useless.
5287 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5288 if (SCS == DeclSpec::SCS_mutable)
5289 // Since mutable is not a viable storage class specifier in C, there is
5290 // no reason to treat it as an extension. Instead, diagnose as an error.
5291 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5292 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5293 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5294 << DeclSpec::getSpecifierName(S: SCS);
5295 }
5296
5297 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5298 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5299 << DeclSpec::getSpecifierName(S: TSCS);
5300 if (DS.getTypeQualifiers()) {
5301 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5302 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5303 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5304 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5305 // Restrict is covered above.
5306 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5307 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5308 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5309 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5310 }
5311
5312 // Warn about ignored type attributes, for example:
5313 // __attribute__((aligned)) struct A;
5314 // Attributes should be placed after tag to apply to type declaration.
5315 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5316 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5317 if (TypeSpecType == DeclSpec::TST_class ||
5318 TypeSpecType == DeclSpec::TST_struct ||
5319 TypeSpecType == DeclSpec::TST_interface ||
5320 TypeSpecType == DeclSpec::TST_union ||
5321 TypeSpecType == DeclSpec::TST_enum) {
5322
5323 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5324 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5325 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5326 DiagnosticId = diag::warn_attribute_ignored;
5327 else if (AL.isRegularKeywordAttribute())
5328 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5329 else
5330 DiagnosticId = diag::warn_declspec_attribute_ignored;
5331 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5332 << AL << GetDiagnosticTypeSpecifierID(DS);
5333 };
5334
5335 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5336 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5337 }
5338 }
5339
5340 return TagD;
5341}
5342
5343/// We are trying to inject an anonymous member into the given scope;
5344/// check if there's an existing declaration that can't be overloaded.
5345///
5346/// \return true if this is a forbidden redeclaration
5347static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5348 DeclContext *Owner,
5349 DeclarationName Name,
5350 SourceLocation NameLoc, bool IsUnion,
5351 StorageClass SC) {
5352 LookupResult R(SemaRef, Name, NameLoc,
5353 Owner->isRecord() ? Sema::LookupMemberName
5354 : Sema::LookupOrdinaryName,
5355 Sema::ForVisibleRedeclaration);
5356 if (!SemaRef.LookupName(R, S)) return false;
5357
5358 // Pick a representative declaration.
5359 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5360 assert(PrevDecl && "Expected a non-null Decl");
5361
5362 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5363 return false;
5364
5365 if (SC == StorageClass::SC_None &&
5366 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5367 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5368 if (!Owner->isRecord())
5369 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5370 return false;
5371 }
5372
5373 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5374 << IsUnion << Name;
5375 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5376
5377 return true;
5378}
5379
5380void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5381 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5382 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5383}
5384
5385/// Emit diagnostic warnings for placeholder members.
5386/// We can only do that after the class is fully constructed,
5387/// as anonymous union/structs can insert placeholders
5388/// in their parent scope (which might be a Record).
5389void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5390 if (!getLangOpts().CPlusPlus)
5391 return;
5392
5393 // This function can be parsed before we have validated the
5394 // structure as an anonymous struct
5395 if (Record->isAnonymousStructOrUnion())
5396 return;
5397
5398 const NamedDecl *First = 0;
5399 for (const Decl *D : Record->decls()) {
5400 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5401 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5402 continue;
5403 if (!First)
5404 First = ND;
5405 else
5406 DiagPlaceholderVariableDefinition(ND->getLocation());
5407 }
5408}
5409
5410/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5411/// anonymous struct or union AnonRecord into the owning context Owner
5412/// and scope S. This routine will be invoked just after we realize
5413/// that an unnamed union or struct is actually an anonymous union or
5414/// struct, e.g.,
5415///
5416/// @code
5417/// union {
5418/// int i;
5419/// float f;
5420/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5421/// // f into the surrounding scope.x
5422/// @endcode
5423///
5424/// This routine is recursive, injecting the names of nested anonymous
5425/// structs/unions into the owning context and scope as well.
5426static bool
5427InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5428 RecordDecl *AnonRecord, AccessSpecifier AS,
5429 StorageClass SC,
5430 SmallVectorImpl<NamedDecl *> &Chaining) {
5431 bool Invalid = false;
5432
5433 // Look every FieldDecl and IndirectFieldDecl with a name.
5434 for (auto *D : AnonRecord->decls()) {
5435 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5436 cast<NamedDecl>(D)->getDeclName()) {
5437 ValueDecl *VD = cast<ValueDecl>(D);
5438 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5439 VD->getLocation(), AnonRecord->isUnion(),
5440 SC)) {
5441 // C++ [class.union]p2:
5442 // The names of the members of an anonymous union shall be
5443 // distinct from the names of any other entity in the
5444 // scope in which the anonymous union is declared.
5445 Invalid = true;
5446 } else {
5447 // C++ [class.union]p2:
5448 // For the purpose of name lookup, after the anonymous union
5449 // definition, the members of the anonymous union are
5450 // considered to have been defined in the scope in which the
5451 // anonymous union is declared.
5452 unsigned OldChainingSize = Chaining.size();
5453 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5454 Chaining.append(IF->chain_begin(), IF->chain_end());
5455 else
5456 Chaining.push_back(VD);
5457
5458 assert(Chaining.size() >= 2);
5459 NamedDecl **NamedChain =
5460 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5461 for (unsigned i = 0; i < Chaining.size(); i++)
5462 NamedChain[i] = Chaining[i];
5463
5464 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5465 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5466 VD->getType(), {NamedChain, Chaining.size()});
5467
5468 for (const auto *Attr : VD->attrs())
5469 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5470
5471 IndirectField->setAccess(AS);
5472 IndirectField->setImplicit();
5473 SemaRef.PushOnScopeChains(IndirectField, S);
5474
5475 // That includes picking up the appropriate access specifier.
5476 if (AS != AS_none) IndirectField->setAccess(AS);
5477
5478 Chaining.resize(OldChainingSize);
5479 }
5480 }
5481 }
5482
5483 return Invalid;
5484}
5485
5486/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5487/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5488/// illegal input values are mapped to SC_None.
5489static StorageClass
5490StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5491 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5492 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5493 "Parser allowed 'typedef' as storage class VarDecl.");
5494 switch (StorageClassSpec) {
5495 case DeclSpec::SCS_unspecified: return SC_None;
5496 case DeclSpec::SCS_extern:
5497 if (DS.isExternInLinkageSpec())
5498 return SC_None;
5499 return SC_Extern;
5500 case DeclSpec::SCS_static: return SC_Static;
5501 case DeclSpec::SCS_auto: return SC_Auto;
5502 case DeclSpec::SCS_register: return SC_Register;
5503 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5504 // Illegal SCSs map to None: error reporting is up to the caller.
5505 case DeclSpec::SCS_mutable: // Fall through.
5506 case DeclSpec::SCS_typedef: return SC_None;
5507 }
5508 llvm_unreachable("unknown storage class specifier");
5509}
5510
5511static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5512 assert(Record->hasInClassInitializer());
5513
5514 for (const auto *I : Record->decls()) {
5515 const auto *FD = dyn_cast<FieldDecl>(I);
5516 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5517 FD = IFD->getAnonField();
5518 if (FD && FD->hasInClassInitializer())
5519 return FD->getLocation();
5520 }
5521
5522 llvm_unreachable("couldn't find in-class initializer");
5523}
5524
5525static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5526 SourceLocation DefaultInitLoc) {
5527 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5528 return;
5529
5530 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5531 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5532}
5533
5534static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5535 CXXRecordDecl *AnonUnion) {
5536 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5537 return;
5538
5539 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5540}
5541
5542/// BuildAnonymousStructOrUnion - Handle the declaration of an
5543/// anonymous structure or union. Anonymous unions are a C++ feature
5544/// (C++ [class.union]) and a C11 feature; anonymous structures
5545/// are a C11 feature and GNU C++ extension.
5546Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5547 AccessSpecifier AS,
5548 RecordDecl *Record,
5549 const PrintingPolicy &Policy) {
5550 DeclContext *Owner = Record->getDeclContext();
5551
5552 // Diagnose whether this anonymous struct/union is an extension.
5553 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5554 Diag(Record->getLocation(), diag::ext_anonymous_union);
5555 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5556 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5557 else if (!Record->isUnion() && !getLangOpts().C11)
5558 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5559
5560 // C and C++ require different kinds of checks for anonymous
5561 // structs/unions.
5562 bool Invalid = false;
5563 if (getLangOpts().CPlusPlus) {
5564 const char *PrevSpec = nullptr;
5565 if (Record->isUnion()) {
5566 // C++ [class.union]p6:
5567 // C++17 [class.union.anon]p2:
5568 // Anonymous unions declared in a named namespace or in the
5569 // global namespace shall be declared static.
5570 unsigned DiagID;
5571 DeclContext *OwnerScope = Owner->getRedeclContext();
5572 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5573 (OwnerScope->isTranslationUnit() ||
5574 (OwnerScope->isNamespace() &&
5575 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5576 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5577 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5578
5579 // Recover by adding 'static'.
5580 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5581 PrevSpec, DiagID, Policy);
5582 }
5583 // C++ [class.union]p6:
5584 // A storage class is not allowed in a declaration of an
5585 // anonymous union in a class scope.
5586 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5587 isa<RecordDecl>(Val: Owner)) {
5588 Diag(DS.getStorageClassSpecLoc(),
5589 diag::err_anonymous_union_with_storage_spec)
5590 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5591
5592 // Recover by removing the storage specifier.
5593 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5594 Loc: SourceLocation(),
5595 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5596 }
5597 }
5598
5599 // Ignore const/volatile/restrict qualifiers.
5600 if (DS.getTypeQualifiers()) {
5601 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5602 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5603 << Record->isUnion() << "const"
5604 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5605 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5606 Diag(DS.getVolatileSpecLoc(),
5607 diag::ext_anonymous_struct_union_qualified)
5608 << Record->isUnion() << "volatile"
5609 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5610 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5611 Diag(DS.getRestrictSpecLoc(),
5612 diag::ext_anonymous_struct_union_qualified)
5613 << Record->isUnion() << "restrict"
5614 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5615 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5616 Diag(DS.getAtomicSpecLoc(),
5617 diag::ext_anonymous_struct_union_qualified)
5618 << Record->isUnion() << "_Atomic"
5619 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5620 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5621 Diag(DS.getUnalignedSpecLoc(),
5622 diag::ext_anonymous_struct_union_qualified)
5623 << Record->isUnion() << "__unaligned"
5624 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5625
5626 DS.ClearTypeQualifiers();
5627 }
5628
5629 // C++ [class.union]p2:
5630 // The member-specification of an anonymous union shall only
5631 // define non-static data members. [Note: nested types and
5632 // functions cannot be declared within an anonymous union. ]
5633 for (auto *Mem : Record->decls()) {
5634 // Ignore invalid declarations; we already diagnosed them.
5635 if (Mem->isInvalidDecl())
5636 continue;
5637
5638 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5639 // C++ [class.union]p3:
5640 // An anonymous union shall not have private or protected
5641 // members (clause 11).
5642 assert(FD->getAccess() != AS_none);
5643 if (FD->getAccess() != AS_public) {
5644 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5645 << Record->isUnion() << (FD->getAccess() == AS_protected);
5646 Invalid = true;
5647 }
5648
5649 // C++ [class.union]p1
5650 // An object of a class with a non-trivial constructor, a non-trivial
5651 // copy constructor, a non-trivial destructor, or a non-trivial copy
5652 // assignment operator cannot be a member of a union, nor can an
5653 // array of such objects.
5654 if (CheckNontrivialField(FD))
5655 Invalid = true;
5656 } else if (Mem->isImplicit()) {
5657 // Any implicit members are fine.
5658 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5659 // This is a type that showed up in an
5660 // elaborated-type-specifier inside the anonymous struct or
5661 // union, but which actually declares a type outside of the
5662 // anonymous struct or union. It's okay.
5663 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5664 if (!MemRecord->isAnonymousStructOrUnion() &&
5665 MemRecord->getDeclName()) {
5666 // Visual C++ allows type definition in anonymous struct or union.
5667 if (getLangOpts().MicrosoftExt)
5668 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5669 << Record->isUnion();
5670 else {
5671 // This is a nested type declaration.
5672 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5673 << Record->isUnion();
5674 Invalid = true;
5675 }
5676 } else {
5677 // This is an anonymous type definition within another anonymous type.
5678 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5679 // not part of standard C++.
5680 Diag(MemRecord->getLocation(),
5681 diag::ext_anonymous_record_with_anonymous_type)
5682 << Record->isUnion();
5683 }
5684 } else if (isa<AccessSpecDecl>(Mem)) {
5685 // Any access specifier is fine.
5686 } else if (isa<StaticAssertDecl>(Mem)) {
5687 // In C++1z, static_assert declarations are also fine.
5688 } else {
5689 // We have something that isn't a non-static data
5690 // member. Complain about it.
5691 unsigned DK = diag::err_anonymous_record_bad_member;
5692 if (isa<TypeDecl>(Mem))
5693 DK = diag::err_anonymous_record_with_type;
5694 else if (isa<FunctionDecl>(Mem))
5695 DK = diag::err_anonymous_record_with_function;
5696 else if (isa<VarDecl>(Mem))
5697 DK = diag::err_anonymous_record_with_static;
5698
5699 // Visual C++ allows type definition in anonymous struct or union.
5700 if (getLangOpts().MicrosoftExt &&
5701 DK == diag::err_anonymous_record_with_type)
5702 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5703 << Record->isUnion();
5704 else {
5705 Diag(Mem->getLocation(), DK) << Record->isUnion();
5706 Invalid = true;
5707 }
5708 }
5709 }
5710
5711 // C++11 [class.union]p8 (DR1460):
5712 // At most one variant member of a union may have a
5713 // brace-or-equal-initializer.
5714 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5715 Owner->isRecord())
5716 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5717 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5718 }
5719
5720 if (!Record->isUnion() && !Owner->isRecord()) {
5721 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5722 << getLangOpts().CPlusPlus;
5723 Invalid = true;
5724 }
5725
5726 // C++ [dcl.dcl]p3:
5727 // [If there are no declarators], and except for the declaration of an
5728 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5729 // names into the program
5730 // C++ [class.mem]p2:
5731 // each such member-declaration shall either declare at least one member
5732 // name of the class or declare at least one unnamed bit-field
5733 //
5734 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5735 if (getLangOpts().CPlusPlus && Record->field_empty())
5736 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5737
5738 // Mock up a declarator.
5739 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5740 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5741 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5742 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5743
5744 // Create a declaration for this anonymous struct/union.
5745 NamedDecl *Anon = nullptr;
5746 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5747 Anon = FieldDecl::Create(
5748 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5749 /*IdentifierInfo=*/Id: nullptr, T: Context.getTypeDeclType(Record), TInfo,
5750 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5751 /*InitStyle=*/ICIS_NoInit);
5752 Anon->setAccess(AS);
5753 ProcessDeclAttributes(S, Anon, Dc);
5754
5755 if (getLangOpts().CPlusPlus)
5756 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5757 } else {
5758 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5759 if (SCSpec == DeclSpec::SCS_mutable) {
5760 // mutable can only appear on non-static class members, so it's always
5761 // an error here
5762 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5763 Invalid = true;
5764 SC = SC_None;
5765 }
5766
5767 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5768 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5769 T: Context.getTypeDeclType(Record), TInfo, S: SC);
5770 ProcessDeclAttributes(S, Anon, Dc);
5771
5772 // Default-initialize the implicit variable. This initialization will be
5773 // trivial in almost all cases, except if a union member has an in-class
5774 // initializer:
5775 // union { int n = 0; };
5776 ActOnUninitializedDecl(Anon);
5777 }
5778 Anon->setImplicit();
5779
5780 // Mark this as an anonymous struct/union type.
5781 Record->setAnonymousStructOrUnion(true);
5782
5783 // Add the anonymous struct/union object to the current
5784 // context. We'll be referencing this object when we refer to one of
5785 // its members.
5786 Owner->addDecl(Anon);
5787
5788 // Inject the members of the anonymous struct/union into the owning
5789 // context and into the identifier resolver chain for name lookup
5790 // purposes.
5791 SmallVector<NamedDecl*, 2> Chain;
5792 Chain.push_back(Elt: Anon);
5793
5794 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5795 Chaining&: Chain))
5796 Invalid = true;
5797
5798 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5799 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5800 MangleNumberingContext *MCtx;
5801 Decl *ManglingContextDecl;
5802 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5803 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5804 if (MCtx) {
5805 Context.setManglingNumber(
5806 NewVD, MCtx->getManglingNumber(
5807 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5808 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5809 }
5810 }
5811 }
5812
5813 if (Invalid)
5814 Anon->setInvalidDecl();
5815
5816 return Anon;
5817}
5818
5819/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5820/// Microsoft C anonymous structure.
5821/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5822/// Example:
5823///
5824/// struct A { int a; };
5825/// struct B { struct A; int b; };
5826///
5827/// void foo() {
5828/// B var;
5829/// var.a = 3;
5830/// }
5831///
5832Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5833 RecordDecl *Record) {
5834 assert(Record && "expected a record!");
5835
5836 // Mock up a declarator.
5837 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5838 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5839 assert(TInfo && "couldn't build declarator info for anonymous struct");
5840
5841 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5842 QualType RecTy = Context.getTypeDeclType(Record);
5843
5844 // Create a declaration for this anonymous struct.
5845 NamedDecl *Anon =
5846 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5847 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5848 /*BitWidth=*/nullptr, /*Mutable=*/false,
5849 /*InitStyle=*/ICIS_NoInit);
5850 Anon->setImplicit();
5851
5852 // Add the anonymous struct object to the current context.
5853 CurContext->addDecl(Anon);
5854
5855 // Inject the members of the anonymous struct into the current
5856 // context and into the identifier resolver chain for name lookup
5857 // purposes.
5858 SmallVector<NamedDecl*, 2> Chain;
5859 Chain.push_back(Elt: Anon);
5860
5861 RecordDecl *RecordDef = Record->getDefinition();
5862 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5863 diag::err_field_incomplete_or_sizeless) ||
5864 InjectAnonymousStructOrUnionMembers(
5865 *this, S, CurContext, RecordDef, AS_none,
5866 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5867 Anon->setInvalidDecl();
5868 ParentDecl->setInvalidDecl();
5869 }
5870
5871 return Anon;
5872}
5873
5874/// GetNameForDeclarator - Determine the full declaration name for the
5875/// given Declarator.
5876DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5877 return GetNameFromUnqualifiedId(Name: D.getName());
5878}
5879
5880/// Retrieves the declaration name from a parsed unqualified-id.
5881DeclarationNameInfo
5882Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5883 DeclarationNameInfo NameInfo;
5884 NameInfo.setLoc(Name.StartLocation);
5885
5886 switch (Name.getKind()) {
5887
5888 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5889 case UnqualifiedIdKind::IK_Identifier:
5890 NameInfo.setName(Name.Identifier);
5891 return NameInfo;
5892
5893 case UnqualifiedIdKind::IK_DeductionGuideName: {
5894 // C++ [temp.deduct.guide]p3:
5895 // The simple-template-id shall name a class template specialization.
5896 // The template-name shall be the same identifier as the template-name
5897 // of the simple-template-id.
5898 // These together intend to imply that the template-name shall name a
5899 // class template.
5900 // FIXME: template<typename T> struct X {};
5901 // template<typename T> using Y = X<T>;
5902 // Y(int) -> Y<int>;
5903 // satisfies these rules but does not name a class template.
5904 TemplateName TN = Name.TemplateName.get().get();
5905 auto *Template = TN.getAsTemplateDecl();
5906 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
5907 Diag(Name.StartLocation,
5908 diag::err_deduction_guide_name_not_class_template)
5909 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5910 if (Template)
5911 NoteTemplateLocation(*Template);
5912 return DeclarationNameInfo();
5913 }
5914
5915 NameInfo.setName(
5916 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
5917 return NameInfo;
5918 }
5919
5920 case UnqualifiedIdKind::IK_OperatorFunctionId:
5921 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5922 Op: Name.OperatorFunctionId.Operator));
5923 NameInfo.setCXXOperatorNameRange(SourceRange(
5924 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5925 return NameInfo;
5926
5927 case UnqualifiedIdKind::IK_LiteralOperatorId:
5928 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5929 II: Name.Identifier));
5930 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5931 return NameInfo;
5932
5933 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5934 TypeSourceInfo *TInfo;
5935 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
5936 if (Ty.isNull())
5937 return DeclarationNameInfo();
5938 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5939 Ty: Context.getCanonicalType(T: Ty)));
5940 NameInfo.setNamedTypeInfo(TInfo);
5941 return NameInfo;
5942 }
5943
5944 case UnqualifiedIdKind::IK_ConstructorName: {
5945 TypeSourceInfo *TInfo;
5946 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
5947 if (Ty.isNull())
5948 return DeclarationNameInfo();
5949 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5950 Ty: Context.getCanonicalType(T: Ty)));
5951 NameInfo.setNamedTypeInfo(TInfo);
5952 return NameInfo;
5953 }
5954
5955 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5956 // In well-formed code, we can only have a constructor
5957 // template-id that refers to the current context, so go there
5958 // to find the actual type being constructed.
5959 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
5960 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5961 return DeclarationNameInfo();
5962
5963 // Determine the type of the class being constructed.
5964 QualType CurClassType = Context.getTypeDeclType(CurClass);
5965
5966 // FIXME: Check two things: that the template-id names the same type as
5967 // CurClassType, and that the template-id does not occur when the name
5968 // was qualified.
5969
5970 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5971 Ty: Context.getCanonicalType(T: CurClassType)));
5972 // FIXME: should we retrieve TypeSourceInfo?
5973 NameInfo.setNamedTypeInfo(nullptr);
5974 return NameInfo;
5975 }
5976
5977 case UnqualifiedIdKind::IK_DestructorName: {
5978 TypeSourceInfo *TInfo;
5979 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
5980 if (Ty.isNull())
5981 return DeclarationNameInfo();
5982 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5983 Ty: Context.getCanonicalType(T: Ty)));
5984 NameInfo.setNamedTypeInfo(TInfo);
5985 return NameInfo;
5986 }
5987
5988 case UnqualifiedIdKind::IK_TemplateId: {
5989 TemplateName TName = Name.TemplateId->Template.get();
5990 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5991 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
5992 }
5993
5994 } // switch (Name.getKind())
5995
5996 llvm_unreachable("Unknown name kind");
5997}
5998
5999static QualType getCoreType(QualType Ty) {
6000 do {
6001 if (Ty->isPointerType() || Ty->isReferenceType())
6002 Ty = Ty->getPointeeType();
6003 else if (Ty->isArrayType())
6004 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6005 else
6006 return Ty.withoutLocalFastQualifiers();
6007 } while (true);
6008}
6009
6010/// hasSimilarParameters - Determine whether the C++ functions Declaration
6011/// and Definition have "nearly" matching parameters. This heuristic is
6012/// used to improve diagnostics in the case where an out-of-line function
6013/// definition doesn't match any declaration within the class or namespace.
6014/// Also sets Params to the list of indices to the parameters that differ
6015/// between the declaration and the definition. If hasSimilarParameters
6016/// returns true and Params is empty, then all of the parameters match.
6017static bool hasSimilarParameters(ASTContext &Context,
6018 FunctionDecl *Declaration,
6019 FunctionDecl *Definition,
6020 SmallVectorImpl<unsigned> &Params) {
6021 Params.clear();
6022 if (Declaration->param_size() != Definition->param_size())
6023 return false;
6024 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6025 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6026 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6027
6028 // The parameter types are identical
6029 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6030 continue;
6031
6032 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6033 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6034 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6035 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6036
6037 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6038 (DeclTyName && DeclTyName == DefTyName))
6039 Params.push_back(Elt: Idx);
6040 else // The two parameters aren't even close
6041 return false;
6042 }
6043
6044 return true;
6045}
6046
6047/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6048/// declarator needs to be rebuilt in the current instantiation.
6049/// Any bits of declarator which appear before the name are valid for
6050/// consideration here. That's specifically the type in the decl spec
6051/// and the base type in any member-pointer chunks.
6052static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6053 DeclarationName Name) {
6054 // The types we specifically need to rebuild are:
6055 // - typenames, typeofs, and decltypes
6056 // - types which will become injected class names
6057 // Of course, we also need to rebuild any type referencing such a
6058 // type. It's safest to just say "dependent", but we call out a
6059 // few cases here.
6060
6061 DeclSpec &DS = D.getMutableDeclSpec();
6062 switch (DS.getTypeSpecType()) {
6063 case DeclSpec::TST_typename:
6064 case DeclSpec::TST_typeofType:
6065 case DeclSpec::TST_typeof_unqualType:
6066#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6067#include "clang/Basic/TransformTypeTraits.def"
6068 case DeclSpec::TST_atomic: {
6069 // Grab the type from the parser.
6070 TypeSourceInfo *TSI = nullptr;
6071 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6072 if (T.isNull() || !T->isInstantiationDependentType()) break;
6073
6074 // Make sure there's a type source info. This isn't really much
6075 // of a waste; most dependent types should have type source info
6076 // attached already.
6077 if (!TSI)
6078 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6079
6080 // Rebuild the type in the current instantiation.
6081 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6082 if (!TSI) return true;
6083
6084 // Store the new type back in the decl spec.
6085 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6086 DS.UpdateTypeRep(Rep: LocType);
6087 break;
6088 }
6089
6090 case DeclSpec::TST_decltype:
6091 case DeclSpec::TST_typeof_unqualExpr:
6092 case DeclSpec::TST_typeofExpr: {
6093 Expr *E = DS.getRepAsExpr();
6094 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6095 if (Result.isInvalid()) return true;
6096 DS.UpdateExprRep(Rep: Result.get());
6097 break;
6098 }
6099
6100 default:
6101 // Nothing to do for these decl specs.
6102 break;
6103 }
6104
6105 // It doesn't matter what order we do this in.
6106 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6107 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6108
6109 // The only type information in the declarator which can come
6110 // before the declaration name is the base type of a member
6111 // pointer.
6112 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6113 continue;
6114
6115 // Rebuild the scope specifier in-place.
6116 CXXScopeSpec &SS = Chunk.Mem.Scope();
6117 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6118 return true;
6119 }
6120
6121 return false;
6122}
6123
6124/// Returns true if the declaration is declared in a system header or from a
6125/// system macro.
6126static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6127 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6128 SM.isInSystemMacro(loc: D->getLocation());
6129}
6130
6131void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6132 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6133 // of system decl.
6134 if (D->getPreviousDecl() || D->isImplicit())
6135 return;
6136 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6137 if (Status != ReservedIdentifierStatus::NotReserved &&
6138 !isFromSystemHeader(Context.getSourceManager(), D)) {
6139 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6140 << D << static_cast<int>(Status);
6141 }
6142}
6143
6144Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6145 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6146
6147 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6148 // declaration only if the `bind_to_declaration` extension is set.
6149 SmallVector<FunctionDecl *, 4> Bases;
6150 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6151 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(TP: llvm::omp::TraitProperty::
6152 implementation_extension_bind_to_declaration))
6153 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6154 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6155
6156 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6157
6158 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6159 Dcl && Dcl->getDeclContext()->isFileContext())
6160 Dcl->setTopLevelDeclInObjCContainer();
6161
6162 if (!Bases.empty())
6163 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl, Bases);
6164
6165 return Dcl;
6166}
6167
6168/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6169/// If T is the name of a class, then each of the following shall have a
6170/// name different from T:
6171/// - every static data member of class T;
6172/// - every member function of class T
6173/// - every member of class T that is itself a type;
6174/// \returns true if the declaration name violates these rules.
6175bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6176 DeclarationNameInfo NameInfo) {
6177 DeclarationName Name = NameInfo.getName();
6178
6179 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6180 while (Record && Record->isAnonymousStructOrUnion())
6181 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6182 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6183 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6184 return true;
6185 }
6186
6187 return false;
6188}
6189
6190/// Diagnose a declaration whose declarator-id has the given
6191/// nested-name-specifier.
6192///
6193/// \param SS The nested-name-specifier of the declarator-id.
6194///
6195/// \param DC The declaration context to which the nested-name-specifier
6196/// resolves.
6197///
6198/// \param Name The name of the entity being declared.
6199///
6200/// \param Loc The location of the name of the entity being declared.
6201///
6202/// \param IsMemberSpecialization Whether we are declaring a member
6203/// specialization.
6204///
6205/// \param TemplateId The template-id, if any.
6206///
6207/// \returns true if we cannot safely recover from this error, false otherwise.
6208bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6209 DeclarationName Name,
6210 SourceLocation Loc,
6211 TemplateIdAnnotation *TemplateId,
6212 bool IsMemberSpecialization) {
6213 DeclContext *Cur = CurContext;
6214 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6215 Cur = Cur->getParent();
6216
6217 // If the user provided a superfluous scope specifier that refers back to the
6218 // class in which the entity is already declared, diagnose and ignore it.
6219 //
6220 // class X {
6221 // void X::f();
6222 // };
6223 //
6224 // Note, it was once ill-formed to give redundant qualification in all
6225 // contexts, but that rule was removed by DR482.
6226 if (Cur->Equals(DC)) {
6227 if (Cur->isRecord()) {
6228 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6229 : diag::err_member_extra_qualification)
6230 << Name << FixItHint::CreateRemoval(SS.getRange());
6231 SS.clear();
6232 } else {
6233 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6234 }
6235 return false;
6236 }
6237
6238 // Check whether the qualifying scope encloses the scope of the original
6239 // declaration. For a template-id, we perform the checks in
6240 // CheckTemplateSpecializationScope.
6241 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6242 if (Cur->isRecord())
6243 Diag(Loc, diag::err_member_qualification)
6244 << Name << SS.getRange();
6245 else if (isa<TranslationUnitDecl>(Val: DC))
6246 Diag(Loc, diag::err_invalid_declarator_global_scope)
6247 << Name << SS.getRange();
6248 else if (isa<FunctionDecl>(Val: Cur))
6249 Diag(Loc, diag::err_invalid_declarator_in_function)
6250 << Name << SS.getRange();
6251 else if (isa<BlockDecl>(Val: Cur))
6252 Diag(Loc, diag::err_invalid_declarator_in_block)
6253 << Name << SS.getRange();
6254 else if (isa<ExportDecl>(Val: Cur)) {
6255 if (!isa<NamespaceDecl>(Val: DC))
6256 Diag(Loc, diag::err_export_non_namespace_scope_name)
6257 << Name << SS.getRange();
6258 else
6259 // The cases that DC is not NamespaceDecl should be handled in
6260 // CheckRedeclarationExported.
6261 return false;
6262 } else
6263 Diag(Loc, diag::err_invalid_declarator_scope)
6264 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6265
6266 return true;
6267 }
6268
6269 if (Cur->isRecord()) {
6270 // Cannot qualify members within a class.
6271 Diag(Loc, diag::err_member_qualification)
6272 << Name << SS.getRange();
6273 SS.clear();
6274
6275 // C++ constructors and destructors with incorrect scopes can break
6276 // our AST invariants by having the wrong underlying types. If
6277 // that's the case, then drop this declaration entirely.
6278 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6279 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6280 !Context.hasSameType(T1: Name.getCXXNameType(),
6281 T2: Context.getTypeDeclType(cast<CXXRecordDecl>(Val: Cur))))
6282 return true;
6283
6284 return false;
6285 }
6286
6287 // C++23 [temp.names]p5:
6288 // The keyword template shall not appear immediately after a declarative
6289 // nested-name-specifier.
6290 //
6291 // First check the template-id (if any), and then check each component of the
6292 // nested-name-specifier in reverse order.
6293 //
6294 // FIXME: nested-name-specifiers in friend declarations are declarative,
6295 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6296 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6297 Diag(Loc, diag::ext_template_after_declarative_nns)
6298 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6299
6300 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6301 while (SpecLoc.getPrefix()) {
6302 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6303 NestedNameSpecifier::TypeSpecWithTemplate)
6304 Diag(Loc, diag::ext_template_after_declarative_nns)
6305 << FixItHint::CreateRemoval(
6306 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6307
6308 SpecLoc = SpecLoc.getPrefix();
6309 }
6310 // C++11 [dcl.meaning]p1:
6311 // [...] "The nested-name-specifier of the qualified declarator-id shall
6312 // not begin with a decltype-specifer"
6313 if (isa_and_nonnull<DecltypeType>(
6314 SpecLoc.getNestedNameSpecifier()->getAsType()))
6315 Diag(Loc, diag::err_decltype_in_declarator)
6316 << SpecLoc.getTypeLoc().getSourceRange();
6317
6318 return false;
6319}
6320
6321NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6322 MultiTemplateParamsArg TemplateParamLists) {
6323 // TODO: consider using NameInfo for diagnostic.
6324 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6325 DeclarationName Name = NameInfo.getName();
6326
6327 // All of these full declarators require an identifier. If it doesn't have
6328 // one, the ParsedFreeStandingDeclSpec action should be used.
6329 if (D.isDecompositionDeclarator()) {
6330 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6331 } else if (!Name) {
6332 if (!D.isInvalidType()) // Reject this if we think it is valid.
6333 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6334 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6335 return nullptr;
6336 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6337 return nullptr;
6338
6339 // The scope passed in may not be a decl scope. Zip up the scope tree until
6340 // we find one that is.
6341 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6342 (S->getFlags() & Scope::TemplateParamScope) != 0)
6343 S = S->getParent();
6344
6345 DeclContext *DC = CurContext;
6346 if (D.getCXXScopeSpec().isInvalid())
6347 D.setInvalidType();
6348 else if (D.getCXXScopeSpec().isSet()) {
6349 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6350 UPPC: UPPC_DeclarationQualifier))
6351 return nullptr;
6352
6353 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6354 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6355 if (!DC || isa<EnumDecl>(Val: DC)) {
6356 // If we could not compute the declaration context, it's because the
6357 // declaration context is dependent but does not refer to a class,
6358 // class template, or class template partial specialization. Complain
6359 // and return early, to avoid the coming semantic disaster.
6360 Diag(D.getIdentifierLoc(),
6361 diag::err_template_qualified_declarator_no_match)
6362 << D.getCXXScopeSpec().getScopeRep()
6363 << D.getCXXScopeSpec().getRange();
6364 return nullptr;
6365 }
6366 bool IsDependentContext = DC->isDependentContext();
6367
6368 if (!IsDependentContext &&
6369 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6370 return nullptr;
6371
6372 // If a class is incomplete, do not parse entities inside it.
6373 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6374 Diag(D.getIdentifierLoc(),
6375 diag::err_member_def_undefined_record)
6376 << Name << DC << D.getCXXScopeSpec().getRange();
6377 return nullptr;
6378 }
6379 if (!D.getDeclSpec().isFriendSpecified()) {
6380 TemplateIdAnnotation *TemplateId =
6381 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6382 ? D.getName().TemplateId
6383 : nullptr;
6384 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6385 Loc: D.getIdentifierLoc(), TemplateId,
6386 /*IsMemberSpecialization=*/false)) {
6387 if (DC->isRecord())
6388 return nullptr;
6389
6390 D.setInvalidType();
6391 }
6392 }
6393
6394 // Check whether we need to rebuild the type of the given
6395 // declaration in the current instantiation.
6396 if (EnteringContext && IsDependentContext &&
6397 TemplateParamLists.size() != 0) {
6398 ContextRAII SavedContext(*this, DC);
6399 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6400 D.setInvalidType();
6401 }
6402 }
6403
6404 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6405 QualType R = TInfo->getType();
6406
6407 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6408 UPPC: UPPC_DeclarationType))
6409 D.setInvalidType();
6410
6411 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6412 forRedeclarationInCurContext());
6413
6414 // See if this is a redefinition of a variable in the same scope.
6415 if (!D.getCXXScopeSpec().isSet()) {
6416 bool IsLinkageLookup = false;
6417 bool CreateBuiltins = false;
6418
6419 // If the declaration we're planning to build will be a function
6420 // or object with linkage, then look for another declaration with
6421 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6422 //
6423 // If the declaration we're planning to build will be declared with
6424 // external linkage in the translation unit, create any builtin with
6425 // the same name.
6426 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6427 /* Do nothing*/;
6428 else if (CurContext->isFunctionOrMethod() &&
6429 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6430 R->isFunctionType())) {
6431 IsLinkageLookup = true;
6432 CreateBuiltins =
6433 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6434 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6435 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6436 CreateBuiltins = true;
6437
6438 if (IsLinkageLookup) {
6439 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6440 Previous.setRedeclarationKind(ForExternalRedeclaration);
6441 }
6442
6443 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6444 } else { // Something like "int foo::x;"
6445 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6446
6447 // C++ [dcl.meaning]p1:
6448 // When the declarator-id is qualified, the declaration shall refer to a
6449 // previously declared member of the class or namespace to which the
6450 // qualifier refers (or, in the case of a namespace, of an element of the
6451 // inline namespace set of that namespace (7.3.1)) or to a specialization
6452 // thereof; [...]
6453 //
6454 // Note that we already checked the context above, and that we do not have
6455 // enough information to make sure that Previous contains the declaration
6456 // we want to match. For example, given:
6457 //
6458 // class X {
6459 // void f();
6460 // void f(float);
6461 // };
6462 //
6463 // void X::f(int) { } // ill-formed
6464 //
6465 // In this case, Previous will point to the overload set
6466 // containing the two f's declared in X, but neither of them
6467 // matches.
6468
6469 RemoveUsingDecls(R&: Previous);
6470 }
6471
6472 if (Previous.isSingleResult() &&
6473 Previous.getFoundDecl()->isTemplateParameter()) {
6474 // Maybe we will complain about the shadowed template parameter.
6475 if (!D.isInvalidType())
6476 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6477 Previous.getFoundDecl());
6478
6479 // Just pretend that we didn't see the previous declaration.
6480 Previous.clear();
6481 }
6482
6483 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6484 // Forget that the previous declaration is the injected-class-name.
6485 Previous.clear();
6486
6487 // In C++, the previous declaration we find might be a tag type
6488 // (class or enum). In this case, the new declaration will hide the
6489 // tag type. Note that this applies to functions, function templates, and
6490 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6491 if (Previous.isSingleTagDecl() &&
6492 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6493 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6494 Previous.clear();
6495
6496 // Check that there are no default arguments other than in the parameters
6497 // of a function declaration (C++ only).
6498 if (getLangOpts().CPlusPlus)
6499 CheckExtraCXXDefaultArguments(D);
6500
6501 NamedDecl *New;
6502
6503 bool AddToScope = true;
6504 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6505 if (TemplateParamLists.size()) {
6506 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6507 return nullptr;
6508 }
6509
6510 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6511 } else if (R->isFunctionType()) {
6512 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6513 TemplateParamLists,
6514 AddToScope);
6515 } else {
6516 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6517 AddToScope);
6518 }
6519
6520 if (!New)
6521 return nullptr;
6522
6523 // If this has an identifier and is not a function template specialization,
6524 // add it to the scope stack.
6525 if (New->getDeclName() && AddToScope)
6526 PushOnScopeChains(D: New, S);
6527
6528 if (isInOpenMPDeclareTargetContext())
6529 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6530
6531 return New;
6532}
6533
6534/// Helper method to turn variable array types into constant array
6535/// types in certain situations which would otherwise be errors (for
6536/// GCC compatibility).
6537static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6538 ASTContext &Context,
6539 bool &SizeIsNegative,
6540 llvm::APSInt &Oversized) {
6541 // This method tries to turn a variable array into a constant
6542 // array even when the size isn't an ICE. This is necessary
6543 // for compatibility with code that depends on gcc's buggy
6544 // constant expression folding, like struct {char x[(int)(char*)2];}
6545 SizeIsNegative = false;
6546 Oversized = 0;
6547
6548 if (T->isDependentType())
6549 return QualType();
6550
6551 QualifierCollector Qs;
6552 const Type *Ty = Qs.strip(type: T);
6553
6554 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6555 QualType Pointee = PTy->getPointeeType();
6556 QualType FixedType =
6557 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6558 Oversized);
6559 if (FixedType.isNull()) return FixedType;
6560 FixedType = Context.getPointerType(T: FixedType);
6561 return Qs.apply(Context, QT: FixedType);
6562 }
6563 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6564 QualType Inner = PTy->getInnerType();
6565 QualType FixedType =
6566 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6567 Oversized);
6568 if (FixedType.isNull()) return FixedType;
6569 FixedType = Context.getParenType(NamedType: FixedType);
6570 return Qs.apply(Context, QT: FixedType);
6571 }
6572
6573 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6574 if (!VLATy)
6575 return QualType();
6576
6577 QualType ElemTy = VLATy->getElementType();
6578 if (ElemTy->isVariablyModifiedType()) {
6579 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6580 SizeIsNegative, Oversized);
6581 if (ElemTy.isNull())
6582 return QualType();
6583 }
6584
6585 Expr::EvalResult Result;
6586 if (!VLATy->getSizeExpr() ||
6587 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6588 return QualType();
6589
6590 llvm::APSInt Res = Result.Val.getInt();
6591
6592 // Check whether the array size is negative.
6593 if (Res.isSigned() && Res.isNegative()) {
6594 SizeIsNegative = true;
6595 return QualType();
6596 }
6597
6598 // Check whether the array is too large to be addressed.
6599 unsigned ActiveSizeBits =
6600 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6601 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6602 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6603 : Res.getActiveBits();
6604 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6605 Oversized = Res;
6606 return QualType();
6607 }
6608
6609 QualType FoldedArrayType = Context.getConstantArrayType(
6610 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6611 return Qs.apply(Context, QT: FoldedArrayType);
6612}
6613
6614static void
6615FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6616 SrcTL = SrcTL.getUnqualifiedLoc();
6617 DstTL = DstTL.getUnqualifiedLoc();
6618 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6619 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6620 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6621 DstPTL.getPointeeLoc());
6622 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6623 return;
6624 }
6625 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6626 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6627 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6628 DstTL: DstPTL.getInnerLoc());
6629 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6630 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6631 return;
6632 }
6633 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6634 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6635 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6636 TypeLoc DstElemTL = DstATL.getElementLoc();
6637 if (VariableArrayTypeLoc SrcElemATL =
6638 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6639 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6640 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6641 } else {
6642 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6643 }
6644 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6645 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6646 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6647}
6648
6649/// Helper method to turn variable array types into constant array
6650/// types in certain situations which would otherwise be errors (for
6651/// GCC compatibility).
6652static TypeSourceInfo*
6653TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6654 ASTContext &Context,
6655 bool &SizeIsNegative,
6656 llvm::APSInt &Oversized) {
6657 QualType FixedTy
6658 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6659 SizeIsNegative, Oversized);
6660 if (FixedTy.isNull())
6661 return nullptr;
6662 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6663 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6664 DstTL: FixedTInfo->getTypeLoc());
6665 return FixedTInfo;
6666}
6667
6668/// Attempt to fold a variable-sized type to a constant-sized type, returning
6669/// true if we were successful.
6670bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6671 QualType &T, SourceLocation Loc,
6672 unsigned FailedFoldDiagID) {
6673 bool SizeIsNegative;
6674 llvm::APSInt Oversized;
6675 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6676 TInfo, Context, SizeIsNegative, Oversized);
6677 if (FixedTInfo) {
6678 Diag(Loc, diag::ext_vla_folded_to_constant);
6679 TInfo = FixedTInfo;
6680 T = FixedTInfo->getType();
6681 return true;
6682 }
6683
6684 if (SizeIsNegative)
6685 Diag(Loc, diag::err_typecheck_negative_array_size);
6686 else if (Oversized.getBoolValue())
6687 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6688 else if (FailedFoldDiagID)
6689 Diag(Loc, DiagID: FailedFoldDiagID);
6690 return false;
6691}
6692
6693/// Register the given locally-scoped extern "C" declaration so
6694/// that it can be found later for redeclarations. We include any extern "C"
6695/// declaration that is not visible in the translation unit here, not just
6696/// function-scope declarations.
6697void
6698Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6699 if (!getLangOpts().CPlusPlus &&
6700 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6701 // Don't need to track declarations in the TU in C.
6702 return;
6703
6704 // Note that we have a locally-scoped external with this name.
6705 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6706}
6707
6708NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6709 // FIXME: We can have multiple results via __attribute__((overloadable)).
6710 auto Result = Context.getExternCContextDecl()->lookup(Name);
6711 return Result.empty() ? nullptr : *Result.begin();
6712}
6713
6714/// Diagnose function specifiers on a declaration of an identifier that
6715/// does not identify a function.
6716void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6717 // FIXME: We should probably indicate the identifier in question to avoid
6718 // confusion for constructs like "virtual int a(), b;"
6719 if (DS.isVirtualSpecified())
6720 Diag(DS.getVirtualSpecLoc(),
6721 diag::err_virtual_non_function);
6722
6723 if (DS.hasExplicitSpecifier())
6724 Diag(DS.getExplicitSpecLoc(),
6725 diag::err_explicit_non_function);
6726
6727 if (DS.isNoreturnSpecified())
6728 Diag(DS.getNoreturnSpecLoc(),
6729 diag::err_noreturn_non_function);
6730}
6731
6732NamedDecl*
6733Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6734 TypeSourceInfo *TInfo, LookupResult &Previous) {
6735 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6736 if (D.getCXXScopeSpec().isSet()) {
6737 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6738 << D.getCXXScopeSpec().getRange();
6739 D.setInvalidType();
6740 // Pretend we didn't see the scope specifier.
6741 DC = CurContext;
6742 Previous.clear();
6743 }
6744
6745 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6746
6747 if (D.getDeclSpec().isInlineSpecified())
6748 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6749 << getLangOpts().CPlusPlus17;
6750 if (D.getDeclSpec().hasConstexprSpecifier())
6751 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6752 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6753
6754 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6755 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6756 Diag(D.getName().StartLocation,
6757 diag::err_deduction_guide_invalid_specifier)
6758 << "typedef";
6759 else
6760 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6761 << D.getName().getSourceRange();
6762 return nullptr;
6763 }
6764
6765 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6766 if (!NewTD) return nullptr;
6767
6768 // Handle attributes prior to checking for duplicates in MergeVarDecl
6769 ProcessDeclAttributes(S, NewTD, D);
6770
6771 CheckTypedefForVariablyModifiedType(S, NewTD);
6772
6773 bool Redeclaration = D.isRedeclaration();
6774 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6775 D.setRedeclaration(Redeclaration);
6776 return ND;
6777}
6778
6779void
6780Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6781 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6782 // then it shall have block scope.
6783 // Note that variably modified types must be fixed before merging the decl so
6784 // that redeclarations will match.
6785 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6786 QualType T = TInfo->getType();
6787 if (T->isVariablyModifiedType()) {
6788 setFunctionHasBranchProtectedScope();
6789
6790 if (S->getFnParent() == nullptr) {
6791 bool SizeIsNegative;
6792 llvm::APSInt Oversized;
6793 TypeSourceInfo *FixedTInfo =
6794 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6795 SizeIsNegative,
6796 Oversized);
6797 if (FixedTInfo) {
6798 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6799 NewTD->setTypeSourceInfo(FixedTInfo);
6800 } else {
6801 if (SizeIsNegative)
6802 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6803 else if (T->isVariableArrayType())
6804 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6805 else if (Oversized.getBoolValue())
6806 Diag(NewTD->getLocation(), diag::err_array_too_large)
6807 << toString(Oversized, 10);
6808 else
6809 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6810 NewTD->setInvalidDecl();
6811 }
6812 }
6813 }
6814}
6815
6816/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6817/// declares a typedef-name, either using the 'typedef' type specifier or via
6818/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6819NamedDecl*
6820Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6821 LookupResult &Previous, bool &Redeclaration) {
6822
6823 // Find the shadowed declaration before filtering for scope.
6824 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6825
6826 // Merge the decl with the existing one if appropriate. If the decl is
6827 // in an outer scope, it isn't the same thing.
6828 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6829 /*AllowInlineNamespace*/false);
6830 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6831 if (!Previous.empty()) {
6832 Redeclaration = true;
6833 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6834 } else {
6835 inferGslPointerAttribute(TD: NewTD);
6836 }
6837
6838 if (ShadowedDecl && !Redeclaration)
6839 CheckShadow(NewTD, ShadowedDecl, Previous);
6840
6841 // If this is the C FILE type, notify the AST context.
6842 if (IdentifierInfo *II = NewTD->getIdentifier())
6843 if (!NewTD->isInvalidDecl() &&
6844 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6845 switch (II->getNotableIdentifierID()) {
6846 case tok::NotableIdentifierKind::FILE:
6847 Context.setFILEDecl(NewTD);
6848 break;
6849 case tok::NotableIdentifierKind::jmp_buf:
6850 Context.setjmp_bufDecl(NewTD);
6851 break;
6852 case tok::NotableIdentifierKind::sigjmp_buf:
6853 Context.setsigjmp_bufDecl(NewTD);
6854 break;
6855 case tok::NotableIdentifierKind::ucontext_t:
6856 Context.setucontext_tDecl(NewTD);
6857 break;
6858 case tok::NotableIdentifierKind::float_t:
6859 case tok::NotableIdentifierKind::double_t:
6860 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6861 break;
6862 default:
6863 break;
6864 }
6865 }
6866
6867 return NewTD;
6868}
6869
6870/// Determines whether the given declaration is an out-of-scope
6871/// previous declaration.
6872///
6873/// This routine should be invoked when name lookup has found a
6874/// previous declaration (PrevDecl) that is not in the scope where a
6875/// new declaration by the same name is being introduced. If the new
6876/// declaration occurs in a local scope, previous declarations with
6877/// linkage may still be considered previous declarations (C99
6878/// 6.2.2p4-5, C++ [basic.link]p6).
6879///
6880/// \param PrevDecl the previous declaration found by name
6881/// lookup
6882///
6883/// \param DC the context in which the new declaration is being
6884/// declared.
6885///
6886/// \returns true if PrevDecl is an out-of-scope previous declaration
6887/// for a new delcaration with the same name.
6888static bool
6889isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6890 ASTContext &Context) {
6891 if (!PrevDecl)
6892 return false;
6893
6894 if (!PrevDecl->hasLinkage())
6895 return false;
6896
6897 if (Context.getLangOpts().CPlusPlus) {
6898 // C++ [basic.link]p6:
6899 // If there is a visible declaration of an entity with linkage
6900 // having the same name and type, ignoring entities declared
6901 // outside the innermost enclosing namespace scope, the block
6902 // scope declaration declares that same entity and receives the
6903 // linkage of the previous declaration.
6904 DeclContext *OuterContext = DC->getRedeclContext();
6905 if (!OuterContext->isFunctionOrMethod())
6906 // This rule only applies to block-scope declarations.
6907 return false;
6908
6909 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6910 if (PrevOuterContext->isRecord())
6911 // We found a member function: ignore it.
6912 return false;
6913
6914 // Find the innermost enclosing namespace for the new and
6915 // previous declarations.
6916 OuterContext = OuterContext->getEnclosingNamespaceContext();
6917 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6918
6919 // The previous declaration is in a different namespace, so it
6920 // isn't the same function.
6921 if (!OuterContext->Equals(DC: PrevOuterContext))
6922 return false;
6923 }
6924
6925 return true;
6926}
6927
6928static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6929 CXXScopeSpec &SS = D.getCXXScopeSpec();
6930 if (!SS.isSet()) return;
6931 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
6932}
6933
6934bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6935 QualType type = decl->getType();
6936 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6937 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6938 // Various kinds of declaration aren't allowed to be __autoreleasing.
6939 unsigned kind = -1U;
6940 if (VarDecl *var = dyn_cast<VarDecl>(Val: decl)) {
6941 if (var->hasAttr<BlocksAttr>())
6942 kind = 0; // __block
6943 else if (!var->hasLocalStorage())
6944 kind = 1; // global
6945 } else if (isa<ObjCIvarDecl>(Val: decl)) {
6946 kind = 3; // ivar
6947 } else if (isa<FieldDecl>(Val: decl)) {
6948 kind = 2; // field
6949 }
6950
6951 if (kind != -1U) {
6952 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6953 << kind;
6954 }
6955 } else if (lifetime == Qualifiers::OCL_None) {
6956 // Try to infer lifetime.
6957 if (!type->isObjCLifetimeType())
6958 return false;
6959
6960 lifetime = type->getObjCARCImplicitLifetime();
6961 type = Context.getLifetimeQualifiedType(type, lifetime);
6962 decl->setType(type);
6963 }
6964
6965 if (VarDecl *var = dyn_cast<VarDecl>(Val: decl)) {
6966 // Thread-local variables cannot have lifetime.
6967 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6968 var->getTLSKind()) {
6969 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6970 << var->getType();
6971 return true;
6972 }
6973 }
6974
6975 return false;
6976}
6977
6978void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6979 if (Decl->getType().hasAddressSpace())
6980 return;
6981 if (Decl->getType()->isDependentType())
6982 return;
6983 if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) {
6984 QualType Type = Var->getType();
6985 if (Type->isSamplerT() || Type->isVoidType())
6986 return;
6987 LangAS ImplAS = LangAS::opencl_private;
6988 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6989 // __opencl_c_program_scope_global_variables feature, the address space
6990 // for a variable at program scope or a static or extern variable inside
6991 // a function are inferred to be __global.
6992 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
6993 Var->hasGlobalStorage())
6994 ImplAS = LangAS::opencl_global;
6995 // If the original type from a decayed type is an array type and that array
6996 // type has no address space yet, deduce it now.
6997 if (auto DT = dyn_cast<DecayedType>(Type)) {
6998 auto OrigTy = DT->getOriginalType();
6999 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7000 // Add the address space to the original array type and then propagate
7001 // that to the element type through `getAsArrayType`.
7002 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
7003 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
7004 // Re-generate the decayed type.
7005 Type = Context.getDecayedType(OrigTy);
7006 }
7007 }
7008 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
7009 // Apply any qualifiers (including address space) from the array type to
7010 // the element type. This implements C99 6.7.3p8: "If the specification of
7011 // an array type includes any type qualifiers, the element type is so
7012 // qualified, not the array type."
7013 if (Type->isArrayType())
7014 Type = QualType(Context.getAsArrayType(T: Type), 0);
7015 Decl->setType(Type);
7016 }
7017}
7018
7019static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7020 // Ensure that an auto decl is deduced otherwise the checks below might cache
7021 // the wrong linkage.
7022 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7023
7024 // 'weak' only applies to declarations with external linkage.
7025 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7026 if (!ND.isExternallyVisible()) {
7027 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7028 ND.dropAttr<WeakAttr>();
7029 }
7030 }
7031 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7032 if (ND.isExternallyVisible()) {
7033 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7034 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7035 }
7036 }
7037
7038 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7039 if (VD->hasInit()) {
7040 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7041 assert(VD->isThisDeclarationADefinition() &&
7042 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7043 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7044 VD->dropAttr<AliasAttr>();
7045 }
7046 }
7047 }
7048
7049 // 'selectany' only applies to externally visible variable declarations.
7050 // It does not apply to functions.
7051 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7052 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7053 S.Diag(Attr->getLocation(),
7054 diag::err_attribute_selectany_non_extern_data);
7055 ND.dropAttr<SelectAnyAttr>();
7056 }
7057 }
7058
7059 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7060 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7061 bool IsAnonymousNS = false;
7062 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7063 if (VD) {
7064 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7065 while (NS && !IsAnonymousNS) {
7066 IsAnonymousNS = NS->isAnonymousNamespace();
7067 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7068 }
7069 }
7070 // dll attributes require external linkage. Static locals may have external
7071 // linkage but still cannot be explicitly imported or exported.
7072 // In Microsoft mode, a variable defined in anonymous namespace must have
7073 // external linkage in order to be exported.
7074 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7075 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7076 (!AnonNSInMicrosoftMode &&
7077 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7078 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7079 << &ND << Attr;
7080 ND.setInvalidDecl();
7081 }
7082 }
7083
7084 // Check the attributes on the function type, if any.
7085 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7086 // Don't declare this variable in the second operand of the for-statement;
7087 // GCC miscompiles that by ending its lifetime before evaluating the
7088 // third operand. See gcc.gnu.org/PR86769.
7089 AttributedTypeLoc ATL;
7090 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7091 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7092 TL = ATL.getModifiedLoc()) {
7093 // The [[lifetimebound]] attribute can be applied to the implicit object
7094 // parameter of a non-static member function (other than a ctor or dtor)
7095 // by applying it to the function type.
7096 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7097 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7098 if (!MD || MD->isStatic()) {
7099 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7100 << !MD << A->getRange();
7101 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7102 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7103 << isa<CXXDestructorDecl>(MD) << A->getRange();
7104 }
7105 }
7106 }
7107 }
7108}
7109
7110static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7111 NamedDecl *NewDecl,
7112 bool IsSpecialization,
7113 bool IsDefinition) {
7114 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7115 return;
7116
7117 bool IsTemplate = false;
7118 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7119 OldDecl = OldTD->getTemplatedDecl();
7120 IsTemplate = true;
7121 if (!IsSpecialization)
7122 IsDefinition = false;
7123 }
7124 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7125 NewDecl = NewTD->getTemplatedDecl();
7126 IsTemplate = true;
7127 }
7128
7129 if (!OldDecl || !NewDecl)
7130 return;
7131
7132 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7133 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7134 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7135 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7136
7137 // dllimport and dllexport are inheritable attributes so we have to exclude
7138 // inherited attribute instances.
7139 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7140 (NewExportAttr && !NewExportAttr->isInherited());
7141
7142 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7143 // the only exception being explicit specializations.
7144 // Implicitly generated declarations are also excluded for now because there
7145 // is no other way to switch these to use dllimport or dllexport.
7146 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7147
7148 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7149 // Allow with a warning for free functions and global variables.
7150 bool JustWarn = false;
7151 if (!OldDecl->isCXXClassMember()) {
7152 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7153 if (VD && !VD->getDescribedVarTemplate())
7154 JustWarn = true;
7155 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7156 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7157 JustWarn = true;
7158 }
7159
7160 // We cannot change a declaration that's been used because IR has already
7161 // been emitted. Dllimported functions will still work though (modulo
7162 // address equality) as they can use the thunk.
7163 if (OldDecl->isUsed())
7164 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7165 JustWarn = false;
7166
7167 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7168 : diag::err_attribute_dll_redeclaration;
7169 S.Diag(NewDecl->getLocation(), DiagID)
7170 << NewDecl
7171 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7172 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7173 if (!JustWarn) {
7174 NewDecl->setInvalidDecl();
7175 return;
7176 }
7177 }
7178
7179 // A redeclaration is not allowed to drop a dllimport attribute, the only
7180 // exceptions being inline function definitions (except for function
7181 // templates), local extern declarations, qualified friend declarations or
7182 // special MSVC extension: in the last case, the declaration is treated as if
7183 // it were marked dllexport.
7184 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7185 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7186 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7187 // Ignore static data because out-of-line definitions are diagnosed
7188 // separately.
7189 IsStaticDataMember = VD->isStaticDataMember();
7190 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7191 VarDecl::DeclarationOnly;
7192 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7193 IsInline = FD->isInlined();
7194 IsQualifiedFriend = FD->getQualifier() &&
7195 FD->getFriendObjectKind() == Decl::FOK_Declared;
7196 }
7197
7198 if (OldImportAttr && !HasNewAttr &&
7199 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7200 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7201 if (IsMicrosoftABI && IsDefinition) {
7202 if (IsSpecialization) {
7203 S.Diag(
7204 NewDecl->getLocation(),
7205 diag::err_attribute_dllimport_function_specialization_definition);
7206 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7207 NewDecl->dropAttr<DLLImportAttr>();
7208 } else {
7209 S.Diag(NewDecl->getLocation(),
7210 diag::warn_redeclaration_without_import_attribute)
7211 << NewDecl;
7212 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7213 NewDecl->dropAttr<DLLImportAttr>();
7214 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7215 S.Context, NewImportAttr->getRange()));
7216 }
7217 } else if (IsMicrosoftABI && IsSpecialization) {
7218 assert(!IsDefinition);
7219 // MSVC allows this. Keep the inherited attribute.
7220 } else {
7221 S.Diag(NewDecl->getLocation(),
7222 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7223 << NewDecl << OldImportAttr;
7224 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7225 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7226 OldDecl->dropAttr<DLLImportAttr>();
7227 NewDecl->dropAttr<DLLImportAttr>();
7228 }
7229 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7230 // In MinGW, seeing a function declared inline drops the dllimport
7231 // attribute.
7232 OldDecl->dropAttr<DLLImportAttr>();
7233 NewDecl->dropAttr<DLLImportAttr>();
7234 S.Diag(NewDecl->getLocation(),
7235 diag::warn_dllimport_dropped_from_inline_function)
7236 << NewDecl << OldImportAttr;
7237 }
7238
7239 // A specialization of a class template member function is processed here
7240 // since it's a redeclaration. If the parent class is dllexport, the
7241 // specialization inherits that attribute. This doesn't happen automatically
7242 // since the parent class isn't instantiated until later.
7243 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7244 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7245 !NewImportAttr && !NewExportAttr) {
7246 if (const DLLExportAttr *ParentExportAttr =
7247 MD->getParent()->getAttr<DLLExportAttr>()) {
7248 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7249 NewAttr->setInherited(true);
7250 NewDecl->addAttr(A: NewAttr);
7251 }
7252 }
7253 }
7254}
7255
7256/// Given that we are within the definition of the given function,
7257/// will that definition behave like C99's 'inline', where the
7258/// definition is discarded except for optimization purposes?
7259static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7260 // Try to avoid calling GetGVALinkageForFunction.
7261
7262 // All cases of this require the 'inline' keyword.
7263 if (!FD->isInlined()) return false;
7264
7265 // This is only possible in C++ with the gnu_inline attribute.
7266 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7267 return false;
7268
7269 // Okay, go ahead and call the relatively-more-expensive function.
7270 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7271}
7272
7273/// Determine whether a variable is extern "C" prior to attaching
7274/// an initializer. We can't just call isExternC() here, because that
7275/// will also compute and cache whether the declaration is externally
7276/// visible, which might change when we attach the initializer.
7277///
7278/// This can only be used if the declaration is known to not be a
7279/// redeclaration of an internal linkage declaration.
7280///
7281/// For instance:
7282///
7283/// auto x = []{};
7284///
7285/// Attaching the initializer here makes this declaration not externally
7286/// visible, because its type has internal linkage.
7287///
7288/// FIXME: This is a hack.
7289template<typename T>
7290static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7291 if (S.getLangOpts().CPlusPlus) {
7292 // In C++, the overloadable attribute negates the effects of extern "C".
7293 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7294 return false;
7295
7296 // So do CUDA's host/device attributes.
7297 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7298 D->template hasAttr<CUDAHostAttr>()))
7299 return false;
7300 }
7301 return D->isExternC();
7302}
7303
7304static bool shouldConsiderLinkage(const VarDecl *VD) {
7305 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7306 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7307 isa<OMPDeclareMapperDecl>(Val: DC))
7308 return VD->hasExternalStorage();
7309 if (DC->isFileContext())
7310 return true;
7311 if (DC->isRecord())
7312 return false;
7313 if (DC->getDeclKind() == Decl::HLSLBuffer)
7314 return false;
7315
7316 if (isa<RequiresExprBodyDecl>(Val: DC))
7317 return false;
7318 llvm_unreachable("Unexpected context");
7319}
7320
7321static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7322 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7323 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7324 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7325 return true;
7326 if (DC->isRecord())
7327 return false;
7328 llvm_unreachable("Unexpected context");
7329}
7330
7331static bool hasParsedAttr(Scope *S, const Declarator &PD,
7332 ParsedAttr::Kind Kind) {
7333 // Check decl attributes on the DeclSpec.
7334 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7335 return true;
7336
7337 // Walk the declarator structure, checking decl attributes that were in a type
7338 // position to the decl itself.
7339 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7340 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7341 return true;
7342 }
7343
7344 // Finally, check attributes on the decl itself.
7345 return PD.getAttributes().hasAttribute(K: Kind) ||
7346 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7347}
7348
7349/// Adjust the \c DeclContext for a function or variable that might be a
7350/// function-local external declaration.
7351bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7352 if (!DC->isFunctionOrMethod())
7353 return false;
7354
7355 // If this is a local extern function or variable declared within a function
7356 // template, don't add it into the enclosing namespace scope until it is
7357 // instantiated; it might have a dependent type right now.
7358 if (DC->isDependentContext())
7359 return true;
7360
7361 // C++11 [basic.link]p7:
7362 // When a block scope declaration of an entity with linkage is not found to
7363 // refer to some other declaration, then that entity is a member of the
7364 // innermost enclosing namespace.
7365 //
7366 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7367 // semantically-enclosing namespace, not a lexically-enclosing one.
7368 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7369 DC = DC->getParent();
7370 return true;
7371}
7372
7373/// Returns true if given declaration has external C language linkage.
7374static bool isDeclExternC(const Decl *D) {
7375 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7376 return FD->isExternC();
7377 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7378 return VD->isExternC();
7379
7380 llvm_unreachable("Unknown type of decl!");
7381}
7382
7383/// Returns true if there hasn't been any invalid type diagnosed.
7384static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7385 DeclContext *DC = NewVD->getDeclContext();
7386 QualType R = NewVD->getType();
7387
7388 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7389 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7390 // argument.
7391 if (R->isImageType() || R->isPipeType()) {
7392 Se.Diag(NewVD->getLocation(),
7393 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7394 << R;
7395 NewVD->setInvalidDecl();
7396 return false;
7397 }
7398
7399 // OpenCL v1.2 s6.9.r:
7400 // The event type cannot be used to declare a program scope variable.
7401 // OpenCL v2.0 s6.9.q:
7402 // The clk_event_t and reserve_id_t types cannot be declared in program
7403 // scope.
7404 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7405 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7406 Se.Diag(NewVD->getLocation(),
7407 diag::err_invalid_type_for_program_scope_var)
7408 << R;
7409 NewVD->setInvalidDecl();
7410 return false;
7411 }
7412 }
7413
7414 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7415 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7416 LO: Se.getLangOpts())) {
7417 QualType NR = R.getCanonicalType();
7418 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7419 NR->isReferenceType()) {
7420 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7421 NR->isFunctionReferenceType()) {
7422 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7423 << NR->isReferenceType();
7424 NewVD->setInvalidDecl();
7425 return false;
7426 }
7427 NR = NR->getPointeeType();
7428 }
7429 }
7430
7431 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7432 LO: Se.getLangOpts())) {
7433 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7434 // half array type (unless the cl_khr_fp16 extension is enabled).
7435 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7436 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7437 NewVD->setInvalidDecl();
7438 return false;
7439 }
7440 }
7441
7442 // OpenCL v1.2 s6.9.r:
7443 // The event type cannot be used with the __local, __constant and __global
7444 // address space qualifiers.
7445 if (R->isEventT()) {
7446 if (R.getAddressSpace() != LangAS::opencl_private) {
7447 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7448 NewVD->setInvalidDecl();
7449 return false;
7450 }
7451 }
7452
7453 if (R->isSamplerT()) {
7454 // OpenCL v1.2 s6.9.b p4:
7455 // The sampler type cannot be used with the __local and __global address
7456 // space qualifiers.
7457 if (R.getAddressSpace() == LangAS::opencl_local ||
7458 R.getAddressSpace() == LangAS::opencl_global) {
7459 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7460 NewVD->setInvalidDecl();
7461 }
7462
7463 // OpenCL v1.2 s6.12.14.1:
7464 // A global sampler must be declared with either the constant address
7465 // space qualifier or with the const qualifier.
7466 if (DC->isTranslationUnit() &&
7467 !(R.getAddressSpace() == LangAS::opencl_constant ||
7468 R.isConstQualified())) {
7469 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7470 NewVD->setInvalidDecl();
7471 }
7472 if (NewVD->isInvalidDecl())
7473 return false;
7474 }
7475
7476 return true;
7477}
7478
7479template <typename AttrTy>
7480static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7481 const TypedefNameDecl *TND = TT->getDecl();
7482 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7483 AttrTy *Clone = Attribute->clone(S.Context);
7484 Clone->setInherited(true);
7485 D->addAttr(A: Clone);
7486 }
7487}
7488
7489// This function emits warning and a corresponding note based on the
7490// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7491// declarations of an annotated type must be const qualified.
7492void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7493 QualType VarType = VD->getType().getCanonicalType();
7494
7495 // Ignore local declarations (for now) and those with const qualification.
7496 // TODO: Local variables should not be allowed if their type declaration has
7497 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7498 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7499 return;
7500
7501 if (VarType->isArrayType()) {
7502 // Retrieve element type for array declarations.
7503 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7504 }
7505
7506 const RecordDecl *RD = VarType->getAsRecordDecl();
7507
7508 // Check if the record declaration is present and if it has any attributes.
7509 if (RD == nullptr)
7510 return;
7511
7512 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7513 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7514 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7515 return;
7516 }
7517}
7518
7519NamedDecl *Sema::ActOnVariableDeclarator(
7520 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7521 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7522 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7523 QualType R = TInfo->getType();
7524 DeclarationName Name = GetNameForDeclarator(D).getName();
7525
7526 IdentifierInfo *II = Name.getAsIdentifierInfo();
7527 bool IsPlaceholderVariable = false;
7528
7529 if (D.isDecompositionDeclarator()) {
7530 // Take the name of the first declarator as our name for diagnostic
7531 // purposes.
7532 auto &Decomp = D.getDecompositionDeclarator();
7533 if (!Decomp.bindings().empty()) {
7534 II = Decomp.bindings()[0].Name;
7535 Name = II;
7536 }
7537 } else if (!II) {
7538 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7539 return nullptr;
7540 }
7541
7542
7543 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7544 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7545
7546 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7547 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7548 IsPlaceholderVariable = true;
7549 if (!Previous.empty()) {
7550 NamedDecl *PrevDecl = *Previous.begin();
7551 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7552 DC->getRedeclContext());
7553 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false))
7554 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7555 }
7556 }
7557
7558 // dllimport globals without explicit storage class are treated as extern. We
7559 // have to change the storage class this early to get the right DeclContext.
7560 if (SC == SC_None && !DC->isRecord() &&
7561 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7562 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7563 SC = SC_Extern;
7564
7565 DeclContext *OriginalDC = DC;
7566 bool IsLocalExternDecl = SC == SC_Extern &&
7567 adjustContextForLocalExternDecl(DC);
7568
7569 if (SCSpec == DeclSpec::SCS_mutable) {
7570 // mutable can only appear on non-static class members, so it's always
7571 // an error here
7572 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7573 D.setInvalidType();
7574 SC = SC_None;
7575 }
7576
7577 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7578 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7579 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7580 // In C++11, the 'register' storage class specifier is deprecated.
7581 // Suppress the warning in system macros, it's used in macros in some
7582 // popular C system headers, such as in glibc's htonl() macro.
7583 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7584 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7585 : diag::warn_deprecated_register)
7586 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7587 }
7588
7589 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7590
7591 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7592 // C99 6.9p2: The storage-class specifiers auto and register shall not
7593 // appear in the declaration specifiers in an external declaration.
7594 // Global Register+Asm is a GNU extension we support.
7595 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7596 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7597 D.setInvalidType();
7598 }
7599 }
7600
7601 // If this variable has a VLA type and an initializer, try to
7602 // fold to a constant-sized type. This is otherwise invalid.
7603 if (D.hasInitializer() && R->isVariableArrayType())
7604 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7605 /*DiagID=*/FailedFoldDiagID: 0);
7606
7607 bool IsMemberSpecialization = false;
7608 bool IsVariableTemplateSpecialization = false;
7609 bool IsPartialSpecialization = false;
7610 bool IsVariableTemplate = false;
7611 VarDecl *NewVD = nullptr;
7612 VarTemplateDecl *NewTemplate = nullptr;
7613 TemplateParameterList *TemplateParams = nullptr;
7614 if (!getLangOpts().CPlusPlus) {
7615 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7616 Id: II, T: R, TInfo, S: SC);
7617
7618 if (R->getContainedDeducedType())
7619 ParsingInitForAutoVars.insert(NewVD);
7620
7621 if (D.isInvalidType())
7622 NewVD->setInvalidDecl();
7623
7624 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7625 NewVD->hasLocalStorage())
7626 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7627 UseContext: NTCUC_AutoVar, NonTrivialKind: NTCUK_Destruct);
7628 } else {
7629 bool Invalid = false;
7630
7631 if (DC->isRecord() && !CurContext->isRecord()) {
7632 // This is an out-of-line definition of a static data member.
7633 switch (SC) {
7634 case SC_None:
7635 break;
7636 case SC_Static:
7637 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7638 diag::err_static_out_of_line)
7639 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7640 break;
7641 case SC_Auto:
7642 case SC_Register:
7643 case SC_Extern:
7644 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7645 // to names of variables declared in a block or to function parameters.
7646 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7647 // of class members
7648
7649 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7650 diag::err_storage_class_for_static_member)
7651 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7652 break;
7653 case SC_PrivateExtern:
7654 llvm_unreachable("C storage class in c++!");
7655 }
7656 }
7657
7658 if (SC == SC_Static && CurContext->isRecord()) {
7659 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7660 // Walk up the enclosing DeclContexts to check for any that are
7661 // incompatible with static data members.
7662 const DeclContext *FunctionOrMethod = nullptr;
7663 const CXXRecordDecl *AnonStruct = nullptr;
7664 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7665 if (Ctxt->isFunctionOrMethod()) {
7666 FunctionOrMethod = Ctxt;
7667 break;
7668 }
7669 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7670 if (ParentDecl && !ParentDecl->getDeclName()) {
7671 AnonStruct = ParentDecl;
7672 break;
7673 }
7674 }
7675 if (FunctionOrMethod) {
7676 // C++ [class.static.data]p5: A local class shall not have static data
7677 // members.
7678 Diag(D.getIdentifierLoc(),
7679 diag::err_static_data_member_not_allowed_in_local_class)
7680 << Name << RD->getDeclName()
7681 << llvm::to_underlying(RD->getTagKind());
7682 } else if (AnonStruct) {
7683 // C++ [class.static.data]p4: Unnamed classes and classes contained
7684 // directly or indirectly within unnamed classes shall not contain
7685 // static data members.
7686 Diag(D.getIdentifierLoc(),
7687 diag::err_static_data_member_not_allowed_in_anon_struct)
7688 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7689 Invalid = true;
7690 } else if (RD->isUnion()) {
7691 // C++98 [class.union]p1: If a union contains a static data member,
7692 // the program is ill-formed. C++11 drops this restriction.
7693 Diag(D.getIdentifierLoc(),
7694 getLangOpts().CPlusPlus11
7695 ? diag::warn_cxx98_compat_static_data_member_in_union
7696 : diag::ext_static_data_member_in_union) << Name;
7697 }
7698 }
7699 }
7700
7701 // Match up the template parameter lists with the scope specifier, then
7702 // determine whether we have a template or a template specialization.
7703 bool InvalidScope = false;
7704 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7705 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7706 SS: D.getCXXScopeSpec(),
7707 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7708 ? D.getName().TemplateId
7709 : nullptr,
7710 ParamLists: TemplateParamLists,
7711 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid&: InvalidScope);
7712 Invalid |= InvalidScope;
7713
7714 if (TemplateParams) {
7715 if (!TemplateParams->size() &&
7716 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7717 // There is an extraneous 'template<>' for this variable. Complain
7718 // about it, but allow the declaration of the variable.
7719 Diag(TemplateParams->getTemplateLoc(),
7720 diag::err_template_variable_noparams)
7721 << II
7722 << SourceRange(TemplateParams->getTemplateLoc(),
7723 TemplateParams->getRAngleLoc());
7724 TemplateParams = nullptr;
7725 } else {
7726 // Check that we can declare a template here.
7727 if (CheckTemplateDeclScope(S, TemplateParams))
7728 return nullptr;
7729
7730 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7731 // This is an explicit specialization or a partial specialization.
7732 IsVariableTemplateSpecialization = true;
7733 IsPartialSpecialization = TemplateParams->size() > 0;
7734 } else { // if (TemplateParams->size() > 0)
7735 // This is a template declaration.
7736 IsVariableTemplate = true;
7737
7738 // Only C++1y supports variable templates (N3651).
7739 Diag(D.getIdentifierLoc(),
7740 getLangOpts().CPlusPlus14
7741 ? diag::warn_cxx11_compat_variable_template
7742 : diag::ext_variable_template);
7743 }
7744 }
7745 } else {
7746 // Check that we can declare a member specialization here.
7747 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7748 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7749 return nullptr;
7750 assert((Invalid ||
7751 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7752 "should have a 'template<>' for this decl");
7753 }
7754
7755 if (IsVariableTemplateSpecialization) {
7756 SourceLocation TemplateKWLoc =
7757 TemplateParamLists.size() > 0
7758 ? TemplateParamLists[0]->getTemplateLoc()
7759 : SourceLocation();
7760 DeclResult Res = ActOnVarTemplateSpecialization(
7761 S, D, DI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7762 IsPartialSpecialization);
7763 if (Res.isInvalid())
7764 return nullptr;
7765 NewVD = cast<VarDecl>(Val: Res.get());
7766 AddToScope = false;
7767 } else if (D.isDecompositionDeclarator()) {
7768 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7769 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
7770 Bindings);
7771 } else
7772 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7773 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
7774
7775 // If this is supposed to be a variable template, create it as such.
7776 if (IsVariableTemplate) {
7777 NewTemplate =
7778 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
7779 Params: TemplateParams, Decl: NewVD);
7780 NewVD->setDescribedVarTemplate(NewTemplate);
7781 }
7782
7783 // If this decl has an auto type in need of deduction, make a note of the
7784 // Decl so we can diagnose uses of it in its own initializer.
7785 if (R->getContainedDeducedType())
7786 ParsingInitForAutoVars.insert(NewVD);
7787
7788 if (D.isInvalidType() || Invalid) {
7789 NewVD->setInvalidDecl();
7790 if (NewTemplate)
7791 NewTemplate->setInvalidDecl();
7792 }
7793
7794 SetNestedNameSpecifier(*this, NewVD, D);
7795
7796 // If we have any template parameter lists that don't directly belong to
7797 // the variable (matching the scope specifier), store them.
7798 // An explicit variable template specialization does not own any template
7799 // parameter lists.
7800 bool IsExplicitSpecialization =
7801 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7802 unsigned VDTemplateParamLists =
7803 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7804 if (TemplateParamLists.size() > VDTemplateParamLists)
7805 NewVD->setTemplateParameterListsInfo(
7806 Context, TemplateParamLists.drop_back(N: VDTemplateParamLists));
7807 }
7808
7809 if (D.getDeclSpec().isInlineSpecified()) {
7810 if (!getLangOpts().CPlusPlus) {
7811 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7812 << 0;
7813 } else if (CurContext->isFunctionOrMethod()) {
7814 // 'inline' is not allowed on block scope variable declaration.
7815 Diag(D.getDeclSpec().getInlineSpecLoc(),
7816 diag::err_inline_declaration_block_scope) << Name
7817 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7818 } else {
7819 Diag(D.getDeclSpec().getInlineSpecLoc(),
7820 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7821 : diag::ext_inline_variable);
7822 NewVD->setInlineSpecified();
7823 }
7824 }
7825
7826 // Set the lexical context. If the declarator has a C++ scope specifier, the
7827 // lexical context will be different from the semantic context.
7828 NewVD->setLexicalDeclContext(CurContext);
7829 if (NewTemplate)
7830 NewTemplate->setLexicalDeclContext(CurContext);
7831
7832 if (IsLocalExternDecl) {
7833 if (D.isDecompositionDeclarator())
7834 for (auto *B : Bindings)
7835 B->setLocalExternDecl();
7836 else
7837 NewVD->setLocalExternDecl();
7838 }
7839
7840 bool EmitTLSUnsupportedError = false;
7841 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7842 // C++11 [dcl.stc]p4:
7843 // When thread_local is applied to a variable of block scope the
7844 // storage-class-specifier static is implied if it does not appear
7845 // explicitly.
7846 // Core issue: 'static' is not implied if the variable is declared
7847 // 'extern'.
7848 if (NewVD->hasLocalStorage() &&
7849 (SCSpec != DeclSpec::SCS_unspecified ||
7850 TSCS != DeclSpec::TSCS_thread_local ||
7851 !DC->isFunctionOrMethod()))
7852 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7853 diag::err_thread_non_global)
7854 << DeclSpec::getSpecifierName(TSCS);
7855 else if (!Context.getTargetInfo().isTLSSupported()) {
7856 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7857 getLangOpts().SYCLIsDevice) {
7858 // Postpone error emission until we've collected attributes required to
7859 // figure out whether it's a host or device variable and whether the
7860 // error should be ignored.
7861 EmitTLSUnsupportedError = true;
7862 // We still need to mark the variable as TLS so it shows up in AST with
7863 // proper storage class for other tools to use even if we're not going
7864 // to emit any code for it.
7865 NewVD->setTSCSpec(TSCS);
7866 } else
7867 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7868 diag::err_thread_unsupported);
7869 } else
7870 NewVD->setTSCSpec(TSCS);
7871 }
7872
7873 switch (D.getDeclSpec().getConstexprSpecifier()) {
7874 case ConstexprSpecKind::Unspecified:
7875 break;
7876
7877 case ConstexprSpecKind::Consteval:
7878 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7879 diag::err_constexpr_wrong_decl_kind)
7880 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7881 [[fallthrough]];
7882
7883 case ConstexprSpecKind::Constexpr:
7884 NewVD->setConstexpr(true);
7885 // C++1z [dcl.spec.constexpr]p1:
7886 // A static data member declared with the constexpr specifier is
7887 // implicitly an inline variable.
7888 if (NewVD->isStaticDataMember() &&
7889 (getLangOpts().CPlusPlus17 ||
7890 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7891 NewVD->setImplicitlyInline();
7892 break;
7893
7894 case ConstexprSpecKind::Constinit:
7895 if (!NewVD->hasGlobalStorage())
7896 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7897 diag::err_constinit_local_variable);
7898 else
7899 NewVD->addAttr(
7900 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7901 ConstInitAttr::Keyword_constinit));
7902 break;
7903 }
7904
7905 // C99 6.7.4p3
7906 // An inline definition of a function with external linkage shall
7907 // not contain a definition of a modifiable object with static or
7908 // thread storage duration...
7909 // We only apply this when the function is required to be defined
7910 // elsewhere, i.e. when the function is not 'extern inline'. Note
7911 // that a local variable with thread storage duration still has to
7912 // be marked 'static'. Also note that it's possible to get these
7913 // semantics in C++ using __attribute__((gnu_inline)).
7914 if (SC == SC_Static && S->getFnParent() != nullptr &&
7915 !NewVD->getType().isConstQualified()) {
7916 FunctionDecl *CurFD = getCurFunctionDecl();
7917 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
7918 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7919 diag::warn_static_local_in_extern_inline);
7920 MaybeSuggestAddingStaticToDecl(D: CurFD);
7921 }
7922 }
7923
7924 if (D.getDeclSpec().isModulePrivateSpecified()) {
7925 if (IsVariableTemplateSpecialization)
7926 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7927 << (IsPartialSpecialization ? 1 : 0)
7928 << FixItHint::CreateRemoval(
7929 D.getDeclSpec().getModulePrivateSpecLoc());
7930 else if (IsMemberSpecialization)
7931 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7932 << 2
7933 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7934 else if (NewVD->hasLocalStorage())
7935 Diag(NewVD->getLocation(), diag::err_module_private_local)
7936 << 0 << NewVD
7937 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7938 << FixItHint::CreateRemoval(
7939 D.getDeclSpec().getModulePrivateSpecLoc());
7940 else {
7941 NewVD->setModulePrivate();
7942 if (NewTemplate)
7943 NewTemplate->setModulePrivate();
7944 for (auto *B : Bindings)
7945 B->setModulePrivate();
7946 }
7947 }
7948
7949 if (getLangOpts().OpenCL) {
7950 deduceOpenCLAddressSpace(NewVD);
7951
7952 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7953 if (TSC != TSCS_unspecified) {
7954 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7955 diag::err_opencl_unknown_type_specifier)
7956 << getLangOpts().getOpenCLVersionString()
7957 << DeclSpec::getSpecifierName(TSC) << 1;
7958 NewVD->setInvalidDecl();
7959 }
7960 }
7961
7962 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7963 // address space if the table has local storage (semantic checks elsewhere
7964 // will produce an error anyway).
7965 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7966 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7967 !NewVD->hasLocalStorage()) {
7968 QualType Type = Context.getAddrSpaceQualType(
7969 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
7970 NewVD->setType(Type);
7971 }
7972 }
7973
7974 // Handle attributes prior to checking for duplicates in MergeVarDecl
7975 ProcessDeclAttributes(S, NewVD, D);
7976
7977 // FIXME: This is probably the wrong location to be doing this and we should
7978 // probably be doing this for more attributes (especially for function
7979 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7980 // the code to copy attributes would be generated by TableGen.
7981 if (R->isFunctionPointerType())
7982 if (const auto *TT = R->getAs<TypedefType>())
7983 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7984
7985 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7986 getLangOpts().SYCLIsDevice) {
7987 if (EmitTLSUnsupportedError &&
7988 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7989 (getLangOpts().OpenMPIsTargetDevice &&
7990 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7991 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7992 diag::err_thread_unsupported);
7993
7994 if (EmitTLSUnsupportedError &&
7995 (LangOpts.SYCLIsDevice ||
7996 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7997 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7998 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7999 // storage [duration]."
8000 if (SC == SC_None && S->getFnParent() != nullptr &&
8001 (NewVD->hasAttr<CUDASharedAttr>() ||
8002 NewVD->hasAttr<CUDAConstantAttr>())) {
8003 NewVD->setStorageClass(SC_Static);
8004 }
8005 }
8006
8007 // Ensure that dllimport globals without explicit storage class are treated as
8008 // extern. The storage class is set above using parsed attributes. Now we can
8009 // check the VarDecl itself.
8010 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8011 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8012 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8013
8014 // In auto-retain/release, infer strong retension for variables of
8015 // retainable type.
8016 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8017 NewVD->setInvalidDecl();
8018
8019 // Handle GNU asm-label extension (encoded as an attribute).
8020 if (Expr *E = (Expr*)D.getAsmLabel()) {
8021 // The parser guarantees this is a string.
8022 StringLiteral *SE = cast<StringLiteral>(Val: E);
8023 StringRef Label = SE->getString();
8024 if (S->getFnParent() != nullptr) {
8025 switch (SC) {
8026 case SC_None:
8027 case SC_Auto:
8028 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8029 break;
8030 case SC_Register:
8031 // Local Named register
8032 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8033 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8034 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8035 break;
8036 case SC_Static:
8037 case SC_Extern:
8038 case SC_PrivateExtern:
8039 break;
8040 }
8041 } else if (SC == SC_Register) {
8042 // Global Named register
8043 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8044 const auto &TI = Context.getTargetInfo();
8045 bool HasSizeMismatch;
8046
8047 if (!TI.isValidGCCRegisterName(Label))
8048 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8049 else if (!TI.validateGlobalRegisterVariable(Label,
8050 Context.getTypeSize(R),
8051 HasSizeMismatch))
8052 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8053 else if (HasSizeMismatch)
8054 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8055 }
8056
8057 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
8058 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8059 NewVD->setInvalidDecl(true);
8060 }
8061 }
8062
8063 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8064 /*IsLiteralLabel=*/true,
8065 SE->getStrTokenLoc(0)));
8066 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8067 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8068 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8069 if (I != ExtnameUndeclaredIdentifiers.end()) {
8070 if (isDeclExternC(NewVD)) {
8071 NewVD->addAttr(A: I->second);
8072 ExtnameUndeclaredIdentifiers.erase(I);
8073 } else
8074 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8075 << /*Variable*/1 << NewVD;
8076 }
8077 }
8078
8079 // Find the shadowed declaration before filtering for scope.
8080 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8081 ? getShadowedDeclaration(D: NewVD, R: Previous)
8082 : nullptr;
8083
8084 // Don't consider existing declarations that are in a different
8085 // scope and are out-of-semantic-context declarations (if the new
8086 // declaration has linkage).
8087 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8088 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8089 IsMemberSpecialization ||
8090 IsVariableTemplateSpecialization);
8091
8092 // Check whether the previous declaration is in the same block scope. This
8093 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8094 if (getLangOpts().CPlusPlus &&
8095 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8096 NewVD->setPreviousDeclInSameBlockScope(
8097 Previous.isSingleResult() && !Previous.isShadowed() &&
8098 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8099
8100 if (!getLangOpts().CPlusPlus) {
8101 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8102 } else {
8103 // If this is an explicit specialization of a static data member, check it.
8104 if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
8105 !NewVD->isInvalidDecl() && CheckMemberSpecialization(NewVD, Previous))
8106 NewVD->setInvalidDecl();
8107
8108 // Merge the decl with the existing one if appropriate.
8109 if (!Previous.empty()) {
8110 if (Previous.isSingleResult() &&
8111 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8112 D.getCXXScopeSpec().isSet()) {
8113 // The user tried to define a non-static data member
8114 // out-of-line (C++ [dcl.meaning]p1).
8115 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8116 << D.getCXXScopeSpec().getRange();
8117 Previous.clear();
8118 NewVD->setInvalidDecl();
8119 }
8120 } else if (D.getCXXScopeSpec().isSet() &&
8121 !IsVariableTemplateSpecialization) {
8122 // No previous declaration in the qualifying scope.
8123 Diag(D.getIdentifierLoc(), diag::err_no_member)
8124 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8125 << D.getCXXScopeSpec().getRange();
8126 NewVD->setInvalidDecl();
8127 }
8128
8129 if (!IsPlaceholderVariable)
8130 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8131
8132 // CheckVariableDeclaration will set NewVD as invalid if something is in
8133 // error like WebAssembly tables being declared as arrays with a non-zero
8134 // size, but then parsing continues and emits further errors on that line.
8135 // To avoid that we check here if it happened and return nullptr.
8136 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8137 return nullptr;
8138
8139 if (NewTemplate) {
8140 VarTemplateDecl *PrevVarTemplate =
8141 NewVD->getPreviousDecl()
8142 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8143 : nullptr;
8144
8145 // Check the template parameter list of this declaration, possibly
8146 // merging in the template parameter list from the previous variable
8147 // template declaration.
8148 if (CheckTemplateParameterList(
8149 NewParams: TemplateParams,
8150 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8151 : nullptr,
8152 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8153 DC->isDependentContext())
8154 ? TPC_ClassTemplateMember
8155 : TPC_VarTemplate))
8156 NewVD->setInvalidDecl();
8157
8158 // If we are providing an explicit specialization of a static variable
8159 // template, make a note of that.
8160 if (PrevVarTemplate &&
8161 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8162 PrevVarTemplate->setMemberSpecialization();
8163 }
8164 }
8165
8166 // Diagnose shadowed variables iff this isn't a redeclaration.
8167 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8168 CheckShadow(NewVD, ShadowedDecl, Previous);
8169
8170 ProcessPragmaWeak(S, NewVD);
8171
8172 // If this is the first declaration of an extern C variable, update
8173 // the map of such variables.
8174 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8175 isIncompleteDeclExternC(S&: *this, D: NewVD))
8176 RegisterLocallyScopedExternCDecl(NewVD, S);
8177
8178 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8179 MangleNumberingContext *MCtx;
8180 Decl *ManglingContextDecl;
8181 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8182 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8183 if (MCtx) {
8184 Context.setManglingNumber(
8185 NewVD, MCtx->getManglingNumber(
8186 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8187 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8188 }
8189 }
8190
8191 // Special handling of variable named 'main'.
8192 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr(Str: "main") &&
8193 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8194 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8195
8196 // C++ [basic.start.main]p3
8197 // A program that declares a variable main at global scope is ill-formed.
8198 if (getLangOpts().CPlusPlus)
8199 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8200
8201 // In C, and external-linkage variable named main results in undefined
8202 // behavior.
8203 else if (NewVD->hasExternalFormalLinkage())
8204 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8205 }
8206
8207 if (D.isRedeclaration() && !Previous.empty()) {
8208 NamedDecl *Prev = Previous.getRepresentativeDecl();
8209 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8210 D.isFunctionDefinition());
8211 }
8212
8213 if (NewTemplate) {
8214 if (NewVD->isInvalidDecl())
8215 NewTemplate->setInvalidDecl();
8216 ActOnDocumentableDecl(NewTemplate);
8217 return NewTemplate;
8218 }
8219
8220 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8221 CompleteMemberSpecialization(NewVD, Previous);
8222
8223 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8224
8225 return NewVD;
8226}
8227
8228/// Enum describing the %select options in diag::warn_decl_shadow.
8229enum ShadowedDeclKind {
8230 SDK_Local,
8231 SDK_Global,
8232 SDK_StaticMember,
8233 SDK_Field,
8234 SDK_Typedef,
8235 SDK_Using,
8236 SDK_StructuredBinding
8237};
8238
8239/// Determine what kind of declaration we're shadowing.
8240static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8241 const DeclContext *OldDC) {
8242 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8243 return SDK_Using;
8244 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8245 return SDK_Typedef;
8246 else if (isa<BindingDecl>(Val: ShadowedDecl))
8247 return SDK_StructuredBinding;
8248 else if (isa<RecordDecl>(Val: OldDC))
8249 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8250
8251 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8252}
8253
8254/// Return the location of the capture if the given lambda captures the given
8255/// variable \p VD, or an invalid source location otherwise.
8256static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8257 const VarDecl *VD) {
8258 for (const Capture &Capture : LSI->Captures) {
8259 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8260 return Capture.getLocation();
8261 }
8262 return SourceLocation();
8263}
8264
8265static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8266 const LookupResult &R) {
8267 // Only diagnose if we're shadowing an unambiguous field or variable.
8268 if (R.getResultKind() != LookupResult::Found)
8269 return false;
8270
8271 // Return false if warning is ignored.
8272 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8273}
8274
8275/// Return the declaration shadowed by the given variable \p D, or null
8276/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8277NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8278 const LookupResult &R) {
8279 if (!shouldWarnIfShadowedDecl(Diags, R))
8280 return nullptr;
8281
8282 // Don't diagnose declarations at file scope.
8283 if (D->hasGlobalStorage() && !D->isStaticLocal())
8284 return nullptr;
8285
8286 NamedDecl *ShadowedDecl = R.getFoundDecl();
8287 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8288 : nullptr;
8289}
8290
8291/// Return the declaration shadowed by the given typedef \p D, or null
8292/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8293NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8294 const LookupResult &R) {
8295 // Don't warn if typedef declaration is part of a class
8296 if (D->getDeclContext()->isRecord())
8297 return nullptr;
8298
8299 if (!shouldWarnIfShadowedDecl(Diags, R))
8300 return nullptr;
8301
8302 NamedDecl *ShadowedDecl = R.getFoundDecl();
8303 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8304}
8305
8306/// Return the declaration shadowed by the given variable \p D, or null
8307/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8308NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8309 const LookupResult &R) {
8310 if (!shouldWarnIfShadowedDecl(Diags, R))
8311 return nullptr;
8312
8313 NamedDecl *ShadowedDecl = R.getFoundDecl();
8314 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8315 : nullptr;
8316}
8317
8318/// Diagnose variable or built-in function shadowing. Implements
8319/// -Wshadow.
8320///
8321/// This method is called whenever a VarDecl is added to a "useful"
8322/// scope.
8323///
8324/// \param ShadowedDecl the declaration that is shadowed by the given variable
8325/// \param R the lookup of the name
8326///
8327void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8328 const LookupResult &R) {
8329 DeclContext *NewDC = D->getDeclContext();
8330
8331 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8332 // Fields are not shadowed by variables in C++ static methods.
8333 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDC))
8334 if (MD->isStatic())
8335 return;
8336
8337 // Fields shadowed by constructor parameters are a special case. Usually
8338 // the constructor initializes the field with the parameter.
8339 if (isa<CXXConstructorDecl>(Val: NewDC))
8340 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8341 // Remember that this was shadowed so we can either warn about its
8342 // modification or its existence depending on warning settings.
8343 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8344 return;
8345 }
8346 }
8347
8348 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8349 if (shadowedVar->isExternC()) {
8350 // For shadowing external vars, make sure that we point to the global
8351 // declaration, not a locally scoped extern declaration.
8352 for (auto *I : shadowedVar->redecls())
8353 if (I->isFileVarDecl()) {
8354 ShadowedDecl = I;
8355 break;
8356 }
8357 }
8358
8359 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8360
8361 unsigned WarningDiag = diag::warn_decl_shadow;
8362 SourceLocation CaptureLoc;
8363 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8364 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8365 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8366 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8367 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8368 if (RD->getLambdaCaptureDefault() == LCD_None) {
8369 // Try to avoid warnings for lambdas with an explicit capture
8370 // list. Warn only when the lambda captures the shadowed decl
8371 // explicitly.
8372 CaptureLoc = getCaptureLocation(LSI, VD);
8373 if (CaptureLoc.isInvalid())
8374 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8375 } else {
8376 // Remember that this was shadowed so we can avoid the warning if
8377 // the shadowed decl isn't captured and the warning settings allow
8378 // it.
8379 cast<LambdaScopeInfo>(Val: getCurFunction())
8380 ->ShadowingDecls.push_back({.VD: D, VD});
8381 return;
8382 }
8383 }
8384 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8385 // If lambda can capture this, then emit default shadowing warning,
8386 // Otherwise it is not really a shadowing case since field is not
8387 // available in lambda's body.
8388 // At this point we don't know that lambda can capture this, so
8389 // remember that this was shadowed and delay until we know.
8390 cast<LambdaScopeInfo>(Val: getCurFunction())
8391 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8392 return;
8393 }
8394 }
8395 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl);
8396 VD && VD->hasLocalStorage()) {
8397 // A variable can't shadow a local variable in an enclosing scope, if
8398 // they are separated by a non-capturing declaration context.
8399 for (DeclContext *ParentDC = NewDC;
8400 ParentDC && !ParentDC->Equals(DC: OldDC);
8401 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8402 // Only block literals, captured statements, and lambda expressions
8403 // can capture; other scopes don't.
8404 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8405 !isLambdaCallOperator(DC: ParentDC)) {
8406 return;
8407 }
8408 }
8409 }
8410 }
8411 }
8412
8413 // Never warn about shadowing a placeholder variable.
8414 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8415 return;
8416
8417 // Only warn about certain kinds of shadowing for class members.
8418 if (NewDC && NewDC->isRecord()) {
8419 // In particular, don't warn about shadowing non-class members.
8420 if (!OldDC->isRecord())
8421 return;
8422
8423 // TODO: should we warn about static data members shadowing
8424 // static data members from base classes?
8425
8426 // TODO: don't diagnose for inaccessible shadowed members.
8427 // This is hard to do perfectly because we might friend the
8428 // shadowing context, but that's just a false negative.
8429 }
8430
8431
8432 DeclarationName Name = R.getLookupName();
8433
8434 // Emit warning and note.
8435 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8436 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8437 if (!CaptureLoc.isInvalid())
8438 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8439 << Name << /*explicitly*/ 1;
8440 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8441}
8442
8443/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8444/// when these variables are captured by the lambda.
8445void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8446 for (const auto &Shadow : LSI->ShadowingDecls) {
8447 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8448 // Try to avoid the warning when the shadowed decl isn't captured.
8449 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8450 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8451 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8452 Diag(Shadow.VD->getLocation(),
8453 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8454 : diag::warn_decl_shadow)
8455 << Shadow.VD->getDeclName()
8456 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8457 if (CaptureLoc.isValid())
8458 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8459 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8460 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8461 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8462 Diag(Shadow.VD->getLocation(),
8463 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8464 : diag::warn_decl_shadow_uncaptured_local)
8465 << Shadow.VD->getDeclName()
8466 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8467 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8468 }
8469 }
8470}
8471
8472/// Check -Wshadow without the advantage of a previous lookup.
8473void Sema::CheckShadow(Scope *S, VarDecl *D) {
8474 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8475 return;
8476
8477 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8478 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8479 LookupName(R, S);
8480 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8481 CheckShadow(D, ShadowedDecl, R);
8482}
8483
8484/// Check if 'E', which is an expression that is about to be modified, refers
8485/// to a constructor parameter that shadows a field.
8486void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8487 // Quickly ignore expressions that can't be shadowing ctor parameters.
8488 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8489 return;
8490 E = E->IgnoreParenImpCasts();
8491 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8492 if (!DRE)
8493 return;
8494 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8495 auto I = ShadowingDecls.find(Val: D);
8496 if (I == ShadowingDecls.end())
8497 return;
8498 const NamedDecl *ShadowedDecl = I->second;
8499 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8500 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8501 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8502 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8503
8504 // Avoid issuing multiple warnings about the same decl.
8505 ShadowingDecls.erase(I);
8506}
8507
8508/// Check for conflict between this global or extern "C" declaration and
8509/// previous global or extern "C" declarations. This is only used in C++.
8510template<typename T>
8511static bool checkGlobalOrExternCConflict(
8512 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8513 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8514 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8515
8516 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8517 // The common case: this global doesn't conflict with any extern "C"
8518 // declaration.
8519 return false;
8520 }
8521
8522 if (Prev) {
8523 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8524 // Both the old and new declarations have C language linkage. This is a
8525 // redeclaration.
8526 Previous.clear();
8527 Previous.addDecl(D: Prev);
8528 return true;
8529 }
8530
8531 // This is a global, non-extern "C" declaration, and there is a previous
8532 // non-global extern "C" declaration. Diagnose if this is a variable
8533 // declaration.
8534 if (!isa<VarDecl>(ND))
8535 return false;
8536 } else {
8537 // The declaration is extern "C". Check for any declaration in the
8538 // translation unit which might conflict.
8539 if (IsGlobal) {
8540 // We have already performed the lookup into the translation unit.
8541 IsGlobal = false;
8542 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8543 I != E; ++I) {
8544 if (isa<VarDecl>(Val: *I)) {
8545 Prev = *I;
8546 break;
8547 }
8548 }
8549 } else {
8550 DeclContext::lookup_result R =
8551 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8552 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8553 I != E; ++I) {
8554 if (isa<VarDecl>(Val: *I)) {
8555 Prev = *I;
8556 break;
8557 }
8558 // FIXME: If we have any other entity with this name in global scope,
8559 // the declaration is ill-formed, but that is a defect: it breaks the
8560 // 'stat' hack, for instance. Only variables can have mangled name
8561 // clashes with extern "C" declarations, so only they deserve a
8562 // diagnostic.
8563 }
8564 }
8565
8566 if (!Prev)
8567 return false;
8568 }
8569
8570 // Use the first declaration's location to ensure we point at something which
8571 // is lexically inside an extern "C" linkage-spec.
8572 assert(Prev && "should have found a previous declaration to diagnose");
8573 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8574 Prev = FD->getFirstDecl();
8575 else
8576 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8577
8578 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8579 << IsGlobal << ND;
8580 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8581 << IsGlobal;
8582 return false;
8583}
8584
8585/// Apply special rules for handling extern "C" declarations. Returns \c true
8586/// if we have found that this is a redeclaration of some prior entity.
8587///
8588/// Per C++ [dcl.link]p6:
8589/// Two declarations [for a function or variable] with C language linkage
8590/// with the same name that appear in different scopes refer to the same
8591/// [entity]. An entity with C language linkage shall not be declared with
8592/// the same name as an entity in global scope.
8593template<typename T>
8594static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8595 LookupResult &Previous) {
8596 if (!S.getLangOpts().CPlusPlus) {
8597 // In C, when declaring a global variable, look for a corresponding 'extern'
8598 // variable declared in function scope. We don't need this in C++, because
8599 // we find local extern decls in the surrounding file-scope DeclContext.
8600 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8601 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8602 Previous.clear();
8603 Previous.addDecl(D: Prev);
8604 return true;
8605 }
8606 }
8607 return false;
8608 }
8609
8610 // A declaration in the translation unit can conflict with an extern "C"
8611 // declaration.
8612 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8613 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8614
8615 // An extern "C" declaration can conflict with a declaration in the
8616 // translation unit or can be a redeclaration of an extern "C" declaration
8617 // in another scope.
8618 if (isIncompleteDeclExternC(S,ND))
8619 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8620
8621 // Neither global nor extern "C": nothing to do.
8622 return false;
8623}
8624
8625void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8626 // If the decl is already known invalid, don't check it.
8627 if (NewVD->isInvalidDecl())
8628 return;
8629
8630 QualType T = NewVD->getType();
8631
8632 // Defer checking an 'auto' type until its initializer is attached.
8633 if (T->isUndeducedType())
8634 return;
8635
8636 if (NewVD->hasAttrs())
8637 CheckAlignasUnderalignment(NewVD);
8638
8639 if (T->isObjCObjectType()) {
8640 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8641 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8642 T = Context.getObjCObjectPointerType(OIT: T);
8643 NewVD->setType(T);
8644 }
8645
8646 // Emit an error if an address space was applied to decl with local storage.
8647 // This includes arrays of objects with address space qualifiers, but not
8648 // automatic variables that point to other address spaces.
8649 // ISO/IEC TR 18037 S5.1.2
8650 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8651 T.getAddressSpace() != LangAS::Default) {
8652 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8653 NewVD->setInvalidDecl();
8654 return;
8655 }
8656
8657 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8658 // scope.
8659 if (getLangOpts().OpenCLVersion == 120 &&
8660 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8661 LO: getLangOpts()) &&
8662 NewVD->isStaticLocal()) {
8663 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8664 NewVD->setInvalidDecl();
8665 return;
8666 }
8667
8668 if (getLangOpts().OpenCL) {
8669 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8670 return;
8671
8672 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8673 if (NewVD->hasAttr<BlocksAttr>()) {
8674 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8675 return;
8676 }
8677
8678 if (T->isBlockPointerType()) {
8679 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8680 // can't use 'extern' storage class.
8681 if (!T.isConstQualified()) {
8682 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8683 << 0 /*const*/;
8684 NewVD->setInvalidDecl();
8685 return;
8686 }
8687 if (NewVD->hasExternalStorage()) {
8688 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8689 NewVD->setInvalidDecl();
8690 return;
8691 }
8692 }
8693
8694 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8695 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8696 NewVD->hasExternalStorage()) {
8697 if (!T->isSamplerT() && !T->isDependentType() &&
8698 !(T.getAddressSpace() == LangAS::opencl_constant ||
8699 (T.getAddressSpace() == LangAS::opencl_global &&
8700 getOpenCLOptions().areProgramScopeVariablesSupported(
8701 Opts: getLangOpts())))) {
8702 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8703 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8704 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8705 << Scope << "global or constant";
8706 else
8707 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8708 << Scope << "constant";
8709 NewVD->setInvalidDecl();
8710 return;
8711 }
8712 } else {
8713 if (T.getAddressSpace() == LangAS::opencl_global) {
8714 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8715 << 1 /*is any function*/ << "global";
8716 NewVD->setInvalidDecl();
8717 return;
8718 }
8719 if (T.getAddressSpace() == LangAS::opencl_constant ||
8720 T.getAddressSpace() == LangAS::opencl_local) {
8721 FunctionDecl *FD = getCurFunctionDecl();
8722 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8723 // in functions.
8724 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8725 if (T.getAddressSpace() == LangAS::opencl_constant)
8726 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8727 << 0 /*non-kernel only*/ << "constant";
8728 else
8729 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8730 << 0 /*non-kernel only*/ << "local";
8731 NewVD->setInvalidDecl();
8732 return;
8733 }
8734 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8735 // in the outermost scope of a kernel function.
8736 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8737 if (!getCurScope()->isFunctionScope()) {
8738 if (T.getAddressSpace() == LangAS::opencl_constant)
8739 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8740 << "constant";
8741 else
8742 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8743 << "local";
8744 NewVD->setInvalidDecl();
8745 return;
8746 }
8747 }
8748 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8749 // If we are parsing a template we didn't deduce an addr
8750 // space yet.
8751 T.getAddressSpace() != LangAS::Default) {
8752 // Do not allow other address spaces on automatic variable.
8753 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8754 NewVD->setInvalidDecl();
8755 return;
8756 }
8757 }
8758 }
8759
8760 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8761 && !NewVD->hasAttr<BlocksAttr>()) {
8762 if (getLangOpts().getGC() != LangOptions::NonGC)
8763 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8764 else {
8765 assert(!getLangOpts().ObjCAutoRefCount);
8766 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8767 }
8768 }
8769
8770 // WebAssembly tables must be static with a zero length and can't be
8771 // declared within functions.
8772 if (T->isWebAssemblyTableType()) {
8773 if (getCurScope()->getParent()) { // Parent is null at top-level
8774 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8775 NewVD->setInvalidDecl();
8776 return;
8777 }
8778 if (NewVD->getStorageClass() != SC_Static) {
8779 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8780 NewVD->setInvalidDecl();
8781 return;
8782 }
8783 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
8784 if (!ATy || ATy->getSize().getSExtValue() != 0) {
8785 Diag(NewVD->getLocation(),
8786 diag::err_typecheck_wasm_table_must_have_zero_length);
8787 NewVD->setInvalidDecl();
8788 return;
8789 }
8790 }
8791
8792 bool isVM = T->isVariablyModifiedType();
8793 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8794 NewVD->hasAttr<BlocksAttr>())
8795 setFunctionHasBranchProtectedScope();
8796
8797 if ((isVM && NewVD->hasLinkage()) ||
8798 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8799 bool SizeIsNegative;
8800 llvm::APSInt Oversized;
8801 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8802 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8803 QualType FixedT;
8804 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8805 FixedT = FixedTInfo->getType();
8806 else if (FixedTInfo) {
8807 // Type and type-as-written are canonically different. We need to fix up
8808 // both types separately.
8809 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8810 Oversized);
8811 }
8812 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8813 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8814 // FIXME: This won't give the correct result for
8815 // int a[10][n];
8816 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8817
8818 if (NewVD->isFileVarDecl())
8819 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8820 << SizeRange;
8821 else if (NewVD->isStaticLocal())
8822 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8823 << SizeRange;
8824 else
8825 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8826 << SizeRange;
8827 NewVD->setInvalidDecl();
8828 return;
8829 }
8830
8831 if (!FixedTInfo) {
8832 if (NewVD->isFileVarDecl())
8833 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8834 else
8835 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8836 NewVD->setInvalidDecl();
8837 return;
8838 }
8839
8840 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8841 NewVD->setType(FixedT);
8842 NewVD->setTypeSourceInfo(FixedTInfo);
8843 }
8844
8845 if (T->isVoidType()) {
8846 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8847 // of objects and functions.
8848 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8849 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8850 << T;
8851 NewVD->setInvalidDecl();
8852 return;
8853 }
8854 }
8855
8856 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8857 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8858 NewVD->setInvalidDecl();
8859 return;
8860 }
8861
8862 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8863 !T.isWebAssemblyReferenceType()) {
8864 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8865 NewVD->setInvalidDecl();
8866 return;
8867 }
8868
8869 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8870 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8871 NewVD->setInvalidDecl();
8872 return;
8873 }
8874
8875 if (NewVD->isConstexpr() && !T->isDependentType() &&
8876 RequireLiteralType(NewVD->getLocation(), T,
8877 diag::err_constexpr_var_non_literal)) {
8878 NewVD->setInvalidDecl();
8879 return;
8880 }
8881
8882 // PPC MMA non-pointer types are not allowed as non-local variable types.
8883 if (Context.getTargetInfo().getTriple().isPPC64() &&
8884 !NewVD->isLocalVarDecl() &&
8885 CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
8886 NewVD->setInvalidDecl();
8887 return;
8888 }
8889
8890 // Check that SVE types are only used in functions with SVE available.
8891 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
8892 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
8893 llvm::StringMap<bool> CallerFeatureMap;
8894 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
8895 if (!Builtin::evaluateRequiredTargetFeatures(
8896 "sve", CallerFeatureMap)) {
8897 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8898 NewVD->setInvalidDecl();
8899 return;
8900 }
8901 }
8902
8903 if (T->isRVVSizelessBuiltinType())
8904 checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext));
8905}
8906
8907/// Perform semantic checking on a newly-created variable
8908/// declaration.
8909///
8910/// This routine performs all of the type-checking required for a
8911/// variable declaration once it has been built. It is used both to
8912/// check variables after they have been parsed and their declarators
8913/// have been translated into a declaration, and to check variables
8914/// that have been instantiated from a template.
8915///
8916/// Sets NewVD->isInvalidDecl() if an error was encountered.
8917///
8918/// Returns true if the variable declaration is a redeclaration.
8919bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8920 CheckVariableDeclarationType(NewVD);
8921
8922 // If the decl is already known invalid, don't check it.
8923 if (NewVD->isInvalidDecl())
8924 return false;
8925
8926 // If we did not find anything by this name, look for a non-visible
8927 // extern "C" declaration with the same name.
8928 if (Previous.empty() &&
8929 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
8930 Previous.setShadowed();
8931
8932 if (!Previous.empty()) {
8933 MergeVarDecl(New: NewVD, Previous);
8934 return true;
8935 }
8936 return false;
8937}
8938
8939/// AddOverriddenMethods - See if a method overrides any in the base classes,
8940/// and if so, check that it's a valid override and remember it.
8941bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8942 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8943
8944 // Look for methods in base classes that this method might override.
8945 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8946 /*DetectVirtual=*/false);
8947 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8948 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8949 DeclarationName Name = MD->getDeclName();
8950
8951 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8952 // We really want to find the base class destructor here.
8953 QualType T = Context.getTypeDeclType(BaseRecord);
8954 CanQualType CT = Context.getCanonicalType(T);
8955 Name = Context.DeclarationNames.getCXXDestructorName(Ty: CT);
8956 }
8957
8958 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8959 CXXMethodDecl *BaseMD =
8960 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8961 if (!BaseMD || !BaseMD->isVirtual() ||
8962 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8963 /*ConsiderCudaAttrs=*/true))
8964 continue;
8965 if (!CheckExplicitObjectOverride(MD, BaseMD))
8966 continue;
8967 if (Overridden.insert(BaseMD).second) {
8968 MD->addOverriddenMethod(BaseMD);
8969 CheckOverridingFunctionReturnType(MD, BaseMD);
8970 CheckOverridingFunctionAttributes(MD, BaseMD);
8971 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8972 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8973 }
8974
8975 // A method can only override one function from each base class. We
8976 // don't track indirectly overridden methods from bases of bases.
8977 return true;
8978 }
8979
8980 return false;
8981 };
8982
8983 DC->lookupInBases(BaseMatches: VisitBase, Paths);
8984 return !Overridden.empty();
8985}
8986
8987namespace {
8988 // Struct for holding all of the extra arguments needed by
8989 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8990 struct ActOnFDArgs {
8991 Scope *S;
8992 Declarator &D;
8993 MultiTemplateParamsArg TemplateParamLists;
8994 bool AddToScope;
8995 };
8996} // end anonymous namespace
8997
8998namespace {
8999
9000// Callback to only accept typo corrections that have a non-zero edit distance.
9001// Also only accept corrections that have the same parent decl.
9002class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9003 public:
9004 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9005 CXXRecordDecl *Parent)
9006 : Context(Context), OriginalFD(TypoFD),
9007 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9008
9009 bool ValidateCandidate(const TypoCorrection &candidate) override {
9010 if (candidate.getEditDistance() == 0)
9011 return false;
9012
9013 SmallVector<unsigned, 1> MismatchedParams;
9014 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9015 CDeclEnd = candidate.end();
9016 CDecl != CDeclEnd; ++CDecl) {
9017 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9018
9019 if (FD && !FD->hasBody() &&
9020 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9021 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9022 CXXRecordDecl *Parent = MD->getParent();
9023 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9024 return true;
9025 } else if (!ExpectedParent) {
9026 return true;
9027 }
9028 }
9029 }
9030
9031 return false;
9032 }
9033
9034 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9035 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9036 }
9037
9038 private:
9039 ASTContext &Context;
9040 FunctionDecl *OriginalFD;
9041 CXXRecordDecl *ExpectedParent;
9042};
9043
9044} // end anonymous namespace
9045
9046void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9047 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9048}
9049
9050/// Generate diagnostics for an invalid function redeclaration.
9051///
9052/// This routine handles generating the diagnostic messages for an invalid
9053/// function redeclaration, including finding possible similar declarations
9054/// or performing typo correction if there are no previous declarations with
9055/// the same name.
9056///
9057/// Returns a NamedDecl iff typo correction was performed and substituting in
9058/// the new declaration name does not cause new errors.
9059static NamedDecl *DiagnoseInvalidRedeclaration(
9060 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9061 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9062 DeclarationName Name = NewFD->getDeclName();
9063 DeclContext *NewDC = NewFD->getDeclContext();
9064 SmallVector<unsigned, 1> MismatchedParams;
9065 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9066 TypoCorrection Correction;
9067 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9068 unsigned DiagMsg =
9069 IsLocalFriend ? diag::err_no_matching_local_friend :
9070 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9071 diag::err_member_decl_does_not_match;
9072 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9073 IsLocalFriend ? Sema::LookupLocalFriendName
9074 : Sema::LookupOrdinaryName,
9075 Sema::ForVisibleRedeclaration);
9076
9077 NewFD->setInvalidDecl();
9078 if (IsLocalFriend)
9079 SemaRef.LookupName(R&: Prev, S);
9080 else
9081 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9082 assert(!Prev.isAmbiguous() &&
9083 "Cannot have an ambiguity in previous-declaration lookup");
9084 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9085 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9086 MD ? MD->getParent() : nullptr);
9087 if (!Prev.empty()) {
9088 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9089 Func != FuncEnd; ++Func) {
9090 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9091 if (FD &&
9092 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9093 // Add 1 to the index so that 0 can mean the mismatch didn't
9094 // involve a parameter
9095 unsigned ParamNum =
9096 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9097 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9098 }
9099 }
9100 // If the qualified name lookup yielded nothing, try typo correction
9101 } else if ((Correction = SemaRef.CorrectTypo(
9102 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9103 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC, Mode: Sema::CTK_ErrorRecovery,
9104 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9105 // Set up everything for the call to ActOnFunctionDeclarator
9106 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9107 IdLoc: ExtraArgs.D.getIdentifierLoc());
9108 Previous.clear();
9109 Previous.setLookupName(Correction.getCorrection());
9110 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9111 CDeclEnd = Correction.end();
9112 CDecl != CDeclEnd; ++CDecl) {
9113 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9114 if (FD && !FD->hasBody() &&
9115 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9116 Previous.addDecl(FD);
9117 }
9118 }
9119 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9120
9121 NamedDecl *Result;
9122 // Retry building the function declaration with the new previous
9123 // declarations, and with errors suppressed.
9124 {
9125 // Trap errors.
9126 Sema::SFINAETrap Trap(SemaRef);
9127
9128 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9129 // pieces need to verify the typo-corrected C++ declaration and hopefully
9130 // eliminate the need for the parameter pack ExtraArgs.
9131 Result = SemaRef.ActOnFunctionDeclarator(
9132 S: ExtraArgs.S, D&: ExtraArgs.D,
9133 DC: Correction.getCorrectionDecl()->getDeclContext(),
9134 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9135 AddToScope&: ExtraArgs.AddToScope);
9136
9137 if (Trap.hasErrorOccurred())
9138 Result = nullptr;
9139 }
9140
9141 if (Result) {
9142 // Determine which correction we picked.
9143 Decl *Canonical = Result->getCanonicalDecl();
9144 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9145 I != E; ++I)
9146 if ((*I)->getCanonicalDecl() == Canonical)
9147 Correction.setCorrectionDecl(*I);
9148
9149 // Let Sema know about the correction.
9150 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9151 SemaRef.diagnoseTypo(
9152 Correction,
9153 SemaRef.PDiag(IsLocalFriend
9154 ? diag::err_no_matching_local_friend_suggest
9155 : diag::err_member_decl_does_not_match_suggest)
9156 << Name << NewDC << IsDefinition);
9157 return Result;
9158 }
9159
9160 // Pretend the typo correction never occurred
9161 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9162 IdLoc: ExtraArgs.D.getIdentifierLoc());
9163 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9164 Previous.clear();
9165 Previous.setLookupName(Name);
9166 }
9167
9168 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9169 << Name << NewDC << IsDefinition << NewFD->getLocation();
9170
9171 bool NewFDisConst = false;
9172 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD))
9173 NewFDisConst = NewMD->isConst();
9174
9175 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9176 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9177 NearMatch != NearMatchEnd; ++NearMatch) {
9178 FunctionDecl *FD = NearMatch->first;
9179 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9180 bool FDisConst = MD && MD->isConst();
9181 bool IsMember = MD || !IsLocalFriend;
9182
9183 // FIXME: These notes are poorly worded for the local friend case.
9184 if (unsigned Idx = NearMatch->second) {
9185 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9186 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9187 if (Loc.isInvalid()) Loc = FD->getLocation();
9188 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9189 : diag::note_local_decl_close_param_match)
9190 << Idx << FDParam->getType()
9191 << NewFD->getParamDecl(Idx - 1)->getType();
9192 } else if (FDisConst != NewFDisConst) {
9193 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9194 << NewFDisConst << FD->getSourceRange().getEnd()
9195 << (NewFDisConst
9196 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9197 .getConstQualifierLoc())
9198 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9199 .getRParenLoc()
9200 .getLocWithOffset(1),
9201 " const"));
9202 } else
9203 SemaRef.Diag(FD->getLocation(),
9204 IsMember ? diag::note_member_def_close_match
9205 : diag::note_local_decl_close_match);
9206 }
9207 return nullptr;
9208}
9209
9210static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9211 switch (D.getDeclSpec().getStorageClassSpec()) {
9212 default: llvm_unreachable("Unknown storage class!");
9213 case DeclSpec::SCS_auto:
9214 case DeclSpec::SCS_register:
9215 case DeclSpec::SCS_mutable:
9216 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9217 diag::err_typecheck_sclass_func);
9218 D.getMutableDeclSpec().ClearStorageClassSpecs();
9219 D.setInvalidType();
9220 break;
9221 case DeclSpec::SCS_unspecified: break;
9222 case DeclSpec::SCS_extern:
9223 if (D.getDeclSpec().isExternInLinkageSpec())
9224 return SC_None;
9225 return SC_Extern;
9226 case DeclSpec::SCS_static: {
9227 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9228 // C99 6.7.1p5:
9229 // The declaration of an identifier for a function that has
9230 // block scope shall have no explicit storage-class specifier
9231 // other than extern
9232 // See also (C++ [dcl.stc]p4).
9233 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9234 diag::err_static_block_func);
9235 break;
9236 } else
9237 return SC_Static;
9238 }
9239 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9240 }
9241
9242 // No explicit storage class has already been returned
9243 return SC_None;
9244}
9245
9246static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9247 DeclContext *DC, QualType &R,
9248 TypeSourceInfo *TInfo,
9249 StorageClass SC,
9250 bool &IsVirtualOkay) {
9251 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9252 DeclarationName Name = NameInfo.getName();
9253
9254 FunctionDecl *NewFD = nullptr;
9255 bool isInline = D.getDeclSpec().isInlineSpecified();
9256
9257 if (!SemaRef.getLangOpts().CPlusPlus) {
9258 // Determine whether the function was written with a prototype. This is
9259 // true when:
9260 // - there is a prototype in the declarator, or
9261 // - the type R of the function is some kind of typedef or other non-
9262 // attributed reference to a type name (which eventually refers to a
9263 // function type). Note, we can't always look at the adjusted type to
9264 // check this case because attributes may cause a non-function
9265 // declarator to still have a function type. e.g.,
9266 // typedef void func(int a);
9267 // __attribute__((noreturn)) func other_func; // This has a prototype
9268 bool HasPrototype =
9269 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9270 (D.getDeclSpec().isTypeRep() &&
9271 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9272 ->isFunctionProtoType()) ||
9273 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9274 assert(
9275 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9276 "Strict prototypes are required");
9277
9278 NewFD = FunctionDecl::Create(
9279 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9280 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9281 ConstexprKind: ConstexprSpecKind::Unspecified,
9282 /*TrailingRequiresClause=*/nullptr);
9283 if (D.isInvalidType())
9284 NewFD->setInvalidDecl();
9285
9286 return NewFD;
9287 }
9288
9289 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9290
9291 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9292 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9293 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9294 diag::err_constexpr_wrong_decl_kind)
9295 << static_cast<int>(ConstexprKind);
9296 ConstexprKind = ConstexprSpecKind::Unspecified;
9297 D.getMutableDeclSpec().ClearConstexprSpec();
9298 }
9299 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9300
9301 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9302
9303 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9304 // This is a C++ constructor declaration.
9305 assert(DC->isRecord() &&
9306 "Constructors can only be declared in a member context");
9307
9308 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9309 return CXXConstructorDecl::Create(
9310 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9311 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9312 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9313 Inherited: InheritedConstructor(), TrailingRequiresClause);
9314
9315 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9316 // This is a C++ destructor declaration.
9317 if (DC->isRecord()) {
9318 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9319 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9320 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9321 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9322 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9323 /*isImplicitlyDeclared=*/false, ConstexprKind,
9324 TrailingRequiresClause);
9325 // User defined destructors start as not selected if the class definition is still
9326 // not done.
9327 if (Record->isBeingDefined())
9328 NewDD->setIneligibleOrNotSelected(true);
9329
9330 // If the destructor needs an implicit exception specification, set it
9331 // now. FIXME: It'd be nice to be able to create the right type to start
9332 // with, but the type needs to reference the destructor declaration.
9333 if (SemaRef.getLangOpts().CPlusPlus11)
9334 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9335
9336 IsVirtualOkay = true;
9337 return NewDD;
9338
9339 } else {
9340 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9341 D.setInvalidType();
9342
9343 // Create a FunctionDecl to satisfy the function definition parsing
9344 // code path.
9345 return FunctionDecl::Create(
9346 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9347 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9348 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9349 }
9350
9351 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9352 if (!DC->isRecord()) {
9353 SemaRef.Diag(D.getIdentifierLoc(),
9354 diag::err_conv_function_not_member);
9355 return nullptr;
9356 }
9357
9358 SemaRef.CheckConversionDeclarator(D, R, SC);
9359 if (D.isInvalidType())
9360 return nullptr;
9361
9362 IsVirtualOkay = true;
9363 return CXXConversionDecl::Create(
9364 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9365 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9366 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9367 TrailingRequiresClause);
9368
9369 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9370 if (TrailingRequiresClause)
9371 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9372 diag::err_trailing_requires_clause_on_deduction_guide)
9373 << TrailingRequiresClause->getSourceRange();
9374 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9375 return nullptr;
9376 return CXXDeductionGuideDecl::Create(C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(),
9377 ES: ExplicitSpecifier, NameInfo, T: R, TInfo,
9378 EndLocation: D.getEndLoc());
9379 } else if (DC->isRecord()) {
9380 // If the name of the function is the same as the name of the record,
9381 // then this must be an invalid constructor that has a return type.
9382 // (The parser checks for a return type and makes the declarator a
9383 // constructor if it has no return type).
9384 if (Name.getAsIdentifierInfo() &&
9385 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9386 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9387 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9388 << SourceRange(D.getIdentifierLoc());
9389 return nullptr;
9390 }
9391
9392 // This is a C++ method declaration.
9393 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9394 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9395 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9396 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9397 IsVirtualOkay = !Ret->isStatic();
9398 return Ret;
9399 } else {
9400 bool isFriend =
9401 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9402 if (!isFriend && SemaRef.CurContext->isRecord())
9403 return nullptr;
9404
9405 // Determine whether the function was written with a
9406 // prototype. This true when:
9407 // - we're in C++ (where every function has a prototype),
9408 return FunctionDecl::Create(
9409 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9410 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9411 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9412 }
9413}
9414
9415enum OpenCLParamType {
9416 ValidKernelParam,
9417 PtrPtrKernelParam,
9418 PtrKernelParam,
9419 InvalidAddrSpacePtrKernelParam,
9420 InvalidKernelParam,
9421 RecordKernelParam
9422};
9423
9424static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9425 // Size dependent types are just typedefs to normal integer types
9426 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9427 // integers other than by their names.
9428 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9429
9430 // Remove typedefs one by one until we reach a typedef
9431 // for a size dependent type.
9432 QualType DesugaredTy = Ty;
9433 do {
9434 ArrayRef<StringRef> Names(SizeTypeNames);
9435 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9436 if (Names.end() != Match)
9437 return true;
9438
9439 Ty = DesugaredTy;
9440 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9441 } while (DesugaredTy != Ty);
9442
9443 return false;
9444}
9445
9446static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9447 if (PT->isDependentType())
9448 return InvalidKernelParam;
9449
9450 if (PT->isPointerType() || PT->isReferenceType()) {
9451 QualType PointeeType = PT->getPointeeType();
9452 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9453 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9454 PointeeType.getAddressSpace() == LangAS::Default)
9455 return InvalidAddrSpacePtrKernelParam;
9456
9457 if (PointeeType->isPointerType()) {
9458 // This is a pointer to pointer parameter.
9459 // Recursively check inner type.
9460 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9461 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9462 ParamKind == InvalidKernelParam)
9463 return ParamKind;
9464
9465 // OpenCL v3.0 s6.11.a:
9466 // A restriction to pass pointers to pointers only applies to OpenCL C
9467 // v1.2 or below.
9468 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9469 return ValidKernelParam;
9470
9471 return PtrPtrKernelParam;
9472 }
9473
9474 // C++ for OpenCL v1.0 s2.4:
9475 // Moreover the types used in parameters of the kernel functions must be:
9476 // Standard layout types for pointer parameters. The same applies to
9477 // reference if an implementation supports them in kernel parameters.
9478 if (S.getLangOpts().OpenCLCPlusPlus &&
9479 !S.getOpenCLOptions().isAvailableOption(
9480 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9481 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9482 bool IsStandardLayoutType = true;
9483 if (CXXRec) {
9484 // If template type is not ODR-used its definition is only available
9485 // in the template definition not its instantiation.
9486 // FIXME: This logic doesn't work for types that depend on template
9487 // parameter (PR58590).
9488 if (!CXXRec->hasDefinition())
9489 CXXRec = CXXRec->getTemplateInstantiationPattern();
9490 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9491 IsStandardLayoutType = false;
9492 }
9493 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9494 !IsStandardLayoutType)
9495 return InvalidKernelParam;
9496 }
9497
9498 // OpenCL v1.2 s6.9.p:
9499 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9500 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9501 return ValidKernelParam;
9502
9503 return PtrKernelParam;
9504 }
9505
9506 // OpenCL v1.2 s6.9.k:
9507 // Arguments to kernel functions in a program cannot be declared with the
9508 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9509 // uintptr_t or a struct and/or union that contain fields declared to be one
9510 // of these built-in scalar types.
9511 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9512 return InvalidKernelParam;
9513
9514 if (PT->isImageType())
9515 return PtrKernelParam;
9516
9517 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9518 return InvalidKernelParam;
9519
9520 // OpenCL extension spec v1.2 s9.5:
9521 // This extension adds support for half scalar and vector types as built-in
9522 // types that can be used for arithmetic operations, conversions etc.
9523 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9524 PT->isHalfType())
9525 return InvalidKernelParam;
9526
9527 // Look into an array argument to check if it has a forbidden type.
9528 if (PT->isArrayType()) {
9529 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9530 // Call ourself to check an underlying type of an array. Since the
9531 // getPointeeOrArrayElementType returns an innermost type which is not an
9532 // array, this recursive call only happens once.
9533 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9534 }
9535
9536 // C++ for OpenCL v1.0 s2.4:
9537 // Moreover the types used in parameters of the kernel functions must be:
9538 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9539 // types) for parameters passed by value;
9540 if (S.getLangOpts().OpenCLCPlusPlus &&
9541 !S.getOpenCLOptions().isAvailableOption(
9542 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9543 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9544 return InvalidKernelParam;
9545
9546 if (PT->isRecordType())
9547 return RecordKernelParam;
9548
9549 return ValidKernelParam;
9550}
9551
9552static void checkIsValidOpenCLKernelParameter(
9553 Sema &S,
9554 Declarator &D,
9555 ParmVarDecl *Param,
9556 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9557 QualType PT = Param->getType();
9558
9559 // Cache the valid types we encounter to avoid rechecking structs that are
9560 // used again
9561 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9562 return;
9563
9564 switch (getOpenCLKernelParameterType(S, PT)) {
9565 case PtrPtrKernelParam:
9566 // OpenCL v3.0 s6.11.a:
9567 // A kernel function argument cannot be declared as a pointer to a pointer
9568 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9569 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9570 D.setInvalidType();
9571 return;
9572
9573 case InvalidAddrSpacePtrKernelParam:
9574 // OpenCL v1.0 s6.5:
9575 // __kernel function arguments declared to be a pointer of a type can point
9576 // to one of the following address spaces only : __global, __local or
9577 // __constant.
9578 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9579 D.setInvalidType();
9580 return;
9581
9582 // OpenCL v1.2 s6.9.k:
9583 // Arguments to kernel functions in a program cannot be declared with the
9584 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9585 // uintptr_t or a struct and/or union that contain fields declared to be
9586 // one of these built-in scalar types.
9587
9588 case InvalidKernelParam:
9589 // OpenCL v1.2 s6.8 n:
9590 // A kernel function argument cannot be declared
9591 // of event_t type.
9592 // Do not diagnose half type since it is diagnosed as invalid argument
9593 // type for any function elsewhere.
9594 if (!PT->isHalfType()) {
9595 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9596
9597 // Explain what typedefs are involved.
9598 const TypedefType *Typedef = nullptr;
9599 while ((Typedef = PT->getAs<TypedefType>())) {
9600 SourceLocation Loc = Typedef->getDecl()->getLocation();
9601 // SourceLocation may be invalid for a built-in type.
9602 if (Loc.isValid())
9603 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9604 PT = Typedef->desugar();
9605 }
9606 }
9607
9608 D.setInvalidType();
9609 return;
9610
9611 case PtrKernelParam:
9612 case ValidKernelParam:
9613 ValidTypes.insert(Ptr: PT.getTypePtr());
9614 return;
9615
9616 case RecordKernelParam:
9617 break;
9618 }
9619
9620 // Track nested structs we will inspect
9621 SmallVector<const Decl *, 4> VisitStack;
9622
9623 // Track where we are in the nested structs. Items will migrate from
9624 // VisitStack to HistoryStack as we do the DFS for bad field.
9625 SmallVector<const FieldDecl *, 4> HistoryStack;
9626 HistoryStack.push_back(Elt: nullptr);
9627
9628 // At this point we already handled everything except of a RecordType or
9629 // an ArrayType of a RecordType.
9630 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9631 const RecordType *RecTy =
9632 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9633 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9634
9635 VisitStack.push_back(RecTy->getDecl());
9636 assert(VisitStack.back() && "First decl null?");
9637
9638 do {
9639 const Decl *Next = VisitStack.pop_back_val();
9640 if (!Next) {
9641 assert(!HistoryStack.empty());
9642 // Found a marker, we have gone up a level
9643 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9644 ValidTypes.insert(Hist->getType().getTypePtr());
9645
9646 continue;
9647 }
9648
9649 // Adds everything except the original parameter declaration (which is not a
9650 // field itself) to the history stack.
9651 const RecordDecl *RD;
9652 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9653 HistoryStack.push_back(Elt: Field);
9654
9655 QualType FieldTy = Field->getType();
9656 // Other field types (known to be valid or invalid) are handled while we
9657 // walk around RecordDecl::fields().
9658 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9659 "Unexpected type.");
9660 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9661
9662 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9663 } else {
9664 RD = cast<RecordDecl>(Val: Next);
9665 }
9666
9667 // Add a null marker so we know when we've gone back up a level
9668 VisitStack.push_back(Elt: nullptr);
9669
9670 for (const auto *FD : RD->fields()) {
9671 QualType QT = FD->getType();
9672
9673 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9674 continue;
9675
9676 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9677 if (ParamType == ValidKernelParam)
9678 continue;
9679
9680 if (ParamType == RecordKernelParam) {
9681 VisitStack.push_back(FD);
9682 continue;
9683 }
9684
9685 // OpenCL v1.2 s6.9.p:
9686 // Arguments to kernel functions that are declared to be a struct or union
9687 // do not allow OpenCL objects to be passed as elements of the struct or
9688 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9689 // of SVM.
9690 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9691 ParamType == InvalidAddrSpacePtrKernelParam) {
9692 S.Diag(Param->getLocation(),
9693 diag::err_record_with_pointers_kernel_param)
9694 << PT->isUnionType()
9695 << PT;
9696 } else {
9697 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9698 }
9699
9700 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9701 << OrigRecDecl->getDeclName();
9702
9703 // We have an error, now let's go back up through history and show where
9704 // the offending field came from
9705 for (ArrayRef<const FieldDecl *>::const_iterator
9706 I = HistoryStack.begin() + 1,
9707 E = HistoryStack.end();
9708 I != E; ++I) {
9709 const FieldDecl *OuterField = *I;
9710 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9711 << OuterField->getType();
9712 }
9713
9714 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9715 << QT->isPointerType()
9716 << QT;
9717 D.setInvalidType();
9718 return;
9719 }
9720 } while (!VisitStack.empty());
9721}
9722
9723/// Find the DeclContext in which a tag is implicitly declared if we see an
9724/// elaborated type specifier in the specified context, and lookup finds
9725/// nothing.
9726static DeclContext *getTagInjectionContext(DeclContext *DC) {
9727 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9728 DC = DC->getParent();
9729 return DC;
9730}
9731
9732/// Find the Scope in which a tag is implicitly declared if we see an
9733/// elaborated type specifier in the specified context, and lookup finds
9734/// nothing.
9735static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9736 while (S->isClassScope() ||
9737 (LangOpts.CPlusPlus &&
9738 S->isFunctionPrototypeScope()) ||
9739 ((S->getFlags() & Scope::DeclScope) == 0) ||
9740 (S->getEntity() && S->getEntity()->isTransparentContext()))
9741 S = S->getParent();
9742 return S;
9743}
9744
9745/// Determine whether a declaration matches a known function in namespace std.
9746static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9747 unsigned BuiltinID) {
9748 switch (BuiltinID) {
9749 case Builtin::BI__GetExceptionInfo:
9750 // No type checking whatsoever.
9751 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9752
9753 case Builtin::BIaddressof:
9754 case Builtin::BI__addressof:
9755 case Builtin::BIforward:
9756 case Builtin::BIforward_like:
9757 case Builtin::BImove:
9758 case Builtin::BImove_if_noexcept:
9759 case Builtin::BIas_const: {
9760 // Ensure that we don't treat the algorithm
9761 // OutputIt std::move(InputIt, InputIt, OutputIt)
9762 // as the builtin std::move.
9763 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9764 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9765 }
9766
9767 default:
9768 return false;
9769 }
9770}
9771
9772NamedDecl*
9773Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9774 TypeSourceInfo *TInfo, LookupResult &Previous,
9775 MultiTemplateParamsArg TemplateParamListsRef,
9776 bool &AddToScope) {
9777 QualType R = TInfo->getType();
9778
9779 assert(R->isFunctionType());
9780 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9781 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9782
9783 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9784 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
9785 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9786 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9787 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9788 TemplateParamLists.back() = Invented;
9789 else
9790 TemplateParamLists.push_back(Elt: Invented);
9791 }
9792
9793 // TODO: consider using NameInfo for diagnostic.
9794 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9795 DeclarationName Name = NameInfo.getName();
9796 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
9797
9798 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9799 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9800 diag::err_invalid_thread)
9801 << DeclSpec::getSpecifierName(TSCS);
9802
9803 if (D.isFirstDeclarationOfMember())
9804 adjustMemberFunctionCC(
9805 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9806 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
9807
9808 bool isFriend = false;
9809 FunctionTemplateDecl *FunctionTemplate = nullptr;
9810 bool isMemberSpecialization = false;
9811 bool isFunctionTemplateSpecialization = false;
9812
9813 bool HasExplicitTemplateArgs = false;
9814 TemplateArgumentListInfo TemplateArgs;
9815
9816 bool isVirtualOkay = false;
9817
9818 DeclContext *OriginalDC = DC;
9819 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9820
9821 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
9822 IsVirtualOkay&: isVirtualOkay);
9823 if (!NewFD) return nullptr;
9824
9825 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9826 NewFD->setTopLevelDeclInObjCContainer();
9827
9828 // Set the lexical context. If this is a function-scope declaration, or has a
9829 // C++ scope specifier, or is the object of a friend declaration, the lexical
9830 // context will be different from the semantic context.
9831 NewFD->setLexicalDeclContext(CurContext);
9832
9833 if (IsLocalExternDecl)
9834 NewFD->setLocalExternDecl();
9835
9836 if (getLangOpts().CPlusPlus) {
9837 // The rules for implicit inlines changed in C++20 for methods and friends
9838 // with an in-class definition (when such a definition is not attached to
9839 // the global module). User-specified 'inline' overrides this (set when
9840 // the function decl is created above).
9841 // FIXME: We need a better way to separate C++ standard and clang modules.
9842 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9843 !NewFD->getOwningModule() ||
9844 NewFD->getOwningModule()->isGlobalModule() ||
9845 NewFD->getOwningModule()->isHeaderLikeModule();
9846 bool isInline = D.getDeclSpec().isInlineSpecified();
9847 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9848 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9849 isFriend = D.getDeclSpec().isFriendSpecified();
9850 if (isFriend && !isInline && D.isFunctionDefinition()) {
9851 // Pre-C++20 [class.friend]p5
9852 // A function can be defined in a friend declaration of a
9853 // class . . . . Such a function is implicitly inline.
9854 // Post C++20 [class.friend]p7
9855 // Such a function is implicitly an inline function if it is attached
9856 // to the global module.
9857 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9858 }
9859
9860 // If this is a method defined in an __interface, and is not a constructor
9861 // or an overloaded operator, then set the pure flag (isVirtual will already
9862 // return true).
9863 if (const CXXRecordDecl *Parent =
9864 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9865 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
9866 NewFD->setIsPureVirtual(true);
9867
9868 // C++ [class.union]p2
9869 // A union can have member functions, but not virtual functions.
9870 if (isVirtual && Parent->isUnion()) {
9871 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9872 NewFD->setInvalidDecl();
9873 }
9874 if ((Parent->isClass() || Parent->isStruct()) &&
9875 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9876 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9877 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9878 if (auto *Def = Parent->getDefinition())
9879 Def->setInitMethod(true);
9880 }
9881 }
9882
9883 SetNestedNameSpecifier(*this, NewFD, D);
9884 isMemberSpecialization = false;
9885 isFunctionTemplateSpecialization = false;
9886 if (D.isInvalidType())
9887 NewFD->setInvalidDecl();
9888
9889 // Match up the template parameter lists with the scope specifier, then
9890 // determine whether we have a template or a template specialization.
9891 bool Invalid = false;
9892 TemplateIdAnnotation *TemplateId =
9893 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9894 ? D.getName().TemplateId
9895 : nullptr;
9896 TemplateParameterList *TemplateParams =
9897 MatchTemplateParametersToScopeSpecifier(
9898 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
9899 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
9900 IsMemberSpecialization&: isMemberSpecialization, Invalid);
9901 if (TemplateParams) {
9902 // Check that we can declare a template here.
9903 if (CheckTemplateDeclScope(S, TemplateParams))
9904 NewFD->setInvalidDecl();
9905
9906 if (TemplateParams->size() > 0) {
9907 // This is a function template
9908
9909 // A destructor cannot be a template.
9910 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9911 Diag(NewFD->getLocation(), diag::err_destructor_template);
9912 NewFD->setInvalidDecl();
9913 // Function template with explicit template arguments.
9914 } else if (TemplateId) {
9915 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9916 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9917 NewFD->setInvalidDecl();
9918 }
9919
9920 // If we're adding a template to a dependent context, we may need to
9921 // rebuilding some of the types used within the template parameter list,
9922 // now that we know what the current instantiation is.
9923 if (DC->isDependentContext()) {
9924 ContextRAII SavedContext(*this, DC);
9925 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
9926 Invalid = true;
9927 }
9928
9929 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
9930 L: NewFD->getLocation(),
9931 Name, Params: TemplateParams,
9932 Decl: NewFD);
9933 FunctionTemplate->setLexicalDeclContext(CurContext);
9934 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9935
9936 // For source fidelity, store the other template param lists.
9937 if (TemplateParamLists.size() > 1) {
9938 NewFD->setTemplateParameterListsInfo(Context,
9939 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9940 .drop_back(N: 1));
9941 }
9942 } else {
9943 // This is a function template specialization.
9944 isFunctionTemplateSpecialization = true;
9945 // For source fidelity, store all the template param lists.
9946 if (TemplateParamLists.size() > 0)
9947 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9948
9949 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9950 if (isFriend) {
9951 // We want to remove the "template<>", found here.
9952 SourceRange RemoveRange = TemplateParams->getSourceRange();
9953
9954 // If we remove the template<> and the name is not a
9955 // template-id, we're actually silently creating a problem:
9956 // the friend declaration will refer to an untemplated decl,
9957 // and clearly the user wants a template specialization. So
9958 // we need to insert '<>' after the name.
9959 SourceLocation InsertLoc;
9960 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9961 InsertLoc = D.getName().getSourceRange().getEnd();
9962 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
9963 }
9964
9965 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9966 << Name << RemoveRange
9967 << FixItHint::CreateRemoval(RemoveRange)
9968 << FixItHint::CreateInsertion(InsertLoc, "<>");
9969 Invalid = true;
9970
9971 // Recover by faking up an empty template argument list.
9972 HasExplicitTemplateArgs = true;
9973 TemplateArgs.setLAngleLoc(InsertLoc);
9974 TemplateArgs.setRAngleLoc(InsertLoc);
9975 }
9976 }
9977 } else {
9978 // Check that we can declare a template here.
9979 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9980 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
9981 NewFD->setInvalidDecl();
9982
9983 // All template param lists were matched against the scope specifier:
9984 // this is NOT (an explicit specialization of) a template.
9985 if (TemplateParamLists.size() > 0)
9986 // For source fidelity, store all the template param lists.
9987 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9988
9989 // "friend void foo<>(int);" is an implicit specialization decl.
9990 if (isFriend && TemplateId)
9991 isFunctionTemplateSpecialization = true;
9992 }
9993
9994 // If this is a function template specialization and the unqualified-id of
9995 // the declarator-id is a template-id, convert the template argument list
9996 // into our AST format and check for unexpanded packs.
9997 if (isFunctionTemplateSpecialization && TemplateId) {
9998 HasExplicitTemplateArgs = true;
9999
10000 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10001 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10002 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10003 TemplateId->NumArgs);
10004 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10005
10006 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10007 // declaration of a function template partial specialization? Should we
10008 // consider the unexpanded pack context to be a partial specialization?
10009 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10010 if (DiagnoseUnexpandedParameterPack(
10011 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10012 : UPPC_ExplicitSpecialization))
10013 NewFD->setInvalidDecl();
10014 }
10015 }
10016
10017 if (Invalid) {
10018 NewFD->setInvalidDecl();
10019 if (FunctionTemplate)
10020 FunctionTemplate->setInvalidDecl();
10021 }
10022
10023 // C++ [dcl.fct.spec]p5:
10024 // The virtual specifier shall only be used in declarations of
10025 // nonstatic class member functions that appear within a
10026 // member-specification of a class declaration; see 10.3.
10027 //
10028 if (isVirtual && !NewFD->isInvalidDecl()) {
10029 if (!isVirtualOkay) {
10030 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10031 diag::err_virtual_non_function);
10032 } else if (!CurContext->isRecord()) {
10033 // 'virtual' was specified outside of the class.
10034 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10035 diag::err_virtual_out_of_class)
10036 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10037 } else if (NewFD->getDescribedFunctionTemplate()) {
10038 // C++ [temp.mem]p3:
10039 // A member function template shall not be virtual.
10040 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10041 diag::err_virtual_member_function_template)
10042 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10043 } else {
10044 // Okay: Add virtual to the method.
10045 NewFD->setVirtualAsWritten(true);
10046 }
10047
10048 if (getLangOpts().CPlusPlus14 &&
10049 NewFD->getReturnType()->isUndeducedType())
10050 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10051 }
10052
10053 if (getLangOpts().CPlusPlus14 &&
10054 (NewFD->isDependentContext() ||
10055 (isFriend && CurContext->isDependentContext())) &&
10056 NewFD->getReturnType()->isUndeducedType()) {
10057 // If the function template is referenced directly (for instance, as a
10058 // member of the current instantiation), pretend it has a dependent type.
10059 // This is not really justified by the standard, but is the only sane
10060 // thing to do.
10061 // FIXME: For a friend function, we have not marked the function as being
10062 // a friend yet, so 'isDependentContext' on the FD doesn't work.
10063 const FunctionProtoType *FPT =
10064 NewFD->getType()->castAs<FunctionProtoType>();
10065 QualType Result = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
10066 NewFD->setType(Context.getFunctionType(ResultTy: Result, Args: FPT->getParamTypes(),
10067 EPI: FPT->getExtProtoInfo()));
10068 }
10069
10070 // C++ [dcl.fct.spec]p3:
10071 // The inline specifier shall not appear on a block scope function
10072 // declaration.
10073 if (isInline && !NewFD->isInvalidDecl()) {
10074 if (CurContext->isFunctionOrMethod()) {
10075 // 'inline' is not allowed on block scope function declaration.
10076 Diag(D.getDeclSpec().getInlineSpecLoc(),
10077 diag::err_inline_declaration_block_scope) << Name
10078 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10079 }
10080 }
10081
10082 // C++ [dcl.fct.spec]p6:
10083 // The explicit specifier shall be used only in the declaration of a
10084 // constructor or conversion function within its class definition;
10085 // see 12.3.1 and 12.3.2.
10086 if (hasExplicit && !NewFD->isInvalidDecl() &&
10087 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10088 if (!CurContext->isRecord()) {
10089 // 'explicit' was specified outside of the class.
10090 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10091 diag::err_explicit_out_of_class)
10092 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10093 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10094 !isa<CXXConversionDecl>(Val: NewFD)) {
10095 // 'explicit' was specified on a function that wasn't a constructor
10096 // or conversion function.
10097 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10098 diag::err_explicit_non_ctor_or_conv_function)
10099 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10100 }
10101 }
10102
10103 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10104 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10105 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10106 // are implicitly inline.
10107 NewFD->setImplicitlyInline();
10108
10109 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10110 // be either constructors or to return a literal type. Therefore,
10111 // destructors cannot be declared constexpr.
10112 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10113 (!getLangOpts().CPlusPlus20 ||
10114 ConstexprKind == ConstexprSpecKind::Consteval)) {
10115 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10116 << static_cast<int>(ConstexprKind);
10117 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10118 ? ConstexprSpecKind::Unspecified
10119 : ConstexprSpecKind::Constexpr);
10120 }
10121 // C++20 [dcl.constexpr]p2: An allocation function, or a
10122 // deallocation function shall not be declared with the consteval
10123 // specifier.
10124 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10125 (NewFD->getOverloadedOperator() == OO_New ||
10126 NewFD->getOverloadedOperator() == OO_Array_New ||
10127 NewFD->getOverloadedOperator() == OO_Delete ||
10128 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10129 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10130 diag::err_invalid_consteval_decl_kind)
10131 << NewFD;
10132 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10133 }
10134 }
10135
10136 // If __module_private__ was specified, mark the function accordingly.
10137 if (D.getDeclSpec().isModulePrivateSpecified()) {
10138 if (isFunctionTemplateSpecialization) {
10139 SourceLocation ModulePrivateLoc
10140 = D.getDeclSpec().getModulePrivateSpecLoc();
10141 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10142 << 0
10143 << FixItHint::CreateRemoval(ModulePrivateLoc);
10144 } else {
10145 NewFD->setModulePrivate();
10146 if (FunctionTemplate)
10147 FunctionTemplate->setModulePrivate();
10148 }
10149 }
10150
10151 if (isFriend) {
10152 if (FunctionTemplate) {
10153 FunctionTemplate->setObjectOfFriendDecl();
10154 FunctionTemplate->setAccess(AS_public);
10155 }
10156 NewFD->setObjectOfFriendDecl();
10157 NewFD->setAccess(AS_public);
10158 }
10159
10160 // If a function is defined as defaulted or deleted, mark it as such now.
10161 // We'll do the relevant checks on defaulted / deleted functions later.
10162 switch (D.getFunctionDefinitionKind()) {
10163 case FunctionDefinitionKind::Declaration:
10164 case FunctionDefinitionKind::Definition:
10165 break;
10166
10167 case FunctionDefinitionKind::Defaulted:
10168 NewFD->setDefaulted();
10169 break;
10170
10171 case FunctionDefinitionKind::Deleted:
10172 NewFD->setDeletedAsWritten();
10173 break;
10174 }
10175
10176 if (isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10177 D.isFunctionDefinition() && !isInline) {
10178 // Pre C++20 [class.mfct]p2:
10179 // A member function may be defined (8.4) in its class definition, in
10180 // which case it is an inline member function (7.1.2)
10181 // Post C++20 [class.mfct]p1:
10182 // If a member function is attached to the global module and is defined
10183 // in its class definition, it is inline.
10184 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10185 }
10186
10187 if (SC == SC_Static && isa<CXXMethodDecl>(Val: NewFD) &&
10188 !CurContext->isRecord()) {
10189 // C++ [class.static]p1:
10190 // A data or function member of a class may be declared static
10191 // in a class definition, in which case it is a static member of
10192 // the class.
10193
10194 // Complain about the 'static' specifier if it's on an out-of-line
10195 // member function definition.
10196
10197 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10198 // member function template declaration and class member template
10199 // declaration (MSVC versions before 2015), warn about this.
10200 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10201 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10202 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10203 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10204 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10205 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10206 }
10207
10208 // C++11 [except.spec]p15:
10209 // A deallocation function with no exception-specification is treated
10210 // as if it were specified with noexcept(true).
10211 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10212 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10213 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10214 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10215 NewFD->setType(Context.getFunctionType(
10216 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10217 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10218
10219 // C++20 [dcl.inline]/7
10220 // If an inline function or variable that is attached to a named module
10221 // is declared in a definition domain, it shall be defined in that
10222 // domain.
10223 // So, if the current declaration does not have a definition, we must
10224 // check at the end of the TU (or when the PMF starts) to see that we
10225 // have a definition at that point.
10226 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10227 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10228 PendingInlineFuncDecls.insert(Ptr: NewFD);
10229 }
10230 }
10231
10232 // Filter out previous declarations that don't match the scope.
10233 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10234 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10235 isMemberSpecialization ||
10236 isFunctionTemplateSpecialization);
10237
10238 // Handle GNU asm-label extension (encoded as an attribute).
10239 if (Expr *E = (Expr*) D.getAsmLabel()) {
10240 // The parser guarantees this is a string.
10241 StringLiteral *SE = cast<StringLiteral>(Val: E);
10242 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10243 /*IsLiteralLabel=*/true,
10244 SE->getStrTokenLoc(0)));
10245 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10246 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10247 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10248 if (I != ExtnameUndeclaredIdentifiers.end()) {
10249 if (isDeclExternC(NewFD)) {
10250 NewFD->addAttr(A: I->second);
10251 ExtnameUndeclaredIdentifiers.erase(I);
10252 } else
10253 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10254 << /*Variable*/0 << NewFD;
10255 }
10256 }
10257
10258 // Copy the parameter declarations from the declarator D to the function
10259 // declaration NewFD, if they are available. First scavenge them into Params.
10260 SmallVector<ParmVarDecl*, 16> Params;
10261 unsigned FTIIdx;
10262 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10263 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10264
10265 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10266 // function that takes no arguments, not a function that takes a
10267 // single void argument.
10268 // We let through "const void" here because Sema::GetTypeForDeclarator
10269 // already checks for that case.
10270 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10271 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10272 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10273 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10274 Param->setDeclContext(NewFD);
10275 Params.push_back(Elt: Param);
10276
10277 if (Param->isInvalidDecl())
10278 NewFD->setInvalidDecl();
10279 }
10280 }
10281
10282 if (!getLangOpts().CPlusPlus) {
10283 // In C, find all the tag declarations from the prototype and move them
10284 // into the function DeclContext. Remove them from the surrounding tag
10285 // injection context of the function, which is typically but not always
10286 // the TU.
10287 DeclContext *PrototypeTagContext =
10288 getTagInjectionContext(NewFD->getLexicalDeclContext());
10289 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10290 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10291
10292 // We don't want to reparent enumerators. Look at their parent enum
10293 // instead.
10294 if (!TD) {
10295 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10296 TD = cast<EnumDecl>(ECD->getDeclContext());
10297 }
10298 if (!TD)
10299 continue;
10300 DeclContext *TagDC = TD->getLexicalDeclContext();
10301 if (!TagDC->containsDecl(TD))
10302 continue;
10303 TagDC->removeDecl(TD);
10304 TD->setDeclContext(NewFD);
10305 NewFD->addDecl(TD);
10306
10307 // Preserve the lexical DeclContext if it is not the surrounding tag
10308 // injection context of the FD. In this example, the semantic context of
10309 // E will be f and the lexical context will be S, while both the
10310 // semantic and lexical contexts of S will be f:
10311 // void f(struct S { enum E { a } f; } s);
10312 if (TagDC != PrototypeTagContext)
10313 TD->setLexicalDeclContext(TagDC);
10314 }
10315 }
10316 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10317 // When we're declaring a function with a typedef, typeof, etc as in the
10318 // following example, we'll need to synthesize (unnamed)
10319 // parameters for use in the declaration.
10320 //
10321 // @code
10322 // typedef void fn(int);
10323 // fn f;
10324 // @endcode
10325
10326 // Synthesize a parameter for each argument type.
10327 for (const auto &AI : FT->param_types()) {
10328 ParmVarDecl *Param =
10329 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10330 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10331 Params.push_back(Elt: Param);
10332 }
10333 } else {
10334 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10335 "Should not need args for typedef of non-prototype fn");
10336 }
10337
10338 // Finally, we know we have the right number of parameters, install them.
10339 NewFD->setParams(Params);
10340
10341 if (D.getDeclSpec().isNoreturnSpecified())
10342 NewFD->addAttr(
10343 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10344
10345 // Functions returning a variably modified type violate C99 6.7.5.2p2
10346 // because all functions have linkage.
10347 if (!NewFD->isInvalidDecl() &&
10348 NewFD->getReturnType()->isVariablyModifiedType()) {
10349 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10350 NewFD->setInvalidDecl();
10351 }
10352
10353 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10354 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10355 !NewFD->hasAttr<SectionAttr>())
10356 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10357 Context, PragmaClangTextSection.SectionName,
10358 PragmaClangTextSection.PragmaLocation));
10359
10360 // Apply an implicit SectionAttr if #pragma code_seg is active.
10361 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10362 !NewFD->hasAttr<SectionAttr>()) {
10363 NewFD->addAttr(SectionAttr::CreateImplicit(
10364 Context, CodeSegStack.CurrentValue->getString(),
10365 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10366 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10367 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10368 ASTContext::PSF_Read,
10369 NewFD))
10370 NewFD->dropAttr<SectionAttr>();
10371 }
10372
10373 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10374 // active.
10375 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10376 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10377 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10378 Context, PragmaClangTextSection.PragmaLocation));
10379
10380 // Apply an implicit CodeSegAttr from class declspec or
10381 // apply an implicit SectionAttr from #pragma code_seg if active.
10382 if (!NewFD->hasAttr<CodeSegAttr>()) {
10383 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10384 IsDefinition: D.isFunctionDefinition())) {
10385 NewFD->addAttr(SAttr);
10386 }
10387 }
10388
10389 // Handle attributes.
10390 ProcessDeclAttributes(S, NewFD, D);
10391 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10392 if (NewTVA && !NewTVA->isDefaultVersion() &&
10393 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10394 // Don't add to scope fmv functions declarations if fmv disabled
10395 AddToScope = false;
10396 return NewFD;
10397 }
10398
10399 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10400 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10401 // type.
10402 //
10403 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10404 // type declaration will generate a compilation error.
10405 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10406 if (AddressSpace != LangAS::Default) {
10407 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10408 NewFD->setInvalidDecl();
10409 }
10410 }
10411
10412 if (!getLangOpts().CPlusPlus) {
10413 // Perform semantic checking on the function declaration.
10414 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10415 CheckMain(FD: NewFD, D: D.getDeclSpec());
10416
10417 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10418 CheckMSVCRTEntryPoint(FD: NewFD);
10419
10420 if (!NewFD->isInvalidDecl())
10421 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10422 IsMemberSpecialization: isMemberSpecialization,
10423 DeclIsDefn: D.isFunctionDefinition()));
10424 else if (!Previous.empty())
10425 // Recover gracefully from an invalid redeclaration.
10426 D.setRedeclaration(true);
10427 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10428 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10429 "previous declaration set still overloaded");
10430
10431 // Diagnose no-prototype function declarations with calling conventions that
10432 // don't support variadic calls. Only do this in C and do it after merging
10433 // possibly prototyped redeclarations.
10434 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10435 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10436 CallingConv CC = FT->getExtInfo().getCC();
10437 if (!supportsVariadicCall(CC)) {
10438 // Windows system headers sometimes accidentally use stdcall without
10439 // (void) parameters, so we relax this to a warning.
10440 int DiagID =
10441 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10442 Diag(NewFD->getLocation(), DiagID)
10443 << FunctionType::getNameForCallConv(CC);
10444 }
10445 }
10446
10447 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10448 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10449 checkNonTrivialCUnion(QT: NewFD->getReturnType(),
10450 Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10451 UseContext: NTCUC_FunctionReturn, NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
10452 } else {
10453 // C++11 [replacement.functions]p3:
10454 // The program's definitions shall not be specified as inline.
10455 //
10456 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10457 //
10458 // Suppress the diagnostic if the function is __attribute__((used)), since
10459 // that forces an external definition to be emitted.
10460 if (D.getDeclSpec().isInlineSpecified() &&
10461 NewFD->isReplaceableGlobalAllocationFunction() &&
10462 !NewFD->hasAttr<UsedAttr>())
10463 Diag(D.getDeclSpec().getInlineSpecLoc(),
10464 diag::ext_operator_new_delete_declared_inline)
10465 << NewFD->getDeclName();
10466
10467 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10468 // C++20 [dcl.decl.general]p4:
10469 // The optional requires-clause in an init-declarator or
10470 // member-declarator shall be present only if the declarator declares a
10471 // templated function.
10472 //
10473 // C++20 [temp.pre]p8:
10474 // An entity is templated if it is
10475 // - a template,
10476 // - an entity defined or created in a templated entity,
10477 // - a member of a templated entity,
10478 // - an enumerator for an enumeration that is a templated entity, or
10479 // - the closure type of a lambda-expression appearing in the
10480 // declaration of a templated entity.
10481 //
10482 // [Note 6: A local class, a local or block variable, or a friend
10483 // function defined in a templated entity is a templated entity.
10484 // — end note]
10485 //
10486 // A templated function is a function template or a function that is
10487 // templated. A templated class is a class template or a class that is
10488 // templated. A templated variable is a variable template or a variable
10489 // that is templated.
10490 if (!FunctionTemplate) {
10491 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10492 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10493 // An explicit specialization shall not have a trailing
10494 // requires-clause unless it declares a function template.
10495 //
10496 // Since a friend function template specialization cannot be
10497 // definition, and since a non-template friend declaration with a
10498 // trailing requires-clause must be a definition, we diagnose
10499 // friend function template specializations with trailing
10500 // requires-clauses on the same path as explicit specializations
10501 // even though they aren't necessarily prohibited by the same
10502 // language rule.
10503 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10504 << isFriend;
10505 } else if (isFriend && NewFD->isTemplated() &&
10506 !D.isFunctionDefinition()) {
10507 // C++ [temp.friend]p9:
10508 // A non-template friend declaration with a requires-clause shall be
10509 // a definition.
10510 Diag(NewFD->getBeginLoc(),
10511 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10512 NewFD->setInvalidDecl();
10513 } else if (!NewFD->isTemplated() ||
10514 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10515 Diag(TRC->getBeginLoc(),
10516 diag::err_constrained_non_templated_function);
10517 }
10518 }
10519 }
10520
10521 // We do not add HD attributes to specializations here because
10522 // they may have different constexpr-ness compared to their
10523 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10524 // may end up with different effective targets. Instead, a
10525 // specialization inherits its target attributes from its template
10526 // in the CheckFunctionTemplateSpecialization() call below.
10527 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10528 maybeAddCUDAHostDeviceAttrs(FD: NewFD, Previous);
10529
10530 // Handle explict specializations of function templates
10531 // and friend function declarations with an explicit
10532 // template argument list.
10533 if (isFunctionTemplateSpecialization) {
10534 bool isDependentSpecialization = false;
10535 if (isFriend) {
10536 // For friend function specializations, this is a dependent
10537 // specialization if its semantic context is dependent, its
10538 // type is dependent, or if its template-id is dependent.
10539 isDependentSpecialization =
10540 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10541 (HasExplicitTemplateArgs &&
10542 TemplateSpecializationType::
10543 anyInstantiationDependentTemplateArguments(
10544 Args: TemplateArgs.arguments()));
10545 assert((!isDependentSpecialization ||
10546 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10547 "dependent friend function specialization without template "
10548 "args");
10549 } else {
10550 // For class-scope explicit specializations of function templates,
10551 // if the lexical context is dependent, then the specialization
10552 // is dependent.
10553 isDependentSpecialization =
10554 CurContext->isRecord() && CurContext->isDependentContext();
10555 }
10556
10557 TemplateArgumentListInfo *ExplicitTemplateArgs =
10558 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10559 if (isDependentSpecialization) {
10560 // If it's a dependent specialization, it may not be possible
10561 // to determine the primary template (for explicit specializations)
10562 // or befriended declaration (for friends) until the enclosing
10563 // template is instantiated. In such cases, we store the declarations
10564 // found by name lookup and defer resolution until instantiation.
10565 if (CheckDependentFunctionTemplateSpecialization(
10566 FD: NewFD, ExplicitTemplateArgs, Previous))
10567 NewFD->setInvalidDecl();
10568 } else if (!NewFD->isInvalidDecl()) {
10569 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10570 Previous))
10571 NewFD->setInvalidDecl();
10572 }
10573
10574 // C++ [dcl.stc]p1:
10575 // A storage-class-specifier shall not be specified in an explicit
10576 // specialization (14.7.3)
10577 // FIXME: We should be checking this for dependent specializations.
10578 FunctionTemplateSpecializationInfo *Info =
10579 NewFD->getTemplateSpecializationInfo();
10580 if (Info && SC != SC_None) {
10581 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10582 Diag(NewFD->getLocation(),
10583 diag::err_explicit_specialization_inconsistent_storage_class)
10584 << SC
10585 << FixItHint::CreateRemoval(
10586 D.getDeclSpec().getStorageClassSpecLoc());
10587
10588 else
10589 Diag(NewFD->getLocation(),
10590 diag::ext_explicit_specialization_storage_class)
10591 << FixItHint::CreateRemoval(
10592 D.getDeclSpec().getStorageClassSpecLoc());
10593 }
10594 } else if (isMemberSpecialization && isa<CXXMethodDecl>(Val: NewFD)) {
10595 if (CheckMemberSpecialization(NewFD, Previous))
10596 NewFD->setInvalidDecl();
10597 }
10598
10599 // Perform semantic checking on the function declaration.
10600 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10601 CheckMain(FD: NewFD, D: D.getDeclSpec());
10602
10603 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10604 CheckMSVCRTEntryPoint(FD: NewFD);
10605
10606 if (!NewFD->isInvalidDecl())
10607 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10608 IsMemberSpecialization: isMemberSpecialization,
10609 DeclIsDefn: D.isFunctionDefinition()));
10610 else if (!Previous.empty())
10611 // Recover gracefully from an invalid redeclaration.
10612 D.setRedeclaration(true);
10613
10614 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10615 !D.isRedeclaration() ||
10616 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10617 "previous declaration set still overloaded");
10618
10619 NamedDecl *PrincipalDecl = (FunctionTemplate
10620 ? cast<NamedDecl>(Val: FunctionTemplate)
10621 : NewFD);
10622
10623 if (isFriend && NewFD->getPreviousDecl()) {
10624 AccessSpecifier Access = AS_public;
10625 if (!NewFD->isInvalidDecl())
10626 Access = NewFD->getPreviousDecl()->getAccess();
10627
10628 NewFD->setAccess(Access);
10629 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10630 }
10631
10632 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10633 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10634 PrincipalDecl->setNonMemberOperator();
10635
10636 // If we have a function template, check the template parameter
10637 // list. This will check and merge default template arguments.
10638 if (FunctionTemplate) {
10639 FunctionTemplateDecl *PrevTemplate =
10640 FunctionTemplate->getPreviousDecl();
10641 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10642 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10643 : nullptr,
10644 TPC: D.getDeclSpec().isFriendSpecified()
10645 ? (D.isFunctionDefinition()
10646 ? TPC_FriendFunctionTemplateDefinition
10647 : TPC_FriendFunctionTemplate)
10648 : (D.getCXXScopeSpec().isSet() &&
10649 DC && DC->isRecord() &&
10650 DC->isDependentContext())
10651 ? TPC_ClassTemplateMember
10652 : TPC_FunctionTemplate);
10653 }
10654
10655 if (NewFD->isInvalidDecl()) {
10656 // Ignore all the rest of this.
10657 } else if (!D.isRedeclaration()) {
10658 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10659 .AddToScope: AddToScope };
10660 // Fake up an access specifier if it's supposed to be a class member.
10661 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10662 NewFD->setAccess(AS_public);
10663
10664 // Qualified decls generally require a previous declaration.
10665 if (D.getCXXScopeSpec().isSet()) {
10666 // ...with the major exception of templated-scope or
10667 // dependent-scope friend declarations.
10668
10669 // TODO: we currently also suppress this check in dependent
10670 // contexts because (1) the parameter depth will be off when
10671 // matching friend templates and (2) we might actually be
10672 // selecting a friend based on a dependent factor. But there
10673 // are situations where these conditions don't apply and we
10674 // can actually do this check immediately.
10675 //
10676 // Unless the scope is dependent, it's always an error if qualified
10677 // redeclaration lookup found nothing at all. Diagnose that now;
10678 // nothing will diagnose that error later.
10679 if (isFriend &&
10680 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10681 (!Previous.empty() && CurContext->isDependentContext()))) {
10682 // ignore these
10683 } else if (NewFD->isCPUDispatchMultiVersion() ||
10684 NewFD->isCPUSpecificMultiVersion()) {
10685 // ignore this, we allow the redeclaration behavior here to create new
10686 // versions of the function.
10687 } else {
10688 // The user tried to provide an out-of-line definition for a
10689 // function that is a member of a class or namespace, but there
10690 // was no such member function declared (C++ [class.mfct]p2,
10691 // C++ [namespace.memdef]p2). For example:
10692 //
10693 // class X {
10694 // void f() const;
10695 // };
10696 //
10697 // void X::f() { } // ill-formed
10698 //
10699 // Complain about this problem, and attempt to suggest close
10700 // matches (e.g., those that differ only in cv-qualifiers and
10701 // whether the parameter types are references).
10702
10703 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10704 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10705 AddToScope = ExtraArgs.AddToScope;
10706 return Result;
10707 }
10708 }
10709
10710 // Unqualified local friend declarations are required to resolve
10711 // to something.
10712 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10713 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10714 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10715 AddToScope = ExtraArgs.AddToScope;
10716 return Result;
10717 }
10718 }
10719 } else if (!D.isFunctionDefinition() &&
10720 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10721 !isFriend && !isFunctionTemplateSpecialization &&
10722 !isMemberSpecialization) {
10723 // An out-of-line member function declaration must also be a
10724 // definition (C++ [class.mfct]p2).
10725 // Note that this is not the case for explicit specializations of
10726 // function templates or member functions of class templates, per
10727 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10728 // extension for compatibility with old SWIG code which likes to
10729 // generate them.
10730 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10731 << D.getCXXScopeSpec().getRange();
10732 }
10733 }
10734
10735 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10736 // Any top level function could potentially be specified as an entry.
10737 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10738 ActOnHLSLTopLevelFunction(FD: NewFD);
10739
10740 if (NewFD->hasAttr<HLSLShaderAttr>())
10741 CheckHLSLEntryPoint(FD: NewFD);
10742 }
10743
10744 // If this is the first declaration of a library builtin function, add
10745 // attributes as appropriate.
10746 if (!D.isRedeclaration()) {
10747 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10748 if (unsigned BuiltinID = II->getBuiltinID()) {
10749 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
10750 if (!InStdNamespace &&
10751 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10752 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10753 // Validate the type matches unless this builtin is specified as
10754 // matching regardless of its declared type.
10755 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
10756 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10757 } else {
10758 ASTContext::GetBuiltinTypeError Error;
10759 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
10760 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
10761
10762 if (!Error && !BuiltinType.isNull() &&
10763 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10764 NewFD->getType(), BuiltinType))
10765 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10766 }
10767 }
10768 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10769 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
10770 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10771 }
10772 }
10773 }
10774 }
10775
10776 ProcessPragmaWeak(S, NewFD);
10777 checkAttributesAfterMerging(*this, *NewFD);
10778
10779 AddKnownFunctionAttributes(FD: NewFD);
10780
10781 if (NewFD->hasAttr<OverloadableAttr>() &&
10782 !NewFD->getType()->getAs<FunctionProtoType>()) {
10783 Diag(NewFD->getLocation(),
10784 diag::err_attribute_overloadable_no_prototype)
10785 << NewFD;
10786 NewFD->dropAttr<OverloadableAttr>();
10787 }
10788
10789 // If there's a #pragma GCC visibility in scope, and this isn't a class
10790 // member, set the visibility of this function.
10791 if (!DC->isRecord() && NewFD->isExternallyVisible())
10792 AddPushedVisibilityAttribute(NewFD);
10793
10794 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10795 // marking the function.
10796 AddCFAuditedAttribute(NewFD);
10797
10798 // If this is a function definition, check if we have to apply any
10799 // attributes (i.e. optnone and no_builtin) due to a pragma.
10800 if (D.isFunctionDefinition()) {
10801 AddRangeBasedOptnone(FD: NewFD);
10802 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
10803 AddSectionMSAllocText(FD: NewFD);
10804 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
10805 }
10806
10807 // If this is the first declaration of an extern C variable, update
10808 // the map of such variables.
10809 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10810 isIncompleteDeclExternC(S&: *this, D: NewFD))
10811 RegisterLocallyScopedExternCDecl(NewFD, S);
10812
10813 // Set this FunctionDecl's range up to the right paren.
10814 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10815
10816 if (D.isRedeclaration() && !Previous.empty()) {
10817 NamedDecl *Prev = Previous.getRepresentativeDecl();
10818 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10819 isMemberSpecialization ||
10820 isFunctionTemplateSpecialization,
10821 D.isFunctionDefinition());
10822 }
10823
10824 if (getLangOpts().CUDA) {
10825 IdentifierInfo *II = NewFD->getIdentifier();
10826 if (II && II->isStr(Str: getCudaConfigureFuncName()) &&
10827 !NewFD->isInvalidDecl() &&
10828 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10829 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10830 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10831 << getCudaConfigureFuncName();
10832 Context.setcudaConfigureCallDecl(NewFD);
10833 }
10834
10835 // Variadic functions, other than a *declaration* of printf, are not allowed
10836 // in device-side CUDA code, unless someone passed
10837 // -fcuda-allow-variadic-functions.
10838 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10839 (NewFD->hasAttr<CUDADeviceAttr>() ||
10840 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10841 !(II && II->isStr("printf") && NewFD->isExternC() &&
10842 !D.isFunctionDefinition())) {
10843 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10844 }
10845 }
10846
10847 MarkUnusedFileScopedDecl(NewFD);
10848
10849
10850
10851 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10852 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10853 if (SC == SC_Static) {
10854 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10855 D.setInvalidType();
10856 }
10857
10858 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10859 if (!NewFD->getReturnType()->isVoidType()) {
10860 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10861 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10862 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10863 : FixItHint());
10864 D.setInvalidType();
10865 }
10866
10867 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10868 for (auto *Param : NewFD->parameters())
10869 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
10870
10871 if (getLangOpts().OpenCLCPlusPlus) {
10872 if (DC->isRecord()) {
10873 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10874 D.setInvalidType();
10875 }
10876 if (FunctionTemplate) {
10877 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10878 D.setInvalidType();
10879 }
10880 }
10881 }
10882
10883 if (getLangOpts().CPlusPlus) {
10884 // Precalculate whether this is a friend function template with a constraint
10885 // that depends on an enclosing template, per [temp.friend]p9.
10886 if (isFriend && FunctionTemplate &&
10887 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
10888 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10889
10890 // C++ [temp.friend]p9:
10891 // A friend function template with a constraint that depends on a
10892 // template parameter from an enclosing template shall be a definition.
10893 if (!D.isFunctionDefinition()) {
10894 Diag(NewFD->getBeginLoc(),
10895 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10896 NewFD->setInvalidDecl();
10897 }
10898 }
10899
10900 if (FunctionTemplate) {
10901 if (NewFD->isInvalidDecl())
10902 FunctionTemplate->setInvalidDecl();
10903 return FunctionTemplate;
10904 }
10905
10906 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10907 CompleteMemberSpecialization(NewFD, Previous);
10908 }
10909
10910 for (const ParmVarDecl *Param : NewFD->parameters()) {
10911 QualType PT = Param->getType();
10912
10913 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10914 // types.
10915 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10916 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10917 QualType ElemTy = PipeTy->getElementType();
10918 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10919 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10920 D.setInvalidType();
10921 }
10922 }
10923 }
10924 // WebAssembly tables can't be used as function parameters.
10925 if (Context.getTargetInfo().getTriple().isWasm()) {
10926 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10927 Diag(Param->getTypeSpecStartLoc(),
10928 diag::err_wasm_table_as_function_parameter);
10929 D.setInvalidType();
10930 }
10931 }
10932 }
10933
10934 // Diagnose availability attributes. Availability cannot be used on functions
10935 // that are run during load/unload.
10936 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10937 if (NewFD->hasAttr<ConstructorAttr>()) {
10938 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10939 << 1;
10940 NewFD->dropAttr<AvailabilityAttr>();
10941 }
10942 if (NewFD->hasAttr<DestructorAttr>()) {
10943 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10944 << 2;
10945 NewFD->dropAttr<AvailabilityAttr>();
10946 }
10947 }
10948
10949 // Diagnose no_builtin attribute on function declaration that are not a
10950 // definition.
10951 // FIXME: We should really be doing this in
10952 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10953 // the FunctionDecl and at this point of the code
10954 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10955 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10956 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10957 switch (D.getFunctionDefinitionKind()) {
10958 case FunctionDefinitionKind::Defaulted:
10959 case FunctionDefinitionKind::Deleted:
10960 Diag(NBA->getLocation(),
10961 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10962 << NBA->getSpelling();
10963 break;
10964 case FunctionDefinitionKind::Declaration:
10965 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10966 << NBA->getSpelling();
10967 break;
10968 case FunctionDefinitionKind::Definition:
10969 break;
10970 }
10971
10972 return NewFD;
10973}
10974
10975/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10976/// when __declspec(code_seg) "is applied to a class, all member functions of
10977/// the class and nested classes -- this includes compiler-generated special
10978/// member functions -- are put in the specified segment."
10979/// The actual behavior is a little more complicated. The Microsoft compiler
10980/// won't check outer classes if there is an active value from #pragma code_seg.
10981/// The CodeSeg is always applied from the direct parent but only from outer
10982/// classes when the #pragma code_seg stack is empty. See:
10983/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10984/// available since MS has removed the page.
10985static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10986 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
10987 if (!Method)
10988 return nullptr;
10989 const CXXRecordDecl *Parent = Method->getParent();
10990 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10991 Attr *NewAttr = SAttr->clone(S.getASTContext());
10992 NewAttr->setImplicit(true);
10993 return NewAttr;
10994 }
10995
10996 // The Microsoft compiler won't check outer classes for the CodeSeg
10997 // when the #pragma code_seg stack is active.
10998 if (S.CodeSegStack.CurrentValue)
10999 return nullptr;
11000
11001 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11002 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11003 Attr *NewAttr = SAttr->clone(S.getASTContext());
11004 NewAttr->setImplicit(true);
11005 return NewAttr;
11006 }
11007 }
11008 return nullptr;
11009}
11010
11011/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
11012/// containing class. Otherwise it will return implicit SectionAttr if the
11013/// function is a definition and there is an active value on CodeSegStack
11014/// (from the current #pragma code-seg value).
11015///
11016/// \param FD Function being declared.
11017/// \param IsDefinition Whether it is a definition or just a declaration.
11018/// \returns A CodeSegAttr or SectionAttr to apply to the function or
11019/// nullptr if no attribute should be added.
11020Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11021 bool IsDefinition) {
11022 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11023 return A;
11024 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11025 CodeSegStack.CurrentValue)
11026 return SectionAttr::CreateImplicit(
11027 getASTContext(), CodeSegStack.CurrentValue->getString(),
11028 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11029 return nullptr;
11030}
11031
11032/// Determines if we can perform a correct type check for \p D as a
11033/// redeclaration of \p PrevDecl. If not, we can generally still perform a
11034/// best-effort check.
11035///
11036/// \param NewD The new declaration.
11037/// \param OldD The old declaration.
11038/// \param NewT The portion of the type of the new declaration to check.
11039/// \param OldT The portion of the type of the old declaration to check.
11040bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11041 QualType NewT, QualType OldT) {
11042 if (!NewD->getLexicalDeclContext()->isDependentContext())
11043 return true;
11044
11045 // For dependently-typed local extern declarations and friends, we can't
11046 // perform a correct type check in general until instantiation:
11047 //
11048 // int f();
11049 // template<typename T> void g() { T f(); }
11050 //
11051 // (valid if g() is only instantiated with T = int).
11052 if (NewT->isDependentType() &&
11053 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11054 return false;
11055
11056 // Similarly, if the previous declaration was a dependent local extern
11057 // declaration, we don't really know its type yet.
11058 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11059 return false;
11060
11061 return true;
11062}
11063
11064/// Checks if the new declaration declared in dependent context must be
11065/// put in the same redeclaration chain as the specified declaration.
11066///
11067/// \param D Declaration that is checked.
11068/// \param PrevDecl Previous declaration found with proper lookup method for the
11069/// same declaration name.
11070/// \returns True if D must be added to the redeclaration chain which PrevDecl
11071/// belongs to.
11072///
11073bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11074 if (!D->getLexicalDeclContext()->isDependentContext())
11075 return true;
11076
11077 // Don't chain dependent friend function definitions until instantiation, to
11078 // permit cases like
11079 //
11080 // void func();
11081 // template<typename T> class C1 { friend void func() {} };
11082 // template<typename T> class C2 { friend void func() {} };
11083 //
11084 // ... which is valid if only one of C1 and C2 is ever instantiated.
11085 //
11086 // FIXME: This need only apply to function definitions. For now, we proxy
11087 // this by checking for a file-scope function. We do not want this to apply
11088 // to friend declarations nominating member functions, because that gets in
11089 // the way of access checks.
11090 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11091 return false;
11092
11093 auto *VD = dyn_cast<ValueDecl>(Val: D);
11094 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11095 return !VD || !PrevVD ||
11096 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11097 OldT: PrevVD->getType());
11098}
11099
11100/// Check the target or target_version attribute of the function for
11101/// MultiVersion validity.
11102///
11103/// Returns true if there was an error, false otherwise.
11104static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11105 const auto *TA = FD->getAttr<TargetAttr>();
11106 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11107 assert(
11108 (TA || TVA) &&
11109 "MultiVersion candidate requires a target or target_version attribute");
11110 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11111 enum ErrType { Feature = 0, Architecture = 1 };
11112
11113 if (TA) {
11114 ParsedTargetAttr ParseInfo =
11115 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11116 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11117 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11118 << Architecture << ParseInfo.CPU;
11119 return true;
11120 }
11121 for (const auto &Feat : ParseInfo.Features) {
11122 auto BareFeat = StringRef{Feat}.substr(1);
11123 if (Feat[0] == '-') {
11124 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11125 << Feature << ("no-" + BareFeat).str();
11126 return true;
11127 }
11128
11129 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11130 !TargetInfo.isValidFeatureName(BareFeat)) {
11131 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11132 << Feature << BareFeat;
11133 return true;
11134 }
11135 }
11136 }
11137
11138 if (TVA) {
11139 llvm::SmallVector<StringRef, 8> Feats;
11140 TVA->getFeatures(Feats);
11141 for (const auto &Feat : Feats) {
11142 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11143 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11144 << Feature << Feat;
11145 return true;
11146 }
11147 }
11148 }
11149 return false;
11150}
11151
11152// Provide a white-list of attributes that are allowed to be combined with
11153// multiversion functions.
11154static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11155 MultiVersionKind MVKind) {
11156 // Note: this list/diagnosis must match the list in
11157 // checkMultiversionAttributesAllSame.
11158 switch (Kind) {
11159 default:
11160 return false;
11161 case attr::Used:
11162 return MVKind == MultiVersionKind::Target;
11163 case attr::NonNull:
11164 case attr::NoThrow:
11165 return true;
11166 }
11167}
11168
11169static bool checkNonMultiVersionCompatAttributes(Sema &S,
11170 const FunctionDecl *FD,
11171 const FunctionDecl *CausedFD,
11172 MultiVersionKind MVKind) {
11173 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11174 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11175 << static_cast<unsigned>(MVKind) << A;
11176 if (CausedFD)
11177 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11178 return true;
11179 };
11180
11181 for (const Attr *A : FD->attrs()) {
11182 switch (A->getKind()) {
11183 case attr::CPUDispatch:
11184 case attr::CPUSpecific:
11185 if (MVKind != MultiVersionKind::CPUDispatch &&
11186 MVKind != MultiVersionKind::CPUSpecific)
11187 return Diagnose(S, A);
11188 break;
11189 case attr::Target:
11190 if (MVKind != MultiVersionKind::Target)
11191 return Diagnose(S, A);
11192 break;
11193 case attr::TargetVersion:
11194 if (MVKind != MultiVersionKind::TargetVersion)
11195 return Diagnose(S, A);
11196 break;
11197 case attr::TargetClones:
11198 if (MVKind != MultiVersionKind::TargetClones)
11199 return Diagnose(S, A);
11200 break;
11201 default:
11202 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11203 return Diagnose(S, A);
11204 break;
11205 }
11206 }
11207 return false;
11208}
11209
11210bool Sema::areMultiversionVariantFunctionsCompatible(
11211 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11212 const PartialDiagnostic &NoProtoDiagID,
11213 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11214 const PartialDiagnosticAt &NoSupportDiagIDAt,
11215 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11216 bool ConstexprSupported, bool CLinkageMayDiffer) {
11217 enum DoesntSupport {
11218 FuncTemplates = 0,
11219 VirtFuncs = 1,
11220 DeducedReturn = 2,
11221 Constructors = 3,
11222 Destructors = 4,
11223 DeletedFuncs = 5,
11224 DefaultedFuncs = 6,
11225 ConstexprFuncs = 7,
11226 ConstevalFuncs = 8,
11227 Lambda = 9,
11228 };
11229 enum Different {
11230 CallingConv = 0,
11231 ReturnType = 1,
11232 ConstexprSpec = 2,
11233 InlineSpec = 3,
11234 Linkage = 4,
11235 LanguageLinkage = 5,
11236 };
11237
11238 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11239 !OldFD->getType()->getAs<FunctionProtoType>()) {
11240 Diag(OldFD->getLocation(), NoProtoDiagID);
11241 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11242 return true;
11243 }
11244
11245 if (NoProtoDiagID.getDiagID() != 0 &&
11246 !NewFD->getType()->getAs<FunctionProtoType>())
11247 return Diag(NewFD->getLocation(), NoProtoDiagID);
11248
11249 if (!TemplatesSupported &&
11250 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11251 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11252 << FuncTemplates;
11253
11254 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11255 if (NewCXXFD->isVirtual())
11256 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11257 << VirtFuncs;
11258
11259 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11260 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11261 << Constructors;
11262
11263 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11264 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11265 << Destructors;
11266 }
11267
11268 if (NewFD->isDeleted())
11269 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11270 << DeletedFuncs;
11271
11272 if (NewFD->isDefaulted())
11273 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11274 << DefaultedFuncs;
11275
11276 if (!ConstexprSupported && NewFD->isConstexpr())
11277 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11278 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11279
11280 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11281 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11282 QualType NewReturnType = NewType->getReturnType();
11283
11284 if (NewReturnType->isUndeducedType())
11285 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11286 << DeducedReturn;
11287
11288 // Ensure the return type is identical.
11289 if (OldFD) {
11290 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11291 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11292 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11293 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11294
11295 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11296 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11297
11298 QualType OldReturnType = OldType->getReturnType();
11299
11300 if (OldReturnType != NewReturnType)
11301 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11302
11303 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11304 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11305
11306 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11307 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11308
11309 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11310 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11311
11312 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11313 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11314
11315 if (CheckEquivalentExceptionSpec(
11316 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11317 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11318 return true;
11319 }
11320 return false;
11321}
11322
11323static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11324 const FunctionDecl *NewFD,
11325 bool CausesMV,
11326 MultiVersionKind MVKind) {
11327 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11328 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11329 if (OldFD)
11330 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11331 return true;
11332 }
11333
11334 bool IsCPUSpecificCPUDispatchMVKind =
11335 MVKind == MultiVersionKind::CPUDispatch ||
11336 MVKind == MultiVersionKind::CPUSpecific;
11337
11338 if (CausesMV && OldFD &&
11339 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11340 return true;
11341
11342 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11343 return true;
11344
11345 // Only allow transition to MultiVersion if it hasn't been used.
11346 if (OldFD && CausesMV && OldFD->isUsed(false))
11347 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11348
11349 return S.areMultiversionVariantFunctionsCompatible(
11350 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11351 PartialDiagnosticAt(NewFD->getLocation(),
11352 S.PDiag(diag::note_multiversioning_caused_here)),
11353 PartialDiagnosticAt(NewFD->getLocation(),
11354 S.PDiag(diag::err_multiversion_doesnt_support)
11355 << static_cast<unsigned>(MVKind)),
11356 PartialDiagnosticAt(NewFD->getLocation(),
11357 S.PDiag(diag::err_multiversion_diff)),
11358 /*TemplatesSupported=*/false,
11359 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11360 /*CLinkageMayDiffer=*/false);
11361}
11362
11363/// Check the validity of a multiversion function declaration that is the
11364/// first of its kind. Also sets the multiversion'ness' of the function itself.
11365///
11366/// This sets NewFD->isInvalidDecl() to true if there was an error.
11367///
11368/// Returns true if there was an error, false otherwise.
11369static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11370 MultiVersionKind MVKind = FD->getMultiVersionKind();
11371 assert(MVKind != MultiVersionKind::None &&
11372 "Function lacks multiversion attribute");
11373 const auto *TA = FD->getAttr<TargetAttr>();
11374 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11375 // Target and target_version only causes MV if it is default, otherwise this
11376 // is a normal function.
11377 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11378 return false;
11379
11380 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11381 FD->setInvalidDecl();
11382 return true;
11383 }
11384
11385 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11386 FD->setInvalidDecl();
11387 return true;
11388 }
11389
11390 FD->setIsMultiVersion();
11391 return false;
11392}
11393
11394static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11395 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11396 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11397 return true;
11398 }
11399
11400 return false;
11401}
11402
11403static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11404 FunctionDecl *NewFD,
11405 bool &Redeclaration,
11406 NamedDecl *&OldDecl,
11407 LookupResult &Previous) {
11408 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11409 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11410 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11411 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11412 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11413 // to change, this is a simple redeclaration.
11414 if ((NewTA && !NewTA->isDefaultVersion() &&
11415 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11416 (NewTVA && !NewTVA->isDefaultVersion() &&
11417 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11418 return false;
11419
11420 // Otherwise, this decl causes MultiVersioning.
11421 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11422 NewTVA ? MultiVersionKind::TargetVersion
11423 : MultiVersionKind::Target)) {
11424 NewFD->setInvalidDecl();
11425 return true;
11426 }
11427
11428 if (CheckMultiVersionValue(S, FD: NewFD)) {
11429 NewFD->setInvalidDecl();
11430 return true;
11431 }
11432
11433 // If this is 'default', permit the forward declaration.
11434 if (!OldFD->isMultiVersion() &&
11435 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11436 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11437 Redeclaration = true;
11438 OldDecl = OldFD;
11439 OldFD->setIsMultiVersion();
11440 NewFD->setIsMultiVersion();
11441 return false;
11442 }
11443
11444 if (CheckMultiVersionValue(S, FD: OldFD)) {
11445 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11446 NewFD->setInvalidDecl();
11447 return true;
11448 }
11449
11450 if (NewTA) {
11451 ParsedTargetAttr OldParsed =
11452 S.getASTContext().getTargetInfo().parseTargetAttr(
11453 Str: OldTA->getFeaturesStr());
11454 llvm::sort(C&: OldParsed.Features);
11455 ParsedTargetAttr NewParsed =
11456 S.getASTContext().getTargetInfo().parseTargetAttr(
11457 Str: NewTA->getFeaturesStr());
11458 // Sort order doesn't matter, it just needs to be consistent.
11459 llvm::sort(C&: NewParsed.Features);
11460 if (OldParsed == NewParsed) {
11461 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11462 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11463 NewFD->setInvalidDecl();
11464 return true;
11465 }
11466 }
11467
11468 if (NewTVA) {
11469 llvm::SmallVector<StringRef, 8> Feats;
11470 OldTVA->getFeatures(Feats);
11471 llvm::sort(C&: Feats);
11472 llvm::SmallVector<StringRef, 8> NewFeats;
11473 NewTVA->getFeatures(NewFeats);
11474 llvm::sort(C&: NewFeats);
11475
11476 if (Feats == NewFeats) {
11477 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11478 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11479 NewFD->setInvalidDecl();
11480 return true;
11481 }
11482 }
11483
11484 for (const auto *FD : OldFD->redecls()) {
11485 const auto *CurTA = FD->getAttr<TargetAttr>();
11486 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11487 // We allow forward declarations before ANY multiversioning attributes, but
11488 // nothing after the fact.
11489 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11490 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11491 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11492 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11493 << (NewTA ? 0 : 2);
11494 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11495 NewFD->setInvalidDecl();
11496 return true;
11497 }
11498 }
11499
11500 OldFD->setIsMultiVersion();
11501 NewFD->setIsMultiVersion();
11502 Redeclaration = false;
11503 OldDecl = nullptr;
11504 Previous.clear();
11505 return false;
11506}
11507
11508static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11509 MultiVersionKind New) {
11510 if (Old == New || Old == MultiVersionKind::None ||
11511 New == MultiVersionKind::None)
11512 return true;
11513
11514 return (Old == MultiVersionKind::CPUDispatch &&
11515 New == MultiVersionKind::CPUSpecific) ||
11516 (Old == MultiVersionKind::CPUSpecific &&
11517 New == MultiVersionKind::CPUDispatch);
11518}
11519
11520/// Check the validity of a new function declaration being added to an existing
11521/// multiversioned declaration collection.
11522static bool CheckMultiVersionAdditionalDecl(
11523 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11524 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11525 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11526 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11527 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11528 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11529 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11530 // Disallow mixing of multiversioning types.
11531 if (!MultiVersionTypesCompatible(Old: OldMVKind, New: NewMVKind)) {
11532 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11533 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11534 NewFD->setInvalidDecl();
11535 return true;
11536 }
11537
11538 ParsedTargetAttr NewParsed;
11539 if (NewTA) {
11540 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11541 Str: NewTA->getFeaturesStr());
11542 llvm::sort(C&: NewParsed.Features);
11543 }
11544 llvm::SmallVector<StringRef, 8> NewFeats;
11545 if (NewTVA) {
11546 NewTVA->getFeatures(NewFeats);
11547 llvm::sort(C&: NewFeats);
11548 }
11549
11550 bool UseMemberUsingDeclRules =
11551 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11552
11553 bool MayNeedOverloadableChecks =
11554 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11555
11556 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11557 // of a previous member of the MultiVersion set.
11558 for (NamedDecl *ND : Previous) {
11559 FunctionDecl *CurFD = ND->getAsFunction();
11560 if (!CurFD || CurFD->isInvalidDecl())
11561 continue;
11562 if (MayNeedOverloadableChecks &&
11563 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11564 continue;
11565
11566 if (NewMVKind == MultiVersionKind::None &&
11567 OldMVKind == MultiVersionKind::TargetVersion) {
11568 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11569 S.Context, "default", NewFD->getSourceRange()));
11570 NewFD->setIsMultiVersion();
11571 NewMVKind = MultiVersionKind::TargetVersion;
11572 if (!NewTVA) {
11573 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11574 NewTVA->getFeatures(NewFeats);
11575 llvm::sort(C&: NewFeats);
11576 }
11577 }
11578
11579 switch (NewMVKind) {
11580 case MultiVersionKind::None:
11581 assert(OldMVKind == MultiVersionKind::TargetClones &&
11582 "Only target_clones can be omitted in subsequent declarations");
11583 break;
11584 case MultiVersionKind::Target: {
11585 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11586 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11587 NewFD->setIsMultiVersion();
11588 Redeclaration = true;
11589 OldDecl = ND;
11590 return false;
11591 }
11592
11593 ParsedTargetAttr CurParsed =
11594 S.getASTContext().getTargetInfo().parseTargetAttr(
11595 Str: CurTA->getFeaturesStr());
11596 llvm::sort(C&: CurParsed.Features);
11597 if (CurParsed == NewParsed) {
11598 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11599 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11600 NewFD->setInvalidDecl();
11601 return true;
11602 }
11603 break;
11604 }
11605 case MultiVersionKind::TargetVersion: {
11606 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11607 if (CurTVA->getName() == NewTVA->getName()) {
11608 NewFD->setIsMultiVersion();
11609 Redeclaration = true;
11610 OldDecl = ND;
11611 return false;
11612 }
11613 llvm::SmallVector<StringRef, 8> CurFeats;
11614 if (CurTVA) {
11615 CurTVA->getFeatures(CurFeats);
11616 llvm::sort(C&: CurFeats);
11617 }
11618 if (CurFeats == NewFeats) {
11619 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11620 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11621 NewFD->setInvalidDecl();
11622 return true;
11623 }
11624 break;
11625 }
11626 case MultiVersionKind::TargetClones: {
11627 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11628 Redeclaration = true;
11629 OldDecl = CurFD;
11630 NewFD->setIsMultiVersion();
11631
11632 if (CurClones && NewClones &&
11633 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11634 !std::equal(CurClones->featuresStrs_begin(),
11635 CurClones->featuresStrs_end(),
11636 NewClones->featuresStrs_begin()))) {
11637 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11638 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11639 NewFD->setInvalidDecl();
11640 return true;
11641 }
11642
11643 return false;
11644 }
11645 case MultiVersionKind::CPUSpecific:
11646 case MultiVersionKind::CPUDispatch: {
11647 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11648 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11649 // Handle CPUDispatch/CPUSpecific versions.
11650 // Only 1 CPUDispatch function is allowed, this will make it go through
11651 // the redeclaration errors.
11652 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11653 CurFD->hasAttr<CPUDispatchAttr>()) {
11654 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11655 std::equal(
11656 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11657 NewCPUDisp->cpus_begin(),
11658 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11659 return Cur->getName() == New->getName();
11660 })) {
11661 NewFD->setIsMultiVersion();
11662 Redeclaration = true;
11663 OldDecl = ND;
11664 return false;
11665 }
11666
11667 // If the declarations don't match, this is an error condition.
11668 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11669 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11670 NewFD->setInvalidDecl();
11671 return true;
11672 }
11673 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11674 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11675 std::equal(
11676 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11677 NewCPUSpec->cpus_begin(),
11678 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11679 return Cur->getName() == New->getName();
11680 })) {
11681 NewFD->setIsMultiVersion();
11682 Redeclaration = true;
11683 OldDecl = ND;
11684 return false;
11685 }
11686
11687 // Only 1 version of CPUSpecific is allowed for each CPU.
11688 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11689 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11690 if (CurII == NewII) {
11691 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11692 << NewII;
11693 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11694 NewFD->setInvalidDecl();
11695 return true;
11696 }
11697 }
11698 }
11699 }
11700 break;
11701 }
11702 }
11703 }
11704
11705 // Else, this is simply a non-redecl case. Checking the 'value' is only
11706 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11707 // handled in the attribute adding step.
11708 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11709 NewMVKind == MultiVersionKind::Target) &&
11710 CheckMultiVersionValue(S, FD: NewFD)) {
11711 NewFD->setInvalidDecl();
11712 return true;
11713 }
11714
11715 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11716 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
11717 NewFD->setInvalidDecl();
11718 return true;
11719 }
11720
11721 // Permit forward declarations in the case where these two are compatible.
11722 if (!OldFD->isMultiVersion()) {
11723 OldFD->setIsMultiVersion();
11724 NewFD->setIsMultiVersion();
11725 Redeclaration = true;
11726 OldDecl = OldFD;
11727 return false;
11728 }
11729
11730 NewFD->setIsMultiVersion();
11731 Redeclaration = false;
11732 OldDecl = nullptr;
11733 Previous.clear();
11734 return false;
11735}
11736
11737/// Check the validity of a mulitversion function declaration.
11738/// Also sets the multiversion'ness' of the function itself.
11739///
11740/// This sets NewFD->isInvalidDecl() to true if there was an error.
11741///
11742/// Returns true if there was an error, false otherwise.
11743static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11744 bool &Redeclaration, NamedDecl *&OldDecl,
11745 LookupResult &Previous) {
11746 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11747 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11748 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11749 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11750 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11751 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11752
11753 // Main isn't allowed to become a multiversion function, however it IS
11754 // permitted to have 'main' be marked with the 'target' optimization hint,
11755 // for 'target_version' only default is allowed.
11756 if (NewFD->isMain()) {
11757 if (MVKind != MultiVersionKind::None &&
11758 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11759 !(MVKind == MultiVersionKind::TargetVersion &&
11760 NewTVA->isDefaultVersion())) {
11761 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11762 NewFD->setInvalidDecl();
11763 return true;
11764 }
11765 return false;
11766 }
11767
11768 // Target attribute on AArch64 is not used for multiversioning
11769 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11770 return false;
11771
11772 if (!OldDecl || !OldDecl->getAsFunction() ||
11773 OldDecl->getDeclContext()->getRedeclContext() !=
11774 NewFD->getDeclContext()->getRedeclContext()) {
11775 // If there's no previous declaration, AND this isn't attempting to cause
11776 // multiversioning, this isn't an error condition.
11777 if (MVKind == MultiVersionKind::None)
11778 return false;
11779 return CheckMultiVersionFirstFunction(S, FD: NewFD);
11780 }
11781
11782 FunctionDecl *OldFD = OldDecl->getAsFunction();
11783
11784 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11785 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11786 return false;
11787 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11788 // Multiversion declaration doesn't have prototype.
11789 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11790 NewFD->setInvalidDecl();
11791 } else {
11792 // No "target_version" attribute is equivalent to "default" attribute.
11793 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11794 S.Context, "default", NewFD->getSourceRange()));
11795 NewFD->setIsMultiVersion();
11796 OldFD->setIsMultiVersion();
11797 OldDecl = OldFD;
11798 Redeclaration = true;
11799 }
11800 return true;
11801 }
11802
11803 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11804 // for target_clones and target_version.
11805 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11806 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11807 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11808 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11809 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11810 NewFD->setInvalidDecl();
11811 return true;
11812 }
11813
11814 if (!OldFD->isMultiVersion()) {
11815 switch (MVKind) {
11816 case MultiVersionKind::Target:
11817 case MultiVersionKind::TargetVersion:
11818 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11819 OldDecl, Previous);
11820 case MultiVersionKind::TargetClones:
11821 if (OldFD->isUsed(false)) {
11822 NewFD->setInvalidDecl();
11823 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11824 }
11825 OldFD->setIsMultiVersion();
11826 break;
11827
11828 case MultiVersionKind::CPUDispatch:
11829 case MultiVersionKind::CPUSpecific:
11830 case MultiVersionKind::None:
11831 break;
11832 }
11833 }
11834
11835 // At this point, we have a multiversion function decl (in OldFD) AND an
11836 // appropriate attribute in the current function decl. Resolve that these are
11837 // still compatible with previous declarations.
11838 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11839 NewCPUSpec, NewClones, Redeclaration,
11840 OldDecl, Previous);
11841}
11842
11843static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
11844 bool IsPure = NewFD->hasAttr<PureAttr>();
11845 bool IsConst = NewFD->hasAttr<ConstAttr>();
11846
11847 // If there are no pure or const attributes, there's nothing to check.
11848 if (!IsPure && !IsConst)
11849 return;
11850
11851 // If the function is marked both pure and const, we retain the const
11852 // attribute because it makes stronger guarantees than the pure attribute, and
11853 // we drop the pure attribute explicitly to prevent later confusion about
11854 // semantics.
11855 if (IsPure && IsConst) {
11856 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11857 NewFD->dropAttrs<PureAttr>();
11858 }
11859
11860 // Constructors and destructors are functions which return void, so are
11861 // handled here as well.
11862 if (NewFD->getReturnType()->isVoidType()) {
11863 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11864 << IsConst;
11865 NewFD->dropAttrs<PureAttr, ConstAttr>();
11866 }
11867}
11868
11869/// Perform semantic checking of a new function declaration.
11870///
11871/// Performs semantic analysis of the new function declaration
11872/// NewFD. This routine performs all semantic checking that does not
11873/// require the actual declarator involved in the declaration, and is
11874/// used both for the declaration of functions as they are parsed
11875/// (called via ActOnDeclarator) and for the declaration of functions
11876/// that have been instantiated via C++ template instantiation (called
11877/// via InstantiateDecl).
11878///
11879/// \param IsMemberSpecialization whether this new function declaration is
11880/// a member specialization (that replaces any definition provided by the
11881/// previous declaration).
11882///
11883/// This sets NewFD->isInvalidDecl() to true if there was an error.
11884///
11885/// \returns true if the function declaration is a redeclaration.
11886bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11887 LookupResult &Previous,
11888 bool IsMemberSpecialization,
11889 bool DeclIsDefn) {
11890 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11891 "Variably modified return types are not handled here");
11892
11893 // Determine whether the type of this function should be merged with
11894 // a previous visible declaration. This never happens for functions in C++,
11895 // and always happens in C if the previous declaration was visible.
11896 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11897 !Previous.isShadowed();
11898
11899 bool Redeclaration = false;
11900 NamedDecl *OldDecl = nullptr;
11901 bool MayNeedOverloadableChecks = false;
11902
11903 // Merge or overload the declaration with an existing declaration of
11904 // the same name, if appropriate.
11905 if (!Previous.empty()) {
11906 // Determine whether NewFD is an overload of PrevDecl or
11907 // a declaration that requires merging. If it's an overload,
11908 // there's no more work to do here; we'll just add the new
11909 // function to the scope.
11910 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
11911 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11912 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11913 Redeclaration = true;
11914 OldDecl = Candidate;
11915 }
11916 } else {
11917 MayNeedOverloadableChecks = true;
11918 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
11919 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
11920 case Ovl_Match:
11921 Redeclaration = true;
11922 break;
11923
11924 case Ovl_NonFunction:
11925 Redeclaration = true;
11926 break;
11927
11928 case Ovl_Overload:
11929 Redeclaration = false;
11930 break;
11931 }
11932 }
11933 }
11934
11935 // Check for a previous extern "C" declaration with this name.
11936 if (!Redeclaration &&
11937 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
11938 if (!Previous.empty()) {
11939 // This is an extern "C" declaration with the same name as a previous
11940 // declaration, and thus redeclares that entity...
11941 Redeclaration = true;
11942 OldDecl = Previous.getFoundDecl();
11943 MergeTypeWithPrevious = false;
11944
11945 // ... except in the presence of __attribute__((overloadable)).
11946 if (OldDecl->hasAttr<OverloadableAttr>() ||
11947 NewFD->hasAttr<OverloadableAttr>()) {
11948 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
11949 MayNeedOverloadableChecks = true;
11950 Redeclaration = false;
11951 OldDecl = nullptr;
11952 }
11953 }
11954 }
11955 }
11956
11957 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
11958 return Redeclaration;
11959
11960 // PPC MMA non-pointer types are not allowed as function return types.
11961 if (Context.getTargetInfo().getTriple().isPPC64() &&
11962 CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
11963 NewFD->setInvalidDecl();
11964 }
11965
11966 CheckConstPureAttributesUsage(S&: *this, NewFD);
11967
11968 // C++11 [dcl.constexpr]p8:
11969 // A constexpr specifier for a non-static member function that is not
11970 // a constructor declares that member function to be const.
11971 //
11972 // This needs to be delayed until we know whether this is an out-of-line
11973 // definition of a static member function.
11974 //
11975 // This rule is not present in C++1y, so we produce a backwards
11976 // compatibility warning whenever it happens in C++11.
11977 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
11978 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11979 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
11980 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
11981 CXXMethodDecl *OldMD = nullptr;
11982 if (OldDecl)
11983 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11984 if (!OldMD || !OldMD->isStatic()) {
11985 const FunctionProtoType *FPT =
11986 MD->getType()->castAs<FunctionProtoType>();
11987 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11988 EPI.TypeQuals.addConst();
11989 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
11990 Args: FPT->getParamTypes(), EPI));
11991
11992 // Warn that we did this, if we're not performing template instantiation.
11993 // In that case, we'll have warned already when the template was defined.
11994 if (!inTemplateInstantiation()) {
11995 SourceLocation AddConstLoc;
11996 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11997 .IgnoreParens().getAs<FunctionTypeLoc>())
11998 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
11999
12000 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12001 << FixItHint::CreateInsertion(AddConstLoc, " const");
12002 }
12003 }
12004 }
12005
12006 if (Redeclaration) {
12007 // NewFD and OldDecl represent declarations that need to be
12008 // merged.
12009 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12010 NewDeclIsDefn: DeclIsDefn)) {
12011 NewFD->setInvalidDecl();
12012 return Redeclaration;
12013 }
12014
12015 Previous.clear();
12016 Previous.addDecl(D: OldDecl);
12017
12018 if (FunctionTemplateDecl *OldTemplateDecl =
12019 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12020 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12021 FunctionTemplateDecl *NewTemplateDecl
12022 = NewFD->getDescribedFunctionTemplate();
12023 assert(NewTemplateDecl && "Template/non-template mismatch");
12024
12025 // The call to MergeFunctionDecl above may have created some state in
12026 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12027 // can add it as a redeclaration.
12028 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12029
12030 NewFD->setPreviousDeclaration(OldFD);
12031 if (NewFD->isCXXClassMember()) {
12032 NewFD->setAccess(OldTemplateDecl->getAccess());
12033 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12034 }
12035
12036 // If this is an explicit specialization of a member that is a function
12037 // template, mark it as a member specialization.
12038 if (IsMemberSpecialization &&
12039 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12040 NewTemplateDecl->setMemberSpecialization();
12041 assert(OldTemplateDecl->isMemberSpecialization());
12042 // Explicit specializations of a member template do not inherit deleted
12043 // status from the parent member template that they are specializing.
12044 if (OldFD->isDeleted()) {
12045 // FIXME: This assert will not hold in the presence of modules.
12046 assert(OldFD->getCanonicalDecl() == OldFD);
12047 // FIXME: We need an update record for this AST mutation.
12048 OldFD->setDeletedAsWritten(false);
12049 }
12050 }
12051
12052 } else {
12053 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12054 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12055 // This needs to happen first so that 'inline' propagates.
12056 NewFD->setPreviousDeclaration(OldFD);
12057 if (NewFD->isCXXClassMember())
12058 NewFD->setAccess(OldFD->getAccess());
12059 }
12060 }
12061 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12062 !NewFD->getAttr<OverloadableAttr>()) {
12063 assert((Previous.empty() ||
12064 llvm::any_of(Previous,
12065 [](const NamedDecl *ND) {
12066 return ND->hasAttr<OverloadableAttr>();
12067 })) &&
12068 "Non-redecls shouldn't happen without overloadable present");
12069
12070 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12071 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12072 return FD && !FD->hasAttr<OverloadableAttr>();
12073 });
12074
12075 if (OtherUnmarkedIter != Previous.end()) {
12076 Diag(NewFD->getLocation(),
12077 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12078 Diag((*OtherUnmarkedIter)->getLocation(),
12079 diag::note_attribute_overloadable_prev_overload)
12080 << false;
12081
12082 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12083 }
12084 }
12085
12086 if (LangOpts.OpenMP)
12087 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12088
12089 // Semantic checking for this function declaration (in isolation).
12090
12091 if (getLangOpts().CPlusPlus) {
12092 // C++-specific checks.
12093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12094 CheckConstructor(Constructor);
12095 } else if (CXXDestructorDecl *Destructor =
12096 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12097 // We check here for invalid destructor names.
12098 // If we have a friend destructor declaration that is dependent, we can't
12099 // diagnose right away because cases like this are still valid:
12100 // template <class T> struct A { friend T::X::~Y(); };
12101 // struct B { struct Y { ~Y(); }; using X = Y; };
12102 // template struct A<B>;
12103 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12104 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12105 CXXRecordDecl *Record = Destructor->getParent();
12106 QualType ClassType = Context.getTypeDeclType(Record);
12107
12108 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12109 Ty: Context.getCanonicalType(T: ClassType));
12110 if (NewFD->getDeclName() != Name) {
12111 Diag(NewFD->getLocation(), diag::err_destructor_name);
12112 NewFD->setInvalidDecl();
12113 return Redeclaration;
12114 }
12115 }
12116 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12117 if (auto *TD = Guide->getDescribedFunctionTemplate())
12118 CheckDeductionGuideTemplate(TD: TD);
12119
12120 // A deduction guide is not on the list of entities that can be
12121 // explicitly specialized.
12122 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12123 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12124 << /*explicit specialization*/ 1;
12125 }
12126
12127 // Find any virtual functions that this function overrides.
12128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12129 if (!Method->isFunctionTemplateSpecialization() &&
12130 !Method->getDescribedFunctionTemplate() &&
12131 Method->isCanonicalDecl()) {
12132 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12133 }
12134 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12135 // C++2a [class.virtual]p6
12136 // A virtual method shall not have a requires-clause.
12137 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12138 diag::err_constrained_virtual_method);
12139
12140 if (Method->isStatic())
12141 checkThisInStaticMemberFunctionType(Method);
12142 }
12143
12144 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12145 ActOnConversionDeclarator(Conversion);
12146
12147 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12148 if (NewFD->isOverloadedOperator() &&
12149 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12150 NewFD->setInvalidDecl();
12151 return Redeclaration;
12152 }
12153
12154 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12155 if (NewFD->getLiteralIdentifier() &&
12156 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12157 NewFD->setInvalidDecl();
12158 return Redeclaration;
12159 }
12160
12161 // In C++, check default arguments now that we have merged decls. Unless
12162 // the lexical context is the class, because in this case this is done
12163 // during delayed parsing anyway.
12164 if (!CurContext->isRecord())
12165 CheckCXXDefaultArguments(FD: NewFD);
12166
12167 // If this function is declared as being extern "C", then check to see if
12168 // the function returns a UDT (class, struct, or union type) that is not C
12169 // compatible, and if it does, warn the user.
12170 // But, issue any diagnostic on the first declaration only.
12171 if (Previous.empty() && NewFD->isExternC()) {
12172 QualType R = NewFD->getReturnType();
12173 if (R->isIncompleteType() && !R->isVoidType())
12174 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12175 << NewFD << R;
12176 else if (!R.isPODType(Context) && !R->isVoidType() &&
12177 !R->isObjCObjectPointerType())
12178 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12179 }
12180
12181 // C++1z [dcl.fct]p6:
12182 // [...] whether the function has a non-throwing exception-specification
12183 // [is] part of the function type
12184 //
12185 // This results in an ABI break between C++14 and C++17 for functions whose
12186 // declared type includes an exception-specification in a parameter or
12187 // return type. (Exception specifications on the function itself are OK in
12188 // most cases, and exception specifications are not permitted in most other
12189 // contexts where they could make it into a mangling.)
12190 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12191 auto HasNoexcept = [&](QualType T) -> bool {
12192 // Strip off declarator chunks that could be between us and a function
12193 // type. We don't need to look far, exception specifications are very
12194 // restricted prior to C++17.
12195 if (auto *RT = T->getAs<ReferenceType>())
12196 T = RT->getPointeeType();
12197 else if (T->isAnyPointerType())
12198 T = T->getPointeeType();
12199 else if (auto *MPT = T->getAs<MemberPointerType>())
12200 T = MPT->getPointeeType();
12201 if (auto *FPT = T->getAs<FunctionProtoType>())
12202 if (FPT->isNothrow())
12203 return true;
12204 return false;
12205 };
12206
12207 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12208 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12209 for (QualType T : FPT->param_types())
12210 AnyNoexcept |= HasNoexcept(T);
12211 if (AnyNoexcept)
12212 Diag(NewFD->getLocation(),
12213 diag::warn_cxx17_compat_exception_spec_in_signature)
12214 << NewFD;
12215 }
12216
12217 if (!Redeclaration && LangOpts.CUDA)
12218 checkCUDATargetOverload(NewFD, Previous);
12219 }
12220
12221 // Check if the function definition uses any AArch64 SME features without
12222 // having the '+sme' feature enabled.
12223 if (DeclIsDefn) {
12224 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12225 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12226 bool UsesZA = Attr && Attr->isNewZA();
12227 bool UsesZT0 = Attr && Attr->isNewZT0();
12228 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12229 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12230 UsesSM |=
12231 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12232 UsesZA |= FunctionType::getArmZAState(AttrBits: EPI.AArch64SMEAttributes) !=
12233 FunctionType::ARM_None;
12234 UsesZT0 |= FunctionType::getArmZT0State(AttrBits: EPI.AArch64SMEAttributes) !=
12235 FunctionType::ARM_None;
12236 }
12237
12238 if (UsesSM || UsesZA) {
12239 llvm::StringMap<bool> FeatureMap;
12240 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12241 if (!FeatureMap.contains(Key: "sme")) {
12242 if (UsesSM)
12243 Diag(NewFD->getLocation(),
12244 diag::err_sme_definition_using_sm_in_non_sme_target);
12245 else
12246 Diag(NewFD->getLocation(),
12247 diag::err_sme_definition_using_za_in_non_sme_target);
12248 }
12249 }
12250 if (UsesZT0) {
12251 llvm::StringMap<bool> FeatureMap;
12252 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12253 if (!FeatureMap.contains(Key: "sme2")) {
12254 Diag(NewFD->getLocation(),
12255 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12256 }
12257 }
12258 }
12259
12260 return Redeclaration;
12261}
12262
12263void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12264 // C++11 [basic.start.main]p3:
12265 // A program that [...] declares main to be inline, static or
12266 // constexpr is ill-formed.
12267 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12268 // appear in a declaration of main.
12269 // static main is not an error under C99, but we should warn about it.
12270 // We accept _Noreturn main as an extension.
12271 if (FD->getStorageClass() == SC_Static)
12272 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12273 ? diag::err_static_main : diag::warn_static_main)
12274 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12275 if (FD->isInlineSpecified())
12276 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12277 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12278 if (DS.isNoreturnSpecified()) {
12279 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12280 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12281 Diag(NoreturnLoc, diag::ext_noreturn_main);
12282 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12283 << FixItHint::CreateRemoval(NoreturnRange);
12284 }
12285 if (FD->isConstexpr()) {
12286 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12287 << FD->isConsteval()
12288 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12289 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12290 }
12291
12292 if (getLangOpts().OpenCL) {
12293 Diag(FD->getLocation(), diag::err_opencl_no_main)
12294 << FD->hasAttr<OpenCLKernelAttr>();
12295 FD->setInvalidDecl();
12296 return;
12297 }
12298
12299 // Functions named main in hlsl are default entries, but don't have specific
12300 // signatures they are required to conform to.
12301 if (getLangOpts().HLSL)
12302 return;
12303
12304 QualType T = FD->getType();
12305 assert(T->isFunctionType() && "function decl is not of function type");
12306 const FunctionType* FT = T->castAs<FunctionType>();
12307
12308 // Set default calling convention for main()
12309 if (FT->getCallConv() != CC_C) {
12310 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12311 FD->setType(QualType(FT, 0));
12312 T = Context.getCanonicalType(FD->getType());
12313 }
12314
12315 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12316 // In C with GNU extensions we allow main() to have non-integer return
12317 // type, but we should warn about the extension, and we disable the
12318 // implicit-return-zero rule.
12319
12320 // GCC in C mode accepts qualified 'int'.
12321 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12322 FD->setHasImplicitReturnZero(true);
12323 else {
12324 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12325 SourceRange RTRange = FD->getReturnTypeSourceRange();
12326 if (RTRange.isValid())
12327 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12328 << FixItHint::CreateReplacement(RTRange, "int");
12329 }
12330 } else {
12331 // In C and C++, main magically returns 0 if you fall off the end;
12332 // set the flag which tells us that.
12333 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12334
12335 // All the standards say that main() should return 'int'.
12336 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12337 FD->setHasImplicitReturnZero(true);
12338 else {
12339 // Otherwise, this is just a flat-out error.
12340 SourceRange RTRange = FD->getReturnTypeSourceRange();
12341 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12342 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12343 : FixItHint());
12344 FD->setInvalidDecl(true);
12345 }
12346 }
12347
12348 // Treat protoless main() as nullary.
12349 if (isa<FunctionNoProtoType>(Val: FT)) return;
12350
12351 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12352 unsigned nparams = FTP->getNumParams();
12353 assert(FD->getNumParams() == nparams);
12354
12355 bool HasExtraParameters = (nparams > 3);
12356
12357 if (FTP->isVariadic()) {
12358 Diag(FD->getLocation(), diag::ext_variadic_main);
12359 // FIXME: if we had information about the location of the ellipsis, we
12360 // could add a FixIt hint to remove it as a parameter.
12361 }
12362
12363 // Darwin passes an undocumented fourth argument of type char**. If
12364 // other platforms start sprouting these, the logic below will start
12365 // getting shifty.
12366 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12367 HasExtraParameters = false;
12368
12369 if (HasExtraParameters) {
12370 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12371 FD->setInvalidDecl(true);
12372 nparams = 3;
12373 }
12374
12375 // FIXME: a lot of the following diagnostics would be improved
12376 // if we had some location information about types.
12377
12378 QualType CharPP =
12379 Context.getPointerType(Context.getPointerType(Context.CharTy));
12380 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12381
12382 for (unsigned i = 0; i < nparams; ++i) {
12383 QualType AT = FTP->getParamType(i);
12384
12385 bool mismatch = true;
12386
12387 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12388 mismatch = false;
12389 else if (Expected[i] == CharPP) {
12390 // As an extension, the following forms are okay:
12391 // char const **
12392 // char const * const *
12393 // char * const *
12394
12395 QualifierCollector qs;
12396 const PointerType* PT;
12397 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12398 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12399 Context.hasSameType(QualType(qs.strip(type: PT->getPointeeType()), 0),
12400 Context.CharTy)) {
12401 qs.removeConst();
12402 mismatch = !qs.empty();
12403 }
12404 }
12405
12406 if (mismatch) {
12407 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12408 // TODO: suggest replacing given type with expected type
12409 FD->setInvalidDecl(true);
12410 }
12411 }
12412
12413 if (nparams == 1 && !FD->isInvalidDecl()) {
12414 Diag(FD->getLocation(), diag::warn_main_one_arg);
12415 }
12416
12417 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12418 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12419 FD->setInvalidDecl();
12420 }
12421}
12422
12423static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12424
12425 // Default calling convention for main and wmain is __cdecl
12426 if (FD->getName() == "main" || FD->getName() == "wmain")
12427 return false;
12428
12429 // Default calling convention for MinGW is __cdecl
12430 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12431 if (T.isWindowsGNUEnvironment())
12432 return false;
12433
12434 // Default calling convention for WinMain, wWinMain and DllMain
12435 // is __stdcall on 32 bit Windows
12436 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12437 return true;
12438
12439 return false;
12440}
12441
12442void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12443 QualType T = FD->getType();
12444 assert(T->isFunctionType() && "function decl is not of function type");
12445 const FunctionType *FT = T->castAs<FunctionType>();
12446
12447 // Set an implicit return of 'zero' if the function can return some integral,
12448 // enumeration, pointer or nullptr type.
12449 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12450 FT->getReturnType()->isAnyPointerType() ||
12451 FT->getReturnType()->isNullPtrType())
12452 // DllMain is exempt because a return value of zero means it failed.
12453 if (FD->getName() != "DllMain")
12454 FD->setHasImplicitReturnZero(true);
12455
12456 // Explicity specified calling conventions are applied to MSVC entry points
12457 if (!hasExplicitCallingConv(T)) {
12458 if (isDefaultStdCall(FD, S&: *this)) {
12459 if (FT->getCallConv() != CC_X86StdCall) {
12460 FT = Context.adjustFunctionType(
12461 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12462 FD->setType(QualType(FT, 0));
12463 }
12464 } else if (FT->getCallConv() != CC_C) {
12465 FT = Context.adjustFunctionType(Fn: FT,
12466 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12467 FD->setType(QualType(FT, 0));
12468 }
12469 }
12470
12471 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12472 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12473 FD->setInvalidDecl();
12474 }
12475}
12476
12477void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) {
12478 auto &TargetInfo = getASTContext().getTargetInfo();
12479
12480 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry)
12481 return;
12482
12483 StringRef Env = TargetInfo.getTriple().getEnvironmentName();
12484 HLSLShaderAttr::ShaderType ShaderType;
12485 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) {
12486 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
12487 // The entry point is already annotated - check that it matches the
12488 // triple.
12489 if (Shader->getType() != ShaderType) {
12490 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
12491 << Shader;
12492 FD->setInvalidDecl();
12493 }
12494 } else {
12495 // Implicitly add the shader attribute if the entry function isn't
12496 // explicitly annotated.
12497 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType,
12498 FD->getBeginLoc()));
12499 }
12500 } else {
12501 switch (TargetInfo.getTriple().getEnvironment()) {
12502 case llvm::Triple::UnknownEnvironment:
12503 case llvm::Triple::Library:
12504 break;
12505 default:
12506 llvm_unreachable("Unhandled environment in triple");
12507 }
12508 }
12509}
12510
12511void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12512 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
12513 assert(ShaderAttr && "Entry point has no shader attribute");
12514 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12515
12516 switch (ST) {
12517 case HLSLShaderAttr::Pixel:
12518 case HLSLShaderAttr::Vertex:
12519 case HLSLShaderAttr::Geometry:
12520 case HLSLShaderAttr::Hull:
12521 case HLSLShaderAttr::Domain:
12522 case HLSLShaderAttr::RayGeneration:
12523 case HLSLShaderAttr::Intersection:
12524 case HLSLShaderAttr::AnyHit:
12525 case HLSLShaderAttr::ClosestHit:
12526 case HLSLShaderAttr::Miss:
12527 case HLSLShaderAttr::Callable:
12528 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
12529 DiagnoseHLSLAttrStageMismatch(NT, ST,
12530 {HLSLShaderAttr::Compute,
12531 HLSLShaderAttr::Amplification,
12532 HLSLShaderAttr::Mesh});
12533 FD->setInvalidDecl();
12534 }
12535 break;
12536
12537 case HLSLShaderAttr::Compute:
12538 case HLSLShaderAttr::Amplification:
12539 case HLSLShaderAttr::Mesh:
12540 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12541 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12542 << HLSLShaderAttr::ConvertShaderTypeToStr(ST);
12543 FD->setInvalidDecl();
12544 }
12545 break;
12546 }
12547
12548 for (ParmVarDecl *Param : FD->parameters()) {
12549 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) {
12550 CheckHLSLSemanticAnnotation(EntryPoint: FD, Param, AnnotationAttr: AnnotationAttr);
12551 } else {
12552 // FIXME: Handle struct parameters where annotations are on struct fields.
12553 // See: https://github.com/llvm/llvm-project/issues/57875
12554 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12555 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12556 FD->setInvalidDecl();
12557 }
12558 }
12559 // FIXME: Verify return type semantic annotation.
12560}
12561
12562void Sema::CheckHLSLSemanticAnnotation(
12563 FunctionDecl *EntryPoint, const Decl *Param,
12564 const HLSLAnnotationAttr *AnnotationAttr) {
12565 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
12566 assert(ShaderAttr && "Entry point has no shader attribute");
12567 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12568
12569 switch (AnnotationAttr->getKind()) {
12570 case attr::HLSLSV_DispatchThreadID:
12571 case attr::HLSLSV_GroupIndex:
12572 if (ST == HLSLShaderAttr::Compute)
12573 return;
12574 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST,
12575 {HLSLShaderAttr::Compute});
12576 break;
12577 default:
12578 llvm_unreachable("Unknown HLSLAnnotationAttr");
12579 }
12580}
12581
12582void Sema::DiagnoseHLSLAttrStageMismatch(
12583 const Attr *A, HLSLShaderAttr::ShaderType Stage,
12584 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) {
12585 SmallVector<StringRef, 8> StageStrings;
12586 llvm::transform(AllowedStages, std::back_inserter(x&: StageStrings),
12587 [](HLSLShaderAttr::ShaderType ST) {
12588 return StringRef(
12589 HLSLShaderAttr::ConvertShaderTypeToStr(ST));
12590 });
12591 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
12592 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage)
12593 << (AllowedStages.size() != 1) << join(StageStrings, ", ");
12594}
12595
12596bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12597 // FIXME: Need strict checking. In C89, we need to check for
12598 // any assignment, increment, decrement, function-calls, or
12599 // commas outside of a sizeof. In C99, it's the same list,
12600 // except that the aforementioned are allowed in unevaluated
12601 // expressions. Everything else falls under the
12602 // "may accept other forms of constant expressions" exception.
12603 //
12604 // Regular C++ code will not end up here (exceptions: language extensions,
12605 // OpenCL C++ etc), so the constant expression rules there don't matter.
12606 if (Init->isValueDependent()) {
12607 assert(Init->containsErrors() &&
12608 "Dependent code should only occur in error-recovery path.");
12609 return true;
12610 }
12611 const Expr *Culprit;
12612 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12613 return false;
12614 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12615 << Culprit->getSourceRange();
12616 return true;
12617}
12618
12619namespace {
12620 // Visits an initialization expression to see if OrigDecl is evaluated in
12621 // its own initialization and throws a warning if it does.
12622 class SelfReferenceChecker
12623 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12624 Sema &S;
12625 Decl *OrigDecl;
12626 bool isRecordType;
12627 bool isPODType;
12628 bool isReferenceType;
12629
12630 bool isInitList;
12631 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12632
12633 public:
12634 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12635
12636 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12637 S(S), OrigDecl(OrigDecl) {
12638 isPODType = false;
12639 isRecordType = false;
12640 isReferenceType = false;
12641 isInitList = false;
12642 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12643 isPODType = VD->getType().isPODType(Context: S.Context);
12644 isRecordType = VD->getType()->isRecordType();
12645 isReferenceType = VD->getType()->isReferenceType();
12646 }
12647 }
12648
12649 // For most expressions, just call the visitor. For initializer lists,
12650 // track the index of the field being initialized since fields are
12651 // initialized in order allowing use of previously initialized fields.
12652 void CheckExpr(Expr *E) {
12653 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12654 if (!InitList) {
12655 Visit(E);
12656 return;
12657 }
12658
12659 // Track and increment the index here.
12660 isInitList = true;
12661 InitFieldIndex.push_back(Elt: 0);
12662 for (auto *Child : InitList->children()) {
12663 CheckExpr(E: cast<Expr>(Val: Child));
12664 ++InitFieldIndex.back();
12665 }
12666 InitFieldIndex.pop_back();
12667 }
12668
12669 // Returns true if MemberExpr is checked and no further checking is needed.
12670 // Returns false if additional checking is required.
12671 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12672 llvm::SmallVector<FieldDecl*, 4> Fields;
12673 Expr *Base = E;
12674 bool ReferenceField = false;
12675
12676 // Get the field members used.
12677 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12678 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12679 if (!FD)
12680 return false;
12681 Fields.push_back(Elt: FD);
12682 if (FD->getType()->isReferenceType())
12683 ReferenceField = true;
12684 Base = ME->getBase()->IgnoreParenImpCasts();
12685 }
12686
12687 // Keep checking only if the base Decl is the same.
12688 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12689 if (!DRE || DRE->getDecl() != OrigDecl)
12690 return false;
12691
12692 // A reference field can be bound to an unininitialized field.
12693 if (CheckReference && !ReferenceField)
12694 return true;
12695
12696 // Convert FieldDecls to their index number.
12697 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12698 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12699 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12700
12701 // See if a warning is needed by checking the first difference in index
12702 // numbers. If field being used has index less than the field being
12703 // initialized, then the use is safe.
12704 for (auto UsedIter = UsedFieldIndex.begin(),
12705 UsedEnd = UsedFieldIndex.end(),
12706 OrigIter = InitFieldIndex.begin(),
12707 OrigEnd = InitFieldIndex.end();
12708 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12709 if (*UsedIter < *OrigIter)
12710 return true;
12711 if (*UsedIter > *OrigIter)
12712 break;
12713 }
12714
12715 // TODO: Add a different warning which will print the field names.
12716 HandleDeclRefExpr(DRE);
12717 return true;
12718 }
12719
12720 // For most expressions, the cast is directly above the DeclRefExpr.
12721 // For conditional operators, the cast can be outside the conditional
12722 // operator if both expressions are DeclRefExpr's.
12723 void HandleValue(Expr *E) {
12724 E = E->IgnoreParens();
12725 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12726 HandleDeclRefExpr(DRE);
12727 return;
12728 }
12729
12730 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12731 Visit(CO->getCond());
12732 HandleValue(E: CO->getTrueExpr());
12733 HandleValue(E: CO->getFalseExpr());
12734 return;
12735 }
12736
12737 if (BinaryConditionalOperator *BCO =
12738 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12739 Visit(BCO->getCond());
12740 HandleValue(E: BCO->getFalseExpr());
12741 return;
12742 }
12743
12744 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12745 if (Expr *SE = OVE->getSourceExpr())
12746 HandleValue(E: SE);
12747 return;
12748 }
12749
12750 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
12751 if (BO->getOpcode() == BO_Comma) {
12752 Visit(BO->getLHS());
12753 HandleValue(E: BO->getRHS());
12754 return;
12755 }
12756 }
12757
12758 if (isa<MemberExpr>(Val: E)) {
12759 if (isInitList) {
12760 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
12761 CheckReference: false /*CheckReference*/))
12762 return;
12763 }
12764
12765 Expr *Base = E->IgnoreParenImpCasts();
12766 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12767 // Check for static member variables and don't warn on them.
12768 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12769 return;
12770 Base = ME->getBase()->IgnoreParenImpCasts();
12771 }
12772 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
12773 HandleDeclRefExpr(DRE);
12774 return;
12775 }
12776
12777 Visit(E);
12778 }
12779
12780 // Reference types not handled in HandleValue are handled here since all
12781 // uses of references are bad, not just r-value uses.
12782 void VisitDeclRefExpr(DeclRefExpr *E) {
12783 if (isReferenceType)
12784 HandleDeclRefExpr(DRE: E);
12785 }
12786
12787 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12788 if (E->getCastKind() == CK_LValueToRValue) {
12789 HandleValue(E: E->getSubExpr());
12790 return;
12791 }
12792
12793 Inherited::VisitImplicitCastExpr(E);
12794 }
12795
12796 void VisitMemberExpr(MemberExpr *E) {
12797 if (isInitList) {
12798 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
12799 return;
12800 }
12801
12802 // Don't warn on arrays since they can be treated as pointers.
12803 if (E->getType()->canDecayToPointerType()) return;
12804
12805 // Warn when a non-static method call is followed by non-static member
12806 // field accesses, which is followed by a DeclRefExpr.
12807 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
12808 bool Warn = (MD && !MD->isStatic());
12809 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12810 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12811 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12812 Warn = false;
12813 Base = ME->getBase()->IgnoreParenImpCasts();
12814 }
12815
12816 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
12817 if (Warn)
12818 HandleDeclRefExpr(DRE);
12819 return;
12820 }
12821
12822 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12823 // Visit that expression.
12824 Visit(Base);
12825 }
12826
12827 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12828 Expr *Callee = E->getCallee();
12829
12830 if (isa<UnresolvedLookupExpr>(Callee))
12831 return Inherited::VisitCXXOperatorCallExpr(E);
12832
12833 Visit(Callee);
12834 for (auto Arg: E->arguments())
12835 HandleValue(Arg->IgnoreParenImpCasts());
12836 }
12837
12838 void VisitUnaryOperator(UnaryOperator *E) {
12839 // For POD record types, addresses of its own members are well-defined.
12840 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12841 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
12842 if (!isPODType)
12843 HandleValue(E: E->getSubExpr());
12844 return;
12845 }
12846
12847 if (E->isIncrementDecrementOp()) {
12848 HandleValue(E: E->getSubExpr());
12849 return;
12850 }
12851
12852 Inherited::VisitUnaryOperator(E);
12853 }
12854
12855 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12856
12857 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12858 if (E->getConstructor()->isCopyConstructor()) {
12859 Expr *ArgExpr = E->getArg(Arg: 0);
12860 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
12861 if (ILE->getNumInits() == 1)
12862 ArgExpr = ILE->getInit(Init: 0);
12863 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
12864 if (ICE->getCastKind() == CK_NoOp)
12865 ArgExpr = ICE->getSubExpr();
12866 HandleValue(E: ArgExpr);
12867 return;
12868 }
12869 Inherited::VisitCXXConstructExpr(E);
12870 }
12871
12872 void VisitCallExpr(CallExpr *E) {
12873 // Treat std::move as a use.
12874 if (E->isCallToStdMove()) {
12875 HandleValue(E: E->getArg(Arg: 0));
12876 return;
12877 }
12878
12879 Inherited::VisitCallExpr(CE: E);
12880 }
12881
12882 void VisitBinaryOperator(BinaryOperator *E) {
12883 if (E->isCompoundAssignmentOp()) {
12884 HandleValue(E: E->getLHS());
12885 Visit(E->getRHS());
12886 return;
12887 }
12888
12889 Inherited::VisitBinaryOperator(E);
12890 }
12891
12892 // A custom visitor for BinaryConditionalOperator is needed because the
12893 // regular visitor would check the condition and true expression separately
12894 // but both point to the same place giving duplicate diagnostics.
12895 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12896 Visit(E->getCond());
12897 Visit(E->getFalseExpr());
12898 }
12899
12900 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12901 Decl* ReferenceDecl = DRE->getDecl();
12902 if (OrigDecl != ReferenceDecl) return;
12903 unsigned diag;
12904 if (isReferenceType) {
12905 diag = diag::warn_uninit_self_reference_in_reference_init;
12906 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
12907 diag = diag::warn_static_self_reference_in_init;
12908 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
12909 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
12910 DRE->getDecl()->getType()->isRecordType()) {
12911 diag = diag::warn_uninit_self_reference_in_init;
12912 } else {
12913 // Local variables will be handled by the CFG analysis.
12914 return;
12915 }
12916
12917 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12918 S.PDiag(DiagID: diag)
12919 << DRE->getDecl() << OrigDecl->getLocation()
12920 << DRE->getSourceRange());
12921 }
12922 };
12923
12924 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12925 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12926 bool DirectInit) {
12927 // Parameters arguments are occassionially constructed with itself,
12928 // for instance, in recursive functions. Skip them.
12929 if (isa<ParmVarDecl>(Val: OrigDecl))
12930 return;
12931
12932 E = E->IgnoreParens();
12933
12934 // Skip checking T a = a where T is not a record or reference type.
12935 // Doing so is a way to silence uninitialized warnings.
12936 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
12937 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12938 if (ICE->getCastKind() == CK_LValueToRValue)
12939 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12940 if (DRE->getDecl() == OrigDecl)
12941 return;
12942
12943 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12944 }
12945} // end anonymous namespace
12946
12947namespace {
12948 // Simple wrapper to add the name of a variable or (if no variable is
12949 // available) a DeclarationName into a diagnostic.
12950 struct VarDeclOrName {
12951 VarDecl *VDecl;
12952 DeclarationName Name;
12953
12954 friend const Sema::SemaDiagnosticBuilder &
12955 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12956 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12957 }
12958 };
12959} // end anonymous namespace
12960
12961QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12962 DeclarationName Name, QualType Type,
12963 TypeSourceInfo *TSI,
12964 SourceRange Range, bool DirectInit,
12965 Expr *Init) {
12966 bool IsInitCapture = !VDecl;
12967 assert((!VDecl || !VDecl->isInitCapture()) &&
12968 "init captures are expected to be deduced prior to initialization");
12969
12970 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
12971
12972 DeducedType *Deduced = Type->getContainedDeducedType();
12973 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12974
12975 // Diagnose auto array declarations in C23, unless it's a supported extension.
12976 if (getLangOpts().C23 && Type->isArrayType() &&
12977 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
12978 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12979 << (int)Deduced->getContainedAutoType()->getKeyword()
12980 << /*in array decl*/ 23 << Range;
12981 return QualType();
12982 }
12983
12984 // C++11 [dcl.spec.auto]p3
12985 if (!Init) {
12986 assert(VDecl && "no init for init capture deduction?");
12987
12988 // Except for class argument deduction, and then for an initializing
12989 // declaration only, i.e. no static at class scope or extern.
12990 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
12991 VDecl->hasExternalStorage() ||
12992 VDecl->isStaticDataMember()) {
12993 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12994 << VDecl->getDeclName() << Type;
12995 return QualType();
12996 }
12997 }
12998
12999 ArrayRef<Expr*> DeduceInits;
13000 if (Init)
13001 DeduceInits = Init;
13002
13003 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13004 if (DirectInit && PL)
13005 DeduceInits = PL->exprs();
13006
13007 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13008 assert(VDecl && "non-auto type for init capture deduction?");
13009 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13010 InitializationKind Kind = InitializationKind::CreateForInit(
13011 Loc: VDecl->getLocation(), DirectInit, Init);
13012 // FIXME: Initialization should not be taking a mutable list of inits.
13013 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
13014 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13015 Init: InitsCopy);
13016 }
13017
13018 if (DirectInit) {
13019 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13020 DeduceInits = IL->inits();
13021 }
13022
13023 // Deduction only works if we have exactly one source expression.
13024 if (DeduceInits.empty()) {
13025 // It isn't possible to write this directly, but it is possible to
13026 // end up in this situation with "auto x(some_pack...);"
13027 Diag(Init->getBeginLoc(), IsInitCapture
13028 ? diag::err_init_capture_no_expression
13029 : diag::err_auto_var_init_no_expression)
13030 << VN << Type << Range;
13031 return QualType();
13032 }
13033
13034 if (DeduceInits.size() > 1) {
13035 Diag(DeduceInits[1]->getBeginLoc(),
13036 IsInitCapture ? diag::err_init_capture_multiple_expressions
13037 : diag::err_auto_var_init_multiple_expressions)
13038 << VN << Type << Range;
13039 return QualType();
13040 }
13041
13042 Expr *DeduceInit = DeduceInits[0];
13043 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13044 Diag(Init->getBeginLoc(), IsInitCapture
13045 ? diag::err_init_capture_paren_braces
13046 : diag::err_auto_var_init_paren_braces)
13047 << isa<InitListExpr>(Init) << VN << Type << Range;
13048 return QualType();
13049 }
13050
13051 // Expressions default to 'id' when we're in a debugger.
13052 bool DefaultedAnyToId = false;
13053 if (getLangOpts().DebuggerCastResultToId &&
13054 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13055 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13056 if (Result.isInvalid()) {
13057 return QualType();
13058 }
13059 Init = Result.get();
13060 DefaultedAnyToId = true;
13061 }
13062
13063 // C++ [dcl.decomp]p1:
13064 // If the assignment-expression [...] has array type A and no ref-qualifier
13065 // is present, e has type cv A
13066 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13067 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13068 DeduceInit->getType()->isConstantArrayType())
13069 return Context.getQualifiedType(T: DeduceInit->getType(),
13070 Qs: Type.getQualifiers());
13071
13072 QualType DeducedType;
13073 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13074 TemplateDeductionResult Result =
13075 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13076 if (Result != TemplateDeductionResult::Success &&
13077 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13078 if (!IsInitCapture)
13079 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13080 else if (isa<InitListExpr>(Init))
13081 Diag(Range.getBegin(),
13082 diag::err_init_capture_deduction_failure_from_init_list)
13083 << VN
13084 << (DeduceInit->getType().isNull() ? TSI->getType()
13085 : DeduceInit->getType())
13086 << DeduceInit->getSourceRange();
13087 else
13088 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13089 << VN << TSI->getType()
13090 << (DeduceInit->getType().isNull() ? TSI->getType()
13091 : DeduceInit->getType())
13092 << DeduceInit->getSourceRange();
13093 }
13094
13095 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13096 // 'id' instead of a specific object type prevents most of our usual
13097 // checks.
13098 // We only want to warn outside of template instantiations, though:
13099 // inside a template, the 'id' could have come from a parameter.
13100 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13101 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13102 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13103 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13104 }
13105
13106 return DeducedType;
13107}
13108
13109bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13110 Expr *Init) {
13111 assert(!Init || !Init->containsErrors());
13112 QualType DeducedType = deduceVarTypeFromInitializer(
13113 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13114 Range: VDecl->getSourceRange(), DirectInit, Init);
13115 if (DeducedType.isNull()) {
13116 VDecl->setInvalidDecl();
13117 return true;
13118 }
13119
13120 VDecl->setType(DeducedType);
13121 assert(VDecl->isLinkageValid());
13122
13123 // In ARC, infer lifetime.
13124 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13125 VDecl->setInvalidDecl();
13126
13127 if (getLangOpts().OpenCL)
13128 deduceOpenCLAddressSpace(VDecl);
13129
13130 // If this is a redeclaration, check that the type we just deduced matches
13131 // the previously declared type.
13132 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13133 // We never need to merge the type, because we cannot form an incomplete
13134 // array of auto, nor deduce such a type.
13135 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13136 }
13137
13138 // Check the deduced type is valid for a variable declaration.
13139 CheckVariableDeclarationType(NewVD: VDecl);
13140 return VDecl->isInvalidDecl();
13141}
13142
13143void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13144 SourceLocation Loc) {
13145 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13146 Init = EWC->getSubExpr();
13147
13148 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13149 Init = CE->getSubExpr();
13150
13151 QualType InitType = Init->getType();
13152 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13153 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13154 "shouldn't be called if type doesn't have a non-trivial C struct");
13155 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13156 for (auto *I : ILE->inits()) {
13157 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13158 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13159 continue;
13160 SourceLocation SL = I->getExprLoc();
13161 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13162 }
13163 return;
13164 }
13165
13166 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13167 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13168 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NTCUC_DefaultInitializedObject,
13169 NonTrivialKind: NTCUK_Init);
13170 } else {
13171 // Assume all other explicit initializers involving copying some existing
13172 // object.
13173 // TODO: ignore any explicit initializers where we can guarantee
13174 // copy-elision.
13175 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13176 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NTCUC_CopyInit, NonTrivialKind: NTCUK_Copy);
13177 }
13178}
13179
13180namespace {
13181
13182bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13183 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13184 // in the source code or implicitly by the compiler if it is in a union
13185 // defined in a system header and has non-trivial ObjC ownership
13186 // qualifications. We don't want those fields to participate in determining
13187 // whether the containing union is non-trivial.
13188 return FD->hasAttr<UnavailableAttr>();
13189}
13190
13191struct DiagNonTrivalCUnionDefaultInitializeVisitor
13192 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13193 void> {
13194 using Super =
13195 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13196 void>;
13197
13198 DiagNonTrivalCUnionDefaultInitializeVisitor(
13199 QualType OrigTy, SourceLocation OrigLoc,
13200 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13201 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13202
13203 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13204 const FieldDecl *FD, bool InNonTrivialUnion) {
13205 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13206 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13207 InNonTrivialUnion);
13208 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13209 }
13210
13211 void visitARCStrong(QualType QT, const FieldDecl *FD,
13212 bool InNonTrivialUnion) {
13213 if (InNonTrivialUnion)
13214 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13215 << 1 << 0 << QT << FD->getName();
13216 }
13217
13218 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13219 if (InNonTrivialUnion)
13220 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13221 << 1 << 0 << QT << FD->getName();
13222 }
13223
13224 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13225 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13226 if (RD->isUnion()) {
13227 if (OrigLoc.isValid()) {
13228 bool IsUnion = false;
13229 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13230 IsUnion = OrigRD->isUnion();
13231 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13232 << 0 << OrigTy << IsUnion << UseContext;
13233 // Reset OrigLoc so that this diagnostic is emitted only once.
13234 OrigLoc = SourceLocation();
13235 }
13236 InNonTrivialUnion = true;
13237 }
13238
13239 if (InNonTrivialUnion)
13240 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13241 << 0 << 0 << QT.getUnqualifiedType() << "";
13242
13243 for (const FieldDecl *FD : RD->fields())
13244 if (!shouldIgnoreForRecordTriviality(FD))
13245 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13246 }
13247
13248 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13249
13250 // The non-trivial C union type or the struct/union type that contains a
13251 // non-trivial C union.
13252 QualType OrigTy;
13253 SourceLocation OrigLoc;
13254 Sema::NonTrivialCUnionContext UseContext;
13255 Sema &S;
13256};
13257
13258struct DiagNonTrivalCUnionDestructedTypeVisitor
13259 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13260 using Super =
13261 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13262
13263 DiagNonTrivalCUnionDestructedTypeVisitor(
13264 QualType OrigTy, SourceLocation OrigLoc,
13265 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13266 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13267
13268 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13269 const FieldDecl *FD, bool InNonTrivialUnion) {
13270 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13271 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13272 InNonTrivialUnion);
13273 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13274 }
13275
13276 void visitARCStrong(QualType QT, const FieldDecl *FD,
13277 bool InNonTrivialUnion) {
13278 if (InNonTrivialUnion)
13279 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13280 << 1 << 1 << QT << FD->getName();
13281 }
13282
13283 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13284 if (InNonTrivialUnion)
13285 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13286 << 1 << 1 << QT << FD->getName();
13287 }
13288
13289 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13290 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13291 if (RD->isUnion()) {
13292 if (OrigLoc.isValid()) {
13293 bool IsUnion = false;
13294 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13295 IsUnion = OrigRD->isUnion();
13296 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13297 << 1 << OrigTy << IsUnion << UseContext;
13298 // Reset OrigLoc so that this diagnostic is emitted only once.
13299 OrigLoc = SourceLocation();
13300 }
13301 InNonTrivialUnion = true;
13302 }
13303
13304 if (InNonTrivialUnion)
13305 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13306 << 0 << 1 << QT.getUnqualifiedType() << "";
13307
13308 for (const FieldDecl *FD : RD->fields())
13309 if (!shouldIgnoreForRecordTriviality(FD))
13310 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13311 }
13312
13313 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13314 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13315 bool InNonTrivialUnion) {}
13316
13317 // The non-trivial C union type or the struct/union type that contains a
13318 // non-trivial C union.
13319 QualType OrigTy;
13320 SourceLocation OrigLoc;
13321 Sema::NonTrivialCUnionContext UseContext;
13322 Sema &S;
13323};
13324
13325struct DiagNonTrivalCUnionCopyVisitor
13326 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13327 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13328
13329 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13330 Sema::NonTrivialCUnionContext UseContext,
13331 Sema &S)
13332 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13333
13334 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13335 const FieldDecl *FD, bool InNonTrivialUnion) {
13336 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13337 return this->asDerived().visit(S.Context.getBaseElementType(VAT: AT), FD,
13338 InNonTrivialUnion);
13339 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13340 }
13341
13342 void visitARCStrong(QualType QT, const FieldDecl *FD,
13343 bool InNonTrivialUnion) {
13344 if (InNonTrivialUnion)
13345 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13346 << 1 << 2 << QT << FD->getName();
13347 }
13348
13349 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13350 if (InNonTrivialUnion)
13351 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13352 << 1 << 2 << QT << FD->getName();
13353 }
13354
13355 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13356 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13357 if (RD->isUnion()) {
13358 if (OrigLoc.isValid()) {
13359 bool IsUnion = false;
13360 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13361 IsUnion = OrigRD->isUnion();
13362 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13363 << 2 << OrigTy << IsUnion << UseContext;
13364 // Reset OrigLoc so that this diagnostic is emitted only once.
13365 OrigLoc = SourceLocation();
13366 }
13367 InNonTrivialUnion = true;
13368 }
13369
13370 if (InNonTrivialUnion)
13371 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13372 << 0 << 2 << QT.getUnqualifiedType() << "";
13373
13374 for (const FieldDecl *FD : RD->fields())
13375 if (!shouldIgnoreForRecordTriviality(FD))
13376 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13377 }
13378
13379 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13380 const FieldDecl *FD, bool InNonTrivialUnion) {}
13381 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13382 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13383 bool InNonTrivialUnion) {}
13384
13385 // The non-trivial C union type or the struct/union type that contains a
13386 // non-trivial C union.
13387 QualType OrigTy;
13388 SourceLocation OrigLoc;
13389 Sema::NonTrivialCUnionContext UseContext;
13390 Sema &S;
13391};
13392
13393} // namespace
13394
13395void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13396 NonTrivialCUnionContext UseContext,
13397 unsigned NonTrivialKind) {
13398 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13399 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13400 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13401 "shouldn't be called if type doesn't have a non-trivial C union");
13402
13403 if ((NonTrivialKind & NTCUK_Init) &&
13404 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13405 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13406 .visit(QT, nullptr, false);
13407 if ((NonTrivialKind & NTCUK_Destruct) &&
13408 QT.hasNonTrivialToPrimitiveDestructCUnion())
13409 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13410 .visit(QT, nullptr, false);
13411 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13412 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13413 .visit(QT, nullptr, false);
13414}
13415
13416/// AddInitializerToDecl - Adds the initializer Init to the
13417/// declaration dcl. If DirectInit is true, this is C++ direct
13418/// initialization rather than copy initialization.
13419void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13420 // If there is no declaration, there was an error parsing it. Just ignore
13421 // the initializer.
13422 if (!RealDecl || RealDecl->isInvalidDecl()) {
13423 CorrectDelayedTyposInExpr(E: Init, InitDecl: dyn_cast_or_null<VarDecl>(Val: RealDecl));
13424 return;
13425 }
13426
13427 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13428 // Pure-specifiers are handled in ActOnPureSpecifier.
13429 Diag(Method->getLocation(), diag::err_member_function_initialization)
13430 << Method->getDeclName() << Init->getSourceRange();
13431 Method->setInvalidDecl();
13432 return;
13433 }
13434
13435 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13436 if (!VDecl) {
13437 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13438 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13439 RealDecl->setInvalidDecl();
13440 return;
13441 }
13442
13443 // WebAssembly tables can't be used to initialise a variable.
13444 if (Init && !Init->getType().isNull() &&
13445 Init->getType()->isWebAssemblyTableType()) {
13446 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13447 VDecl->setInvalidDecl();
13448 return;
13449 }
13450
13451 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13452 if (VDecl->getType()->isUndeducedType()) {
13453 // Attempt typo correction early so that the type of the init expression can
13454 // be deduced based on the chosen correction if the original init contains a
13455 // TypoExpr.
13456 ExprResult Res = CorrectDelayedTyposInExpr(E: Init, InitDecl: VDecl);
13457 if (!Res.isUsable()) {
13458 // There are unresolved typos in Init, just drop them.
13459 // FIXME: improve the recovery strategy to preserve the Init.
13460 RealDecl->setInvalidDecl();
13461 return;
13462 }
13463 if (Res.get()->containsErrors()) {
13464 // Invalidate the decl as we don't know the type for recovery-expr yet.
13465 RealDecl->setInvalidDecl();
13466 VDecl->setInit(Res.get());
13467 return;
13468 }
13469 Init = Res.get();
13470
13471 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13472 return;
13473 }
13474
13475 // dllimport cannot be used on variable definitions.
13476 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13477 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13478 VDecl->setInvalidDecl();
13479 return;
13480 }
13481
13482 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13483 // the identifier has external or internal linkage, the declaration shall
13484 // have no initializer for the identifier.
13485 // C++14 [dcl.init]p5 is the same restriction for C++.
13486 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13487 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13488 VDecl->setInvalidDecl();
13489 return;
13490 }
13491
13492 if (!VDecl->getType()->isDependentType()) {
13493 // A definition must end up with a complete type, which means it must be
13494 // complete with the restriction that an array type might be completed by
13495 // the initializer; note that later code assumes this restriction.
13496 QualType BaseDeclType = VDecl->getType();
13497 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13498 BaseDeclType = Array->getElementType();
13499 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13500 diag::err_typecheck_decl_incomplete_type)) {
13501 RealDecl->setInvalidDecl();
13502 return;
13503 }
13504
13505 // The variable can not have an abstract class type.
13506 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13507 diag::err_abstract_type_in_decl,
13508 AbstractVariableType))
13509 VDecl->setInvalidDecl();
13510 }
13511
13512 // C++ [module.import/6] external definitions are not permitted in header
13513 // units.
13514 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13515 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13516 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13517 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl)) {
13518 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13519 VDecl->setInvalidDecl();
13520 }
13521
13522 // If adding the initializer will turn this declaration into a definition,
13523 // and we already have a definition for this variable, diagnose or otherwise
13524 // handle the situation.
13525 if (VarDecl *Def = VDecl->getDefinition())
13526 if (Def != VDecl &&
13527 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13528 !VDecl->isThisDeclarationADemotedDefinition() &&
13529 checkVarDeclRedefinition(Old: Def, New: VDecl))
13530 return;
13531
13532 if (getLangOpts().CPlusPlus) {
13533 // C++ [class.static.data]p4
13534 // If a static data member is of const integral or const
13535 // enumeration type, its declaration in the class definition can
13536 // specify a constant-initializer which shall be an integral
13537 // constant expression (5.19). In that case, the member can appear
13538 // in integral constant expressions. The member shall still be
13539 // defined in a namespace scope if it is used in the program and the
13540 // namespace scope definition shall not contain an initializer.
13541 //
13542 // We already performed a redefinition check above, but for static
13543 // data members we also need to check whether there was an in-class
13544 // declaration with an initializer.
13545 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13546 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13547 << VDecl->getDeclName();
13548 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13549 diag::note_previous_initializer)
13550 << 0;
13551 return;
13552 }
13553
13554 if (VDecl->hasLocalStorage())
13555 setFunctionHasBranchProtectedScope();
13556
13557 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13558 VDecl->setInvalidDecl();
13559 return;
13560 }
13561 }
13562
13563 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13564 // a kernel function cannot be initialized."
13565 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13566 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13567 VDecl->setInvalidDecl();
13568 return;
13569 }
13570
13571 // The LoaderUninitialized attribute acts as a definition (of undef).
13572 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13573 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13574 VDecl->setInvalidDecl();
13575 return;
13576 }
13577
13578 // Get the decls type and save a reference for later, since
13579 // CheckInitializerTypes may change it.
13580 QualType DclT = VDecl->getType(), SavT = DclT;
13581
13582 // Expressions default to 'id' when we're in a debugger
13583 // and we are assigning it to a variable of Objective-C pointer type.
13584 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13585 Init->getType() == Context.UnknownAnyTy) {
13586 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13587 if (Result.isInvalid()) {
13588 VDecl->setInvalidDecl();
13589 return;
13590 }
13591 Init = Result.get();
13592 }
13593
13594 // Perform the initialization.
13595 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init);
13596 bool IsParenListInit = false;
13597 if (!VDecl->isInvalidDecl()) {
13598 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13599 InitializationKind Kind = InitializationKind::CreateForInit(
13600 Loc: VDecl->getLocation(), DirectInit, Init);
13601
13602 MultiExprArg Args = Init;
13603 if (CXXDirectInit)
13604 Args = MultiExprArg(CXXDirectInit->getExprs(),
13605 CXXDirectInit->getNumExprs());
13606
13607 // Try to correct any TypoExprs in the initialization arguments.
13608 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13609 ExprResult Res = CorrectDelayedTyposInExpr(
13610 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13611 [this, Entity, Kind](Expr *E) {
13612 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13613 return Init.Failed() ? ExprError() : E;
13614 });
13615 if (Res.isInvalid()) {
13616 VDecl->setInvalidDecl();
13617 } else if (Res.get() != Args[Idx]) {
13618 Args[Idx] = Res.get();
13619 }
13620 }
13621 if (VDecl->isInvalidDecl())
13622 return;
13623
13624 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13625 /*TopLevelOfInitList=*/false,
13626 /*TreatUnavailableAsInvalid=*/false);
13627 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
13628 if (Result.isInvalid()) {
13629 // If the provided initializer fails to initialize the var decl,
13630 // we attach a recovery expr for better recovery.
13631 auto RecoveryExpr =
13632 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
13633 if (RecoveryExpr.get())
13634 VDecl->setInit(RecoveryExpr.get());
13635 // In general, for error recovery purposes, the initalizer doesn't play
13636 // part in the valid bit of the declaration. There are a few exceptions:
13637 // 1) if the var decl has a deduced auto type, and the type cannot be
13638 // deduced by an invalid initializer;
13639 // 2) if the var decl is decompsition decl with a non-deduced type, and
13640 // the initialization fails (e.g. `int [a] = {1, 2};`);
13641 // Case 1) was already handled elsewhere.
13642 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
13643 VDecl->setInvalidDecl();
13644 return;
13645 }
13646
13647 Init = Result.getAs<Expr>();
13648 IsParenListInit = !InitSeq.steps().empty() &&
13649 InitSeq.step_begin()->Kind ==
13650 InitializationSequence::SK_ParenthesizedListInit;
13651 QualType VDeclType = VDecl->getType();
13652 if (Init && !Init->getType().isNull() &&
13653 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13654 Context.getAsIncompleteArrayType(T: VDeclType) &&
13655 Context.getAsIncompleteArrayType(T: Init->getType())) {
13656 // Bail out if it is not possible to deduce array size from the
13657 // initializer.
13658 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13659 << VDeclType;
13660 VDecl->setInvalidDecl();
13661 return;
13662 }
13663 }
13664
13665 // Check for self-references within variable initializers.
13666 // Variables declared within a function/method body (except for references)
13667 // are handled by a dataflow analysis.
13668 // This is undefined behavior in C++, but valid in C.
13669 if (getLangOpts().CPlusPlus)
13670 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13671 VDecl->getType()->isReferenceType())
13672 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
13673
13674 // If the type changed, it means we had an incomplete type that was
13675 // completed by the initializer. For example:
13676 // int ary[] = { 1, 3, 5 };
13677 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13678 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13679 VDecl->setType(DclT);
13680
13681 if (!VDecl->isInvalidDecl()) {
13682 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
13683
13684 if (VDecl->hasAttr<BlocksAttr>())
13685 checkRetainCycles(Var: VDecl, Init);
13686
13687 // It is safe to assign a weak reference into a strong variable.
13688 // Although this code can still have problems:
13689 // id x = self.weakProp;
13690 // id y = self.weakProp;
13691 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13692 // paths through the function. This should be revisited if
13693 // -Wrepeated-use-of-weak is made flow-sensitive.
13694 if (FunctionScopeInfo *FSI = getCurFunction())
13695 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13696 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13697 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13698 Init->getBeginLoc()))
13699 FSI->markSafeWeakUse(E: Init);
13700 }
13701
13702 // The initialization is usually a full-expression.
13703 //
13704 // FIXME: If this is a braced initialization of an aggregate, it is not
13705 // an expression, and each individual field initializer is a separate
13706 // full-expression. For instance, in:
13707 //
13708 // struct Temp { ~Temp(); };
13709 // struct S { S(Temp); };
13710 // struct T { S a, b; } t = { Temp(), Temp() }
13711 //
13712 // we should destroy the first Temp before constructing the second.
13713 ExprResult Result =
13714 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13715 /*DiscardedValue*/ false, VDecl->isConstexpr());
13716 if (Result.isInvalid()) {
13717 VDecl->setInvalidDecl();
13718 return;
13719 }
13720 Init = Result.get();
13721
13722 // Attach the initializer to the decl.
13723 VDecl->setInit(Init);
13724
13725 if (VDecl->isLocalVarDecl()) {
13726 // Don't check the initializer if the declaration is malformed.
13727 if (VDecl->isInvalidDecl()) {
13728 // do nothing
13729
13730 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13731 // This is true even in C++ for OpenCL.
13732 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13733 CheckForConstantInitializer(Init, DclT);
13734
13735 // Otherwise, C++ does not restrict the initializer.
13736 } else if (getLangOpts().CPlusPlus) {
13737 // do nothing
13738
13739 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13740 // static storage duration shall be constant expressions or string literals.
13741 } else if (VDecl->getStorageClass() == SC_Static) {
13742 CheckForConstantInitializer(Init, DclT);
13743
13744 // C89 is stricter than C99 for aggregate initializers.
13745 // C89 6.5.7p3: All the expressions [...] in an initializer list
13746 // for an object that has aggregate or union type shall be
13747 // constant expressions.
13748 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13749 isa<InitListExpr>(Val: Init)) {
13750 const Expr *Culprit;
13751 if (!Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit)) {
13752 Diag(Culprit->getExprLoc(),
13753 diag::ext_aggregate_init_not_constant)
13754 << Culprit->getSourceRange();
13755 }
13756 }
13757
13758 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
13759 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13760 if (VDecl->hasLocalStorage())
13761 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13762 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13763 VDecl->getLexicalDeclContext()->isRecord()) {
13764 // This is an in-class initialization for a static data member, e.g.,
13765 //
13766 // struct S {
13767 // static const int value = 17;
13768 // };
13769
13770 // C++ [class.mem]p4:
13771 // A member-declarator can contain a constant-initializer only
13772 // if it declares a static member (9.4) of const integral or
13773 // const enumeration type, see 9.4.2.
13774 //
13775 // C++11 [class.static.data]p3:
13776 // If a non-volatile non-inline const static data member is of integral
13777 // or enumeration type, its declaration in the class definition can
13778 // specify a brace-or-equal-initializer in which every initializer-clause
13779 // that is an assignment-expression is a constant expression. A static
13780 // data member of literal type can be declared in the class definition
13781 // with the constexpr specifier; if so, its declaration shall specify a
13782 // brace-or-equal-initializer in which every initializer-clause that is
13783 // an assignment-expression is a constant expression.
13784
13785 // Do nothing on dependent types.
13786 if (DclT->isDependentType()) {
13787
13788 // Allow any 'static constexpr' members, whether or not they are of literal
13789 // type. We separately check that every constexpr variable is of literal
13790 // type.
13791 } else if (VDecl->isConstexpr()) {
13792
13793 // Require constness.
13794 } else if (!DclT.isConstQualified()) {
13795 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13796 << Init->getSourceRange();
13797 VDecl->setInvalidDecl();
13798
13799 // We allow integer constant expressions in all cases.
13800 } else if (DclT->isIntegralOrEnumerationType()) {
13801 // Check whether the expression is a constant expression.
13802 SourceLocation Loc;
13803 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13804 // In C++11, a non-constexpr const static data member with an
13805 // in-class initializer cannot be volatile.
13806 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13807 else if (Init->isValueDependent())
13808 ; // Nothing to check.
13809 else if (Init->isIntegerConstantExpr(Ctx: Context, Loc: &Loc))
13810 ; // Ok, it's an ICE!
13811 else if (Init->getType()->isScopedEnumeralType() &&
13812 Init->isCXX11ConstantExpr(Ctx: Context))
13813 ; // Ok, it is a scoped-enum constant expression.
13814 else if (Init->isEvaluatable(Ctx: Context)) {
13815 // If we can constant fold the initializer through heroics, accept it,
13816 // but report this as a use of an extension for -pedantic.
13817 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13818 << Init->getSourceRange();
13819 } else {
13820 // Otherwise, this is some crazy unknown case. Report the issue at the
13821 // location provided by the isIntegerConstantExpr failed check.
13822 Diag(Loc, diag::err_in_class_initializer_non_constant)
13823 << Init->getSourceRange();
13824 VDecl->setInvalidDecl();
13825 }
13826
13827 // We allow foldable floating-point constants as an extension.
13828 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13829 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13830 // it anyway and provide a fixit to add the 'constexpr'.
13831 if (getLangOpts().CPlusPlus11) {
13832 Diag(VDecl->getLocation(),
13833 diag::ext_in_class_initializer_float_type_cxx11)
13834 << DclT << Init->getSourceRange();
13835 Diag(VDecl->getBeginLoc(),
13836 diag::note_in_class_initializer_float_type_cxx11)
13837 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13838 } else {
13839 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13840 << DclT << Init->getSourceRange();
13841
13842 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
13843 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13844 << Init->getSourceRange();
13845 VDecl->setInvalidDecl();
13846 }
13847 }
13848
13849 // Suggest adding 'constexpr' in C++11 for literal types.
13850 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
13851 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13852 << DclT << Init->getSourceRange()
13853 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13854 VDecl->setConstexpr(true);
13855
13856 } else {
13857 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13858 << DclT << Init->getSourceRange();
13859 VDecl->setInvalidDecl();
13860 }
13861 } else if (VDecl->isFileVarDecl()) {
13862 // In C, extern is typically used to avoid tentative definitions when
13863 // declaring variables in headers, but adding an intializer makes it a
13864 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13865 // In C++, extern is often used to give implictly static const variables
13866 // external linkage, so don't warn in that case. If selectany is present,
13867 // this might be header code intended for C and C++ inclusion, so apply the
13868 // C++ rules.
13869 if (VDecl->getStorageClass() == SC_Extern &&
13870 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13871 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13872 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13873 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13874 Diag(VDecl->getLocation(), diag::warn_extern_init);
13875
13876 // In Microsoft C++ mode, a const variable defined in namespace scope has
13877 // external linkage by default if the variable is declared with
13878 // __declspec(dllexport).
13879 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13880 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13881 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13882 VDecl->setStorageClass(SC_Extern);
13883
13884 // C99 6.7.8p4. All file scoped initializers need to be constant.
13885 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13886 CheckForConstantInitializer(Init, DclT);
13887 }
13888
13889 QualType InitType = Init->getType();
13890 if (!InitType.isNull() &&
13891 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13892 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13893 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
13894
13895 // We will represent direct-initialization similarly to copy-initialization:
13896 // int x(1); -as-> int x = 1;
13897 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13898 //
13899 // Clients that want to distinguish between the two forms, can check for
13900 // direct initializer using VarDecl::getInitStyle().
13901 // A major benefit is that clients that don't particularly care about which
13902 // exactly form was it (like the CodeGen) can handle both cases without
13903 // special case code.
13904
13905 // C++ 8.5p11:
13906 // The form of initialization (using parentheses or '=') is generally
13907 // insignificant, but does matter when the entity being initialized has a
13908 // class type.
13909 if (CXXDirectInit) {
13910 assert(DirectInit && "Call-style initializer must be direct init.");
13911 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13912 : VarDecl::CallInit);
13913 } else if (DirectInit) {
13914 // This must be list-initialization. No other way is direct-initialization.
13915 VDecl->setInitStyle(VarDecl::ListInit);
13916 }
13917
13918 if (LangOpts.OpenMP &&
13919 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13920 VDecl->isFileVarDecl())
13921 DeclsToCheckForDeferredDiags.insert(VDecl);
13922 CheckCompleteVariableDeclaration(VD: VDecl);
13923}
13924
13925/// ActOnInitializerError - Given that there was an error parsing an
13926/// initializer for the given declaration, try to at least re-establish
13927/// invariants such as whether a variable's type is either dependent or
13928/// complete.
13929void Sema::ActOnInitializerError(Decl *D) {
13930 // Our main concern here is re-establishing invariants like "a
13931 // variable's type is either dependent or complete".
13932 if (!D || D->isInvalidDecl()) return;
13933
13934 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
13935 if (!VD) return;
13936
13937 // Bindings are not usable if we can't make sense of the initializer.
13938 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
13939 for (auto *BD : DD->bindings())
13940 BD->setInvalidDecl();
13941
13942 // Auto types are meaningless if we can't make sense of the initializer.
13943 if (VD->getType()->isUndeducedType()) {
13944 D->setInvalidDecl();
13945 return;
13946 }
13947
13948 QualType Ty = VD->getType();
13949 if (Ty->isDependentType()) return;
13950
13951 // Require a complete type.
13952 if (RequireCompleteType(VD->getLocation(),
13953 Context.getBaseElementType(Ty),
13954 diag::err_typecheck_decl_incomplete_type)) {
13955 VD->setInvalidDecl();
13956 return;
13957 }
13958
13959 // Require a non-abstract type.
13960 if (RequireNonAbstractType(VD->getLocation(), Ty,
13961 diag::err_abstract_type_in_decl,
13962 AbstractVariableType)) {
13963 VD->setInvalidDecl();
13964 return;
13965 }
13966
13967 // Don't bother complaining about constructors or destructors,
13968 // though.
13969}
13970
13971void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13972 // If there is no declaration, there was an error parsing it. Just ignore it.
13973 if (!RealDecl)
13974 return;
13975
13976 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
13977 QualType Type = Var->getType();
13978
13979 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13980 if (isa<DecompositionDecl>(Val: RealDecl)) {
13981 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13982 Var->setInvalidDecl();
13983 return;
13984 }
13985
13986 if (Type->isUndeducedType() &&
13987 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
13988 return;
13989
13990 // C++11 [class.static.data]p3: A static data member can be declared with
13991 // the constexpr specifier; if so, its declaration shall specify
13992 // a brace-or-equal-initializer.
13993 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13994 // the definition of a variable [...] or the declaration of a static data
13995 // member.
13996 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13997 !Var->isThisDeclarationADemotedDefinition()) {
13998 if (Var->isStaticDataMember()) {
13999 // C++1z removes the relevant rule; the in-class declaration is always
14000 // a definition there.
14001 if (!getLangOpts().CPlusPlus17 &&
14002 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14003 Diag(Var->getLocation(),
14004 diag::err_constexpr_static_mem_var_requires_init)
14005 << Var;
14006 Var->setInvalidDecl();
14007 return;
14008 }
14009 } else {
14010 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14011 Var->setInvalidDecl();
14012 return;
14013 }
14014 }
14015
14016 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14017 // be initialized.
14018 if (!Var->isInvalidDecl() &&
14019 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14020 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14021 bool HasConstExprDefaultConstructor = false;
14022 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14023 for (auto *Ctor : RD->ctors()) {
14024 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14025 Ctor->getMethodQualifiers().getAddressSpace() ==
14026 LangAS::opencl_constant) {
14027 HasConstExprDefaultConstructor = true;
14028 }
14029 }
14030 }
14031 if (!HasConstExprDefaultConstructor) {
14032 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14033 Var->setInvalidDecl();
14034 return;
14035 }
14036 }
14037
14038 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14039 if (Var->getStorageClass() == SC_Extern) {
14040 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14041 << Var;
14042 Var->setInvalidDecl();
14043 return;
14044 }
14045 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14046 diag::err_typecheck_decl_incomplete_type)) {
14047 Var->setInvalidDecl();
14048 return;
14049 }
14050 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14051 if (!RD->hasTrivialDefaultConstructor()) {
14052 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14053 Var->setInvalidDecl();
14054 return;
14055 }
14056 }
14057 // The declaration is unitialized, no need for further checks.
14058 return;
14059 }
14060
14061 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14062 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14063 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14064 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14065 UseContext: NTCUC_DefaultInitializedObject, NonTrivialKind: NTCUK_Init);
14066
14067
14068 switch (DefKind) {
14069 case VarDecl::Definition:
14070 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14071 break;
14072
14073 // We have an out-of-line definition of a static data member
14074 // that has an in-class initializer, so we type-check this like
14075 // a declaration.
14076 //
14077 [[fallthrough]];
14078
14079 case VarDecl::DeclarationOnly:
14080 // It's only a declaration.
14081
14082 // Block scope. C99 6.7p7: If an identifier for an object is
14083 // declared with no linkage (C99 6.2.2p6), the type for the
14084 // object shall be complete.
14085 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14086 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14087 RequireCompleteType(Var->getLocation(), Type,
14088 diag::err_typecheck_decl_incomplete_type))
14089 Var->setInvalidDecl();
14090
14091 // Make sure that the type is not abstract.
14092 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14093 RequireNonAbstractType(Var->getLocation(), Type,
14094 diag::err_abstract_type_in_decl,
14095 AbstractVariableType))
14096 Var->setInvalidDecl();
14097 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14098 Var->getStorageClass() == SC_PrivateExtern) {
14099 Diag(Var->getLocation(), diag::warn_private_extern);
14100 Diag(Var->getLocation(), diag::note_private_extern);
14101 }
14102
14103 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14104 !Var->isInvalidDecl())
14105 ExternalDeclarations.push_back(Elt: Var);
14106
14107 return;
14108
14109 case VarDecl::TentativeDefinition:
14110 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14111 // object that has file scope without an initializer, and without a
14112 // storage-class specifier or with the storage-class specifier "static",
14113 // constitutes a tentative definition. Note: A tentative definition with
14114 // external linkage is valid (C99 6.2.2p5).
14115 if (!Var->isInvalidDecl()) {
14116 if (const IncompleteArrayType *ArrayT
14117 = Context.getAsIncompleteArrayType(T: Type)) {
14118 if (RequireCompleteSizedType(
14119 Var->getLocation(), ArrayT->getElementType(),
14120 diag::err_array_incomplete_or_sizeless_type))
14121 Var->setInvalidDecl();
14122 } else if (Var->getStorageClass() == SC_Static) {
14123 // C99 6.9.2p3: If the declaration of an identifier for an object is
14124 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14125 // declared type shall not be an incomplete type.
14126 // NOTE: code such as the following
14127 // static struct s;
14128 // struct s { int a; };
14129 // is accepted by gcc. Hence here we issue a warning instead of
14130 // an error and we do not invalidate the static declaration.
14131 // NOTE: to avoid multiple warnings, only check the first declaration.
14132 if (Var->isFirstDecl())
14133 RequireCompleteType(Var->getLocation(), Type,
14134 diag::ext_typecheck_decl_incomplete_type);
14135 }
14136 }
14137
14138 // Record the tentative definition; we're done.
14139 if (!Var->isInvalidDecl())
14140 TentativeDefinitions.push_back(LocalValue: Var);
14141 return;
14142 }
14143
14144 // Provide a specific diagnostic for uninitialized variable
14145 // definitions with incomplete array type.
14146 if (Type->isIncompleteArrayType()) {
14147 if (Var->isConstexpr())
14148 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14149 << Var;
14150 else
14151 Diag(Var->getLocation(),
14152 diag::err_typecheck_incomplete_array_needs_initializer);
14153 Var->setInvalidDecl();
14154 return;
14155 }
14156
14157 // Provide a specific diagnostic for uninitialized variable
14158 // definitions with reference type.
14159 if (Type->isReferenceType()) {
14160 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14161 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14162 return;
14163 }
14164
14165 // Do not attempt to type-check the default initializer for a
14166 // variable with dependent type.
14167 if (Type->isDependentType())
14168 return;
14169
14170 if (Var->isInvalidDecl())
14171 return;
14172
14173 if (!Var->hasAttr<AliasAttr>()) {
14174 if (RequireCompleteType(Var->getLocation(),
14175 Context.getBaseElementType(Type),
14176 diag::err_typecheck_decl_incomplete_type)) {
14177 Var->setInvalidDecl();
14178 return;
14179 }
14180 } else {
14181 return;
14182 }
14183
14184 // The variable can not have an abstract class type.
14185 if (RequireNonAbstractType(Var->getLocation(), Type,
14186 diag::err_abstract_type_in_decl,
14187 AbstractVariableType)) {
14188 Var->setInvalidDecl();
14189 return;
14190 }
14191
14192 // Check for jumps past the implicit initializer. C++0x
14193 // clarifies that this applies to a "variable with automatic
14194 // storage duration", not a "local variable".
14195 // C++11 [stmt.dcl]p3
14196 // A program that jumps from a point where a variable with automatic
14197 // storage duration is not in scope to a point where it is in scope is
14198 // ill-formed unless the variable has scalar type, class type with a
14199 // trivial default constructor and a trivial destructor, a cv-qualified
14200 // version of one of these types, or an array of one of the preceding
14201 // types and is declared without an initializer.
14202 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14203 if (const RecordType *Record
14204 = Context.getBaseElementType(QT: Type)->getAs<RecordType>()) {
14205 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record->getDecl());
14206 // Mark the function (if we're in one) for further checking even if the
14207 // looser rules of C++11 do not require such checks, so that we can
14208 // diagnose incompatibilities with C++98.
14209 if (!CXXRecord->isPOD())
14210 setFunctionHasBranchProtectedScope();
14211 }
14212 }
14213 // In OpenCL, we can't initialize objects in the __local address space,
14214 // even implicitly, so don't synthesize an implicit initializer.
14215 if (getLangOpts().OpenCL &&
14216 Var->getType().getAddressSpace() == LangAS::opencl_local)
14217 return;
14218 // C++03 [dcl.init]p9:
14219 // If no initializer is specified for an object, and the
14220 // object is of (possibly cv-qualified) non-POD class type (or
14221 // array thereof), the object shall be default-initialized; if
14222 // the object is of const-qualified type, the underlying class
14223 // type shall have a user-declared default
14224 // constructor. Otherwise, if no initializer is specified for
14225 // a non- static object, the object and its subobjects, if
14226 // any, have an indeterminate initial value); if the object
14227 // or any of its subobjects are of const-qualified type, the
14228 // program is ill-formed.
14229 // C++0x [dcl.init]p11:
14230 // If no initializer is specified for an object, the object is
14231 // default-initialized; [...].
14232 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14233 InitializationKind Kind
14234 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14235
14236 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14237 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: std::nullopt);
14238
14239 if (Init.get()) {
14240 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14241 // This is important for template substitution.
14242 Var->setInitStyle(VarDecl::CallInit);
14243 } else if (Init.isInvalid()) {
14244 // If default-init fails, attach a recovery-expr initializer to track
14245 // that initialization was attempted and failed.
14246 auto RecoveryExpr =
14247 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14248 if (RecoveryExpr.get())
14249 Var->setInit(RecoveryExpr.get());
14250 }
14251
14252 CheckCompleteVariableDeclaration(VD: Var);
14253 }
14254}
14255
14256void Sema::ActOnCXXForRangeDecl(Decl *D) {
14257 // If there is no declaration, there was an error parsing it. Ignore it.
14258 if (!D)
14259 return;
14260
14261 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14262 if (!VD) {
14263 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14264 D->setInvalidDecl();
14265 return;
14266 }
14267
14268 VD->setCXXForRangeDecl(true);
14269
14270 // for-range-declaration cannot be given a storage class specifier.
14271 int Error = -1;
14272 switch (VD->getStorageClass()) {
14273 case SC_None:
14274 break;
14275 case SC_Extern:
14276 Error = 0;
14277 break;
14278 case SC_Static:
14279 Error = 1;
14280 break;
14281 case SC_PrivateExtern:
14282 Error = 2;
14283 break;
14284 case SC_Auto:
14285 Error = 3;
14286 break;
14287 case SC_Register:
14288 Error = 4;
14289 break;
14290 }
14291
14292 // for-range-declaration cannot be given a storage class specifier con't.
14293 switch (VD->getTSCSpec()) {
14294 case TSCS_thread_local:
14295 Error = 6;
14296 break;
14297 case TSCS___thread:
14298 case TSCS__Thread_local:
14299 case TSCS_unspecified:
14300 break;
14301 }
14302
14303 if (Error != -1) {
14304 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14305 << VD << Error;
14306 D->setInvalidDecl();
14307 }
14308}
14309
14310StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14311 IdentifierInfo *Ident,
14312 ParsedAttributes &Attrs) {
14313 // C++1y [stmt.iter]p1:
14314 // A range-based for statement of the form
14315 // for ( for-range-identifier : for-range-initializer ) statement
14316 // is equivalent to
14317 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14318 DeclSpec DS(Attrs.getPool().getFactory());
14319
14320 const char *PrevSpec;
14321 unsigned DiagID;
14322 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14323 Policy: getPrintingPolicy());
14324
14325 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14326 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14327 D.takeAttributes(attrs&: Attrs);
14328
14329 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14330 EndLoc: IdentLoc);
14331 Decl *Var = ActOnDeclarator(S, D);
14332 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14333 FinalizeDeclaration(D: Var);
14334 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14335 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14336 : IdentLoc);
14337}
14338
14339void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14340 if (var->isInvalidDecl()) return;
14341
14342 MaybeAddCUDAConstantAttr(VD: var);
14343
14344 if (getLangOpts().OpenCL) {
14345 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14346 // initialiser
14347 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14348 !var->hasInit()) {
14349 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14350 << 1 /*Init*/;
14351 var->setInvalidDecl();
14352 return;
14353 }
14354 }
14355
14356 // In Objective-C, don't allow jumps past the implicit initialization of a
14357 // local retaining variable.
14358 if (getLangOpts().ObjC &&
14359 var->hasLocalStorage()) {
14360 switch (var->getType().getObjCLifetime()) {
14361 case Qualifiers::OCL_None:
14362 case Qualifiers::OCL_ExplicitNone:
14363 case Qualifiers::OCL_Autoreleasing:
14364 break;
14365
14366 case Qualifiers::OCL_Weak:
14367 case Qualifiers::OCL_Strong:
14368 setFunctionHasBranchProtectedScope();
14369 break;
14370 }
14371 }
14372
14373 if (var->hasLocalStorage() &&
14374 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14375 setFunctionHasBranchProtectedScope();
14376
14377 // Warn about externally-visible variables being defined without a
14378 // prior declaration. We only want to do this for global
14379 // declarations, but we also specifically need to avoid doing it for
14380 // class members because the linkage of an anonymous class can
14381 // change if it's later given a typedef name.
14382 if (var->isThisDeclarationADefinition() &&
14383 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14384 var->isExternallyVisible() && var->hasLinkage() &&
14385 !var->isInline() && !var->getDescribedVarTemplate() &&
14386 var->getStorageClass() != SC_Register &&
14387 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14388 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14389 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14390 var->getLocation())) {
14391 // Find a previous declaration that's not a definition.
14392 VarDecl *prev = var->getPreviousDecl();
14393 while (prev && prev->isThisDeclarationADefinition())
14394 prev = prev->getPreviousDecl();
14395
14396 if (!prev) {
14397 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14398 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14399 << /* variable */ 0;
14400 }
14401 }
14402
14403 // Cache the result of checking for constant initialization.
14404 std::optional<bool> CacheHasConstInit;
14405 const Expr *CacheCulprit = nullptr;
14406 auto checkConstInit = [&]() mutable {
14407 if (!CacheHasConstInit)
14408 CacheHasConstInit = var->getInit()->isConstantInitializer(
14409 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14410 return *CacheHasConstInit;
14411 };
14412
14413 if (var->getTLSKind() == VarDecl::TLS_Static) {
14414 if (var->getType().isDestructedType()) {
14415 // GNU C++98 edits for __thread, [basic.start.term]p3:
14416 // The type of an object with thread storage duration shall not
14417 // have a non-trivial destructor.
14418 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14419 if (getLangOpts().CPlusPlus11)
14420 Diag(var->getLocation(), diag::note_use_thread_local);
14421 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14422 if (!checkConstInit()) {
14423 // GNU C++98 edits for __thread, [basic.start.init]p4:
14424 // An object of thread storage duration shall not require dynamic
14425 // initialization.
14426 // FIXME: Need strict checking here.
14427 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14428 << CacheCulprit->getSourceRange();
14429 if (getLangOpts().CPlusPlus11)
14430 Diag(var->getLocation(), diag::note_use_thread_local);
14431 }
14432 }
14433 }
14434
14435
14436 if (!var->getType()->isStructureType() && var->hasInit() &&
14437 isa<InitListExpr>(Val: var->getInit())) {
14438 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14439 unsigned NumInits = ILE->getNumInits();
14440 if (NumInits > 2)
14441 for (unsigned I = 0; I < NumInits; ++I) {
14442 const auto *Init = ILE->getInit(Init: I);
14443 if (!Init)
14444 break;
14445 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14446 if (!SL)
14447 break;
14448
14449 unsigned NumConcat = SL->getNumConcatenated();
14450 // Diagnose missing comma in string array initialization.
14451 // Do not warn when all the elements in the initializer are concatenated
14452 // together. Do not warn for macros too.
14453 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14454 bool OnlyOneMissingComma = true;
14455 for (unsigned J = I + 1; J < NumInits; ++J) {
14456 const auto *Init = ILE->getInit(Init: J);
14457 if (!Init)
14458 break;
14459 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14460 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14461 OnlyOneMissingComma = false;
14462 break;
14463 }
14464 }
14465
14466 if (OnlyOneMissingComma) {
14467 SmallVector<FixItHint, 1> Hints;
14468 for (unsigned i = 0; i < NumConcat - 1; ++i)
14469 Hints.push_back(Elt: FixItHint::CreateInsertion(
14470 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14471
14472 Diag(SL->getStrTokenLoc(1),
14473 diag::warn_concatenated_literal_array_init)
14474 << Hints;
14475 Diag(SL->getBeginLoc(),
14476 diag::note_concatenated_string_literal_silence);
14477 }
14478 // In any case, stop now.
14479 break;
14480 }
14481 }
14482 }
14483
14484
14485 QualType type = var->getType();
14486
14487 if (var->hasAttr<BlocksAttr>())
14488 getCurFunction()->addByrefBlockVar(VD: var);
14489
14490 Expr *Init = var->getInit();
14491 bool GlobalStorage = var->hasGlobalStorage();
14492 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14493 QualType baseType = Context.getBaseElementType(QT: type);
14494 bool HasConstInit = true;
14495
14496 // Check whether the initializer is sufficiently constant.
14497 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14498 !Init->isValueDependent() &&
14499 (GlobalStorage || var->isConstexpr() ||
14500 var->mightBeUsableInConstantExpressions(C: Context))) {
14501 // If this variable might have a constant initializer or might be usable in
14502 // constant expressions, check whether or not it actually is now. We can't
14503 // do this lazily, because the result might depend on things that change
14504 // later, such as which constexpr functions happen to be defined.
14505 SmallVector<PartialDiagnosticAt, 8> Notes;
14506 if (!getLangOpts().CPlusPlus11) {
14507 // Prior to C++11, in contexts where a constant initializer is required,
14508 // the set of valid constant initializers is described by syntactic rules
14509 // in [expr.const]p2-6.
14510 // FIXME: Stricter checking for these rules would be useful for constinit /
14511 // -Wglobal-constructors.
14512 HasConstInit = checkConstInit();
14513
14514 // Compute and cache the constant value, and remember that we have a
14515 // constant initializer.
14516 if (HasConstInit) {
14517 (void)var->checkForConstantInitialization(Notes);
14518 Notes.clear();
14519 } else if (CacheCulprit) {
14520 Notes.emplace_back(CacheCulprit->getExprLoc(),
14521 PDiag(diag::note_invalid_subexpr_in_const_expr));
14522 Notes.back().second << CacheCulprit->getSourceRange();
14523 }
14524 } else {
14525 // Evaluate the initializer to see if it's a constant initializer.
14526 HasConstInit = var->checkForConstantInitialization(Notes);
14527 }
14528
14529 if (HasConstInit) {
14530 // FIXME: Consider replacing the initializer with a ConstantExpr.
14531 } else if (var->isConstexpr()) {
14532 SourceLocation DiagLoc = var->getLocation();
14533 // If the note doesn't add any useful information other than a source
14534 // location, fold it into the primary diagnostic.
14535 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14536 diag::note_invalid_subexpr_in_const_expr) {
14537 DiagLoc = Notes[0].first;
14538 Notes.clear();
14539 }
14540 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14541 << var << Init->getSourceRange();
14542 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14543 Diag(Loc: Notes[I].first, PD: Notes[I].second);
14544 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14545 auto *Attr = var->getAttr<ConstInitAttr>();
14546 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14547 << Init->getSourceRange();
14548 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14549 << Attr->getRange() << Attr->isConstinit();
14550 for (auto &it : Notes)
14551 Diag(Loc: it.first, PD: it.second);
14552 } else if (IsGlobal &&
14553 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14554 var->getLocation())) {
14555 // Warn about globals which don't have a constant initializer. Don't
14556 // warn about globals with a non-trivial destructor because we already
14557 // warned about them.
14558 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14559 if (!(RD && !RD->hasTrivialDestructor())) {
14560 // checkConstInit() here permits trivial default initialization even in
14561 // C++11 onwards, where such an initializer is not a constant initializer
14562 // but nonetheless doesn't require a global constructor.
14563 if (!checkConstInit())
14564 Diag(var->getLocation(), diag::warn_global_constructor)
14565 << Init->getSourceRange();
14566 }
14567 }
14568 }
14569
14570 // Apply section attributes and pragmas to global variables.
14571 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14572 !inTemplateInstantiation()) {
14573 PragmaStack<StringLiteral *> *Stack = nullptr;
14574 int SectionFlags = ASTContext::PSF_Read;
14575 bool MSVCEnv =
14576 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14577 std::optional<QualType::NonConstantStorageReason> Reason;
14578 if (HasConstInit &&
14579 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14580 Stack = &ConstSegStack;
14581 } else {
14582 SectionFlags |= ASTContext::PSF_Write;
14583 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14584 }
14585 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14586 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14587 SectionFlags |= ASTContext::PSF_Implicit;
14588 UnifySection(SA->getName(), SectionFlags, var);
14589 } else if (Stack->CurrentValue) {
14590 if (Stack != &ConstSegStack && MSVCEnv &&
14591 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14592 var->getType().isConstQualified()) {
14593 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14594 NonConstNonReferenceType) &&
14595 "This case should've already been handled elsewhere");
14596 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14597 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14598 ? QualType::NonConstantStorageReason::NonTrivialCtor
14599 : *Reason);
14600 }
14601 SectionFlags |= ASTContext::PSF_Implicit;
14602 auto SectionName = Stack->CurrentValue->getString();
14603 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14604 Stack->CurrentPragmaLocation,
14605 SectionAttr::Declspec_allocate));
14606 if (UnifySection(SectionName, SectionFlags, var))
14607 var->dropAttr<SectionAttr>();
14608 }
14609
14610 // Apply the init_seg attribute if this has an initializer. If the
14611 // initializer turns out to not be dynamic, we'll end up ignoring this
14612 // attribute.
14613 if (CurInitSeg && var->getInit())
14614 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14615 CurInitSegLoc));
14616 }
14617
14618 // All the following checks are C++ only.
14619 if (!getLangOpts().CPlusPlus) {
14620 // If this variable must be emitted, add it as an initializer for the
14621 // current module.
14622 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14623 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14624 return;
14625 }
14626
14627 // Require the destructor.
14628 if (!type->isDependentType())
14629 if (const RecordType *recordType = baseType->getAs<RecordType>())
14630 FinalizeVarWithDestructor(VD: var, DeclInitType: recordType);
14631
14632 // If this variable must be emitted, add it as an initializer for the current
14633 // module.
14634 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14635 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14636
14637 // Build the bindings if this is a structured binding declaration.
14638 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
14639 CheckCompleteDecompositionDeclaration(DD);
14640}
14641
14642/// Check if VD needs to be dllexport/dllimport due to being in a
14643/// dllexport/import function.
14644void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14645 assert(VD->isStaticLocal());
14646
14647 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14648
14649 // Find outermost function when VD is in lambda function.
14650 while (FD && !getDLLAttr(FD) &&
14651 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14652 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14653 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14654 }
14655
14656 if (!FD)
14657 return;
14658
14659 // Static locals inherit dll attributes from their function.
14660 if (Attr *A = getDLLAttr(FD)) {
14661 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
14662 NewAttr->setInherited(true);
14663 VD->addAttr(A: NewAttr);
14664 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14665 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14666 NewAttr->setInherited(true);
14667 VD->addAttr(A: NewAttr);
14668
14669 // Export this function to enforce exporting this static variable even
14670 // if it is not used in this compilation unit.
14671 if (!FD->hasAttr<DLLExportAttr>())
14672 FD->addAttr(NewAttr);
14673
14674 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14675 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14676 NewAttr->setInherited(true);
14677 VD->addAttr(A: NewAttr);
14678 }
14679}
14680
14681void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14682 assert(VD->getTLSKind());
14683
14684 // Perform TLS alignment check here after attributes attached to the variable
14685 // which may affect the alignment have been processed. Only perform the check
14686 // if the target has a maximum TLS alignment (zero means no constraints).
14687 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14688 // Protect the check so that it's not performed on dependent types and
14689 // dependent alignments (we can't determine the alignment in that case).
14690 if (!VD->hasDependentAlignment()) {
14691 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
14692 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14693 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14694 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14695 << (unsigned)MaxAlignChars.getQuantity();
14696 }
14697 }
14698 }
14699}
14700
14701/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14702/// any semantic actions necessary after any initializer has been attached.
14703void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14704 // Note that we are no longer parsing the initializer for this declaration.
14705 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
14706
14707 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
14708 if (!VD)
14709 return;
14710
14711 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14712 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14713 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14714 if (PragmaClangBSSSection.Valid)
14715 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14716 Context, PragmaClangBSSSection.SectionName,
14717 PragmaClangBSSSection.PragmaLocation));
14718 if (PragmaClangDataSection.Valid)
14719 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14720 Context, PragmaClangDataSection.SectionName,
14721 PragmaClangDataSection.PragmaLocation));
14722 if (PragmaClangRodataSection.Valid)
14723 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14724 Context, PragmaClangRodataSection.SectionName,
14725 PragmaClangRodataSection.PragmaLocation));
14726 if (PragmaClangRelroSection.Valid)
14727 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14728 Context, PragmaClangRelroSection.SectionName,
14729 PragmaClangRelroSection.PragmaLocation));
14730 }
14731
14732 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
14733 for (auto *BD : DD->bindings()) {
14734 FinalizeDeclaration(BD);
14735 }
14736 }
14737
14738 checkAttributesAfterMerging(*this, *VD);
14739
14740 if (VD->isStaticLocal())
14741 CheckStaticLocalForDllExport(VD);
14742
14743 if (VD->getTLSKind())
14744 CheckThreadLocalForLargeAlignment(VD);
14745
14746 // Perform check for initializers of device-side global variables.
14747 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14748 // 7.5). We must also apply the same checks to all __shared__
14749 // variables whether they are local or not. CUDA also allows
14750 // constant initializers for __constant__ and __device__ variables.
14751 if (getLangOpts().CUDA)
14752 checkAllowedCUDAInitializer(VD);
14753
14754 // Grab the dllimport or dllexport attribute off of the VarDecl.
14755 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14756
14757 // Imported static data members cannot be defined out-of-line.
14758 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14759 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14760 VD->isThisDeclarationADefinition()) {
14761 // We allow definitions of dllimport class template static data members
14762 // with a warning.
14763 CXXRecordDecl *Context =
14764 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14765 bool IsClassTemplateMember =
14766 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
14767 Context->getDescribedClassTemplate();
14768
14769 Diag(VD->getLocation(),
14770 IsClassTemplateMember
14771 ? diag::warn_attribute_dllimport_static_field_definition
14772 : diag::err_attribute_dllimport_static_field_definition);
14773 Diag(IA->getLocation(), diag::note_attribute);
14774 if (!IsClassTemplateMember)
14775 VD->setInvalidDecl();
14776 }
14777 }
14778
14779 // dllimport/dllexport variables cannot be thread local, their TLS index
14780 // isn't exported with the variable.
14781 if (DLLAttr && VD->getTLSKind()) {
14782 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14783 if (F && getDLLAttr(F)) {
14784 assert(VD->isStaticLocal());
14785 // But if this is a static local in a dlimport/dllexport function, the
14786 // function will never be inlined, which means the var would never be
14787 // imported, so having it marked import/export is safe.
14788 } else {
14789 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14790 << DLLAttr;
14791 VD->setInvalidDecl();
14792 }
14793 }
14794
14795 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14796 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14797 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14798 << Attr;
14799 VD->dropAttr<UsedAttr>();
14800 }
14801 }
14802 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14803 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14804 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14805 << Attr;
14806 VD->dropAttr<RetainAttr>();
14807 }
14808 }
14809
14810 const DeclContext *DC = VD->getDeclContext();
14811 // If there's a #pragma GCC visibility in scope, and this isn't a class
14812 // member, set the visibility of this variable.
14813 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14814 AddPushedVisibilityAttribute(VD);
14815
14816 // FIXME: Warn on unused var template partial specializations.
14817 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
14818 MarkUnusedFileScopedDecl(VD);
14819
14820 // Now we have parsed the initializer and can update the table of magic
14821 // tag values.
14822 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14823 !VD->getType()->isIntegralOrEnumerationType())
14824 return;
14825
14826 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14827 const Expr *MagicValueExpr = VD->getInit();
14828 if (!MagicValueExpr) {
14829 continue;
14830 }
14831 std::optional<llvm::APSInt> MagicValueInt;
14832 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14833 Diag(I->getRange().getBegin(),
14834 diag::err_type_tag_for_datatype_not_ice)
14835 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14836 continue;
14837 }
14838 if (MagicValueInt->getActiveBits() > 64) {
14839 Diag(I->getRange().getBegin(),
14840 diag::err_type_tag_for_datatype_too_large)
14841 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14842 continue;
14843 }
14844 uint64_t MagicValue = MagicValueInt->getZExtValue();
14845 RegisterTypeTagForDatatype(I->getArgumentKind(),
14846 MagicValue,
14847 I->getMatchingCType(),
14848 I->getLayoutCompatible(),
14849 I->getMustBeNull());
14850 }
14851}
14852
14853static bool hasDeducedAuto(DeclaratorDecl *DD) {
14854 auto *VD = dyn_cast<VarDecl>(Val: DD);
14855 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14856}
14857
14858Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14859 ArrayRef<Decl *> Group) {
14860 SmallVector<Decl*, 8> Decls;
14861
14862 if (DS.isTypeSpecOwned())
14863 Decls.push_back(Elt: DS.getRepAsDecl());
14864
14865 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14866 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14867 bool DiagnosedMultipleDecomps = false;
14868 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14869 bool DiagnosedNonDeducedAuto = false;
14870
14871 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14872 if (Decl *D = Group[i]) {
14873 // Check if the Decl has been declared in '#pragma omp declare target'
14874 // directive and has static storage duration.
14875 if (auto *VD = dyn_cast<VarDecl>(Val: D);
14876 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14877 VD->hasGlobalStorage())
14878 ActOnOpenMPDeclareTargetInitializer(D);
14879 // For declarators, there are some additional syntactic-ish checks we need
14880 // to perform.
14881 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
14882 if (!FirstDeclaratorInGroup)
14883 FirstDeclaratorInGroup = DD;
14884 if (!FirstDecompDeclaratorInGroup)
14885 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
14886 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14887 !hasDeducedAuto(DD))
14888 FirstNonDeducedAutoInGroup = DD;
14889
14890 if (FirstDeclaratorInGroup != DD) {
14891 // A decomposition declaration cannot be combined with any other
14892 // declaration in the same group.
14893 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14894 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14895 diag::err_decomp_decl_not_alone)
14896 << FirstDeclaratorInGroup->getSourceRange()
14897 << DD->getSourceRange();
14898 DiagnosedMultipleDecomps = true;
14899 }
14900
14901 // A declarator that uses 'auto' in any way other than to declare a
14902 // variable with a deduced type cannot be combined with any other
14903 // declarator in the same group.
14904 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14905 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14906 diag::err_auto_non_deduced_not_alone)
14907 << FirstNonDeducedAutoInGroup->getType()
14908 ->hasAutoForTrailingReturnType()
14909 << FirstDeclaratorInGroup->getSourceRange()
14910 << DD->getSourceRange();
14911 DiagnosedNonDeducedAuto = true;
14912 }
14913 }
14914 }
14915
14916 Decls.push_back(Elt: D);
14917 }
14918 }
14919
14920 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
14921 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
14922 handleTagNumbering(Tag, TagScope: S);
14923 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14924 getLangOpts().CPlusPlus)
14925 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
14926 }
14927 }
14928
14929 return BuildDeclaratorGroup(Group: Decls);
14930}
14931
14932/// BuildDeclaratorGroup - convert a list of declarations into a declaration
14933/// group, performing any necessary semantic checking.
14934Sema::DeclGroupPtrTy
14935Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14936 // C++14 [dcl.spec.auto]p7: (DR1347)
14937 // If the type that replaces the placeholder type is not the same in each
14938 // deduction, the program is ill-formed.
14939 if (Group.size() > 1) {
14940 QualType Deduced;
14941 VarDecl *DeducedDecl = nullptr;
14942 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14943 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
14944 if (!D || D->isInvalidDecl())
14945 break;
14946 DeducedType *DT = D->getType()->getContainedDeducedType();
14947 if (!DT || DT->getDeducedType().isNull())
14948 continue;
14949 if (Deduced.isNull()) {
14950 Deduced = DT->getDeducedType();
14951 DeducedDecl = D;
14952 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
14953 auto *AT = dyn_cast<AutoType>(Val: DT);
14954 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14955 diag::err_auto_different_deductions)
14956 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14957 << DeducedDecl->getDeclName() << DT->getDeducedType()
14958 << D->getDeclName();
14959 if (DeducedDecl->hasInit())
14960 Dia << DeducedDecl->getInit()->getSourceRange();
14961 if (D->getInit())
14962 Dia << D->getInit()->getSourceRange();
14963 D->setInvalidDecl();
14964 break;
14965 }
14966 }
14967 }
14968
14969 ActOnDocumentableDecls(Group);
14970
14971 return DeclGroupPtrTy::make(
14972 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
14973}
14974
14975void Sema::ActOnDocumentableDecl(Decl *D) {
14976 ActOnDocumentableDecls(Group: D);
14977}
14978
14979void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14980 // Don't parse the comment if Doxygen diagnostics are ignored.
14981 if (Group.empty() || !Group[0])
14982 return;
14983
14984 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14985 Group[0]->getLocation()) &&
14986 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14987 Group[0]->getLocation()))
14988 return;
14989
14990 if (Group.size() >= 2) {
14991 // This is a decl group. Normally it will contain only declarations
14992 // produced from declarator list. But in case we have any definitions or
14993 // additional declaration references:
14994 // 'typedef struct S {} S;'
14995 // 'typedef struct S *S;'
14996 // 'struct S *pS;'
14997 // FinalizeDeclaratorGroup adds these as separate declarations.
14998 Decl *MaybeTagDecl = Group[0];
14999 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15000 Group = Group.slice(N: 1);
15001 }
15002 }
15003
15004 // FIMXE: We assume every Decl in the group is in the same file.
15005 // This is false when preprocessor constructs the group from decls in
15006 // different files (e. g. macros or #include).
15007 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15008}
15009
15010/// Common checks for a parameter-declaration that should apply to both function
15011/// parameters and non-type template parameters.
15012void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15013 // Check that there are no default arguments inside the type of this
15014 // parameter.
15015 if (getLangOpts().CPlusPlus)
15016 CheckExtraCXXDefaultArguments(D);
15017
15018 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15019 if (D.getCXXScopeSpec().isSet()) {
15020 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15021 << D.getCXXScopeSpec().getRange();
15022 }
15023
15024 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15025 // simple identifier except [...irrelevant cases...].
15026 switch (D.getName().getKind()) {
15027 case UnqualifiedIdKind::IK_Identifier:
15028 break;
15029
15030 case UnqualifiedIdKind::IK_OperatorFunctionId:
15031 case UnqualifiedIdKind::IK_ConversionFunctionId:
15032 case UnqualifiedIdKind::IK_LiteralOperatorId:
15033 case UnqualifiedIdKind::IK_ConstructorName:
15034 case UnqualifiedIdKind::IK_DestructorName:
15035 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15036 case UnqualifiedIdKind::IK_DeductionGuideName:
15037 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15038 << GetNameForDeclarator(D).getName();
15039 break;
15040
15041 case UnqualifiedIdKind::IK_TemplateId:
15042 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15043 // GetNameForDeclarator would not produce a useful name in this case.
15044 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15045 break;
15046 }
15047}
15048
15049static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15050 SourceLocation ExplicitThisLoc) {
15051 if (!ExplicitThisLoc.isValid())
15052 return;
15053 assert(S.getLangOpts().CPlusPlus &&
15054 "explicit parameter in non-cplusplus mode");
15055 if (!S.getLangOpts().CPlusPlus23)
15056 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15057 << P->getSourceRange();
15058
15059 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15060 // parameter pack.
15061 if (P->isParameterPack()) {
15062 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15063 << P->getSourceRange();
15064 return;
15065 }
15066 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15067 if (LambdaScopeInfo *LSI = S.getCurLambda())
15068 LSI->ExplicitObjectParameter = P;
15069}
15070
15071/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15072/// to introduce parameters into function prototype scope.
15073Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15074 SourceLocation ExplicitThisLoc) {
15075 const DeclSpec &DS = D.getDeclSpec();
15076
15077 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15078
15079 // C++03 [dcl.stc]p2 also permits 'auto'.
15080 StorageClass SC = SC_None;
15081 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15082 SC = SC_Register;
15083 // In C++11, the 'register' storage class specifier is deprecated.
15084 // In C++17, it is not allowed, but we tolerate it as an extension.
15085 if (getLangOpts().CPlusPlus11) {
15086 Diag(DS.getStorageClassSpecLoc(),
15087 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15088 : diag::warn_deprecated_register)
15089 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15090 }
15091 } else if (getLangOpts().CPlusPlus &&
15092 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15093 SC = SC_Auto;
15094 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15095 Diag(DS.getStorageClassSpecLoc(),
15096 diag::err_invalid_storage_class_in_func_decl);
15097 D.getMutableDeclSpec().ClearStorageClassSpecs();
15098 }
15099
15100 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15101 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15102 << DeclSpec::getSpecifierName(TSCS);
15103 if (DS.isInlineSpecified())
15104 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15105 << getLangOpts().CPlusPlus17;
15106 if (DS.hasConstexprSpecifier())
15107 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15108 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15109
15110 DiagnoseFunctionSpecifiers(DS);
15111
15112 CheckFunctionOrTemplateParamDeclarator(S, D);
15113
15114 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15115 QualType parmDeclType = TInfo->getType();
15116
15117 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15118 IdentifierInfo *II = D.getIdentifier();
15119 if (II) {
15120 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15121 ForVisibleRedeclaration);
15122 LookupName(R, S);
15123 if (!R.empty()) {
15124 NamedDecl *PrevDecl = *R.begin();
15125 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15126 // Maybe we will complain about the shadowed template parameter.
15127 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15128 // Just pretend that we didn't see the previous declaration.
15129 PrevDecl = nullptr;
15130 }
15131 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15132 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15133 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15134 // Recover by removing the name
15135 II = nullptr;
15136 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15137 D.setInvalidType(true);
15138 }
15139 }
15140 }
15141
15142 // Temporarily put parameter variables in the translation unit, not
15143 // the enclosing context. This prevents them from accidentally
15144 // looking like class members in C++.
15145 ParmVarDecl *New =
15146 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15147 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15148
15149 if (D.isInvalidType())
15150 New->setInvalidDecl();
15151
15152 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15153
15154 assert(S->isFunctionPrototypeScope());
15155 assert(S->getFunctionPrototypeDepth() >= 1);
15156 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15157 parameterIndex: S->getNextFunctionPrototypeIndex());
15158
15159 // Add the parameter declaration into this scope.
15160 S->AddDecl(New);
15161 if (II)
15162 IdResolver.AddDecl(New);
15163
15164 ProcessDeclAttributes(S, New, D);
15165
15166 if (D.getDeclSpec().isModulePrivateSpecified())
15167 Diag(New->getLocation(), diag::err_module_private_local)
15168 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15169 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15170
15171 if (New->hasAttr<BlocksAttr>()) {
15172 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15173 }
15174
15175 if (getLangOpts().OpenCL)
15176 deduceOpenCLAddressSpace(New);
15177
15178 return New;
15179}
15180
15181/// Synthesizes a variable for a parameter arising from a
15182/// typedef.
15183ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15184 SourceLocation Loc,
15185 QualType T) {
15186 /* FIXME: setting StartLoc == Loc.
15187 Would it be worth to modify callers so as to provide proper source
15188 location for the unnamed parameters, embedding the parameter's type? */
15189 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15190 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15191 S: SC_None, DefArg: nullptr);
15192 Param->setImplicit();
15193 return Param;
15194}
15195
15196void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15197 // Don't diagnose unused-parameter errors in template instantiations; we
15198 // will already have done so in the template itself.
15199 if (inTemplateInstantiation())
15200 return;
15201
15202 for (const ParmVarDecl *Parameter : Parameters) {
15203 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15204 !Parameter->hasAttr<UnusedAttr>() &&
15205 !Parameter->getIdentifier()->isPlaceholder()) {
15206 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15207 << Parameter->getDeclName();
15208 }
15209 }
15210}
15211
15212void Sema::DiagnoseSizeOfParametersAndReturnValue(
15213 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15214 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15215 return;
15216
15217 // Warn if the return value is pass-by-value and larger than the specified
15218 // threshold.
15219 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15220 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15221 if (Size > LangOpts.NumLargeByValueCopy)
15222 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15223 }
15224
15225 // Warn if any parameter is pass-by-value and larger than the specified
15226 // threshold.
15227 for (const ParmVarDecl *Parameter : Parameters) {
15228 QualType T = Parameter->getType();
15229 if (T->isDependentType() || !T.isPODType(Context))
15230 continue;
15231 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15232 if (Size > LangOpts.NumLargeByValueCopy)
15233 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15234 << Parameter << Size;
15235 }
15236}
15237
15238QualType Sema::AdjustParameterTypeForObjCAutoRefCount(QualType T,
15239 SourceLocation NameLoc,
15240 TypeSourceInfo *TSInfo) {
15241 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15242 if (!getLangOpts().ObjCAutoRefCount ||
15243 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType())
15244 return T;
15245
15246 Qualifiers::ObjCLifetime Lifetime;
15247
15248 // Special cases for arrays:
15249 // - if it's const, use __unsafe_unretained
15250 // - otherwise, it's an error
15251 if (T->isArrayType()) {
15252 if (!T.isConstQualified()) {
15253 if (DelayedDiagnostics.shouldDelayDiagnostics())
15254 DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType(
15255 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15256 else
15257 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15258 << TSInfo->getTypeLoc().getSourceRange();
15259 }
15260 Lifetime = Qualifiers::OCL_ExplicitNone;
15261 } else {
15262 Lifetime = T->getObjCARCImplicitLifetime();
15263 }
15264 T = Context.getLifetimeQualifiedType(type: T, lifetime: Lifetime);
15265
15266 return T;
15267}
15268
15269ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15270 SourceLocation NameLoc, IdentifierInfo *Name,
15271 QualType T, TypeSourceInfo *TSInfo,
15272 StorageClass SC) {
15273 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15274 if (getLangOpts().ObjCAutoRefCount &&
15275 T.getObjCLifetime() == Qualifiers::OCL_None &&
15276 T->isObjCLifetimeType()) {
15277
15278 Qualifiers::ObjCLifetime lifetime;
15279
15280 // Special cases for arrays:
15281 // - if it's const, use __unsafe_unretained
15282 // - otherwise, it's an error
15283 if (T->isArrayType()) {
15284 if (!T.isConstQualified()) {
15285 if (DelayedDiagnostics.shouldDelayDiagnostics())
15286 DelayedDiagnostics.add(
15287 sema::DelayedDiagnostic::makeForbiddenType(
15288 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15289 else
15290 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15291 << TSInfo->getTypeLoc().getSourceRange();
15292 }
15293 lifetime = Qualifiers::OCL_ExplicitNone;
15294 } else {
15295 lifetime = T->getObjCARCImplicitLifetime();
15296 }
15297 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15298 }
15299
15300 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15301 T: Context.getAdjustedParameterType(T),
15302 TInfo: TSInfo, S: SC, DefArg: nullptr);
15303
15304 // Make a note if we created a new pack in the scope of a lambda, so that
15305 // we know that references to that pack must also be expanded within the
15306 // lambda scope.
15307 if (New->isParameterPack())
15308 if (auto *LSI = getEnclosingLambda())
15309 LSI->LocalPacks.push_back(New);
15310
15311 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15312 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15313 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15314 UseContext: NTCUC_FunctionParam, NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
15315
15316 // Parameter declarators cannot be interface types. All ObjC objects are
15317 // passed by reference.
15318 if (T->isObjCObjectType()) {
15319 SourceLocation TypeEndLoc =
15320 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15321 Diag(NameLoc,
15322 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15323 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15324 T = Context.getObjCObjectPointerType(OIT: T);
15325 New->setType(T);
15326 }
15327
15328 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15329 // duration shall not be qualified by an address-space qualifier."
15330 // Since all parameters have automatic store duration, they can not have
15331 // an address space.
15332 if (T.getAddressSpace() != LangAS::Default &&
15333 // OpenCL allows function arguments declared to be an array of a type
15334 // to be qualified with an address space.
15335 !(getLangOpts().OpenCL &&
15336 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15337 // WebAssembly allows reference types as parameters. Funcref in particular
15338 // lives in a different address space.
15339 !(T->isFunctionPointerType() &&
15340 T.getAddressSpace() == LangAS::wasm_funcref)) {
15341 Diag(NameLoc, diag::err_arg_with_address_space);
15342 New->setInvalidDecl();
15343 }
15344
15345 // PPC MMA non-pointer types are not allowed as function argument types.
15346 if (Context.getTargetInfo().getTriple().isPPC64() &&
15347 CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15348 New->setInvalidDecl();
15349 }
15350
15351 return New;
15352}
15353
15354void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15355 SourceLocation LocAfterDecls) {
15356 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15357
15358 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15359 // in the declaration list shall have at least one declarator, those
15360 // declarators shall only declare identifiers from the identifier list, and
15361 // every identifier in the identifier list shall be declared.
15362 //
15363 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15364 // identifiers it names shall be declared in the declaration list."
15365 //
15366 // This is why we only diagnose in C99 and later. Note, the other conditions
15367 // listed are checked elsewhere.
15368 if (!FTI.hasPrototype) {
15369 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15370 --i;
15371 if (FTI.Params[i].Param == nullptr) {
15372 if (getLangOpts().C99) {
15373 SmallString<256> Code;
15374 llvm::raw_svector_ostream(Code)
15375 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15376 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15377 << FTI.Params[i].Ident
15378 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15379 }
15380
15381 // Implicitly declare the argument as type 'int' for lack of a better
15382 // type.
15383 AttributeFactory attrs;
15384 DeclSpec DS(attrs);
15385 const char* PrevSpec; // unused
15386 unsigned DiagID; // unused
15387 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15388 DiagID, Policy: Context.getPrintingPolicy());
15389 // Use the identifier location for the type source range.
15390 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15391 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15392 Declarator ParamD(DS, ParsedAttributesView::none(),
15393 DeclaratorContext::KNRTypeList);
15394 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15395 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15396 }
15397 }
15398 }
15399}
15400
15401Decl *
15402Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15403 MultiTemplateParamsArg TemplateParameterLists,
15404 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15405 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15406 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15407 Scope *ParentScope = FnBodyScope->getParent();
15408
15409 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15410 // we define a non-templated function definition, we will create a declaration
15411 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15412 // The base function declaration will have the equivalent of an `omp declare
15413 // variant` annotation which specifies the mangled definition as a
15414 // specialization function under the OpenMP context defined as part of the
15415 // `omp begin declare variant`.
15416 SmallVector<FunctionDecl *, 4> Bases;
15417 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15418 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15419 S: ParentScope, D, TemplateParameterLists, Bases);
15420
15421 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15422 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15423 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15424
15425 if (!Bases.empty())
15426 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl, Bases);
15427
15428 return Dcl;
15429}
15430
15431void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15432 Consumer.HandleInlineFunctionDefinition(D);
15433}
15434
15435static bool FindPossiblePrototype(const FunctionDecl *FD,
15436 const FunctionDecl *&PossiblePrototype) {
15437 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15438 Prev = Prev->getPreviousDecl()) {
15439 // Ignore any declarations that occur in function or method
15440 // scope, because they aren't visible from the header.
15441 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15442 continue;
15443
15444 PossiblePrototype = Prev;
15445 return Prev->getType()->isFunctionProtoType();
15446 }
15447 return false;
15448}
15449
15450static bool
15451ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15452 const FunctionDecl *&PossiblePrototype) {
15453 // Don't warn about invalid declarations.
15454 if (FD->isInvalidDecl())
15455 return false;
15456
15457 // Or declarations that aren't global.
15458 if (!FD->isGlobal())
15459 return false;
15460
15461 // Don't warn about C++ member functions.
15462 if (isa<CXXMethodDecl>(Val: FD))
15463 return false;
15464
15465 // Don't warn about 'main'.
15466 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15467 if (IdentifierInfo *II = FD->getIdentifier())
15468 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15469 return false;
15470
15471 // Don't warn about inline functions.
15472 if (FD->isInlined())
15473 return false;
15474
15475 // Don't warn about function templates.
15476 if (FD->getDescribedFunctionTemplate())
15477 return false;
15478
15479 // Don't warn about function template specializations.
15480 if (FD->isFunctionTemplateSpecialization())
15481 return false;
15482
15483 // Don't warn for OpenCL kernels.
15484 if (FD->hasAttr<OpenCLKernelAttr>())
15485 return false;
15486
15487 // Don't warn on explicitly deleted functions.
15488 if (FD->isDeleted())
15489 return false;
15490
15491 // Don't warn on implicitly local functions (such as having local-typed
15492 // parameters).
15493 if (!FD->isExternallyVisible())
15494 return false;
15495
15496 // If we were able to find a potential prototype, don't warn.
15497 if (FindPossiblePrototype(FD, PossiblePrototype))
15498 return false;
15499
15500 return true;
15501}
15502
15503void
15504Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15505 const FunctionDecl *EffectiveDefinition,
15506 SkipBodyInfo *SkipBody) {
15507 const FunctionDecl *Definition = EffectiveDefinition;
15508 if (!Definition &&
15509 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15510 return;
15511
15512 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15513 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15514 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15515 // A merged copy of the same function, instantiated as a member of
15516 // the same class, is OK.
15517 if (declaresSameEntity(OrigFD, OrigDef) &&
15518 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15519 cast<Decl>(FD->getLexicalDeclContext())))
15520 return;
15521 }
15522 }
15523 }
15524
15525 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
15526 return;
15527
15528 // Don't emit an error when this is redefinition of a typo-corrected
15529 // definition.
15530 if (TypoCorrectedFunctionDefinitions.count(Definition))
15531 return;
15532
15533 // If we don't have a visible definition of the function, and it's inline or
15534 // a template, skip the new definition.
15535 if (SkipBody && !hasVisibleDefinition(Definition) &&
15536 (Definition->getFormalLinkage() == Linkage::Internal ||
15537 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15538 Definition->getNumTemplateParameterLists())) {
15539 SkipBody->ShouldSkip = true;
15540 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15541 if (auto *TD = Definition->getDescribedFunctionTemplate())
15542 makeMergedDefinitionVisible(TD);
15543 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15544 return;
15545 }
15546
15547 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15548 Definition->getStorageClass() == SC_Extern)
15549 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15550 << FD << getLangOpts().CPlusPlus;
15551 else
15552 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15553
15554 Diag(Definition->getLocation(), diag::note_previous_definition);
15555 FD->setInvalidDecl();
15556}
15557
15558LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15559 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15560
15561 LambdaScopeInfo *LSI = PushLambdaScope();
15562 LSI->CallOperator = CallOperator;
15563 LSI->Lambda = LambdaClass;
15564 LSI->ReturnType = CallOperator->getReturnType();
15565 // This function in calls in situation where the context of the call operator
15566 // is not entered, so we set AfterParameterList to false, so that
15567 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15568 LSI->AfterParameterList = false;
15569 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15570
15571 if (LCD == LCD_None)
15572 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15573 else if (LCD == LCD_ByCopy)
15574 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15575 else if (LCD == LCD_ByRef)
15576 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15577 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15578
15579 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15580 LSI->Mutable = !CallOperator->isConst();
15581 if (CallOperator->isExplicitObjectMemberFunction())
15582 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15583
15584 // Add the captures to the LSI so they can be noted as already
15585 // captured within tryCaptureVar.
15586 auto I = LambdaClass->field_begin();
15587 for (const auto &C : LambdaClass->captures()) {
15588 if (C.capturesVariable()) {
15589 ValueDecl *VD = C.getCapturedVar();
15590 if (VD->isInitCapture())
15591 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15592 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15593 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
15594 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
15595 /*EllipsisLoc*/C.isPackExpansion()
15596 ? C.getEllipsisLoc() : SourceLocation(),
15597 CaptureType: I->getType(), /*Invalid*/false);
15598
15599 } else if (C.capturesThis()) {
15600 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
15601 ByCopy: C.getCaptureKind() == LCK_StarThis);
15602 } else {
15603 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
15604 CaptureType: I->getType());
15605 }
15606 ++I;
15607 }
15608 return LSI;
15609}
15610
15611Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15612 SkipBodyInfo *SkipBody,
15613 FnBodyKind BodyKind) {
15614 if (!D) {
15615 // Parsing the function declaration failed in some way. Push on a fake scope
15616 // anyway so we can try to parse the function body.
15617 PushFunctionScope();
15618 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
15619 return D;
15620 }
15621
15622 FunctionDecl *FD = nullptr;
15623
15624 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
15625 FD = FunTmpl->getTemplatedDecl();
15626 else
15627 FD = cast<FunctionDecl>(Val: D);
15628
15629 // Do not push if it is a lambda because one is already pushed when building
15630 // the lambda in ActOnStartOfLambdaDefinition().
15631 if (!isLambdaCallOperator(FD))
15632 // [expr.const]/p14.1
15633 // An expression or conversion is in an immediate function context if it is
15634 // potentially evaluated and either: its innermost enclosing non-block scope
15635 // is a function parameter scope of an immediate function.
15636 PushExpressionEvaluationContext(
15637 NewContext: FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15638 : ExprEvalContexts.back().Context);
15639
15640 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15641 // context is nested in an immediate function context, so smaller contexts
15642 // that appear inside immediate functions (like variable initializers) are
15643 // considered to be inside an immediate function context even though by
15644 // themselves they are not immediate function contexts. But when a new
15645 // function is entered, we need to reset this tracking, since the entered
15646 // function might be not an immediate function.
15647 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15648 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15649 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15650
15651 // Check for defining attributes before the check for redefinition.
15652 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15653 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15654 FD->dropAttr<AliasAttr>();
15655 FD->setInvalidDecl();
15656 }
15657 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15658 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15659 FD->dropAttr<IFuncAttr>();
15660 FD->setInvalidDecl();
15661 }
15662 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15663 if (!Context.getTargetInfo().hasFeature(Feature: "fmv") &&
15664 !Attr->isDefaultVersion()) {
15665 // If function multi versioning disabled skip parsing function body
15666 // defined with non-default target_version attribute
15667 if (SkipBody)
15668 SkipBody->ShouldSkip = true;
15669 return nullptr;
15670 }
15671 }
15672
15673 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
15674 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15675 Ctor->isDefaultConstructor() &&
15676 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15677 // If this is an MS ABI dllexport default constructor, instantiate any
15678 // default arguments.
15679 InstantiateDefaultCtorDefaultArgs(Ctor);
15680 }
15681 }
15682
15683 // See if this is a redefinition. If 'will have body' (or similar) is already
15684 // set, then these checks were already performed when it was set.
15685 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15686 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15687 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
15688
15689 // If we're skipping the body, we're done. Don't enter the scope.
15690 if (SkipBody && SkipBody->ShouldSkip)
15691 return D;
15692 }
15693
15694 // Mark this function as "will have a body eventually". This lets users to
15695 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15696 // this function.
15697 FD->setWillHaveBody();
15698
15699 // If we are instantiating a generic lambda call operator, push
15700 // a LambdaScopeInfo onto the function stack. But use the information
15701 // that's already been calculated (ActOnLambdaExpr) to prime the current
15702 // LambdaScopeInfo.
15703 // When the template operator is being specialized, the LambdaScopeInfo,
15704 // has to be properly restored so that tryCaptureVariable doesn't try
15705 // and capture any new variables. In addition when calculating potential
15706 // captures during transformation of nested lambdas, it is necessary to
15707 // have the LSI properly restored.
15708 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15709 assert(inTemplateInstantiation() &&
15710 "There should be an active template instantiation on the stack "
15711 "when instantiating a generic lambda!");
15712 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
15713 } else {
15714 // Enter a new function scope
15715 PushFunctionScope();
15716 }
15717
15718 // Builtin functions cannot be defined.
15719 if (unsigned BuiltinID = FD->getBuiltinID()) {
15720 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
15721 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
15722 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15723 FD->setInvalidDecl();
15724 }
15725 }
15726
15727 // The return type of a function definition must be complete (C99 6.9.1p3).
15728 // C++23 [dcl.fct.def.general]/p2
15729 // The type of [...] the return for a function definition
15730 // shall not be a (possibly cv-qualified) class type that is incomplete
15731 // or abstract within the function body unless the function is deleted.
15732 QualType ResultType = FD->getReturnType();
15733 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15734 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15735 (RequireCompleteType(FD->getLocation(), ResultType,
15736 diag::err_func_def_incomplete_result) ||
15737 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15738 diag::err_abstract_type_in_decl,
15739 AbstractReturnType)))
15740 FD->setInvalidDecl();
15741
15742 if (FnBodyScope)
15743 PushDeclContext(FnBodyScope, FD);
15744
15745 // Check the validity of our function parameters
15746 if (BodyKind != FnBodyKind::Delete)
15747 CheckParmsForFunctionDef(Parameters: FD->parameters(),
15748 /*CheckParameterNames=*/true);
15749
15750 // Add non-parameter declarations already in the function to the current
15751 // scope.
15752 if (FnBodyScope) {
15753 for (Decl *NPD : FD->decls()) {
15754 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15755 if (!NonParmDecl)
15756 continue;
15757 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15758 "parameters should not be in newly created FD yet");
15759
15760 // If the decl has a name, make it accessible in the current scope.
15761 if (NonParmDecl->getDeclName())
15762 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15763
15764 // Similarly, dive into enums and fish their constants out, making them
15765 // accessible in this scope.
15766 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15767 for (auto *EI : ED->enumerators())
15768 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15769 }
15770 }
15771 }
15772
15773 // Introduce our parameters into the function scope
15774 for (auto *Param : FD->parameters()) {
15775 Param->setOwningFunction(FD);
15776
15777 // If this has an identifier, add it to the scope stack.
15778 if (Param->getIdentifier() && FnBodyScope) {
15779 CheckShadow(FnBodyScope, Param);
15780
15781 PushOnScopeChains(Param, FnBodyScope);
15782 }
15783 }
15784
15785 // C++ [module.import/6] external definitions are not permitted in header
15786 // units. Deleted and Defaulted functions are implicitly inline (but the
15787 // inline state is not set at this point, so check the BodyKind explicitly).
15788 // FIXME: Consider an alternate location for the test where the inlined()
15789 // state is complete.
15790 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15791 !FD->isInvalidDecl() && !FD->isInlined() &&
15792 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15793 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15794 !FD->isTemplateInstantiation()) {
15795 assert(FD->isThisDeclarationADefinition());
15796 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15797 FD->setInvalidDecl();
15798 }
15799
15800 // Ensure that the function's exception specification is instantiated.
15801 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15802 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
15803
15804 // dllimport cannot be applied to non-inline function definitions.
15805 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15806 !FD->isTemplateInstantiation()) {
15807 assert(!FD->hasAttr<DLLExportAttr>());
15808 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15809 FD->setInvalidDecl();
15810 return D;
15811 }
15812 // We want to attach documentation to original Decl (which might be
15813 // a function template).
15814 ActOnDocumentableDecl(D);
15815 if (getCurLexicalContext()->isObjCContainer() &&
15816 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15817 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15818 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15819
15820 return D;
15821}
15822
15823/// Given the set of return statements within a function body,
15824/// compute the variables that are subject to the named return value
15825/// optimization.
15826///
15827/// Each of the variables that is subject to the named return value
15828/// optimization will be marked as NRVO variables in the AST, and any
15829/// return statement that has a marked NRVO variable as its NRVO candidate can
15830/// use the named return value optimization.
15831///
15832/// This function applies a very simplistic algorithm for NRVO: if every return
15833/// statement in the scope of a variable has the same NRVO candidate, that
15834/// candidate is an NRVO variable.
15835void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15836 ReturnStmt **Returns = Scope->Returns.data();
15837
15838 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15839 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15840 if (!NRVOCandidate->isNRVOVariable())
15841 Returns[I]->setNRVOCandidate(nullptr);
15842 }
15843 }
15844}
15845
15846bool Sema::canDelayFunctionBody(const Declarator &D) {
15847 // We can't delay parsing the body of a constexpr function template (yet).
15848 if (D.getDeclSpec().hasConstexprSpecifier())
15849 return false;
15850
15851 // We can't delay parsing the body of a function template with a deduced
15852 // return type (yet).
15853 if (D.getDeclSpec().hasAutoTypeSpec()) {
15854 // If the placeholder introduces a non-deduced trailing return type,
15855 // we can still delay parsing it.
15856 if (D.getNumTypeObjects()) {
15857 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
15858 if (Outer.Kind == DeclaratorChunk::Function &&
15859 Outer.Fun.hasTrailingReturnType()) {
15860 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
15861 return Ty.isNull() || !Ty->isUndeducedType();
15862 }
15863 }
15864 return false;
15865 }
15866
15867 return true;
15868}
15869
15870bool Sema::canSkipFunctionBody(Decl *D) {
15871 // We cannot skip the body of a function (or function template) which is
15872 // constexpr, since we may need to evaluate its body in order to parse the
15873 // rest of the file.
15874 // We cannot skip the body of a function with an undeduced return type,
15875 // because any callers of that function need to know the type.
15876 if (const FunctionDecl *FD = D->getAsFunction()) {
15877 if (FD->isConstexpr())
15878 return false;
15879 // We can't simply call Type::isUndeducedType here, because inside template
15880 // auto can be deduced to a dependent type, which is not considered
15881 // "undeduced".
15882 if (FD->getReturnType()->getContainedDeducedType())
15883 return false;
15884 }
15885 return Consumer.shouldSkipFunctionBody(D);
15886}
15887
15888Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15889 if (!Decl)
15890 return nullptr;
15891 if (FunctionDecl *FD = Decl->getAsFunction())
15892 FD->setHasSkippedBody();
15893 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
15894 MD->setHasSkippedBody();
15895 return Decl;
15896}
15897
15898Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15899 return ActOnFinishFunctionBody(Decl: D, Body: BodyArg, /*IsInstantiation=*/false);
15900}
15901
15902/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15903/// body.
15904class ExitFunctionBodyRAII {
15905public:
15906 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15907 ~ExitFunctionBodyRAII() {
15908 if (!IsLambda)
15909 S.PopExpressionEvaluationContext();
15910 }
15911
15912private:
15913 Sema &S;
15914 bool IsLambda = false;
15915};
15916
15917static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15918 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15919
15920 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15921 if (EscapeInfo.count(Val: BD))
15922 return EscapeInfo[BD];
15923
15924 bool R = false;
15925 const BlockDecl *CurBD = BD;
15926
15927 do {
15928 R = !CurBD->doesNotEscape();
15929 if (R)
15930 break;
15931 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15932 } while (CurBD);
15933
15934 return EscapeInfo[BD] = R;
15935 };
15936
15937 // If the location where 'self' is implicitly retained is inside a escaping
15938 // block, emit a diagnostic.
15939 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15940 S.ImplicitlyRetainedSelfLocs)
15941 if (IsOrNestedInEscapingBlock(P.second))
15942 S.Diag(P.first, diag::warn_implicitly_retains_self)
15943 << FixItHint::CreateInsertion(P.first, "self->");
15944}
15945
15946static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15947 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
15948 FD->getDeclName().isIdentifier() && FD->getName().equals(Name);
15949}
15950
15951bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
15952 return methodHasName(FD, Name: "get_return_object");
15953}
15954
15955bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
15956 return FD->isStatic() &&
15957 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
15958}
15959
15960void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
15961 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
15962 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15963 return;
15964 // Allow some_promise_type::get_return_object().
15965 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
15966 return;
15967 if (!FD->hasAttr<CoroWrapperAttr>())
15968 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15969}
15970
15971Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15972 bool IsInstantiation) {
15973 FunctionScopeInfo *FSI = getCurFunction();
15974 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15975
15976 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15977 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15978
15979 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15980 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15981
15982 // If we skip function body, we can't tell if a function is a coroutine.
15983 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15984 if (FSI->isCoroutine())
15985 CheckCompletedCoroutineBody(FD, Body);
15986 else
15987 CheckCoroutineWrapper(FD);
15988 }
15989
15990 {
15991 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15992 // one is already popped when finishing the lambda in BuildLambdaExpr().
15993 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15994 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15995 if (FD) {
15996 FD->setBody(Body);
15997 FD->setWillHaveBody(false);
15998 CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15999
16000 if (getLangOpts().CPlusPlus14) {
16001 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16002 FD->getReturnType()->isUndeducedType()) {
16003 // For a function with a deduced result type to return void,
16004 // the result type as written must be 'auto' or 'decltype(auto)',
16005 // possibly cv-qualified or constrained, but not ref-qualified.
16006 if (!FD->getReturnType()->getAs<AutoType>()) {
16007 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16008 << FD->getReturnType();
16009 FD->setInvalidDecl();
16010 } else {
16011 // Falling off the end of the function is the same as 'return;'.
16012 Expr *Dummy = nullptr;
16013 if (DeduceFunctionTypeFromReturnExpr(
16014 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16015 AT: FD->getReturnType()->getAs<AutoType>()))
16016 FD->setInvalidDecl();
16017 }
16018 }
16019 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
16020 // In C++11, we don't use 'auto' deduction rules for lambda call
16021 // operators because we don't support return type deduction.
16022 auto *LSI = getCurLambda();
16023 if (LSI->HasImplicitReturnType) {
16024 deduceClosureReturnType(*LSI);
16025
16026 // C++11 [expr.prim.lambda]p4:
16027 // [...] if there are no return statements in the compound-statement
16028 // [the deduced type is] the type void
16029 QualType RetType =
16030 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16031
16032 // Update the return type to the deduced type.
16033 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16034 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16035 EPI: Proto->getExtProtoInfo()));
16036 }
16037 }
16038
16039 // If the function implicitly returns zero (like 'main') or is naked,
16040 // don't complain about missing return statements.
16041 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16042 WP.disableCheckFallThrough();
16043
16044 // MSVC permits the use of pure specifier (=0) on function definition,
16045 // defined at class scope, warn about this non-standard construct.
16046 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16047 !FD->isOutOfLine())
16048 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16049
16050 if (!FD->isInvalidDecl()) {
16051 // Don't diagnose unused parameters of defaulted, deleted or naked
16052 // functions.
16053 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16054 !FD->hasAttr<NakedAttr>())
16055 DiagnoseUnusedParameters(Parameters: FD->parameters());
16056 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
16057 FD->getReturnType(), FD);
16058
16059 // If this is a structor, we need a vtable.
16060 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16061 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16062 else if (CXXDestructorDecl *Destructor =
16063 dyn_cast<CXXDestructorDecl>(Val: FD))
16064 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16065
16066 // Try to apply the named return value optimization. We have to check
16067 // if we can do this here because lambdas keep return statements around
16068 // to deduce an implicit return type.
16069 if (FD->getReturnType()->isRecordType() &&
16070 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16071 computeNRVO(Body, Scope: FSI);
16072 }
16073
16074 // GNU warning -Wmissing-prototypes:
16075 // Warn if a global function is defined without a previous
16076 // prototype declaration. This warning is issued even if the
16077 // definition itself provides a prototype. The aim is to detect
16078 // global functions that fail to be declared in header files.
16079 const FunctionDecl *PossiblePrototype = nullptr;
16080 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16081 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16082
16083 if (PossiblePrototype) {
16084 // We found a declaration that is not a prototype,
16085 // but that could be a zero-parameter prototype
16086 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16087 TypeLoc TL = TI->getTypeLoc();
16088 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16089 Diag(PossiblePrototype->getLocation(),
16090 diag::note_declaration_not_a_prototype)
16091 << (FD->getNumParams() != 0)
16092 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16093 FTL.getRParenLoc(), "void")
16094 : FixItHint{});
16095 }
16096 } else {
16097 // Returns true if the token beginning at this Loc is `const`.
16098 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16099 const LangOptions &LangOpts) {
16100 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16101 if (LocInfo.first.isInvalid())
16102 return false;
16103
16104 bool Invalid = false;
16105 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16106 if (Invalid)
16107 return false;
16108
16109 if (LocInfo.second > Buffer.size())
16110 return false;
16111
16112 const char *LexStart = Buffer.data() + LocInfo.second;
16113 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16114
16115 return StartTok.consume_front(Prefix: "const") &&
16116 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16117 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16118 };
16119
16120 auto findBeginLoc = [&]() {
16121 // If the return type has `const` qualifier, we want to insert
16122 // `static` before `const` (and not before the typename).
16123 if ((FD->getReturnType()->isAnyPointerType() &&
16124 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16125 FD->getReturnType().isConstQualified()) {
16126 // But only do this if we can determine where the `const` is.
16127
16128 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16129 getLangOpts()))
16130
16131 return FD->getBeginLoc();
16132 }
16133 return FD->getTypeSpecStartLoc();
16134 };
16135 Diag(FD->getTypeSpecStartLoc(),
16136 diag::note_static_for_internal_linkage)
16137 << /* function */ 1
16138 << (FD->getStorageClass() == SC_None
16139 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16140 : FixItHint{});
16141 }
16142 }
16143
16144 // We might not have found a prototype because we didn't wish to warn on
16145 // the lack of a missing prototype. Try again without the checks for
16146 // whether we want to warn on the missing prototype.
16147 if (!PossiblePrototype)
16148 (void)FindPossiblePrototype(FD, PossiblePrototype);
16149
16150 // If the function being defined does not have a prototype, then we may
16151 // need to diagnose it as changing behavior in C23 because we now know
16152 // whether the function accepts arguments or not. This only handles the
16153 // case where the definition has no prototype but does have parameters
16154 // and either there is no previous potential prototype, or the previous
16155 // potential prototype also has no actual prototype. This handles cases
16156 // like:
16157 // void f(); void f(a) int a; {}
16158 // void g(a) int a; {}
16159 // See MergeFunctionDecl() for other cases of the behavior change
16160 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16161 // type without a prototype.
16162 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16163 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16164 !PossiblePrototype->isImplicit()))) {
16165 // The function definition has parameters, so this will change behavior
16166 // in C23. If there is a possible prototype, it comes before the
16167 // function definition.
16168 // FIXME: The declaration may have already been diagnosed as being
16169 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16170 // there's no way to test for the "changes behavior" condition in
16171 // SemaType.cpp when forming the declaration's function type. So, we do
16172 // this awkward dance instead.
16173 //
16174 // If we have a possible prototype and it declares a function with a
16175 // prototype, we don't want to diagnose it; if we have a possible
16176 // prototype and it has no prototype, it may have already been
16177 // diagnosed in SemaType.cpp as deprecated depending on whether
16178 // -Wstrict-prototypes is enabled. If we already warned about it being
16179 // deprecated, add a note that it also changes behavior. If we didn't
16180 // warn about it being deprecated (because the diagnostic is not
16181 // enabled), warn now that it is deprecated and changes behavior.
16182
16183 // This K&R C function definition definitely changes behavior in C23,
16184 // so diagnose it.
16185 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16186 << /*definition*/ 1 << /* not supported in C23 */ 0;
16187
16188 // If we have a possible prototype for the function which is a user-
16189 // visible declaration, we already tested that it has no prototype.
16190 // This will change behavior in C23. This gets a warning rather than a
16191 // note because it's the same behavior-changing problem as with the
16192 // definition.
16193 if (PossiblePrototype)
16194 Diag(PossiblePrototype->getLocation(),
16195 diag::warn_non_prototype_changes_behavior)
16196 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16197 << /*definition*/ 1;
16198 }
16199
16200 // Warn on CPUDispatch with an actual body.
16201 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16202 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16203 if (!CmpndBody->body_empty())
16204 Diag(CmpndBody->body_front()->getBeginLoc(),
16205 diag::warn_dispatch_body_ignored);
16206
16207 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16208 const CXXMethodDecl *KeyFunction;
16209 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16210 MD->isVirtual() &&
16211 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16212 MD == KeyFunction->getCanonicalDecl()) {
16213 // Update the key-function state if necessary for this ABI.
16214 if (FD->isInlined() &&
16215 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16216 Context.setNonKeyFunction(MD);
16217
16218 // If the newly-chosen key function is already defined, then we
16219 // need to mark the vtable as used retroactively.
16220 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16221 const FunctionDecl *Definition;
16222 if (KeyFunction && KeyFunction->isDefined(Definition))
16223 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16224 } else {
16225 // We just defined they key function; mark the vtable as used.
16226 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16227 }
16228 }
16229 }
16230
16231 assert(
16232 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
16233 "Function parsing confused");
16234 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16235 assert(MD == getCurMethodDecl() && "Method parsing confused");
16236 MD->setBody(Body);
16237 if (!MD->isInvalidDecl()) {
16238 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16239 MD->getReturnType(), MD);
16240
16241 if (Body)
16242 computeNRVO(Body, Scope: FSI);
16243 }
16244 if (FSI->ObjCShouldCallSuper) {
16245 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16246 << MD->getSelector().getAsString();
16247 FSI->ObjCShouldCallSuper = false;
16248 }
16249 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16250 const ObjCMethodDecl *InitMethod = nullptr;
16251 bool isDesignated =
16252 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16253 assert(isDesignated && InitMethod);
16254 (void)isDesignated;
16255
16256 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16257 auto IFace = MD->getClassInterface();
16258 if (!IFace)
16259 return false;
16260 auto SuperD = IFace->getSuperClass();
16261 if (!SuperD)
16262 return false;
16263 return SuperD->getIdentifier() ==
16264 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16265 };
16266 // Don't issue this warning for unavailable inits or direct subclasses
16267 // of NSObject.
16268 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16269 Diag(MD->getLocation(),
16270 diag::warn_objc_designated_init_missing_super_call);
16271 Diag(InitMethod->getLocation(),
16272 diag::note_objc_designated_init_marked_here);
16273 }
16274 FSI->ObjCWarnForNoDesignatedInitChain = false;
16275 }
16276 if (FSI->ObjCWarnForNoInitDelegation) {
16277 // Don't issue this warning for unavaialable inits.
16278 if (!MD->isUnavailable())
16279 Diag(MD->getLocation(),
16280 diag::warn_objc_secondary_init_missing_init_call);
16281 FSI->ObjCWarnForNoInitDelegation = false;
16282 }
16283
16284 diagnoseImplicitlyRetainedSelf(S&: *this);
16285 } else {
16286 // Parsing the function declaration failed in some way. Pop the fake scope
16287 // we pushed on.
16288 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16289 return nullptr;
16290 }
16291
16292 if (Body && FSI->HasPotentialAvailabilityViolations)
16293 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16294
16295 assert(!FSI->ObjCShouldCallSuper &&
16296 "This should only be set for ObjC methods, which should have been "
16297 "handled in the block above.");
16298
16299 // Verify and clean out per-function state.
16300 if (Body && (!FD || !FD->isDefaulted())) {
16301 // C++ constructors that have function-try-blocks can't have return
16302 // statements in the handlers of that block. (C++ [except.handle]p14)
16303 // Verify this.
16304 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16305 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16306
16307 // Verify that gotos and switch cases don't jump into scopes illegally.
16308 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16309 DiagnoseInvalidJumps(Body);
16310
16311 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16312 if (!Destructor->getParent()->isDependentType())
16313 CheckDestructor(Destructor);
16314
16315 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16316 Record: Destructor->getParent());
16317 }
16318
16319 // If any errors have occurred, clear out any temporaries that may have
16320 // been leftover. This ensures that these temporaries won't be picked up
16321 // for deletion in some later function.
16322 if (hasUncompilableErrorOccurred() ||
16323 hasAnyUnrecoverableErrorsInThisFunction() ||
16324 getDiagnostics().getSuppressAllDiagnostics()) {
16325 DiscardCleanupsInEvaluationContext();
16326 }
16327 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16328 // Since the body is valid, issue any analysis-based warnings that are
16329 // enabled.
16330 ActivePolicy = &WP;
16331 }
16332
16333 if (!IsInstantiation && FD &&
16334 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16335 !FD->isInvalidDecl() &&
16336 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16337 FD->setInvalidDecl();
16338
16339 if (FD && FD->hasAttr<NakedAttr>()) {
16340 for (const Stmt *S : Body->children()) {
16341 // Allow local register variables without initializer as they don't
16342 // require prologue.
16343 bool RegisterVariables = false;
16344 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16345 for (const auto *Decl : DS->decls()) {
16346 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16347 RegisterVariables =
16348 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16349 if (!RegisterVariables)
16350 break;
16351 }
16352 }
16353 }
16354 if (RegisterVariables)
16355 continue;
16356 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16357 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16358 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16359 FD->setInvalidDecl();
16360 break;
16361 }
16362 }
16363 }
16364
16365 assert(ExprCleanupObjects.size() ==
16366 ExprEvalContexts.back().NumCleanupObjects &&
16367 "Leftover temporaries in function");
16368 assert(!Cleanup.exprNeedsCleanups() &&
16369 "Unaccounted cleanups in function");
16370 assert(MaybeODRUseExprs.empty() &&
16371 "Leftover expressions for odr-use checking");
16372 }
16373 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16374 // the declaration context below. Otherwise, we're unable to transform
16375 // 'this' expressions when transforming immediate context functions.
16376
16377 if (!IsInstantiation)
16378 PopDeclContext();
16379
16380 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16381 // If any errors have occurred, clear out any temporaries that may have
16382 // been leftover. This ensures that these temporaries won't be picked up for
16383 // deletion in some later function.
16384 if (hasUncompilableErrorOccurred()) {
16385 DiscardCleanupsInEvaluationContext();
16386 }
16387
16388 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16389 !LangOpts.OMPTargetTriples.empty())) ||
16390 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16391 auto ES = getEmissionStatus(Decl: FD);
16392 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16393 ES == Sema::FunctionEmissionStatus::Unknown)
16394 DeclsToCheckForDeferredDiags.insert(FD);
16395 }
16396
16397 if (FD && !FD->isDeleted())
16398 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16399
16400 return dcl;
16401}
16402
16403/// When we finish delayed parsing of an attribute, we must attach it to the
16404/// relevant Decl.
16405void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16406 ParsedAttributes &Attrs) {
16407 // Always attach attributes to the underlying decl.
16408 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
16409 D = TD->getTemplatedDecl();
16410 ProcessDeclAttributeList(S, D, AttrList: Attrs);
16411
16412 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
16413 if (Method->isStatic())
16414 checkThisInStaticMemberFunctionAttributes(Method);
16415}
16416
16417/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16418/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16419NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16420 IdentifierInfo &II, Scope *S) {
16421 // It is not valid to implicitly define a function in C23.
16422 assert(LangOpts.implicitFunctionsAllowed() &&
16423 "Implicit function declarations aren't allowed in this language mode");
16424
16425 // Find the scope in which the identifier is injected and the corresponding
16426 // DeclContext.
16427 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16428 // In that case, we inject the declaration into the translation unit scope
16429 // instead.
16430 Scope *BlockScope = S;
16431 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16432 BlockScope = BlockScope->getParent();
16433
16434 // Loop until we find a DeclContext that is either a function/method or the
16435 // translation unit, which are the only two valid places to implicitly define
16436 // a function. This avoids accidentally defining the function within a tag
16437 // declaration, for example.
16438 Scope *ContextScope = BlockScope;
16439 while (!ContextScope->getEntity() ||
16440 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16441 !ContextScope->getEntity()->isTranslationUnit()))
16442 ContextScope = ContextScope->getParent();
16443 ContextRAII SavedContext(*this, ContextScope->getEntity());
16444
16445 // Before we produce a declaration for an implicitly defined
16446 // function, see whether there was a locally-scoped declaration of
16447 // this name as a function or variable. If so, use that
16448 // (non-visible) declaration, and complain about it.
16449 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
16450 if (ExternCPrev) {
16451 // We still need to inject the function into the enclosing block scope so
16452 // that later (non-call) uses can see it.
16453 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
16454
16455 // C89 footnote 38:
16456 // If in fact it is not defined as having type "function returning int",
16457 // the behavior is undefined.
16458 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
16459 !Context.typesAreCompatible(
16460 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
16461 T2: Context.getFunctionNoProtoType(Context.IntTy))) {
16462 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16463 << ExternCPrev << !getLangOpts().C99;
16464 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16465 return ExternCPrev;
16466 }
16467 }
16468
16469 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16470 unsigned diag_id;
16471 if (II.getName().starts_with("__builtin_"))
16472 diag_id = diag::warn_builtin_unknown;
16473 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16474 else if (getLangOpts().C99)
16475 diag_id = diag::ext_implicit_function_decl_c99;
16476 else
16477 diag_id = diag::warn_implicit_function_decl;
16478
16479 TypoCorrection Corrected;
16480 // Because typo correction is expensive, only do it if the implicit
16481 // function declaration is going to be treated as an error.
16482 //
16483 // Perform the correction before issuing the main diagnostic, as some
16484 // consumers use typo-correction callbacks to enhance the main diagnostic.
16485 if (S && !ExternCPrev &&
16486 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
16487 DeclFilterCCC<FunctionDecl> CCC{};
16488 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
16489 S, SS: nullptr, CCC, Mode: CTK_NonError);
16490 }
16491
16492 Diag(Loc, DiagID: diag_id) << &II;
16493 if (Corrected) {
16494 // If the correction is going to suggest an implicitly defined function,
16495 // skip the correction as not being a particularly good idea.
16496 bool Diagnose = true;
16497 if (const auto *D = Corrected.getCorrectionDecl())
16498 Diagnose = !D->isImplicit();
16499 if (Diagnose)
16500 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16501 /*ErrorRecovery*/ false);
16502 }
16503
16504 // If we found a prior declaration of this function, don't bother building
16505 // another one. We've already pushed that one into scope, so there's nothing
16506 // more to do.
16507 if (ExternCPrev)
16508 return ExternCPrev;
16509
16510 // Set a Declarator for the implicit definition: int foo();
16511 const char *Dummy;
16512 AttributeFactory attrFactory;
16513 DeclSpec DS(attrFactory);
16514 unsigned DiagID;
16515 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
16516 Policy: Context.getPrintingPolicy());
16517 (void)Error; // Silence warning.
16518 assert(!Error && "Error setting up implicit decl!");
16519 SourceLocation NoLoc;
16520 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16521 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
16522 /*IsAmbiguous=*/false,
16523 /*LParenLoc=*/NoLoc,
16524 /*Params=*/nullptr,
16525 /*NumParams=*/0,
16526 /*EllipsisLoc=*/NoLoc,
16527 /*RParenLoc=*/NoLoc,
16528 /*RefQualifierIsLvalueRef=*/true,
16529 /*RefQualifierLoc=*/NoLoc,
16530 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
16531 /*ESpecRange=*/SourceRange(),
16532 /*Exceptions=*/nullptr,
16533 /*ExceptionRanges=*/nullptr,
16534 /*NumExceptions=*/0,
16535 /*NoexceptExpr=*/nullptr,
16536 /*ExceptionSpecTokens=*/nullptr,
16537 /*DeclsInPrototype=*/std::nullopt,
16538 LocalRangeBegin: Loc, LocalRangeEnd: Loc, TheDeclarator&: D),
16539 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
16540 D.SetIdentifier(Id: &II, IdLoc: Loc);
16541
16542 // Insert this function into the enclosing block scope.
16543 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
16544 FD->setImplicit();
16545
16546 AddKnownFunctionAttributes(FD);
16547
16548 return FD;
16549}
16550
16551/// If this function is a C++ replaceable global allocation function
16552/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16553/// adds any function attributes that we know a priori based on the standard.
16554///
16555/// We need to check for duplicate attributes both here and where user-written
16556/// attributes are applied to declarations.
16557void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16558 FunctionDecl *FD) {
16559 if (FD->isInvalidDecl())
16560 return;
16561
16562 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16563 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16564 return;
16565
16566 std::optional<unsigned> AlignmentParam;
16567 bool IsNothrow = false;
16568 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
16569 return;
16570
16571 // C++2a [basic.stc.dynamic.allocation]p4:
16572 // An allocation function that has a non-throwing exception specification
16573 // indicates failure by returning a null pointer value. Any other allocation
16574 // function never returns a null pointer value and indicates failure only by
16575 // throwing an exception [...]
16576 //
16577 // However, -fcheck-new invalidates this possible assumption, so don't add
16578 // NonNull when that is enabled.
16579 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16580 !getLangOpts().CheckNew)
16581 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16582
16583 // C++2a [basic.stc.dynamic.allocation]p2:
16584 // An allocation function attempts to allocate the requested amount of
16585 // storage. [...] If the request succeeds, the value returned by a
16586 // replaceable allocation function is a [...] pointer value p0 different
16587 // from any previously returned value p1 [...]
16588 //
16589 // However, this particular information is being added in codegen,
16590 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16591
16592 // C++2a [basic.stc.dynamic.allocation]p2:
16593 // An allocation function attempts to allocate the requested amount of
16594 // storage. If it is successful, it returns the address of the start of a
16595 // block of storage whose length in bytes is at least as large as the
16596 // requested size.
16597 if (!FD->hasAttr<AllocSizeAttr>()) {
16598 FD->addAttr(AllocSizeAttr::CreateImplicit(
16599 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16600 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16601 }
16602
16603 // C++2a [basic.stc.dynamic.allocation]p3:
16604 // For an allocation function [...], the pointer returned on a successful
16605 // call shall represent the address of storage that is aligned as follows:
16606 // (3.1) If the allocation function takes an argument of type
16607 // std​::​align_­val_­t, the storage will have the alignment
16608 // specified by the value of this argument.
16609 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16610 FD->addAttr(AllocAlignAttr::CreateImplicit(
16611 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16612 }
16613
16614 // FIXME:
16615 // C++2a [basic.stc.dynamic.allocation]p3:
16616 // For an allocation function [...], the pointer returned on a successful
16617 // call shall represent the address of storage that is aligned as follows:
16618 // (3.2) Otherwise, if the allocation function is named operator new[],
16619 // the storage is aligned for any object that does not have
16620 // new-extended alignment ([basic.align]) and is no larger than the
16621 // requested size.
16622 // (3.3) Otherwise, the storage is aligned for any object that does not
16623 // have new-extended alignment and is of the requested size.
16624}
16625
16626/// Adds any function attributes that we know a priori based on
16627/// the declaration of this function.
16628///
16629/// These attributes can apply both to implicitly-declared builtins
16630/// (like __builtin___printf_chk) or to library-declared functions
16631/// like NSLog or printf.
16632///
16633/// We need to check for duplicate attributes both here and where user-written
16634/// attributes are applied to declarations.
16635void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16636 if (FD->isInvalidDecl())
16637 return;
16638
16639 // If this is a built-in function, map its builtin attributes to
16640 // actual attributes.
16641 if (unsigned BuiltinID = FD->getBuiltinID()) {
16642 // Handle printf-formatting attributes.
16643 unsigned FormatIdx;
16644 bool HasVAListArg;
16645 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
16646 if (!FD->hasAttr<FormatAttr>()) {
16647 const char *fmt = "printf";
16648 unsigned int NumParams = FD->getNumParams();
16649 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16650 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
16651 fmt = "NSString";
16652 FD->addAttr(FormatAttr::CreateImplicit(Context,
16653 &Context.Idents.get(fmt),
16654 FormatIdx+1,
16655 HasVAListArg ? 0 : FormatIdx+2,
16656 FD->getLocation()));
16657 }
16658 }
16659 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
16660 HasVAListArg)) {
16661 if (!FD->hasAttr<FormatAttr>())
16662 FD->addAttr(FormatAttr::CreateImplicit(Context,
16663 &Context.Idents.get("scanf"),
16664 FormatIdx+1,
16665 HasVAListArg ? 0 : FormatIdx+2,
16666 FD->getLocation()));
16667 }
16668
16669 // Handle automatically recognized callbacks.
16670 SmallVector<int, 4> Encoding;
16671 if (!FD->hasAttr<CallbackAttr>() &&
16672 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16673 FD->addAttr(CallbackAttr::CreateImplicit(
16674 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16675
16676 // Mark const if we don't care about errno and/or floating point exceptions
16677 // that are the only thing preventing the function from being const. This
16678 // allows IRgen to use LLVM intrinsics for such functions.
16679 bool NoExceptions =
16680 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16681 bool ConstWithoutErrnoAndExceptions =
16682 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
16683 bool ConstWithoutExceptions =
16684 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
16685 if (!FD->hasAttr<ConstAttr>() &&
16686 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16687 (!ConstWithoutErrnoAndExceptions ||
16688 (!getLangOpts().MathErrno && NoExceptions)) &&
16689 (!ConstWithoutExceptions || NoExceptions))
16690 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16691
16692 // We make "fma" on GNU or Windows const because we know it does not set
16693 // errno in those environments even though it could set errno based on the
16694 // C standard.
16695 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16696 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16697 !FD->hasAttr<ConstAttr>()) {
16698 switch (BuiltinID) {
16699 case Builtin::BI__builtin_fma:
16700 case Builtin::BI__builtin_fmaf:
16701 case Builtin::BI__builtin_fmal:
16702 case Builtin::BIfma:
16703 case Builtin::BIfmaf:
16704 case Builtin::BIfmal:
16705 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16706 break;
16707 default:
16708 break;
16709 }
16710 }
16711
16712 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16713 !FD->hasAttr<ReturnsTwiceAttr>())
16714 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16715 FD->getLocation()));
16716 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16717 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16718 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16719 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16720 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16721 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16722 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16723 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16724 // Add the appropriate attribute, depending on the CUDA compilation mode
16725 // and which target the builtin belongs to. For example, during host
16726 // compilation, aux builtins are __device__, while the rest are __host__.
16727 if (getLangOpts().CUDAIsDevice !=
16728 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16729 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16730 else
16731 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16732 }
16733
16734 // Add known guaranteed alignment for allocation functions.
16735 switch (BuiltinID) {
16736 case Builtin::BImemalign:
16737 case Builtin::BIaligned_alloc:
16738 if (!FD->hasAttr<AllocAlignAttr>())
16739 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16740 FD->getLocation()));
16741 break;
16742 default:
16743 break;
16744 }
16745
16746 // Add allocsize attribute for allocation functions.
16747 switch (BuiltinID) {
16748 case Builtin::BIcalloc:
16749 FD->addAttr(AllocSizeAttr::CreateImplicit(
16750 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16751 break;
16752 case Builtin::BImemalign:
16753 case Builtin::BIaligned_alloc:
16754 case Builtin::BIrealloc:
16755 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16756 ParamIdx(), FD->getLocation()));
16757 break;
16758 case Builtin::BImalloc:
16759 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16760 ParamIdx(), FD->getLocation()));
16761 break;
16762 default:
16763 break;
16764 }
16765
16766 // Add lifetime attribute to std::move, std::fowrard et al.
16767 switch (BuiltinID) {
16768 case Builtin::BIaddressof:
16769 case Builtin::BI__addressof:
16770 case Builtin::BI__builtin_addressof:
16771 case Builtin::BIas_const:
16772 case Builtin::BIforward:
16773 case Builtin::BIforward_like:
16774 case Builtin::BImove:
16775 case Builtin::BImove_if_noexcept:
16776 if (ParmVarDecl *P = FD->getParamDecl(0u);
16777 !P->hasAttr<LifetimeBoundAttr>())
16778 P->addAttr(
16779 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16780 break;
16781 default:
16782 break;
16783 }
16784 }
16785
16786 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16787
16788 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16789 // throw, add an implicit nothrow attribute to any extern "C" function we come
16790 // across.
16791 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16792 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16793 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16794 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16795 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16796 }
16797
16798 IdentifierInfo *Name = FD->getIdentifier();
16799 if (!Name)
16800 return;
16801 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16802 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16803 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16804 LinkageSpecLanguageIDs::C)) {
16805 // Okay: this could be a libc/libm/Objective-C function we know
16806 // about.
16807 } else
16808 return;
16809
16810 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
16811 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16812 // target-specific builtins, perhaps?
16813 if (!FD->hasAttr<FormatAttr>())
16814 FD->addAttr(FormatAttr::CreateImplicit(Context,
16815 &Context.Idents.get("printf"), 2,
16816 Name->isStr("vasprintf") ? 0 : 3,
16817 FD->getLocation()));
16818 }
16819
16820 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
16821 // We already have a __builtin___CFStringMakeConstantString,
16822 // but builds that use -fno-constant-cfstrings don't go through that.
16823 if (!FD->hasAttr<FormatArgAttr>())
16824 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16825 FD->getLocation()));
16826 }
16827}
16828
16829TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16830 TypeSourceInfo *TInfo) {
16831 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16832 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16833
16834 if (!TInfo) {
16835 assert(D.isInvalidType() && "no declarator info for valid type");
16836 TInfo = Context.getTrivialTypeSourceInfo(T);
16837 }
16838
16839 // Scope manipulation handled by caller.
16840 TypedefDecl *NewTD =
16841 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
16842 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
16843
16844 // Bail out immediately if we have an invalid declaration.
16845 if (D.isInvalidType()) {
16846 NewTD->setInvalidDecl();
16847 return NewTD;
16848 }
16849
16850 if (D.getDeclSpec().isModulePrivateSpecified()) {
16851 if (CurContext->isFunctionOrMethod())
16852 Diag(NewTD->getLocation(), diag::err_module_private_local)
16853 << 2 << NewTD
16854 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16855 << FixItHint::CreateRemoval(
16856 D.getDeclSpec().getModulePrivateSpecLoc());
16857 else
16858 NewTD->setModulePrivate();
16859 }
16860
16861 // C++ [dcl.typedef]p8:
16862 // If the typedef declaration defines an unnamed class (or
16863 // enum), the first typedef-name declared by the declaration
16864 // to be that class type (or enum type) is used to denote the
16865 // class type (or enum type) for linkage purposes only.
16866 // We need to check whether the type was declared in the declaration.
16867 switch (D.getDeclSpec().getTypeSpecType()) {
16868 case TST_enum:
16869 case TST_struct:
16870 case TST_interface:
16871 case TST_union:
16872 case TST_class: {
16873 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
16874 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16875 break;
16876 }
16877
16878 default:
16879 break;
16880 }
16881
16882 return NewTD;
16883}
16884
16885/// Check that this is a valid underlying type for an enum declaration.
16886bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16887 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16888 QualType T = TI->getType();
16889
16890 if (T->isDependentType())
16891 return false;
16892
16893 // This doesn't use 'isIntegralType' despite the error message mentioning
16894 // integral type because isIntegralType would also allow enum types in C.
16895 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16896 if (BT->isInteger())
16897 return false;
16898
16899 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16900 << T << T->isBitIntType();
16901}
16902
16903/// Check whether this is a valid redeclaration of a previous enumeration.
16904/// \return true if the redeclaration was invalid.
16905bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16906 QualType EnumUnderlyingTy, bool IsFixed,
16907 const EnumDecl *Prev) {
16908 if (IsScoped != Prev->isScoped()) {
16909 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16910 << Prev->isScoped();
16911 Diag(Prev->getLocation(), diag::note_previous_declaration);
16912 return true;
16913 }
16914
16915 if (IsFixed && Prev->isFixed()) {
16916 if (!EnumUnderlyingTy->isDependentType() &&
16917 !Prev->getIntegerType()->isDependentType() &&
16918 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
16919 T2: Prev->getIntegerType())) {
16920 // TODO: Highlight the underlying type of the redeclaration.
16921 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16922 << EnumUnderlyingTy << Prev->getIntegerType();
16923 Diag(Prev->getLocation(), diag::note_previous_declaration)
16924 << Prev->getIntegerTypeRange();
16925 return true;
16926 }
16927 } else if (IsFixed != Prev->isFixed()) {
16928 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16929 << Prev->isFixed();
16930 Diag(Prev->getLocation(), diag::note_previous_declaration);
16931 return true;
16932 }
16933
16934 return false;
16935}
16936
16937/// Get diagnostic %select index for tag kind for
16938/// redeclaration diagnostic message.
16939/// WARNING: Indexes apply to particular diagnostics only!
16940///
16941/// \returns diagnostic %select index.
16942static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16943 switch (Tag) {
16944 case TagTypeKind::Struct:
16945 return 0;
16946 case TagTypeKind::Interface:
16947 return 1;
16948 case TagTypeKind::Class:
16949 return 2;
16950 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16951 }
16952}
16953
16954/// Determine if tag kind is a class-key compatible with
16955/// class for redeclaration (class, struct, or __interface).
16956///
16957/// \returns true iff the tag kind is compatible.
16958static bool isClassCompatTagKind(TagTypeKind Tag)
16959{
16960 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16961 Tag == TagTypeKind::Interface;
16962}
16963
16964Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16965 TagTypeKind TTK) {
16966 if (isa<TypedefDecl>(Val: PrevDecl))
16967 return NTK_Typedef;
16968 else if (isa<TypeAliasDecl>(Val: PrevDecl))
16969 return NTK_TypeAlias;
16970 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
16971 return NTK_Template;
16972 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
16973 return NTK_TypeAliasTemplate;
16974 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
16975 return NTK_TemplateTemplateArgument;
16976 switch (TTK) {
16977 case TagTypeKind::Struct:
16978 case TagTypeKind::Interface:
16979 case TagTypeKind::Class:
16980 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16981 case TagTypeKind::Union:
16982 return NTK_NonUnion;
16983 case TagTypeKind::Enum:
16984 return NTK_NonEnum;
16985 }
16986 llvm_unreachable("invalid TTK");
16987}
16988
16989/// Determine whether a tag with a given kind is acceptable
16990/// as a redeclaration of the given tag declaration.
16991///
16992/// \returns true if the new tag kind is acceptable, false otherwise.
16993bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16994 TagTypeKind NewTag, bool isDefinition,
16995 SourceLocation NewTagLoc,
16996 const IdentifierInfo *Name) {
16997 // C++ [dcl.type.elab]p3:
16998 // The class-key or enum keyword present in the
16999 // elaborated-type-specifier shall agree in kind with the
17000 // declaration to which the name in the elaborated-type-specifier
17001 // refers. This rule also applies to the form of
17002 // elaborated-type-specifier that declares a class-name or
17003 // friend class since it can be construed as referring to the
17004 // definition of the class. Thus, in any
17005 // elaborated-type-specifier, the enum keyword shall be used to
17006 // refer to an enumeration (7.2), the union class-key shall be
17007 // used to refer to a union (clause 9), and either the class or
17008 // struct class-key shall be used to refer to a class (clause 9)
17009 // declared using the class or struct class-key.
17010 TagTypeKind OldTag = Previous->getTagKind();
17011 if (OldTag != NewTag &&
17012 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17013 return false;
17014
17015 // Tags are compatible, but we might still want to warn on mismatched tags.
17016 // Non-class tags can't be mismatched at this point.
17017 if (!isClassCompatTagKind(Tag: NewTag))
17018 return true;
17019
17020 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17021 // by our warning analysis. We don't want to warn about mismatches with (eg)
17022 // declarations in system headers that are designed to be specialized, but if
17023 // a user asks us to warn, we should warn if their code contains mismatched
17024 // declarations.
17025 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17026 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17027 Loc);
17028 };
17029 if (IsIgnoredLoc(NewTagLoc))
17030 return true;
17031
17032 auto IsIgnored = [&](const TagDecl *Tag) {
17033 return IsIgnoredLoc(Tag->getLocation());
17034 };
17035 while (IsIgnored(Previous)) {
17036 Previous = Previous->getPreviousDecl();
17037 if (!Previous)
17038 return true;
17039 OldTag = Previous->getTagKind();
17040 }
17041
17042 bool isTemplate = false;
17043 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17044 isTemplate = Record->getDescribedClassTemplate();
17045
17046 if (inTemplateInstantiation()) {
17047 if (OldTag != NewTag) {
17048 // In a template instantiation, do not offer fix-its for tag mismatches
17049 // since they usually mess up the template instead of fixing the problem.
17050 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17051 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17052 << getRedeclDiagFromTagKind(OldTag);
17053 // FIXME: Note previous location?
17054 }
17055 return true;
17056 }
17057
17058 if (isDefinition) {
17059 // On definitions, check all previous tags and issue a fix-it for each
17060 // one that doesn't match the current tag.
17061 if (Previous->getDefinition()) {
17062 // Don't suggest fix-its for redefinitions.
17063 return true;
17064 }
17065
17066 bool previousMismatch = false;
17067 for (const TagDecl *I : Previous->redecls()) {
17068 if (I->getTagKind() != NewTag) {
17069 // Ignore previous declarations for which the warning was disabled.
17070 if (IsIgnored(I))
17071 continue;
17072
17073 if (!previousMismatch) {
17074 previousMismatch = true;
17075 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17076 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17077 << getRedeclDiagFromTagKind(I->getTagKind());
17078 }
17079 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17080 << getRedeclDiagFromTagKind(NewTag)
17081 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17082 TypeWithKeyword::getTagTypeKindName(NewTag));
17083 }
17084 }
17085 return true;
17086 }
17087
17088 // Identify the prevailing tag kind: this is the kind of the definition (if
17089 // there is a non-ignored definition), or otherwise the kind of the prior
17090 // (non-ignored) declaration.
17091 const TagDecl *PrevDef = Previous->getDefinition();
17092 if (PrevDef && IsIgnored(PrevDef))
17093 PrevDef = nullptr;
17094 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17095 if (Redecl->getTagKind() != NewTag) {
17096 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17097 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17098 << getRedeclDiagFromTagKind(OldTag);
17099 Diag(Redecl->getLocation(), diag::note_previous_use);
17100
17101 // If there is a previous definition, suggest a fix-it.
17102 if (PrevDef) {
17103 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17104 << getRedeclDiagFromTagKind(Redecl->getTagKind())
17105 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
17106 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
17107 }
17108 }
17109
17110 return true;
17111}
17112
17113/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17114/// from an outer enclosing namespace or file scope inside a friend declaration.
17115/// This should provide the commented out code in the following snippet:
17116/// namespace N {
17117/// struct X;
17118/// namespace M {
17119/// struct Y { friend struct /*N::*/ X; };
17120/// }
17121/// }
17122static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17123 SourceLocation NameLoc) {
17124 // While the decl is in a namespace, do repeated lookup of that name and see
17125 // if we get the same namespace back. If we do not, continue until
17126 // translation unit scope, at which point we have a fully qualified NNS.
17127 SmallVector<IdentifierInfo *, 4> Namespaces;
17128 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17129 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17130 // This tag should be declared in a namespace, which can only be enclosed by
17131 // other namespaces. Bail if there's an anonymous namespace in the chain.
17132 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17133 if (!Namespace || Namespace->isAnonymousNamespace())
17134 return FixItHint();
17135 IdentifierInfo *II = Namespace->getIdentifier();
17136 Namespaces.push_back(Elt: II);
17137 NamedDecl *Lookup = SemaRef.LookupSingleName(
17138 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17139 if (Lookup == Namespace)
17140 break;
17141 }
17142
17143 // Once we have all the namespaces, reverse them to go outermost first, and
17144 // build an NNS.
17145 SmallString<64> Insertion;
17146 llvm::raw_svector_ostream OS(Insertion);
17147 if (DC->isTranslationUnit())
17148 OS << "::";
17149 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17150 for (auto *II : Namespaces)
17151 OS << II->getName() << "::";
17152 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17153}
17154
17155/// Determine whether a tag originally declared in context \p OldDC can
17156/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17157/// found a declaration in \p OldDC as a previous decl, perhaps through a
17158/// using-declaration).
17159static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17160 DeclContext *NewDC) {
17161 OldDC = OldDC->getRedeclContext();
17162 NewDC = NewDC->getRedeclContext();
17163
17164 if (OldDC->Equals(DC: NewDC))
17165 return true;
17166
17167 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17168 // encloses the other).
17169 if (S.getLangOpts().MSVCCompat &&
17170 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17171 return true;
17172
17173 return false;
17174}
17175
17176/// This is invoked when we see 'struct foo' or 'struct {'. In the
17177/// former case, Name will be non-null. In the later case, Name will be null.
17178/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17179/// reference/declaration/definition of a tag.
17180///
17181/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17182/// trailing-type-specifier) other than one in an alias-declaration.
17183///
17184/// \param SkipBody If non-null, will be set to indicate if the caller should
17185/// skip the definition of this tag and treat it as if it were a declaration.
17186DeclResult
17187Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17188 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17189 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17190 SourceLocation ModulePrivateLoc,
17191 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17192 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17193 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17194 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17195 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17196 // If this is not a definition, it must have a name.
17197 IdentifierInfo *OrigName = Name;
17198 assert((Name != nullptr || TUK == TUK_Definition) &&
17199 "Nameless record must be a definition!");
17200 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17201
17202 OwnedDecl = false;
17203 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17204 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17205
17206 // FIXME: Check member specializations more carefully.
17207 bool isMemberSpecialization = false;
17208 bool Invalid = false;
17209
17210 // We only need to do this matching if we have template parameters
17211 // or a scope specifier, which also conveniently avoids this work
17212 // for non-C++ cases.
17213 if (TemplateParameterLists.size() > 0 ||
17214 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17215 TemplateParameterList *TemplateParams =
17216 MatchTemplateParametersToScopeSpecifier(
17217 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17218 IsFriend: TUK == TUK_Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17219
17220 // C++23 [dcl.type.elab] p2:
17221 // If an elaborated-type-specifier is the sole constituent of a
17222 // declaration, the declaration is ill-formed unless it is an explicit
17223 // specialization, an explicit instantiation or it has one of the
17224 // following forms: [...]
17225 // C++23 [dcl.enum] p1:
17226 // If the enum-head-name of an opaque-enum-declaration contains a
17227 // nested-name-specifier, the declaration shall be an explicit
17228 // specialization.
17229 //
17230 // FIXME: Class template partial specializations can be forward declared
17231 // per CWG2213, but the resolution failed to allow qualified forward
17232 // declarations. This is almost certainly unintentional, so we allow them.
17233 if (TUK == TUK_Declaration && SS.isNotEmpty() && !isMemberSpecialization)
17234 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17235 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17236
17237 if (TemplateParams) {
17238 if (Kind == TagTypeKind::Enum) {
17239 Diag(KWLoc, diag::err_enum_template);
17240 return true;
17241 }
17242
17243 if (TemplateParams->size() > 0) {
17244 // This is a declaration or definition of a class template (which may
17245 // be a member of another template).
17246
17247 if (Invalid)
17248 return true;
17249
17250 OwnedDecl = false;
17251 DeclResult Result = CheckClassTemplate(
17252 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17253 AS, ModulePrivateLoc,
17254 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17255 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17256 return Result.get();
17257 } else {
17258 // The "template<>" header is extraneous.
17259 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17260 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17261 isMemberSpecialization = true;
17262 }
17263 }
17264
17265 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17266 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17267 return true;
17268 }
17269
17270 if (TUK == TUK_Friend && Kind == TagTypeKind::Enum) {
17271 // C++23 [dcl.type.elab]p4:
17272 // If an elaborated-type-specifier appears with the friend specifier as
17273 // an entire member-declaration, the member-declaration shall have one
17274 // of the following forms:
17275 // friend class-key nested-name-specifier(opt) identifier ;
17276 // friend class-key simple-template-id ;
17277 // friend class-key nested-name-specifier template(opt)
17278 // simple-template-id ;
17279 //
17280 // Since enum is not a class-key, so declarations like "friend enum E;"
17281 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17282 // invalid, most implementations accept so we issue a pedantic warning.
17283 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17284 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17285 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17286 Diag(KWLoc, diag::note_enum_friend)
17287 << (ScopedEnum + ScopedEnumUsesClassTag);
17288 }
17289
17290 // Figure out the underlying type if this a enum declaration. We need to do
17291 // this early, because it's needed to detect if this is an incompatible
17292 // redeclaration.
17293 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17294 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17295
17296 if (Kind == TagTypeKind::Enum) {
17297 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17298 // No underlying type explicitly specified, or we failed to parse the
17299 // type, default to int.
17300 EnumUnderlying = Context.IntTy.getTypePtr();
17301 } else if (UnderlyingType.get()) {
17302 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17303 // integral type; any cv-qualification is ignored.
17304 TypeSourceInfo *TI = nullptr;
17305 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17306 EnumUnderlying = TI;
17307
17308 if (CheckEnumUnderlyingType(TI))
17309 // Recover by falling back to int.
17310 EnumUnderlying = Context.IntTy.getTypePtr();
17311
17312 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17313 UPPC: UPPC_FixedUnderlyingType))
17314 EnumUnderlying = Context.IntTy.getTypePtr();
17315
17316 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17317 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17318 // of 'int'. However, if this is an unfixed forward declaration, don't set
17319 // the underlying type unless the user enables -fms-compatibility. This
17320 // makes unfixed forward declared enums incomplete and is more conforming.
17321 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17322 EnumUnderlying = Context.IntTy.getTypePtr();
17323 }
17324 }
17325
17326 DeclContext *SearchDC = CurContext;
17327 DeclContext *DC = CurContext;
17328 bool isStdBadAlloc = false;
17329 bool isStdAlignValT = false;
17330
17331 RedeclarationKind Redecl = forRedeclarationInCurContext();
17332 if (TUK == TUK_Friend || TUK == TUK_Reference)
17333 Redecl = NotForRedeclaration;
17334
17335 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17336 /// implemented asks for structural equivalence checking, the returned decl
17337 /// here is passed back to the parser, allowing the tag body to be parsed.
17338 auto createTagFromNewDecl = [&]() -> TagDecl * {
17339 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17340 // If there is an identifier, use the location of the identifier as the
17341 // location of the decl, otherwise use the location of the struct/union
17342 // keyword.
17343 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17344 TagDecl *New = nullptr;
17345
17346 if (Kind == TagTypeKind::Enum) {
17347 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17348 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17349 // If this is an undefined enum, bail.
17350 if (TUK != TUK_Definition && !Invalid)
17351 return nullptr;
17352 if (EnumUnderlying) {
17353 EnumDecl *ED = cast<EnumDecl>(Val: New);
17354 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17355 ED->setIntegerTypeSourceInfo(TI);
17356 else
17357 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17358 QualType EnumTy = ED->getIntegerType();
17359 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17360 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17361 : EnumTy);
17362 }
17363 } else { // struct/union
17364 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17365 PrevDecl: nullptr);
17366 }
17367
17368 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17369 // Add alignment attributes if necessary; these attributes are checked
17370 // when the ASTContext lays out the structure.
17371 //
17372 // It is important for implementing the correct semantics that this
17373 // happen here (in ActOnTag). The #pragma pack stack is
17374 // maintained as a result of parser callbacks which can occur at
17375 // many points during the parsing of a struct declaration (because
17376 // the #pragma tokens are effectively skipped over during the
17377 // parsing of the struct).
17378 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17379 AddAlignmentAttributesForRecord(RD);
17380 AddMsStructLayoutForRecord(RD);
17381 }
17382 }
17383 New->setLexicalDeclContext(CurContext);
17384 return New;
17385 };
17386
17387 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17388 if (Name && SS.isNotEmpty()) {
17389 // We have a nested-name tag ('struct foo::bar').
17390
17391 // Check for invalid 'foo::'.
17392 if (SS.isInvalid()) {
17393 Name = nullptr;
17394 goto CreateNewDecl;
17395 }
17396
17397 // If this is a friend or a reference to a class in a dependent
17398 // context, don't try to make a decl for it.
17399 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17400 DC = computeDeclContext(SS, EnteringContext: false);
17401 if (!DC) {
17402 IsDependent = true;
17403 return true;
17404 }
17405 } else {
17406 DC = computeDeclContext(SS, EnteringContext: true);
17407 if (!DC) {
17408 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17409 << SS.getRange();
17410 return true;
17411 }
17412 }
17413
17414 if (RequireCompleteDeclContext(SS, DC))
17415 return true;
17416
17417 SearchDC = DC;
17418 // Look-up name inside 'foo::'.
17419 LookupQualifiedName(R&: Previous, LookupCtx: DC);
17420
17421 if (Previous.isAmbiguous())
17422 return true;
17423
17424 if (Previous.empty()) {
17425 // Name lookup did not find anything. However, if the
17426 // nested-name-specifier refers to the current instantiation,
17427 // and that current instantiation has any dependent base
17428 // classes, we might find something at instantiation time: treat
17429 // this as a dependent elaborated-type-specifier.
17430 // But this only makes any sense for reference-like lookups.
17431 if (Previous.wasNotFoundInCurrentInstantiation() &&
17432 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17433 IsDependent = true;
17434 return true;
17435 }
17436
17437 // A tag 'foo::bar' must already exist.
17438 Diag(NameLoc, diag::err_not_tag_in_scope)
17439 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17440 Name = nullptr;
17441 Invalid = true;
17442 goto CreateNewDecl;
17443 }
17444 } else if (Name) {
17445 // C++14 [class.mem]p14:
17446 // If T is the name of a class, then each of the following shall have a
17447 // name different from T:
17448 // -- every member of class T that is itself a type
17449 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17450 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
17451 return true;
17452
17453 // If this is a named struct, check to see if there was a previous forward
17454 // declaration or definition.
17455 // FIXME: We're looking into outer scopes here, even when we
17456 // shouldn't be. Doing so can result in ambiguities that we
17457 // shouldn't be diagnosing.
17458 LookupName(R&: Previous, S);
17459
17460 // When declaring or defining a tag, ignore ambiguities introduced
17461 // by types using'ed into this scope.
17462 if (Previous.isAmbiguous() &&
17463 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17464 LookupResult::Filter F = Previous.makeFilter();
17465 while (F.hasNext()) {
17466 NamedDecl *ND = F.next();
17467 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17468 SearchDC->getRedeclContext()))
17469 F.erase();
17470 }
17471 F.done();
17472 }
17473
17474 // C++11 [namespace.memdef]p3:
17475 // If the name in a friend declaration is neither qualified nor
17476 // a template-id and the declaration is a function or an
17477 // elaborated-type-specifier, the lookup to determine whether
17478 // the entity has been previously declared shall not consider
17479 // any scopes outside the innermost enclosing namespace.
17480 //
17481 // MSVC doesn't implement the above rule for types, so a friend tag
17482 // declaration may be a redeclaration of a type declared in an enclosing
17483 // scope. They do implement this rule for friend functions.
17484 //
17485 // Does it matter that this should be by scope instead of by
17486 // semantic context?
17487 if (!Previous.empty() && TUK == TUK_Friend) {
17488 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17489 LookupResult::Filter F = Previous.makeFilter();
17490 bool FriendSawTagOutsideEnclosingNamespace = false;
17491 while (F.hasNext()) {
17492 NamedDecl *ND = F.next();
17493 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17494 if (DC->isFileContext() &&
17495 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
17496 if (getLangOpts().MSVCCompat)
17497 FriendSawTagOutsideEnclosingNamespace = true;
17498 else
17499 F.erase();
17500 }
17501 }
17502 F.done();
17503
17504 // Diagnose this MSVC extension in the easy case where lookup would have
17505 // unambiguously found something outside the enclosing namespace.
17506 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17507 NamedDecl *ND = Previous.getFoundDecl();
17508 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17509 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17510 }
17511 }
17512
17513 // Note: there used to be some attempt at recovery here.
17514 if (Previous.isAmbiguous())
17515 return true;
17516
17517 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17518 // FIXME: This makes sure that we ignore the contexts associated
17519 // with C structs, unions, and enums when looking for a matching
17520 // tag declaration or definition. See the similar lookup tweak
17521 // in Sema::LookupName; is there a better way to deal with this?
17522 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
17523 SearchDC = SearchDC->getParent();
17524 } else if (getLangOpts().CPlusPlus) {
17525 // Inside ObjCContainer want to keep it as a lexical decl context but go
17526 // past it (most often to TranslationUnit) to find the semantic decl
17527 // context.
17528 while (isa<ObjCContainerDecl>(Val: SearchDC))
17529 SearchDC = SearchDC->getParent();
17530 }
17531 } else if (getLangOpts().CPlusPlus) {
17532 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17533 // TagDecl the same way as we skip it for named TagDecl.
17534 while (isa<ObjCContainerDecl>(Val: SearchDC))
17535 SearchDC = SearchDC->getParent();
17536 }
17537
17538 if (Previous.isSingleResult() &&
17539 Previous.getFoundDecl()->isTemplateParameter()) {
17540 // Maybe we will complain about the shadowed template parameter.
17541 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17542 // Just pretend that we didn't see the previous declaration.
17543 Previous.clear();
17544 }
17545
17546 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17547 DC->Equals(getStdNamespace())) {
17548 if (Name->isStr(Str: "bad_alloc")) {
17549 // This is a declaration of or a reference to "std::bad_alloc".
17550 isStdBadAlloc = true;
17551
17552 // If std::bad_alloc has been implicitly declared (but made invisible to
17553 // name lookup), fill in this implicit declaration as the previous
17554 // declaration, so that the declarations get chained appropriately.
17555 if (Previous.empty() && StdBadAlloc)
17556 Previous.addDecl(getStdBadAlloc());
17557 } else if (Name->isStr(Str: "align_val_t")) {
17558 isStdAlignValT = true;
17559 if (Previous.empty() && StdAlignValT)
17560 Previous.addDecl(getStdAlignValT());
17561 }
17562 }
17563
17564 // If we didn't find a previous declaration, and this is a reference
17565 // (or friend reference), move to the correct scope. In C++, we
17566 // also need to do a redeclaration lookup there, just in case
17567 // there's a shadow friend decl.
17568 if (Name && Previous.empty() &&
17569 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17570 if (Invalid) goto CreateNewDecl;
17571 assert(SS.isEmpty());
17572
17573 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17574 // C++ [basic.scope.pdecl]p5:
17575 // -- for an elaborated-type-specifier of the form
17576 //
17577 // class-key identifier
17578 //
17579 // if the elaborated-type-specifier is used in the
17580 // decl-specifier-seq or parameter-declaration-clause of a
17581 // function defined in namespace scope, the identifier is
17582 // declared as a class-name in the namespace that contains
17583 // the declaration; otherwise, except as a friend
17584 // declaration, the identifier is declared in the smallest
17585 // non-class, non-function-prototype scope that contains the
17586 // declaration.
17587 //
17588 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17589 // C structs and unions.
17590 //
17591 // It is an error in C++ to declare (rather than define) an enum
17592 // type, including via an elaborated type specifier. We'll
17593 // diagnose that later; for now, declare the enum in the same
17594 // scope as we would have picked for any other tag type.
17595 //
17596 // GNU C also supports this behavior as part of its incomplete
17597 // enum types extension, while GNU C++ does not.
17598 //
17599 // Find the context where we'll be declaring the tag.
17600 // FIXME: We would like to maintain the current DeclContext as the
17601 // lexical context,
17602 SearchDC = getTagInjectionContext(DC: SearchDC);
17603
17604 // Find the scope where we'll be declaring the tag.
17605 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17606 } else {
17607 assert(TUK == TUK_Friend);
17608 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
17609
17610 // C++ [namespace.memdef]p3:
17611 // If a friend declaration in a non-local class first declares a
17612 // class or function, the friend class or function is a member of
17613 // the innermost enclosing namespace.
17614 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17615 : SearchDC->getEnclosingNamespaceContext();
17616 }
17617
17618 // In C++, we need to do a redeclaration lookup to properly
17619 // diagnose some problems.
17620 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17621 // hidden declaration so that we don't get ambiguity errors when using a
17622 // type declared by an elaborated-type-specifier. In C that is not correct
17623 // and we should instead merge compatible types found by lookup.
17624 if (getLangOpts().CPlusPlus) {
17625 // FIXME: This can perform qualified lookups into function contexts,
17626 // which are meaningless.
17627 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17628 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
17629 } else {
17630 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17631 LookupName(R&: Previous, S);
17632 }
17633 }
17634
17635 // If we have a known previous declaration to use, then use it.
17636 if (Previous.empty() && SkipBody && SkipBody->Previous)
17637 Previous.addDecl(D: SkipBody->Previous);
17638
17639 if (!Previous.empty()) {
17640 NamedDecl *PrevDecl = Previous.getFoundDecl();
17641 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17642
17643 // It's okay to have a tag decl in the same scope as a typedef
17644 // which hides a tag decl in the same scope. Finding this
17645 // with a redeclaration lookup can only actually happen in C++.
17646 //
17647 // This is also okay for elaborated-type-specifiers, which is
17648 // technically forbidden by the current standard but which is
17649 // okay according to the likely resolution of an open issue;
17650 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17651 if (getLangOpts().CPlusPlus) {
17652 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
17653 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17654 TagDecl *Tag = TT->getDecl();
17655 if (Tag->getDeclName() == Name &&
17656 Tag->getDeclContext()->getRedeclContext()
17657 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17658 PrevDecl = Tag;
17659 Previous.clear();
17660 Previous.addDecl(Tag);
17661 Previous.resolveKind();
17662 }
17663 }
17664 }
17665 }
17666
17667 // If this is a redeclaration of a using shadow declaration, it must
17668 // declare a tag in the same context. In MSVC mode, we allow a
17669 // redefinition if either context is within the other.
17670 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
17671 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
17672 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17673 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17674 !(OldTag && isAcceptableTagRedeclContext(
17675 *this, OldTag->getDeclContext(), SearchDC))) {
17676 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17677 Diag(Shadow->getTargetDecl()->getLocation(),
17678 diag::note_using_decl_target);
17679 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17680 << 0;
17681 // Recover by ignoring the old declaration.
17682 Previous.clear();
17683 goto CreateNewDecl;
17684 }
17685 }
17686
17687 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
17688 // If this is a use of a previous tag, or if the tag is already declared
17689 // in the same scope (so that the definition/declaration completes or
17690 // rementions the tag), reuse the decl.
17691 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17692 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
17693 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
17694 // Make sure that this wasn't declared as an enum and now used as a
17695 // struct or something similar.
17696 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
17697 isDefinition: TUK == TUK_Definition, NewTagLoc: KWLoc,
17698 Name)) {
17699 bool SafeToContinue =
17700 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17701 Kind != TagTypeKind::Enum);
17702 if (SafeToContinue)
17703 Diag(KWLoc, diag::err_use_with_wrong_tag)
17704 << Name
17705 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17706 PrevTagDecl->getKindName());
17707 else
17708 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17709 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17710
17711 if (SafeToContinue)
17712 Kind = PrevTagDecl->getTagKind();
17713 else {
17714 // Recover by making this an anonymous redefinition.
17715 Name = nullptr;
17716 Previous.clear();
17717 Invalid = true;
17718 }
17719 }
17720
17721 if (Kind == TagTypeKind::Enum &&
17722 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17723 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
17724 if (TUK == TUK_Reference || TUK == TUK_Friend)
17725 return PrevTagDecl;
17726
17727 QualType EnumUnderlyingTy;
17728 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17729 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17730 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17731 EnumUnderlyingTy = QualType(T, 0);
17732
17733 // All conflicts with previous declarations are recovered by
17734 // returning the previous declaration, unless this is a definition,
17735 // in which case we want the caller to bail out.
17736 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
17737 IsScoped: ScopedEnum, EnumUnderlyingTy,
17738 IsFixed, Prev: PrevEnum))
17739 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17740 }
17741
17742 // C++11 [class.mem]p1:
17743 // A member shall not be declared twice in the member-specification,
17744 // except that a nested class or member class template can be declared
17745 // and then later defined.
17746 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17747 S->isDeclScope(PrevDecl)) {
17748 Diag(NameLoc, diag::ext_member_redeclared);
17749 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17750 }
17751
17752 if (!Invalid) {
17753 // If this is a use, just return the declaration we found, unless
17754 // we have attributes.
17755 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17756 if (!Attrs.empty()) {
17757 // FIXME: Diagnose these attributes. For now, we create a new
17758 // declaration to hold them.
17759 } else if (TUK == TUK_Reference &&
17760 (PrevTagDecl->getFriendObjectKind() ==
17761 Decl::FOK_Undeclared ||
17762 PrevDecl->getOwningModule() != getCurrentModule()) &&
17763 SS.isEmpty()) {
17764 // This declaration is a reference to an existing entity, but
17765 // has different visibility from that entity: it either makes
17766 // a friend visible or it makes a type visible in a new module.
17767 // In either case, create a new declaration. We only do this if
17768 // the declaration would have meant the same thing if no prior
17769 // declaration were found, that is, if it was found in the same
17770 // scope where we would have injected a declaration.
17771 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
17772 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
17773 return PrevTagDecl;
17774 // This is in the injected scope, create a new declaration in
17775 // that scope.
17776 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17777 } else {
17778 return PrevTagDecl;
17779 }
17780 }
17781
17782 // Diagnose attempts to redefine a tag.
17783 if (TUK == TUK_Definition) {
17784 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17785 // If we're defining a specialization and the previous definition
17786 // is from an implicit instantiation, don't emit an error
17787 // here; we'll catch this in the general case below.
17788 bool IsExplicitSpecializationAfterInstantiation = false;
17789 if (isMemberSpecialization) {
17790 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
17791 IsExplicitSpecializationAfterInstantiation =
17792 RD->getTemplateSpecializationKind() !=
17793 TSK_ExplicitSpecialization;
17794 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
17795 IsExplicitSpecializationAfterInstantiation =
17796 ED->getTemplateSpecializationKind() !=
17797 TSK_ExplicitSpecialization;
17798 }
17799
17800 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17801 // not keep more that one definition around (merge them). However,
17802 // ensure the decl passes the structural compatibility check in
17803 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17804 NamedDecl *Hidden = nullptr;
17805 if (SkipBody && !hasVisibleDefinition(D: Def, Suggested: &Hidden)) {
17806 // There is a definition of this tag, but it is not visible. We
17807 // explicitly make use of C++'s one definition rule here, and
17808 // assume that this definition is identical to the hidden one
17809 // we already have. Make the existing definition visible and
17810 // use it in place of this one.
17811 if (!getLangOpts().CPlusPlus) {
17812 // Postpone making the old definition visible until after we
17813 // complete parsing the new one and do the structural
17814 // comparison.
17815 SkipBody->CheckSameAsPrevious = true;
17816 SkipBody->New = createTagFromNewDecl();
17817 SkipBody->Previous = Def;
17818 return Def;
17819 } else {
17820 SkipBody->ShouldSkip = true;
17821 SkipBody->Previous = Def;
17822 makeMergedDefinitionVisible(ND: Hidden);
17823 // Carry on and handle it like a normal definition. We'll
17824 // skip starting the definitiion later.
17825 }
17826 } else if (!IsExplicitSpecializationAfterInstantiation) {
17827 // A redeclaration in function prototype scope in C isn't
17828 // visible elsewhere, so merely issue a warning.
17829 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17830 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17831 else
17832 Diag(NameLoc, diag::err_redefinition) << Name;
17833 notePreviousDefinition(Old: Def,
17834 New: NameLoc.isValid() ? NameLoc : KWLoc);
17835 // If this is a redefinition, recover by making this
17836 // struct be anonymous, which will make any later
17837 // references get the previous definition.
17838 Name = nullptr;
17839 Previous.clear();
17840 Invalid = true;
17841 }
17842 } else {
17843 // If the type is currently being defined, complain
17844 // about a nested redefinition.
17845 auto *TD = Context.getTagDeclType(Decl: PrevTagDecl)->getAsTagDecl();
17846 if (TD->isBeingDefined()) {
17847 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17848 Diag(PrevTagDecl->getLocation(),
17849 diag::note_previous_definition);
17850 Name = nullptr;
17851 Previous.clear();
17852 Invalid = true;
17853 }
17854 }
17855
17856 // Okay, this is definition of a previously declared or referenced
17857 // tag. We're going to create a new Decl for it.
17858 }
17859
17860 // Okay, we're going to make a redeclaration. If this is some kind
17861 // of reference, make sure we build the redeclaration in the same DC
17862 // as the original, and ignore the current access specifier.
17863 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17864 SearchDC = PrevTagDecl->getDeclContext();
17865 AS = AS_none;
17866 }
17867 }
17868 // If we get here we have (another) forward declaration or we
17869 // have a definition. Just create a new decl.
17870
17871 } else {
17872 // If we get here, this is a definition of a new tag type in a nested
17873 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17874 // new decl/type. We set PrevDecl to NULL so that the entities
17875 // have distinct types.
17876 Previous.clear();
17877 }
17878 // If we get here, we're going to create a new Decl. If PrevDecl
17879 // is non-NULL, it's a definition of the tag declared by
17880 // PrevDecl. If it's NULL, we have a new definition.
17881
17882 // Otherwise, PrevDecl is not a tag, but was found with tag
17883 // lookup. This is only actually possible in C++, where a few
17884 // things like templates still live in the tag namespace.
17885 } else {
17886 // Use a better diagnostic if an elaborated-type-specifier
17887 // found the wrong kind of type on the first
17888 // (non-redeclaration) lookup.
17889 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17890 !Previous.isForRedeclaration()) {
17891 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17892 Diag(NameLoc, diag::err_tag_reference_non_tag)
17893 << PrevDecl << NTK << llvm::to_underlying(Kind);
17894 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17895 Invalid = true;
17896
17897 // Otherwise, only diagnose if the declaration is in scope.
17898 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
17899 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
17900 // do nothing
17901
17902 // Diagnose implicit declarations introduced by elaborated types.
17903 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17904 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17905 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17906 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17907 Invalid = true;
17908
17909 // Otherwise it's a declaration. Call out a particularly common
17910 // case here.
17911 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
17912 unsigned Kind = 0;
17913 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
17914 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17915 << Name << Kind << TND->getUnderlyingType();
17916 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17917 Invalid = true;
17918
17919 // Otherwise, diagnose.
17920 } else {
17921 // The tag name clashes with something else in the target scope,
17922 // issue an error and recover by making this tag be anonymous.
17923 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17924 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
17925 Name = nullptr;
17926 Invalid = true;
17927 }
17928
17929 // The existing declaration isn't relevant to us; we're in a
17930 // new scope, so clear out the previous declaration.
17931 Previous.clear();
17932 }
17933 }
17934
17935CreateNewDecl:
17936
17937 TagDecl *PrevDecl = nullptr;
17938 if (Previous.isSingleResult())
17939 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
17940
17941 // If there is an identifier, use the location of the identifier as the
17942 // location of the decl, otherwise use the location of the struct/union
17943 // keyword.
17944 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17945
17946 // Otherwise, create a new declaration. If there is a previous
17947 // declaration of the same entity, the two will be linked via
17948 // PrevDecl.
17949 TagDecl *New;
17950
17951 if (Kind == TagTypeKind::Enum) {
17952 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17953 // enum X { A, B, C } D; D should chain to X.
17954 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17955 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
17956 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17957
17958 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17959 StdAlignValT = cast<EnumDecl>(Val: New);
17960
17961 // If this is an undefined enum, warn.
17962 if (TUK != TUK_Definition && !Invalid) {
17963 TagDecl *Def;
17964 if (IsFixed && cast<EnumDecl>(Val: New)->isFixed()) {
17965 // C++0x: 7.2p2: opaque-enum-declaration.
17966 // Conflicts are diagnosed above. Do nothing.
17967 }
17968 else if (PrevDecl && (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
17969 Diag(Loc, diag::ext_forward_ref_enum_def)
17970 << New;
17971 Diag(Def->getLocation(), diag::note_previous_definition);
17972 } else {
17973 unsigned DiagID = diag::ext_forward_ref_enum;
17974 if (getLangOpts().MSVCCompat)
17975 DiagID = diag::ext_ms_forward_ref_enum;
17976 else if (getLangOpts().CPlusPlus)
17977 DiagID = diag::err_forward_ref_enum;
17978 Diag(Loc, DiagID);
17979 }
17980 }
17981
17982 if (EnumUnderlying) {
17983 EnumDecl *ED = cast<EnumDecl>(Val: New);
17984 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17985 ED->setIntegerTypeSourceInfo(TI);
17986 else
17987 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17988 QualType EnumTy = ED->getIntegerType();
17989 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17990 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17991 : EnumTy);
17992 assert(ED->isComplete() && "enum with type should be complete");
17993 }
17994 } else {
17995 // struct/union/class
17996
17997 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17998 // struct X { int A; } D; D should chain to X.
17999 if (getLangOpts().CPlusPlus) {
18000 // FIXME: Look for a way to use RecordDecl for simple structs.
18001 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18002 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18003
18004 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18005 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18006 } else
18007 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18008 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18009 }
18010
18011 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
18012 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18013 << (OOK == OOK_Macro) << New->getSourceRange();
18014
18015 // C++11 [dcl.type]p3:
18016 // A type-specifier-seq shall not define a class or enumeration [...].
18017 if (!Invalid && getLangOpts().CPlusPlus &&
18018 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
18019 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18020 << Context.getTagDeclType(New);
18021 Invalid = true;
18022 }
18023
18024 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
18025 DC->getDeclKind() == Decl::Enum) {
18026 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18027 << Context.getTagDeclType(New);
18028 Invalid = true;
18029 }
18030
18031 // Maybe add qualifier info.
18032 if (SS.isNotEmpty()) {
18033 if (SS.isSet()) {
18034 // If this is either a declaration or a definition, check the
18035 // nested-name-specifier against the current context.
18036 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
18037 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18038 /*TemplateId=*/nullptr,
18039 IsMemberSpecialization: isMemberSpecialization))
18040 Invalid = true;
18041
18042 New->setQualifierInfo(SS.getWithLocInContext(Context));
18043 if (TemplateParameterLists.size() > 0) {
18044 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18045 }
18046 }
18047 else
18048 Invalid = true;
18049 }
18050
18051 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18052 // Add alignment attributes if necessary; these attributes are checked when
18053 // the ASTContext lays out the structure.
18054 //
18055 // It is important for implementing the correct semantics that this
18056 // happen here (in ActOnTag). The #pragma pack stack is
18057 // maintained as a result of parser callbacks which can occur at
18058 // many points during the parsing of a struct declaration (because
18059 // the #pragma tokens are effectively skipped over during the
18060 // parsing of the struct).
18061 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18062 AddAlignmentAttributesForRecord(RD);
18063 AddMsStructLayoutForRecord(RD);
18064 }
18065 }
18066
18067 if (ModulePrivateLoc.isValid()) {
18068 if (isMemberSpecialization)
18069 Diag(New->getLocation(), diag::err_module_private_specialization)
18070 << 2
18071 << FixItHint::CreateRemoval(ModulePrivateLoc);
18072 // __module_private__ does not apply to local classes. However, we only
18073 // diagnose this as an error when the declaration specifiers are
18074 // freestanding. Here, we just ignore the __module_private__.
18075 else if (!SearchDC->isFunctionOrMethod())
18076 New->setModulePrivate();
18077 }
18078
18079 // If this is a specialization of a member class (of a class template),
18080 // check the specialization.
18081 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18082 Invalid = true;
18083
18084 // If we're declaring or defining a tag in function prototype scope in C,
18085 // note that this type can only be used within the function and add it to
18086 // the list of decls to inject into the function definition scope.
18087 if ((Name || Kind == TagTypeKind::Enum) &&
18088 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18089 if (getLangOpts().CPlusPlus) {
18090 // C++ [dcl.fct]p6:
18091 // Types shall not be defined in return or parameter types.
18092 if (TUK == TUK_Definition && !IsTypeSpecifier) {
18093 Diag(Loc, diag::err_type_defined_in_param_type)
18094 << Name;
18095 Invalid = true;
18096 }
18097 } else if (!PrevDecl) {
18098 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18099 }
18100 }
18101
18102 if (Invalid)
18103 New->setInvalidDecl();
18104
18105 // Set the lexical context. If the tag has a C++ scope specifier, the
18106 // lexical context will be different from the semantic context.
18107 New->setLexicalDeclContext(CurContext);
18108
18109 // Mark this as a friend decl if applicable.
18110 // In Microsoft mode, a friend declaration also acts as a forward
18111 // declaration so we always pass true to setObjectOfFriendDecl to make
18112 // the tag name visible.
18113 if (TUK == TUK_Friend)
18114 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18115
18116 // Set the access specifier.
18117 if (!Invalid && SearchDC->isRecord())
18118 SetMemberAccessSpecifier(New, PrevDecl, AS);
18119
18120 if (PrevDecl)
18121 CheckRedeclarationInModule(New, PrevDecl);
18122
18123 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18124 New->startDefinition();
18125
18126 ProcessDeclAttributeList(S, New, Attrs);
18127 AddPragmaAttributes(S, New);
18128
18129 // If this has an identifier, add it to the scope stack.
18130 if (TUK == TUK_Friend) {
18131 // We might be replacing an existing declaration in the lookup tables;
18132 // if so, borrow its access specifier.
18133 if (PrevDecl)
18134 New->setAccess(PrevDecl->getAccess());
18135
18136 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18137 DC->makeDeclVisibleInContext(New);
18138 if (Name) // can be null along some error paths
18139 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18140 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18141 } else if (Name) {
18142 S = getNonFieldDeclScope(S);
18143 PushOnScopeChains(New, S, true);
18144 } else {
18145 CurContext->addDecl(New);
18146 }
18147
18148 // If this is the C FILE type, notify the AST context.
18149 if (IdentifierInfo *II = New->getIdentifier())
18150 if (!New->isInvalidDecl() &&
18151 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18152 II->isStr(Str: "FILE"))
18153 Context.setFILEDecl(New);
18154
18155 if (PrevDecl)
18156 mergeDeclAttributes(New, PrevDecl);
18157
18158 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New))
18159 inferGslOwnerPointerAttribute(Record: CXXRD);
18160
18161 // If there's a #pragma GCC visibility in scope, set the visibility of this
18162 // record.
18163 AddPushedVisibilityAttribute(New);
18164
18165 if (isMemberSpecialization && !New->isInvalidDecl())
18166 CompleteMemberSpecialization(New, Previous);
18167
18168 OwnedDecl = true;
18169 // In C++, don't return an invalid declaration. We can't recover well from
18170 // the cases where we make the type anonymous.
18171 if (Invalid && getLangOpts().CPlusPlus) {
18172 if (New->isBeingDefined())
18173 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18174 RD->completeDefinition();
18175 return true;
18176 } else if (SkipBody && SkipBody->ShouldSkip) {
18177 return SkipBody->Previous;
18178 } else {
18179 return New;
18180 }
18181}
18182
18183void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18184 AdjustDeclIfTemplate(Decl&: TagD);
18185 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18186
18187 // Enter the tag context.
18188 PushDeclContext(S, Tag);
18189
18190 ActOnDocumentableDecl(D: TagD);
18191
18192 // If there's a #pragma GCC visibility in scope, set the visibility of this
18193 // record.
18194 AddPushedVisibilityAttribute(Tag);
18195}
18196
18197bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
18198 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18199 return false;
18200
18201 // Make the previous decl visible.
18202 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18203 return true;
18204}
18205
18206void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
18207 assert(IDecl->getLexicalParent() == CurContext &&
18208 "The next DeclContext should be lexically contained in the current one.");
18209 CurContext = IDecl;
18210}
18211
18212void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18213 SourceLocation FinalLoc,
18214 bool IsFinalSpelledSealed,
18215 bool IsAbstract,
18216 SourceLocation LBraceLoc) {
18217 AdjustDeclIfTemplate(Decl&: TagD);
18218 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18219
18220 FieldCollector->StartClass();
18221
18222 if (!Record->getIdentifier())
18223 return;
18224
18225 if (IsAbstract)
18226 Record->markAbstract();
18227
18228 if (FinalLoc.isValid()) {
18229 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18230 IsFinalSpelledSealed
18231 ? FinalAttr::Keyword_sealed
18232 : FinalAttr::Keyword_final));
18233 }
18234 // C++ [class]p2:
18235 // [...] The class-name is also inserted into the scope of the
18236 // class itself; this is known as the injected-class-name. For
18237 // purposes of access checking, the injected-class-name is treated
18238 // as if it were a public member name.
18239 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18240 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18241 IdLoc: Record->getLocation(), Id: Record->getIdentifier(),
18242 /*PrevDecl=*/nullptr,
18243 /*DelayTypeCreation=*/true);
18244 Context.getTypeDeclType(InjectedClassName, Record);
18245 InjectedClassName->setImplicit();
18246 InjectedClassName->setAccess(AS_public);
18247 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18248 InjectedClassName->setDescribedClassTemplate(Template);
18249 PushOnScopeChains(InjectedClassName, S);
18250 assert(InjectedClassName->isInjectedClassName() &&
18251 "Broken injected-class-name");
18252}
18253
18254void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18255 SourceRange BraceRange) {
18256 AdjustDeclIfTemplate(Decl&: TagD);
18257 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18258 Tag->setBraceRange(BraceRange);
18259
18260 // Make sure we "complete" the definition even it is invalid.
18261 if (Tag->isBeingDefined()) {
18262 assert(Tag->isInvalidDecl() && "We should already have completed it");
18263 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18264 RD->completeDefinition();
18265 }
18266
18267 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18268 FieldCollector->FinishClass();
18269 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18270 auto *Def = RD->getDefinition();
18271 assert(Def && "The record is expected to have a completed definition");
18272 unsigned NumInitMethods = 0;
18273 for (auto *Method : Def->methods()) {
18274 if (!Method->getIdentifier())
18275 continue;
18276 if (Method->getName() == "__init")
18277 NumInitMethods++;
18278 }
18279 if (NumInitMethods > 1 || !Def->hasInitMethod())
18280 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18281 }
18282 }
18283
18284 // Exit this scope of this tag's definition.
18285 PopDeclContext();
18286
18287 if (getCurLexicalContext()->isObjCContainer() &&
18288 Tag->getDeclContext()->isFileContext())
18289 Tag->setTopLevelDeclInObjCContainer();
18290
18291 // Notify the consumer that we've defined a tag.
18292 if (!Tag->isInvalidDecl())
18293 Consumer.HandleTagDeclDefinition(D: Tag);
18294
18295 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18296 // from XLs and instead matches the XL #pragma pack(1) behavior.
18297 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18298 AlignPackStack.hasValue()) {
18299 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18300 // Only diagnose #pragma align(packed).
18301 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18302 return;
18303 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18304 if (!RD)
18305 return;
18306 // Only warn if there is at least 1 bitfield member.
18307 if (llvm::any_of(RD->fields(),
18308 [](const FieldDecl *FD) { return FD->isBitField(); }))
18309 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18310 }
18311}
18312
18313void Sema::ActOnObjCContainerFinishDefinition() {
18314 // Exit this scope of this interface definition.
18315 PopDeclContext();
18316}
18317
18318void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
18319 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18320 OriginalLexicalContext = ObjCCtx;
18321 ActOnObjCContainerFinishDefinition();
18322}
18323
18324void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
18325 ActOnObjCContainerStartDefinition(IDecl: ObjCCtx);
18326 OriginalLexicalContext = nullptr;
18327}
18328
18329void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18330 AdjustDeclIfTemplate(Decl&: TagD);
18331 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18332 Tag->setInvalidDecl();
18333
18334 // Make sure we "complete" the definition even it is invalid.
18335 if (Tag->isBeingDefined()) {
18336 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18337 RD->completeDefinition();
18338 }
18339
18340 // We're undoing ActOnTagStartDefinition here, not
18341 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18342 // the FieldCollector.
18343
18344 PopDeclContext();
18345}
18346
18347// Note that FieldName may be null for anonymous bitfields.
18348ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18349 IdentifierInfo *FieldName, QualType FieldTy,
18350 bool IsMsStruct, Expr *BitWidth) {
18351 assert(BitWidth);
18352 if (BitWidth->containsErrors())
18353 return ExprError();
18354
18355 // C99 6.7.2.1p4 - verify the field type.
18356 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18357 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18358 // Handle incomplete and sizeless types with a specific error.
18359 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18360 diag::err_field_incomplete_or_sizeless))
18361 return ExprError();
18362 if (FieldName)
18363 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18364 << FieldName << FieldTy << BitWidth->getSourceRange();
18365 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18366 << FieldTy << BitWidth->getSourceRange();
18367 } else if (DiagnoseUnexpandedParameterPack(E: const_cast<Expr *>(BitWidth),
18368 UPPC: UPPC_BitFieldWidth))
18369 return ExprError();
18370
18371 // If the bit-width is type- or value-dependent, don't try to check
18372 // it now.
18373 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18374 return BitWidth;
18375
18376 llvm::APSInt Value;
18377 ExprResult ICE = VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFold);
18378 if (ICE.isInvalid())
18379 return ICE;
18380 BitWidth = ICE.get();
18381
18382 // Zero-width bitfield is ok for anonymous field.
18383 if (Value == 0 && FieldName)
18384 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18385 << FieldName << BitWidth->getSourceRange();
18386
18387 if (Value.isSigned() && Value.isNegative()) {
18388 if (FieldName)
18389 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18390 << FieldName << toString(Value, 10);
18391 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18392 << toString(Value, 10);
18393 }
18394
18395 // The size of the bit-field must not exceed our maximum permitted object
18396 // size.
18397 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18398 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18399 << !FieldName << FieldName << toString(Value, 10);
18400 }
18401
18402 if (!FieldTy->isDependentType()) {
18403 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
18404 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
18405 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
18406
18407 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18408 // ABI.
18409 bool CStdConstraintViolation =
18410 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18411 bool MSBitfieldViolation =
18412 Value.ugt(RHS: TypeStorageSize) &&
18413 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18414 if (CStdConstraintViolation || MSBitfieldViolation) {
18415 unsigned DiagWidth =
18416 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18417 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18418 << (bool)FieldName << FieldName << toString(Value, 10)
18419 << !CStdConstraintViolation << DiagWidth;
18420 }
18421
18422 // Warn on types where the user might conceivably expect to get all
18423 // specified bits as value bits: that's all integral types other than
18424 // 'bool'.
18425 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18426 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18427 << FieldName << toString(Value, 10)
18428 << (unsigned)TypeWidth;
18429 }
18430 }
18431
18432 return BitWidth;
18433}
18434
18435/// ActOnField - Each field of a C struct/union is passed into this in order
18436/// to create a FieldDecl object for it.
18437Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18438 Declarator &D, Expr *BitfieldWidth) {
18439 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
18440 D, BitfieldWidth,
18441 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
18442 return Res;
18443}
18444
18445/// HandleField - Analyze a field of a C struct or a C++ data member.
18446///
18447FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18448 SourceLocation DeclStart,
18449 Declarator &D, Expr *BitWidth,
18450 InClassInitStyle InitStyle,
18451 AccessSpecifier AS) {
18452 if (D.isDecompositionDeclarator()) {
18453 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18454 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18455 << Decomp.getSourceRange();
18456 return nullptr;
18457 }
18458
18459 IdentifierInfo *II = D.getIdentifier();
18460 SourceLocation Loc = DeclStart;
18461 if (II) Loc = D.getIdentifierLoc();
18462
18463 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18464 QualType T = TInfo->getType();
18465 if (getLangOpts().CPlusPlus) {
18466 CheckExtraCXXDefaultArguments(D);
18467
18468 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
18469 UPPC: UPPC_DataMemberType)) {
18470 D.setInvalidType();
18471 T = Context.IntTy;
18472 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18473 }
18474 }
18475
18476 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
18477
18478 if (D.getDeclSpec().isInlineSpecified())
18479 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18480 << getLangOpts().CPlusPlus17;
18481 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18482 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18483 diag::err_invalid_thread)
18484 << DeclSpec::getSpecifierName(TSCS);
18485
18486 // Check to see if this name was declared as a member previously
18487 NamedDecl *PrevDecl = nullptr;
18488 LookupResult Previous(*this, II, Loc, LookupMemberName,
18489 ForVisibleRedeclaration);
18490 LookupName(R&: Previous, S);
18491 switch (Previous.getResultKind()) {
18492 case LookupResult::Found:
18493 case LookupResult::FoundUnresolvedValue:
18494 PrevDecl = Previous.getAsSingle<NamedDecl>();
18495 break;
18496
18497 case LookupResult::FoundOverloaded:
18498 PrevDecl = Previous.getRepresentativeDecl();
18499 break;
18500
18501 case LookupResult::NotFound:
18502 case LookupResult::NotFoundInCurrentInstantiation:
18503 case LookupResult::Ambiguous:
18504 break;
18505 }
18506 Previous.suppressDiagnostics();
18507
18508 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18509 // Maybe we will complain about the shadowed template parameter.
18510 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18511 // Just pretend that we didn't see the previous declaration.
18512 PrevDecl = nullptr;
18513 }
18514
18515 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18516 PrevDecl = nullptr;
18517
18518 bool Mutable
18519 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18520 SourceLocation TSSL = D.getBeginLoc();
18521 FieldDecl *NewFD
18522 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
18523 TSSL, AS, PrevDecl, D: &D);
18524
18525 if (NewFD->isInvalidDecl())
18526 Record->setInvalidDecl();
18527
18528 if (D.getDeclSpec().isModulePrivateSpecified())
18529 NewFD->setModulePrivate();
18530
18531 if (NewFD->isInvalidDecl() && PrevDecl) {
18532 // Don't introduce NewFD into scope; there's already something
18533 // with the same name in the same scope.
18534 } else if (II) {
18535 PushOnScopeChains(NewFD, S);
18536 } else
18537 Record->addDecl(NewFD);
18538
18539 return NewFD;
18540}
18541
18542/// Build a new FieldDecl and check its well-formedness.
18543///
18544/// This routine builds a new FieldDecl given the fields name, type,
18545/// record, etc. \p PrevDecl should refer to any previous declaration
18546/// with the same name and in the same scope as the field to be
18547/// created.
18548///
18549/// \returns a new FieldDecl.
18550///
18551/// \todo The Declarator argument is a hack. It will be removed once
18552FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18553 TypeSourceInfo *TInfo,
18554 RecordDecl *Record, SourceLocation Loc,
18555 bool Mutable, Expr *BitWidth,
18556 InClassInitStyle InitStyle,
18557 SourceLocation TSSL,
18558 AccessSpecifier AS, NamedDecl *PrevDecl,
18559 Declarator *D) {
18560 IdentifierInfo *II = Name.getAsIdentifierInfo();
18561 bool InvalidDecl = false;
18562 if (D) InvalidDecl = D->isInvalidType();
18563
18564 // If we receive a broken type, recover by assuming 'int' and
18565 // marking this declaration as invalid.
18566 if (T.isNull() || T->containsErrors()) {
18567 InvalidDecl = true;
18568 T = Context.IntTy;
18569 }
18570
18571 QualType EltTy = Context.getBaseElementType(QT: T);
18572 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18573 if (RequireCompleteSizedType(Loc, EltTy,
18574 diag::err_field_incomplete_or_sizeless)) {
18575 // Fields of incomplete type force their record to be invalid.
18576 Record->setInvalidDecl();
18577 InvalidDecl = true;
18578 } else {
18579 NamedDecl *Def;
18580 EltTy->isIncompleteType(Def: &Def);
18581 if (Def && Def->isInvalidDecl()) {
18582 Record->setInvalidDecl();
18583 InvalidDecl = true;
18584 }
18585 }
18586 }
18587
18588 // TR 18037 does not allow fields to be declared with address space
18589 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18590 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18591 Diag(Loc, diag::err_field_with_address_space);
18592 Record->setInvalidDecl();
18593 InvalidDecl = true;
18594 }
18595
18596 if (LangOpts.OpenCL) {
18597 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18598 // used as structure or union field: image, sampler, event or block types.
18599 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18600 T->isBlockPointerType()) {
18601 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18602 Record->setInvalidDecl();
18603 InvalidDecl = true;
18604 }
18605 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18606 // is enabled.
18607 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18608 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
18609 Diag(Loc, diag::err_opencl_bitfields);
18610 InvalidDecl = true;
18611 }
18612 }
18613
18614 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18615 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18616 T.hasQualifiers()) {
18617 InvalidDecl = true;
18618 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18619 }
18620
18621 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18622 // than a variably modified type.
18623 if (!InvalidDecl && T->isVariablyModifiedType()) {
18624 if (!tryToFixVariablyModifiedVarType(
18625 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18626 InvalidDecl = true;
18627 }
18628
18629 // Fields can not have abstract class types
18630 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18631 diag::err_abstract_type_in_decl,
18632 AbstractFieldType))
18633 InvalidDecl = true;
18634
18635 if (InvalidDecl)
18636 BitWidth = nullptr;
18637 // If this is declared as a bit-field, check the bit-field.
18638 if (BitWidth) {
18639 BitWidth =
18640 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
18641 if (!BitWidth) {
18642 InvalidDecl = true;
18643 BitWidth = nullptr;
18644 }
18645 }
18646
18647 // Check that 'mutable' is consistent with the type of the declaration.
18648 if (!InvalidDecl && Mutable) {
18649 unsigned DiagID = 0;
18650 if (T->isReferenceType())
18651 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18652 : diag::err_mutable_reference;
18653 else if (T.isConstQualified())
18654 DiagID = diag::err_mutable_const;
18655
18656 if (DiagID) {
18657 SourceLocation ErrLoc = Loc;
18658 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18659 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18660 Diag(Loc: ErrLoc, DiagID);
18661 if (DiagID != diag::ext_mutable_reference) {
18662 Mutable = false;
18663 InvalidDecl = true;
18664 }
18665 }
18666 }
18667
18668 // C++11 [class.union]p8 (DR1460):
18669 // At most one variant member of a union may have a
18670 // brace-or-equal-initializer.
18671 if (InitStyle != ICIS_NoInit)
18672 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
18673
18674 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18675 BitWidth, Mutable, InitStyle);
18676 if (InvalidDecl)
18677 NewFD->setInvalidDecl();
18678
18679 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
18680 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
18681 Diag(Loc, diag::err_duplicate_member) << II;
18682 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18683 NewFD->setInvalidDecl();
18684 }
18685
18686 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18687 if (Record->isUnion()) {
18688 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18689 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
18690 if (RDecl->getDefinition()) {
18691 // C++ [class.union]p1: An object of a class with a non-trivial
18692 // constructor, a non-trivial copy constructor, a non-trivial
18693 // destructor, or a non-trivial copy assignment operator
18694 // cannot be a member of a union, nor can an array of such
18695 // objects.
18696 if (CheckNontrivialField(FD: NewFD))
18697 NewFD->setInvalidDecl();
18698 }
18699 }
18700
18701 // C++ [class.union]p1: If a union contains a member of reference type,
18702 // the program is ill-formed, except when compiling with MSVC extensions
18703 // enabled.
18704 if (EltTy->isReferenceType()) {
18705 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18706 diag::ext_union_member_of_reference_type :
18707 diag::err_union_member_of_reference_type)
18708 << NewFD->getDeclName() << EltTy;
18709 if (!getLangOpts().MicrosoftExt)
18710 NewFD->setInvalidDecl();
18711 }
18712 }
18713 }
18714
18715 // FIXME: We need to pass in the attributes given an AST
18716 // representation, not a parser representation.
18717 if (D) {
18718 // FIXME: The current scope is almost... but not entirely... correct here.
18719 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18720
18721 if (NewFD->hasAttrs())
18722 CheckAlignasUnderalignment(NewFD);
18723 }
18724
18725 // In auto-retain/release, infer strong retension for fields of
18726 // retainable type.
18727 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18728 NewFD->setInvalidDecl();
18729
18730 if (T.isObjCGCWeak())
18731 Diag(Loc, diag::warn_attribute_weak_on_field);
18732
18733 // PPC MMA non-pointer types are not allowed as field types.
18734 if (Context.getTargetInfo().getTriple().isPPC64() &&
18735 CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
18736 NewFD->setInvalidDecl();
18737
18738 NewFD->setAccess(AS);
18739 return NewFD;
18740}
18741
18742bool Sema::CheckNontrivialField(FieldDecl *FD) {
18743 assert(FD);
18744 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18745
18746 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18747 return false;
18748
18749 QualType EltTy = Context.getBaseElementType(FD->getType());
18750 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18751 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
18752 if (RDecl->getDefinition()) {
18753 // We check for copy constructors before constructors
18754 // because otherwise we'll never get complaints about
18755 // copy constructors.
18756
18757 CXXSpecialMember member = CXXInvalid;
18758 // We're required to check for any non-trivial constructors. Since the
18759 // implicit default constructor is suppressed if there are any
18760 // user-declared constructors, we just need to check that there is a
18761 // trivial default constructor and a trivial copy constructor. (We don't
18762 // worry about move constructors here, since this is a C++98 check.)
18763 if (RDecl->hasNonTrivialCopyConstructor())
18764 member = CXXCopyConstructor;
18765 else if (!RDecl->hasTrivialDefaultConstructor())
18766 member = CXXDefaultConstructor;
18767 else if (RDecl->hasNonTrivialCopyAssignment())
18768 member = CXXCopyAssignment;
18769 else if (RDecl->hasNonTrivialDestructor())
18770 member = CXXDestructor;
18771
18772 if (member != CXXInvalid) {
18773 if (!getLangOpts().CPlusPlus11 &&
18774 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18775 // Objective-C++ ARC: it is an error to have a non-trivial field of
18776 // a union. However, system headers in Objective-C programs
18777 // occasionally have Objective-C lifetime objects within unions,
18778 // and rather than cause the program to fail, we make those
18779 // members unavailable.
18780 SourceLocation Loc = FD->getLocation();
18781 if (getSourceManager().isInSystemHeader(Loc)) {
18782 if (!FD->hasAttr<UnavailableAttr>())
18783 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18784 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18785 return false;
18786 }
18787 }
18788
18789 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18790 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18791 diag::err_illegal_union_or_anon_struct_member)
18792 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18793 DiagnoseNontrivial(Record: RDecl, CSM: member);
18794 return !getLangOpts().CPlusPlus11;
18795 }
18796 }
18797 }
18798
18799 return false;
18800}
18801
18802/// TranslateIvarVisibility - Translate visibility from a token ID to an
18803/// AST enum value.
18804static ObjCIvarDecl::AccessControl
18805TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18806 switch (ivarVisibility) {
18807 default: llvm_unreachable("Unknown visitibility kind");
18808 case tok::objc_private: return ObjCIvarDecl::Private;
18809 case tok::objc_public: return ObjCIvarDecl::Public;
18810 case tok::objc_protected: return ObjCIvarDecl::Protected;
18811 case tok::objc_package: return ObjCIvarDecl::Package;
18812 }
18813}
18814
18815/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18816/// in order to create an IvarDecl object for it.
18817Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
18818 Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
18819
18820 IdentifierInfo *II = D.getIdentifier();
18821 SourceLocation Loc = DeclStart;
18822 if (II) Loc = D.getIdentifierLoc();
18823
18824 // FIXME: Unnamed fields can be handled in various different ways, for
18825 // example, unnamed unions inject all members into the struct namespace!
18826
18827 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18828 QualType T = TInfo->getType();
18829
18830 if (BitWidth) {
18831 // 6.7.2.1p3, 6.7.2.1p4
18832 BitWidth = VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, /*IsMsStruct*/false, BitWidth).get();
18833 if (!BitWidth)
18834 D.setInvalidType();
18835 } else {
18836 // Not a bitfield.
18837
18838 // validate II.
18839
18840 }
18841 if (T->isReferenceType()) {
18842 Diag(Loc, diag::err_ivar_reference_type);
18843 D.setInvalidType();
18844 }
18845 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18846 // than a variably modified type.
18847 else if (T->isVariablyModifiedType()) {
18848 if (!tryToFixVariablyModifiedVarType(
18849 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18850 D.setInvalidType();
18851 }
18852
18853 // Get the visibility (access control) for this ivar.
18854 ObjCIvarDecl::AccessControl ac =
18855 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(ivarVisibility: Visibility)
18856 : ObjCIvarDecl::None;
18857 // Must set ivar's DeclContext to its enclosing interface.
18858 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(Val: CurContext);
18859 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18860 return nullptr;
18861 ObjCContainerDecl *EnclosingContext;
18862 if (ObjCImplementationDecl *IMPDecl =
18863 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
18864 if (LangOpts.ObjCRuntime.isFragile()) {
18865 // Case of ivar declared in an implementation. Context is that of its class.
18866 EnclosingContext = IMPDecl->getClassInterface();
18867 assert(EnclosingContext && "Implementation has no class interface!");
18868 }
18869 else
18870 EnclosingContext = EnclosingDecl;
18871 } else {
18872 if (ObjCCategoryDecl *CDecl =
18873 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
18874 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18875 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18876 return nullptr;
18877 }
18878 }
18879 EnclosingContext = EnclosingDecl;
18880 }
18881
18882 // Construct the decl.
18883 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(
18884 C&: Context, DC: EnclosingContext, StartLoc: DeclStart, IdLoc: Loc, Id: II, T, TInfo, ac, BW: BitWidth);
18885
18886 if (T->containsErrors())
18887 NewID->setInvalidDecl();
18888
18889 if (II) {
18890 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc, NameKind: LookupMemberName,
18891 Redecl: ForVisibleRedeclaration);
18892 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18893 && !isa<TagDecl>(Val: PrevDecl)) {
18894 Diag(Loc, diag::err_duplicate_member) << II;
18895 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18896 NewID->setInvalidDecl();
18897 }
18898 }
18899
18900 // Process attributes attached to the ivar.
18901 ProcessDeclAttributes(S, NewID, D);
18902
18903 if (D.isInvalidType())
18904 NewID->setInvalidDecl();
18905
18906 // In ARC, infer 'retaining' for ivars of retainable type.
18907 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18908 NewID->setInvalidDecl();
18909
18910 if (D.getDeclSpec().isModulePrivateSpecified())
18911 NewID->setModulePrivate();
18912
18913 if (II) {
18914 // FIXME: When interfaces are DeclContexts, we'll need to add
18915 // these to the interface.
18916 S->AddDecl(NewID);
18917 IdResolver.AddDecl(NewID);
18918 }
18919
18920 if (LangOpts.ObjCRuntime.isNonFragile() &&
18921 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18922 Diag(Loc, diag::warn_ivars_in_interface);
18923
18924 return NewID;
18925}
18926
18927/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18928/// class and class extensions. For every class \@interface and class
18929/// extension \@interface, if the last ivar is a bitfield of any type,
18930/// then add an implicit `char :0` ivar to the end of that interface.
18931void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18932 SmallVectorImpl<Decl *> &AllIvarDecls) {
18933 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18934 return;
18935
18936 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18937 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
18938
18939 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18940 return;
18941 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
18942 if (!ID) {
18943 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
18944 if (!CD->IsClassExtension())
18945 return;
18946 }
18947 // No need to add this to end of @implementation.
18948 else
18949 return;
18950 }
18951 // All conditions are met. Add a new bitfield to the tail end of ivars.
18952 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18953 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18954
18955 Ivar = ObjCIvarDecl::Create(C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext),
18956 StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
18957 T: Context.CharTy,
18958 TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy,
18959 Loc: DeclLoc),
18960 ac: ObjCIvarDecl::Private, BW,
18961 synthesized: true);
18962 AllIvarDecls.push_back(Ivar);
18963}
18964
18965/// [class.dtor]p4:
18966/// At the end of the definition of a class, overload resolution is
18967/// performed among the prospective destructors declared in that class with
18968/// an empty argument list to select the destructor for the class, also
18969/// known as the selected destructor.
18970///
18971/// We do the overload resolution here, then mark the selected constructor in the AST.
18972/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18973static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18974 if (!Record->hasUserDeclaredDestructor()) {
18975 return;
18976 }
18977
18978 SourceLocation Loc = Record->getLocation();
18979 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18980
18981 for (auto *Decl : Record->decls()) {
18982 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18983 if (DD->isInvalidDecl())
18984 continue;
18985 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18986 OCS);
18987 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18988 }
18989 }
18990
18991 if (OCS.empty()) {
18992 return;
18993 }
18994 OverloadCandidateSet::iterator Best;
18995 unsigned Msg = 0;
18996 OverloadCandidateDisplayKind DisplayKind;
18997
18998 switch (OCS.BestViableFunction(S, Loc, Best)) {
18999 case OR_Success:
19000 case OR_Deleted:
19001 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19002 break;
19003
19004 case OR_Ambiguous:
19005 Msg = diag::err_ambiguous_destructor;
19006 DisplayKind = OCD_AmbiguousCandidates;
19007 break;
19008
19009 case OR_No_Viable_Function:
19010 Msg = diag::err_no_viable_destructor;
19011 DisplayKind = OCD_AllCandidates;
19012 break;
19013 }
19014
19015 if (Msg) {
19016 // OpenCL have got their own thing going with destructors. It's slightly broken,
19017 // but we allow it.
19018 if (!S.LangOpts.OpenCL) {
19019 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19020 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19021 Record->setInvalidDecl();
19022 }
19023 // It's a bit hacky: At this point we've raised an error but we want the
19024 // rest of the compiler to continue somehow working. However almost
19025 // everything we'll try to do with the class will depend on there being a
19026 // destructor. So let's pretend the first one is selected and hope for the
19027 // best.
19028 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19029 }
19030}
19031
19032/// [class.mem.special]p5
19033/// Two special member functions are of the same kind if:
19034/// - they are both default constructors,
19035/// - they are both copy or move constructors with the same first parameter
19036/// type, or
19037/// - they are both copy or move assignment operators with the same first
19038/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19039static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19040 CXXMethodDecl *M1,
19041 CXXMethodDecl *M2,
19042 Sema::CXXSpecialMember CSM) {
19043 // We don't want to compare templates to non-templates: See
19044 // https://github.com/llvm/llvm-project/issues/59206
19045 if (CSM == Sema::CXXDefaultConstructor)
19046 return bool(M1->getDescribedFunctionTemplate()) ==
19047 bool(M2->getDescribedFunctionTemplate());
19048 // FIXME: better resolve CWG
19049 // https://cplusplus.github.io/CWG/issues/2787.html
19050 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19051 M2->getNonObjectParameter(0)->getType()))
19052 return false;
19053 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19054 T2: M2->getFunctionObjectParameterReferenceType()))
19055 return false;
19056
19057 return true;
19058}
19059
19060/// [class.mem.special]p6:
19061/// An eligible special member function is a special member function for which:
19062/// - the function is not deleted,
19063/// - the associated constraints, if any, are satisfied, and
19064/// - no special member function of the same kind whose associated constraints
19065/// [CWG2595], if any, are satisfied is more constrained.
19066static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19067 ArrayRef<CXXMethodDecl *> Methods,
19068 Sema::CXXSpecialMember CSM) {
19069 SmallVector<bool, 4> SatisfactionStatus;
19070
19071 for (CXXMethodDecl *Method : Methods) {
19072 const Expr *Constraints = Method->getTrailingRequiresClause();
19073 if (!Constraints)
19074 SatisfactionStatus.push_back(Elt: true);
19075 else {
19076 ConstraintSatisfaction Satisfaction;
19077 if (S.CheckFunctionConstraints(Method, Satisfaction))
19078 SatisfactionStatus.push_back(Elt: false);
19079 else
19080 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19081 }
19082 }
19083
19084 for (size_t i = 0; i < Methods.size(); i++) {
19085 if (!SatisfactionStatus[i])
19086 continue;
19087 CXXMethodDecl *Method = Methods[i];
19088 CXXMethodDecl *OrigMethod = Method;
19089 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19090 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19091
19092 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
19093 bool AnotherMethodIsMoreConstrained = false;
19094 for (size_t j = 0; j < Methods.size(); j++) {
19095 if (i == j || !SatisfactionStatus[j])
19096 continue;
19097 CXXMethodDecl *OtherMethod = Methods[j];
19098 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19099 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19100
19101 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19102 CSM))
19103 continue;
19104
19105 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
19106 if (!OtherConstraints)
19107 continue;
19108 if (!Constraints) {
19109 AnotherMethodIsMoreConstrained = true;
19110 break;
19111 }
19112 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
19113 {Constraints},
19114 AnotherMethodIsMoreConstrained)) {
19115 // There was an error with the constraints comparison. Exit the loop
19116 // and don't consider this function eligible.
19117 AnotherMethodIsMoreConstrained = true;
19118 }
19119 if (AnotherMethodIsMoreConstrained)
19120 break;
19121 }
19122 // FIXME: Do not consider deleted methods as eligible after implementing
19123 // DR1734 and DR1496.
19124 if (!AnotherMethodIsMoreConstrained) {
19125 Method->setIneligibleOrNotSelected(false);
19126 Record->addedEligibleSpecialMemberFunction(MD: Method, SMKind: 1 << CSM);
19127 }
19128 }
19129}
19130
19131static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19132 CXXRecordDecl *Record) {
19133 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19134 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19135 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19136 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19137 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19138
19139 for (auto *Decl : Record->decls()) {
19140 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19141 if (!MD) {
19142 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19143 if (FTD)
19144 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19145 }
19146 if (!MD)
19147 continue;
19148 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19149 if (CD->isInvalidDecl())
19150 continue;
19151 if (CD->isDefaultConstructor())
19152 DefaultConstructors.push_back(MD);
19153 else if (CD->isCopyConstructor())
19154 CopyConstructors.push_back(MD);
19155 else if (CD->isMoveConstructor())
19156 MoveConstructors.push_back(MD);
19157 } else if (MD->isCopyAssignmentOperator()) {
19158 CopyAssignmentOperators.push_back(MD);
19159 } else if (MD->isMoveAssignmentOperator()) {
19160 MoveAssignmentOperators.push_back(MD);
19161 }
19162 }
19163
19164 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19165 CSM: Sema::CXXDefaultConstructor);
19166 SetEligibleMethods(S, Record, Methods: CopyConstructors, CSM: Sema::CXXCopyConstructor);
19167 SetEligibleMethods(S, Record, Methods: MoveConstructors, CSM: Sema::CXXMoveConstructor);
19168 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19169 CSM: Sema::CXXCopyAssignment);
19170 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19171 CSM: Sema::CXXMoveAssignment);
19172}
19173
19174void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19175 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19176 SourceLocation RBrac,
19177 const ParsedAttributesView &Attrs) {
19178 assert(EnclosingDecl && "missing record or interface decl");
19179
19180 // If this is an Objective-C @implementation or category and we have
19181 // new fields here we should reset the layout of the interface since
19182 // it will now change.
19183 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19184 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19185 switch (DC->getKind()) {
19186 default: break;
19187 case Decl::ObjCCategory:
19188 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19189 break;
19190 case Decl::ObjCImplementation:
19191 Context.
19192 ResetObjCLayout(CD: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19193 break;
19194 }
19195 }
19196
19197 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19198 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19199
19200 // Start counting up the number of named members; make sure to include
19201 // members of anonymous structs and unions in the total.
19202 unsigned NumNamedMembers = 0;
19203 if (Record) {
19204 for (const auto *I : Record->decls()) {
19205 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19206 if (IFD->getDeclName())
19207 ++NumNamedMembers;
19208 }
19209 }
19210
19211 // Verify that all the fields are okay.
19212 SmallVector<FieldDecl*, 32> RecFields;
19213
19214 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19215 i != end; ++i) {
19216 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19217
19218 // Get the type for the field.
19219 const Type *FDTy = FD->getType().getTypePtr();
19220
19221 if (!FD->isAnonymousStructOrUnion()) {
19222 // Remember all fields written by the user.
19223 RecFields.push_back(Elt: FD);
19224 }
19225
19226 // If the field is already invalid for some reason, don't emit more
19227 // diagnostics about it.
19228 if (FD->isInvalidDecl()) {
19229 EnclosingDecl->setInvalidDecl();
19230 continue;
19231 }
19232
19233 // C99 6.7.2.1p2:
19234 // A structure or union shall not contain a member with
19235 // incomplete or function type (hence, a structure shall not
19236 // contain an instance of itself, but may contain a pointer to
19237 // an instance of itself), except that the last member of a
19238 // structure with more than one named member may have incomplete
19239 // array type; such a structure (and any union containing,
19240 // possibly recursively, a member that is such a structure)
19241 // shall not be a member of a structure or an element of an
19242 // array.
19243 bool IsLastField = (i + 1 == Fields.end());
19244 if (FDTy->isFunctionType()) {
19245 // Field declared as a function.
19246 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19247 << FD->getDeclName();
19248 FD->setInvalidDecl();
19249 EnclosingDecl->setInvalidDecl();
19250 continue;
19251 } else if (FDTy->isIncompleteArrayType() &&
19252 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19253 if (Record) {
19254 // Flexible array member.
19255 // Microsoft and g++ is more permissive regarding flexible array.
19256 // It will accept flexible array in union and also
19257 // as the sole element of a struct/class.
19258 unsigned DiagID = 0;
19259 if (!Record->isUnion() && !IsLastField) {
19260 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19261 << FD->getDeclName() << FD->getType()
19262 << llvm::to_underlying(Record->getTagKind());
19263 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19264 FD->setInvalidDecl();
19265 EnclosingDecl->setInvalidDecl();
19266 continue;
19267 } else if (Record->isUnion())
19268 DiagID = getLangOpts().MicrosoftExt
19269 ? diag::ext_flexible_array_union_ms
19270 : getLangOpts().CPlusPlus
19271 ? diag::ext_flexible_array_union_gnu
19272 : diag::err_flexible_array_union;
19273 else if (NumNamedMembers < 1)
19274 DiagID = getLangOpts().MicrosoftExt
19275 ? diag::ext_flexible_array_empty_aggregate_ms
19276 : getLangOpts().CPlusPlus
19277 ? diag::ext_flexible_array_empty_aggregate_gnu
19278 : diag::err_flexible_array_empty_aggregate;
19279
19280 if (DiagID)
19281 Diag(FD->getLocation(), DiagID)
19282 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19283 // While the layout of types that contain virtual bases is not specified
19284 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19285 // virtual bases after the derived members. This would make a flexible
19286 // array member declared at the end of an object not adjacent to the end
19287 // of the type.
19288 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19289 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19290 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19291 if (!getLangOpts().C99)
19292 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19293 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19294
19295 // If the element type has a non-trivial destructor, we would not
19296 // implicitly destroy the elements, so disallow it for now.
19297 //
19298 // FIXME: GCC allows this. We should probably either implicitly delete
19299 // the destructor of the containing class, or just allow this.
19300 QualType BaseElem = Context.getBaseElementType(FD->getType());
19301 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19302 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19303 << FD->getDeclName() << FD->getType();
19304 FD->setInvalidDecl();
19305 EnclosingDecl->setInvalidDecl();
19306 continue;
19307 }
19308 // Okay, we have a legal flexible array member at the end of the struct.
19309 Record->setHasFlexibleArrayMember(true);
19310 } else {
19311 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19312 // unless they are followed by another ivar. That check is done
19313 // elsewhere, after synthesized ivars are known.
19314 }
19315 } else if (!FDTy->isDependentType() &&
19316 RequireCompleteSizedType(
19317 FD->getLocation(), FD->getType(),
19318 diag::err_field_incomplete_or_sizeless)) {
19319 // Incomplete type
19320 FD->setInvalidDecl();
19321 EnclosingDecl->setInvalidDecl();
19322 continue;
19323 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19324 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19325 // A type which contains a flexible array member is considered to be a
19326 // flexible array member.
19327 Record->setHasFlexibleArrayMember(true);
19328 if (!Record->isUnion()) {
19329 // If this is a struct/class and this is not the last element, reject
19330 // it. Note that GCC supports variable sized arrays in the middle of
19331 // structures.
19332 if (!IsLastField)
19333 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19334 << FD->getDeclName() << FD->getType();
19335 else {
19336 // We support flexible arrays at the end of structs in
19337 // other structs as an extension.
19338 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19339 << FD->getDeclName();
19340 }
19341 }
19342 }
19343 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19344 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19345 diag::err_abstract_type_in_decl,
19346 AbstractIvarType)) {
19347 // Ivars can not have abstract class types
19348 FD->setInvalidDecl();
19349 }
19350 if (Record && FDTTy->getDecl()->hasObjectMember())
19351 Record->setHasObjectMember(true);
19352 if (Record && FDTTy->getDecl()->hasVolatileMember())
19353 Record->setHasVolatileMember(true);
19354 } else if (FDTy->isObjCObjectType()) {
19355 /// A field cannot be an Objective-c object
19356 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19357 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19358 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19359 FD->setType(T);
19360 } else if (Record && Record->isUnion() &&
19361 FD->getType().hasNonTrivialObjCLifetime() &&
19362 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19363 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19364 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19365 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19366 // For backward compatibility, fields of C unions declared in system
19367 // headers that have non-trivial ObjC ownership qualifications are marked
19368 // as unavailable unless the qualifier is explicit and __strong. This can
19369 // break ABI compatibility between programs compiled with ARC and MRR, but
19370 // is a better option than rejecting programs using those unions under
19371 // ARC.
19372 FD->addAttr(UnavailableAttr::CreateImplicit(
19373 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19374 FD->getLocation()));
19375 } else if (getLangOpts().ObjC &&
19376 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19377 !Record->hasObjectMember()) {
19378 if (FD->getType()->isObjCObjectPointerType() ||
19379 FD->getType().isObjCGCStrong())
19380 Record->setHasObjectMember(true);
19381 else if (Context.getAsArrayType(T: FD->getType())) {
19382 QualType BaseType = Context.getBaseElementType(FD->getType());
19383 if (BaseType->isRecordType() &&
19384 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19385 Record->setHasObjectMember(true);
19386 else if (BaseType->isObjCObjectPointerType() ||
19387 BaseType.isObjCGCStrong())
19388 Record->setHasObjectMember(true);
19389 }
19390 }
19391
19392 if (Record && !getLangOpts().CPlusPlus &&
19393 !shouldIgnoreForRecordTriviality(FD)) {
19394 QualType FT = FD->getType();
19395 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19396 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19397 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19398 Record->isUnion())
19399 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19400 }
19401 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19402 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19403 Record->setNonTrivialToPrimitiveCopy(true);
19404 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19405 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19406 }
19407 if (FT.isDestructedType()) {
19408 Record->setNonTrivialToPrimitiveDestroy(true);
19409 Record->setParamDestroyedInCallee(true);
19410 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19411 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19412 }
19413
19414 if (const auto *RT = FT->getAs<RecordType>()) {
19415 if (RT->getDecl()->getArgPassingRestrictions() ==
19416 RecordArgPassingKind::CanNeverPassInRegs)
19417 Record->setArgPassingRestrictions(
19418 RecordArgPassingKind::CanNeverPassInRegs);
19419 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19420 Record->setArgPassingRestrictions(
19421 RecordArgPassingKind::CanNeverPassInRegs);
19422 }
19423
19424 if (Record && FD->getType().isVolatileQualified())
19425 Record->setHasVolatileMember(true);
19426 // Keep track of the number of named members.
19427 if (FD->getIdentifier())
19428 ++NumNamedMembers;
19429 }
19430
19431 // Okay, we successfully defined 'Record'.
19432 if (Record) {
19433 bool Completed = false;
19434 if (CXXRecord) {
19435 if (!CXXRecord->isInvalidDecl()) {
19436 // Set access bits correctly on the directly-declared conversions.
19437 for (CXXRecordDecl::conversion_iterator
19438 I = CXXRecord->conversion_begin(),
19439 E = CXXRecord->conversion_end(); I != E; ++I)
19440 I.setAccess((*I)->getAccess());
19441 }
19442
19443 // Add any implicitly-declared members to this class.
19444 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
19445
19446 if (!CXXRecord->isDependentType()) {
19447 if (!CXXRecord->isInvalidDecl()) {
19448 // If we have virtual base classes, we may end up finding multiple
19449 // final overriders for a given virtual function. Check for this
19450 // problem now.
19451 if (CXXRecord->getNumVBases()) {
19452 CXXFinalOverriderMap FinalOverriders;
19453 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
19454
19455 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19456 MEnd = FinalOverriders.end();
19457 M != MEnd; ++M) {
19458 for (OverridingMethods::iterator SO = M->second.begin(),
19459 SOEnd = M->second.end();
19460 SO != SOEnd; ++SO) {
19461 assert(SO->second.size() > 0 &&
19462 "Virtual function without overriding functions?");
19463 if (SO->second.size() == 1)
19464 continue;
19465
19466 // C++ [class.virtual]p2:
19467 // In a derived class, if a virtual member function of a base
19468 // class subobject has more than one final overrider the
19469 // program is ill-formed.
19470 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19471 << (const NamedDecl *)M->first << Record;
19472 Diag(M->first->getLocation(),
19473 diag::note_overridden_virtual_function);
19474 for (OverridingMethods::overriding_iterator
19475 OM = SO->second.begin(),
19476 OMEnd = SO->second.end();
19477 OM != OMEnd; ++OM)
19478 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19479 << (const NamedDecl *)M->first << OM->Method->getParent();
19480
19481 Record->setInvalidDecl();
19482 }
19483 }
19484 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
19485 Completed = true;
19486 }
19487 }
19488 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
19489 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
19490 }
19491 }
19492
19493 if (!Completed)
19494 Record->completeDefinition();
19495
19496 // Handle attributes before checking the layout.
19497 ProcessDeclAttributeList(S, Record, Attrs);
19498
19499 // Check to see if a FieldDecl is a pointer to a function.
19500 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19501 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19502 if (!FD) {
19503 // Check whether this is a forward declaration that was inserted by
19504 // Clang. This happens when a non-forward declared / defined type is
19505 // used, e.g.:
19506 //
19507 // struct foo {
19508 // struct bar *(*f)();
19509 // struct bar *(*g)();
19510 // };
19511 //
19512 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19513 // incomplete definition.
19514 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19515 return !TD->isCompleteDefinition();
19516 return false;
19517 }
19518 QualType FieldType = FD->getType().getDesugaredType(Context);
19519 if (isa<PointerType>(Val: FieldType)) {
19520 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19521 return PointeeType.getDesugaredType(Context)->isFunctionType();
19522 }
19523 return false;
19524 };
19525
19526 // Maybe randomize the record's decls. We automatically randomize a record
19527 // of function pointers, unless it has the "no_randomize_layout" attribute.
19528 if (!getLangOpts().CPlusPlus &&
19529 (Record->hasAttr<RandomizeLayoutAttr>() ||
19530 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19531 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19532 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19533 !Record->isRandomized()) {
19534 SmallVector<Decl *, 32> NewDeclOrdering;
19535 if (randstruct::randomizeStructureLayout(Context, RD: Record,
19536 FinalOrdering&: NewDeclOrdering))
19537 Record->reorderDecls(Decls: NewDeclOrdering);
19538 }
19539
19540 // We may have deferred checking for a deleted destructor. Check now.
19541 if (CXXRecord) {
19542 auto *Dtor = CXXRecord->getDestructor();
19543 if (Dtor && Dtor->isImplicit() &&
19544 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19545 CXXRecord->setImplicitDestructorIsDeleted();
19546 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
19547 }
19548 }
19549
19550 if (Record->hasAttrs()) {
19551 CheckAlignasUnderalignment(Record);
19552
19553 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19554 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
19555 Range: IA->getRange(), BestCase: IA->getBestCase(),
19556 SemanticSpelling: IA->getInheritanceModel());
19557 }
19558
19559 // Check if the structure/union declaration is a type that can have zero
19560 // size in C. For C this is a language extension, for C++ it may cause
19561 // compatibility problems.
19562 bool CheckForZeroSize;
19563 if (!getLangOpts().CPlusPlus) {
19564 CheckForZeroSize = true;
19565 } else {
19566 // For C++ filter out types that cannot be referenced in C code.
19567 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
19568 CheckForZeroSize =
19569 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19570 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19571 CXXRecord->isCLike();
19572 }
19573 if (CheckForZeroSize) {
19574 bool ZeroSize = true;
19575 bool IsEmpty = true;
19576 unsigned NonBitFields = 0;
19577 for (RecordDecl::field_iterator I = Record->field_begin(),
19578 E = Record->field_end();
19579 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19580 IsEmpty = false;
19581 if (I->isUnnamedBitfield()) {
19582 if (!I->isZeroLengthBitField(Ctx: Context))
19583 ZeroSize = false;
19584 } else {
19585 ++NonBitFields;
19586 QualType FieldType = I->getType();
19587 if (FieldType->isIncompleteType() ||
19588 !Context.getTypeSizeInChars(T: FieldType).isZero())
19589 ZeroSize = false;
19590 }
19591 }
19592
19593 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19594 // allowed in C++, but warn if its declaration is inside
19595 // extern "C" block.
19596 if (ZeroSize) {
19597 Diag(RecLoc, getLangOpts().CPlusPlus ?
19598 diag::warn_zero_size_struct_union_in_extern_c :
19599 diag::warn_zero_size_struct_union_compat)
19600 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19601 }
19602
19603 // Structs without named members are extension in C (C99 6.7.2.1p7),
19604 // but are accepted by GCC.
19605 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19606 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19607 diag::ext_no_named_members_in_struct_union)
19608 << Record->isUnion();
19609 }
19610 }
19611 } else {
19612 ObjCIvarDecl **ClsFields =
19613 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19614 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
19615 ID->setEndOfDefinitionLoc(RBrac);
19616 // Add ivar's to class's DeclContext.
19617 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19618 ClsFields[i]->setLexicalDeclContext(ID);
19619 ID->addDecl(ClsFields[i]);
19620 }
19621 // Must enforce the rule that ivars in the base classes may not be
19622 // duplicates.
19623 if (ID->getSuperClass())
19624 DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
19625 } else if (ObjCImplementationDecl *IMPDecl =
19626 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
19627 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19628 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19629 // Ivar declared in @implementation never belongs to the implementation.
19630 // Only it is in implementation's lexical context.
19631 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19632 CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(), Loc: RBrac);
19633 IMPDecl->setIvarLBraceLoc(LBrac);
19634 IMPDecl->setIvarRBraceLoc(RBrac);
19635 } else if (ObjCCategoryDecl *CDecl =
19636 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
19637 // case of ivars in class extension; all other cases have been
19638 // reported as errors elsewhere.
19639 // FIXME. Class extension does not have a LocEnd field.
19640 // CDecl->setLocEnd(RBrac);
19641 // Add ivar's to class extension's DeclContext.
19642 // Diagnose redeclaration of private ivars.
19643 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19644 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19645 if (IDecl) {
19646 if (const ObjCIvarDecl *ClsIvar =
19647 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19648 Diag(ClsFields[i]->getLocation(),
19649 diag::err_duplicate_ivar_declaration);
19650 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19651 continue;
19652 }
19653 for (const auto *Ext : IDecl->known_extensions()) {
19654 if (const ObjCIvarDecl *ClsExtIvar
19655 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19656 Diag(ClsFields[i]->getLocation(),
19657 diag::err_duplicate_ivar_declaration);
19658 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19659 continue;
19660 }
19661 }
19662 }
19663 ClsFields[i]->setLexicalDeclContext(CDecl);
19664 CDecl->addDecl(ClsFields[i]);
19665 }
19666 CDecl->setIvarLBraceLoc(LBrac);
19667 CDecl->setIvarRBraceLoc(RBrac);
19668 }
19669 }
19670}
19671
19672/// Determine whether the given integral value is representable within
19673/// the given type T.
19674static bool isRepresentableIntegerValue(ASTContext &Context,
19675 llvm::APSInt &Value,
19676 QualType T) {
19677 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19678 "Integral type required!");
19679 unsigned BitWidth = Context.getIntWidth(T);
19680
19681 if (Value.isUnsigned() || Value.isNonNegative()) {
19682 if (T->isSignedIntegerOrEnumerationType())
19683 --BitWidth;
19684 return Value.getActiveBits() <= BitWidth;
19685 }
19686 return Value.getSignificantBits() <= BitWidth;
19687}
19688
19689// Given an integral type, return the next larger integral type
19690// (or a NULL type of no such type exists).
19691static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19692 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19693 // enum checking below.
19694 assert((T->isIntegralType(Context) ||
19695 T->isEnumeralType()) && "Integral type required!");
19696 const unsigned NumTypes = 4;
19697 QualType SignedIntegralTypes[NumTypes] = {
19698 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19699 };
19700 QualType UnsignedIntegralTypes[NumTypes] = {
19701 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19702 Context.UnsignedLongLongTy
19703 };
19704
19705 unsigned BitWidth = Context.getTypeSize(T);
19706 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19707 : UnsignedIntegralTypes;
19708 for (unsigned I = 0; I != NumTypes; ++I)
19709 if (Context.getTypeSize(T: Types[I]) > BitWidth)
19710 return Types[I];
19711
19712 return QualType();
19713}
19714
19715EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19716 EnumConstantDecl *LastEnumConst,
19717 SourceLocation IdLoc,
19718 IdentifierInfo *Id,
19719 Expr *Val) {
19720 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19721 llvm::APSInt EnumVal(IntWidth);
19722 QualType EltTy;
19723
19724 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
19725 Val = nullptr;
19726
19727 if (Val)
19728 Val = DefaultLvalueConversion(E: Val).get();
19729
19730 if (Val) {
19731 if (Enum->isDependentType() || Val->isTypeDependent() ||
19732 Val->containsErrors())
19733 EltTy = Context.DependentTy;
19734 else {
19735 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19736 // underlying type, but do allow it in all other contexts.
19737 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19738 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19739 // constant-expression in the enumerator-definition shall be a converted
19740 // constant expression of the underlying type.
19741 EltTy = Enum->getIntegerType();
19742 ExprResult Converted =
19743 CheckConvertedConstantExpression(From: Val, T: EltTy, Value&: EnumVal,
19744 CCE: CCEK_Enumerator);
19745 if (Converted.isInvalid())
19746 Val = nullptr;
19747 else
19748 Val = Converted.get();
19749 } else if (!Val->isValueDependent() &&
19750 !(Val =
19751 VerifyIntegerConstantExpression(E: Val, Result: &EnumVal, CanFold: AllowFold)
19752 .get())) {
19753 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19754 } else {
19755 if (Enum->isComplete()) {
19756 EltTy = Enum->getIntegerType();
19757
19758 // In Obj-C and Microsoft mode, require the enumeration value to be
19759 // representable in the underlying type of the enumeration. In C++11,
19760 // we perform a non-narrowing conversion as part of converted constant
19761 // expression checking.
19762 if (!isRepresentableIntegerValue(Context, Value&: EnumVal, T: EltTy)) {
19763 if (Context.getTargetInfo()
19764 .getTriple()
19765 .isWindowsMSVCEnvironment()) {
19766 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19767 } else {
19768 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19769 }
19770 }
19771
19772 // Cast to the underlying type.
19773 Val = ImpCastExprToType(E: Val, Type: EltTy,
19774 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
19775 : CK_IntegralCast)
19776 .get();
19777 } else if (getLangOpts().CPlusPlus) {
19778 // C++11 [dcl.enum]p5:
19779 // If the underlying type is not fixed, the type of each enumerator
19780 // is the type of its initializing value:
19781 // - If an initializer is specified for an enumerator, the
19782 // initializing value has the same type as the expression.
19783 EltTy = Val->getType();
19784 } else {
19785 // C99 6.7.2.2p2:
19786 // The expression that defines the value of an enumeration constant
19787 // shall be an integer constant expression that has a value
19788 // representable as an int.
19789
19790 // Complain if the value is not representable in an int.
19791 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19792 Diag(IdLoc, diag::ext_enum_value_not_int)
19793 << toString(EnumVal, 10) << Val->getSourceRange()
19794 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19795 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19796 // Force the type of the expression to 'int'.
19797 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
19798 }
19799 EltTy = Val->getType();
19800 }
19801 }
19802 }
19803 }
19804
19805 if (!Val) {
19806 if (Enum->isDependentType())
19807 EltTy = Context.DependentTy;
19808 else if (!LastEnumConst) {
19809 // C++0x [dcl.enum]p5:
19810 // If the underlying type is not fixed, the type of each enumerator
19811 // is the type of its initializing value:
19812 // - If no initializer is specified for the first enumerator, the
19813 // initializing value has an unspecified integral type.
19814 //
19815 // GCC uses 'int' for its unspecified integral type, as does
19816 // C99 6.7.2.2p3.
19817 if (Enum->isFixed()) {
19818 EltTy = Enum->getIntegerType();
19819 }
19820 else {
19821 EltTy = Context.IntTy;
19822 }
19823 } else {
19824 // Assign the last value + 1.
19825 EnumVal = LastEnumConst->getInitVal();
19826 ++EnumVal;
19827 EltTy = LastEnumConst->getType();
19828
19829 // Check for overflow on increment.
19830 if (EnumVal < LastEnumConst->getInitVal()) {
19831 // C++0x [dcl.enum]p5:
19832 // If the underlying type is not fixed, the type of each enumerator
19833 // is the type of its initializing value:
19834 //
19835 // - Otherwise the type of the initializing value is the same as
19836 // the type of the initializing value of the preceding enumerator
19837 // unless the incremented value is not representable in that type,
19838 // in which case the type is an unspecified integral type
19839 // sufficient to contain the incremented value. If no such type
19840 // exists, the program is ill-formed.
19841 QualType T = getNextLargerIntegralType(Context, T: EltTy);
19842 if (T.isNull() || Enum->isFixed()) {
19843 // There is no integral type larger enough to represent this
19844 // value. Complain, then allow the value to wrap around.
19845 EnumVal = LastEnumConst->getInitVal();
19846 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
19847 ++EnumVal;
19848 if (Enum->isFixed())
19849 // When the underlying type is fixed, this is ill-formed.
19850 Diag(IdLoc, diag::err_enumerator_wrapped)
19851 << toString(EnumVal, 10)
19852 << EltTy;
19853 else
19854 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19855 << toString(EnumVal, 10);
19856 } else {
19857 EltTy = T;
19858 }
19859
19860 // Retrieve the last enumerator's value, extent that type to the
19861 // type that is supposed to be large enough to represent the incremented
19862 // value, then increment.
19863 EnumVal = LastEnumConst->getInitVal();
19864 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19865 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
19866 ++EnumVal;
19867
19868 // If we're not in C++, diagnose the overflow of enumerator values,
19869 // which in C99 means that the enumerator value is not representable in
19870 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19871 // permits enumerator values that are representable in some larger
19872 // integral type.
19873 if (!getLangOpts().CPlusPlus && !T.isNull())
19874 Diag(IdLoc, diag::warn_enum_value_overflow);
19875 } else if (!getLangOpts().CPlusPlus &&
19876 !EltTy->isDependentType() &&
19877 !isRepresentableIntegerValue(Context, Value&: EnumVal, T: EltTy)) {
19878 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19879 Diag(IdLoc, diag::ext_enum_value_not_int)
19880 << toString(EnumVal, 10) << 1;
19881 }
19882 }
19883 }
19884
19885 if (!EltTy->isDependentType()) {
19886 // Make the enumerator value match the signedness and size of the
19887 // enumerator's type.
19888 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
19889 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19890 }
19891
19892 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
19893 E: Val, V: EnumVal);
19894}
19895
19896Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19897 SourceLocation IILoc) {
19898 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19899 !getLangOpts().CPlusPlus)
19900 return SkipBodyInfo();
19901
19902 // We have an anonymous enum definition. Look up the first enumerator to
19903 // determine if we should merge the definition with an existing one and
19904 // skip the body.
19905 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
19906 Redecl: forRedeclarationInCurContext());
19907 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
19908 if (!PrevECD)
19909 return SkipBodyInfo();
19910
19911 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19912 NamedDecl *Hidden;
19913 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19914 SkipBodyInfo Skip;
19915 Skip.Previous = Hidden;
19916 return Skip;
19917 }
19918
19919 return SkipBodyInfo();
19920}
19921
19922Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19923 SourceLocation IdLoc, IdentifierInfo *Id,
19924 const ParsedAttributesView &Attrs,
19925 SourceLocation EqualLoc, Expr *Val) {
19926 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
19927 EnumConstantDecl *LastEnumConst =
19928 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
19929
19930 // The scope passed in may not be a decl scope. Zip up the scope tree until
19931 // we find one that is.
19932 S = getNonFieldDeclScope(S);
19933
19934 // Verify that there isn't already something declared with this name in this
19935 // scope.
19936 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19937 LookupName(R, S);
19938 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19939
19940 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19941 // Maybe we will complain about the shadowed template parameter.
19942 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19943 // Just pretend that we didn't see the previous declaration.
19944 PrevDecl = nullptr;
19945 }
19946
19947 // C++ [class.mem]p15:
19948 // If T is the name of a class, then each of the following shall have a name
19949 // different from T:
19950 // - every enumerator of every member of class T that is an unscoped
19951 // enumerated type
19952 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19953 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
19954 NameInfo: DeclarationNameInfo(Id, IdLoc));
19955
19956 EnumConstantDecl *New =
19957 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19958 if (!New)
19959 return nullptr;
19960
19961 if (PrevDecl) {
19962 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
19963 // Check for other kinds of shadowing not already handled.
19964 CheckShadow(New, PrevDecl, R);
19965 }
19966
19967 // When in C++, we may get a TagDecl with the same name; in this case the
19968 // enum constant will 'hide' the tag.
19969 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19970 "Received TagDecl when not in C++!");
19971 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
19972 if (isa<EnumConstantDecl>(PrevDecl))
19973 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19974 else
19975 Diag(IdLoc, diag::err_redefinition) << Id;
19976 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
19977 return nullptr;
19978 }
19979 }
19980
19981 // Process attributes.
19982 ProcessDeclAttributeList(S, New, Attrs);
19983 AddPragmaAttributes(S, New);
19984
19985 // Register this decl in the current scope stack.
19986 New->setAccess(TheEnumDecl->getAccess());
19987 PushOnScopeChains(New, S);
19988
19989 ActOnDocumentableDecl(New);
19990
19991 return New;
19992}
19993
19994// Returns true when the enum initial expression does not trigger the
19995// duplicate enum warning. A few common cases are exempted as follows:
19996// Element2 = Element1
19997// Element2 = Element1 + 1
19998// Element2 = Element1 - 1
19999// Where Element2 and Element1 are from the same enum.
20000static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20001 Expr *InitExpr = ECD->getInitExpr();
20002 if (!InitExpr)
20003 return true;
20004 InitExpr = InitExpr->IgnoreImpCasts();
20005
20006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20007 if (!BO->isAdditiveOp())
20008 return true;
20009 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20010 if (!IL)
20011 return true;
20012 if (IL->getValue() != 1)
20013 return true;
20014
20015 InitExpr = BO->getLHS();
20016 }
20017
20018 // This checks if the elements are from the same enum.
20019 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20020 if (!DRE)
20021 return true;
20022
20023 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20024 if (!EnumConstant)
20025 return true;
20026
20027 if (cast<EnumDecl>(TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20028 Enum)
20029 return true;
20030
20031 return false;
20032}
20033
20034// Emits a warning when an element is implicitly set a value that
20035// a previous element has already been set to.
20036static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20037 EnumDecl *Enum, QualType EnumType) {
20038 // Avoid anonymous enums
20039 if (!Enum->getIdentifier())
20040 return;
20041
20042 // Only check for small enums.
20043 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20044 return;
20045
20046 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20047 return;
20048
20049 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20050 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20051
20052 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20053
20054 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20055 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20056
20057 // Use int64_t as a key to avoid needing special handling for map keys.
20058 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20059 llvm::APSInt Val = D->getInitVal();
20060 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20061 };
20062
20063 DuplicatesVector DupVector;
20064 ValueToVectorMap EnumMap;
20065
20066 // Populate the EnumMap with all values represented by enum constants without
20067 // an initializer.
20068 for (auto *Element : Elements) {
20069 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20070
20071 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20072 // this constant. Skip this enum since it may be ill-formed.
20073 if (!ECD) {
20074 return;
20075 }
20076
20077 // Constants with initializers are handled in the next loop.
20078 if (ECD->getInitExpr())
20079 continue;
20080
20081 // Duplicate values are handled in the next loop.
20082 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20083 }
20084
20085 if (EnumMap.size() == 0)
20086 return;
20087
20088 // Create vectors for any values that has duplicates.
20089 for (auto *Element : Elements) {
20090 // The last loop returned if any constant was null.
20091 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20092 if (!ValidDuplicateEnum(ECD, Enum))
20093 continue;
20094
20095 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20096 if (Iter == EnumMap.end())
20097 continue;
20098
20099 DeclOrVector& Entry = Iter->second;
20100 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
20101 // Ensure constants are different.
20102 if (D == ECD)
20103 continue;
20104
20105 // Create new vector and push values onto it.
20106 auto Vec = std::make_unique<ECDVector>();
20107 Vec->push_back(Elt: D);
20108 Vec->push_back(Elt: ECD);
20109
20110 // Update entry to point to the duplicates vector.
20111 Entry = Vec.get();
20112
20113 // Store the vector somewhere we can consult later for quick emission of
20114 // diagnostics.
20115 DupVector.emplace_back(Args: std::move(Vec));
20116 continue;
20117 }
20118
20119 ECDVector *Vec = Entry.get<ECDVector*>();
20120 // Make sure constants are not added more than once.
20121 if (*Vec->begin() == ECD)
20122 continue;
20123
20124 Vec->push_back(Elt: ECD);
20125 }
20126
20127 // Emit diagnostics.
20128 for (const auto &Vec : DupVector) {
20129 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20130
20131 // Emit warning for one enum constant.
20132 auto *FirstECD = Vec->front();
20133 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20134 << FirstECD << toString(FirstECD->getInitVal(), 10)
20135 << FirstECD->getSourceRange();
20136
20137 // Emit one note for each of the remaining enum constants with
20138 // the same value.
20139 for (auto *ECD : llvm::drop_begin(*Vec))
20140 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20141 << ECD << toString(ECD->getInitVal(), 10)
20142 << ECD->getSourceRange();
20143 }
20144}
20145
20146bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20147 bool AllowMask) const {
20148 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20149 assert(ED->isCompleteDefinition() && "expected enum definition");
20150
20151 auto R = FlagBitsCache.insert(KV: std::make_pair(x&: ED, y: llvm::APInt()));
20152 llvm::APInt &FlagBits = R.first->second;
20153
20154 if (R.second) {
20155 for (auto *E : ED->enumerators()) {
20156 const auto &EVal = E->getInitVal();
20157 // Only single-bit enumerators introduce new flag values.
20158 if (EVal.isPowerOf2())
20159 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20160 }
20161 }
20162
20163 // A value is in a flag enum if either its bits are a subset of the enum's
20164 // flag bits (the first condition) or we are allowing masks and the same is
20165 // true of its complement (the second condition). When masks are allowed, we
20166 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20167 //
20168 // While it's true that any value could be used as a mask, the assumption is
20169 // that a mask will have all of the insignificant bits set. Anything else is
20170 // likely a logic error.
20171 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20172 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20173}
20174
20175void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20176 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20177 const ParsedAttributesView &Attrs) {
20178 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20179 QualType EnumType = Context.getTypeDeclType(Enum);
20180
20181 ProcessDeclAttributeList(S, Enum, Attrs);
20182
20183 if (Enum->isDependentType()) {
20184 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20185 EnumConstantDecl *ECD =
20186 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20187 if (!ECD) continue;
20188
20189 ECD->setType(EnumType);
20190 }
20191
20192 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20193 return;
20194 }
20195
20196 // TODO: If the result value doesn't fit in an int, it must be a long or long
20197 // long value. ISO C does not support this, but GCC does as an extension,
20198 // emit a warning.
20199 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20200 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20201 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20202
20203 // Verify that all the values are okay, compute the size of the values, and
20204 // reverse the list.
20205 unsigned NumNegativeBits = 0;
20206 unsigned NumPositiveBits = 0;
20207
20208 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20209 EnumConstantDecl *ECD =
20210 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20211 if (!ECD) continue; // Already issued a diagnostic.
20212
20213 const llvm::APSInt &InitVal = ECD->getInitVal();
20214
20215 // Keep track of the size of positive and negative values.
20216 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20217 // If the enumerator is zero that should still be counted as a positive
20218 // bit since we need a bit to store the value zero.
20219 unsigned ActiveBits = InitVal.getActiveBits();
20220 NumPositiveBits = std::max(l: {NumPositiveBits, ActiveBits, 1u});
20221 } else {
20222 NumNegativeBits =
20223 std::max(a: NumNegativeBits, b: (unsigned)InitVal.getSignificantBits());
20224 }
20225 }
20226
20227 // If we have an empty set of enumerators we still need one bit.
20228 // From [dcl.enum]p8
20229 // If the enumerator-list is empty, the values of the enumeration are as if
20230 // the enumeration had a single enumerator with value 0
20231 if (!NumPositiveBits && !NumNegativeBits)
20232 NumPositiveBits = 1;
20233
20234 // Figure out the type that should be used for this enum.
20235 QualType BestType;
20236 unsigned BestWidth;
20237
20238 // C++0x N3000 [conv.prom]p3:
20239 // An rvalue of an unscoped enumeration type whose underlying
20240 // type is not fixed can be converted to an rvalue of the first
20241 // of the following types that can represent all the values of
20242 // the enumeration: int, unsigned int, long int, unsigned long
20243 // int, long long int, or unsigned long long int.
20244 // C99 6.4.4.3p2:
20245 // An identifier declared as an enumeration constant has type int.
20246 // The C99 rule is modified by a gcc extension
20247 QualType BestPromotionType;
20248
20249 bool Packed = Enum->hasAttr<PackedAttr>();
20250 // -fshort-enums is the equivalent to specifying the packed attribute on all
20251 // enum definitions.
20252 if (LangOpts.ShortEnums)
20253 Packed = true;
20254
20255 // If the enum already has a type because it is fixed or dictated by the
20256 // target, promote that type instead of analyzing the enumerators.
20257 if (Enum->isComplete()) {
20258 BestType = Enum->getIntegerType();
20259 if (Context.isPromotableIntegerType(T: BestType))
20260 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20261 else
20262 BestPromotionType = BestType;
20263
20264 BestWidth = Context.getIntWidth(T: BestType);
20265 }
20266 else if (NumNegativeBits) {
20267 // If there is a negative value, figure out the smallest integer type (of
20268 // int/long/longlong) that fits.
20269 // If it's packed, check also if it fits a char or a short.
20270 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20271 BestType = Context.SignedCharTy;
20272 BestWidth = CharWidth;
20273 } else if (Packed && NumNegativeBits <= ShortWidth &&
20274 NumPositiveBits < ShortWidth) {
20275 BestType = Context.ShortTy;
20276 BestWidth = ShortWidth;
20277 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20278 BestType = Context.IntTy;
20279 BestWidth = IntWidth;
20280 } else {
20281 BestWidth = Context.getTargetInfo().getLongWidth();
20282
20283 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20284 BestType = Context.LongTy;
20285 } else {
20286 BestWidth = Context.getTargetInfo().getLongLongWidth();
20287
20288 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20289 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20290 BestType = Context.LongLongTy;
20291 }
20292 }
20293 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20294 } else {
20295 // If there is no negative value, figure out the smallest type that fits
20296 // all of the enumerator values.
20297 // If it's packed, check also if it fits a char or a short.
20298 if (Packed && NumPositiveBits <= CharWidth) {
20299 BestType = Context.UnsignedCharTy;
20300 BestPromotionType = Context.IntTy;
20301 BestWidth = CharWidth;
20302 } else if (Packed && NumPositiveBits <= ShortWidth) {
20303 BestType = Context.UnsignedShortTy;
20304 BestPromotionType = Context.IntTy;
20305 BestWidth = ShortWidth;
20306 } else if (NumPositiveBits <= IntWidth) {
20307 BestType = Context.UnsignedIntTy;
20308 BestWidth = IntWidth;
20309 BestPromotionType
20310 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20311 ? Context.UnsignedIntTy : Context.IntTy;
20312 } else if (NumPositiveBits <=
20313 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20314 BestType = Context.UnsignedLongTy;
20315 BestPromotionType
20316 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20317 ? Context.UnsignedLongTy : Context.LongTy;
20318 } else {
20319 BestWidth = Context.getTargetInfo().getLongLongWidth();
20320 assert(NumPositiveBits <= BestWidth &&
20321 "How could an initializer get larger than ULL?");
20322 BestType = Context.UnsignedLongLongTy;
20323 BestPromotionType
20324 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20325 ? Context.UnsignedLongLongTy : Context.LongLongTy;
20326 }
20327 }
20328
20329 // Loop over all of the enumerator constants, changing their types to match
20330 // the type of the enum if needed.
20331 for (auto *D : Elements) {
20332 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20333 if (!ECD) continue; // Already issued a diagnostic.
20334
20335 // Standard C says the enumerators have int type, but we allow, as an
20336 // extension, the enumerators to be larger than int size. If each
20337 // enumerator value fits in an int, type it as an int, otherwise type it the
20338 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20339 // that X has type 'int', not 'unsigned'.
20340
20341 // Determine whether the value fits into an int.
20342 llvm::APSInt InitVal = ECD->getInitVal();
20343
20344 // If it fits into an integer type, force it. Otherwise force it to match
20345 // the enum decl type.
20346 QualType NewTy;
20347 unsigned NewWidth;
20348 bool NewSign;
20349 if (!getLangOpts().CPlusPlus &&
20350 !Enum->isFixed() &&
20351 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20352 NewTy = Context.IntTy;
20353 NewWidth = IntWidth;
20354 NewSign = true;
20355 } else if (ECD->getType() == BestType) {
20356 // Already the right type!
20357 if (getLangOpts().CPlusPlus)
20358 // C++ [dcl.enum]p4: Following the closing brace of an
20359 // enum-specifier, each enumerator has the type of its
20360 // enumeration.
20361 ECD->setType(EnumType);
20362 continue;
20363 } else {
20364 NewTy = BestType;
20365 NewWidth = BestWidth;
20366 NewSign = BestType->isSignedIntegerOrEnumerationType();
20367 }
20368
20369 // Adjust the APSInt value.
20370 InitVal = InitVal.extOrTrunc(width: NewWidth);
20371 InitVal.setIsSigned(NewSign);
20372 ECD->setInitVal(C: Context, V: InitVal);
20373
20374 // Adjust the Expr initializer and type.
20375 if (ECD->getInitExpr() &&
20376 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20377 ECD->setInitExpr(ImplicitCastExpr::Create(
20378 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20379 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20380 if (getLangOpts().CPlusPlus)
20381 // C++ [dcl.enum]p4: Following the closing brace of an
20382 // enum-specifier, each enumerator has the type of its
20383 // enumeration.
20384 ECD->setType(EnumType);
20385 else
20386 ECD->setType(NewTy);
20387 }
20388
20389 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20390 NumPositiveBits, NumNegativeBits);
20391
20392 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20393
20394 if (Enum->isClosedFlag()) {
20395 for (Decl *D : Elements) {
20396 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20397 if (!ECD) continue; // Already issued a diagnostic.
20398
20399 llvm::APSInt InitVal = ECD->getInitVal();
20400 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20401 !IsValueInFlagEnum(Enum, InitVal, true))
20402 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20403 << ECD << Enum;
20404 }
20405 }
20406
20407 // Now that the enum type is defined, ensure it's not been underaligned.
20408 if (Enum->hasAttrs())
20409 CheckAlignasUnderalignment(Enum);
20410}
20411
20412Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20413 SourceLocation StartLoc,
20414 SourceLocation EndLoc) {
20415 StringLiteral *AsmString = cast<StringLiteral>(Val: expr);
20416
20417 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(C&: Context, DC: CurContext,
20418 Str: AsmString, AsmLoc: StartLoc,
20419 RParenLoc: EndLoc);
20420 CurContext->addDecl(New);
20421 return New;
20422}
20423
20424Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
20425 auto *New = TopLevelStmtDecl::Create(C&: Context, Statement);
20426 Context.getTranslationUnitDecl()->addDecl(New);
20427 return New;
20428}
20429
20430void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20431 IdentifierInfo* AliasName,
20432 SourceLocation PragmaLoc,
20433 SourceLocation NameLoc,
20434 SourceLocation AliasNameLoc) {
20435 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20436 NameKind: LookupOrdinaryName);
20437 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20438 AttributeCommonInfo::Form::Pragma());
20439 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20440 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20441
20442 // If a declaration that:
20443 // 1) declares a function or a variable
20444 // 2) has external linkage
20445 // already exists, add a label attribute to it.
20446 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20447 if (isDeclExternC(PrevDecl))
20448 PrevDecl->addAttr(A: Attr);
20449 else
20450 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20451 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20452 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20453 } else
20454 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20455}
20456
20457void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20458 SourceLocation PragmaLoc,
20459 SourceLocation NameLoc) {
20460 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
20461
20462 if (PrevDecl) {
20463 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20464 } else {
20465 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
20466 }
20467}
20468
20469void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20470 IdentifierInfo* AliasName,
20471 SourceLocation PragmaLoc,
20472 SourceLocation NameLoc,
20473 SourceLocation AliasNameLoc) {
20474 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
20475 NameKind: LookupOrdinaryName);
20476 WeakInfo W = WeakInfo(Name, NameLoc);
20477
20478 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20479 if (!PrevDecl->hasAttr<AliasAttr>())
20480 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
20481 DeclApplyPragmaWeak(S: TUScope, ND, W);
20482 } else {
20483 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
20484 }
20485}
20486
20487ObjCContainerDecl *Sema::getObjCDeclContext() const {
20488 return (dyn_cast_or_null<ObjCContainerDecl>(Val: CurContext));
20489}
20490
20491Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20492 bool Final) {
20493 assert(FD && "Expected non-null FunctionDecl");
20494
20495 // SYCL functions can be template, so we check if they have appropriate
20496 // attribute prior to checking if it is a template.
20497 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20498 return FunctionEmissionStatus::Emitted;
20499
20500 // Templates are emitted when they're instantiated.
20501 if (FD->isDependentContext())
20502 return FunctionEmissionStatus::TemplateDiscarded;
20503
20504 // Check whether this function is an externally visible definition.
20505 auto IsEmittedForExternalSymbol = [this, FD]() {
20506 // We have to check the GVA linkage of the function's *definition* -- if we
20507 // only have a declaration, we don't know whether or not the function will
20508 // be emitted, because (say) the definition could include "inline".
20509 const FunctionDecl *Def = FD->getDefinition();
20510
20511 return Def && !isDiscardableGVALinkage(
20512 L: getASTContext().GetGVALinkageForFunction(FD: Def));
20513 };
20514
20515 if (LangOpts.OpenMPIsTargetDevice) {
20516 // In OpenMP device mode we will not emit host only functions, or functions
20517 // we don't need due to their linkage.
20518 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20519 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20520 // DevTy may be changed later by
20521 // #pragma omp declare target to(*) device_type(*).
20522 // Therefore DevTy having no value does not imply host. The emission status
20523 // will be checked again at the end of compilation unit with Final = true.
20524 if (DevTy)
20525 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20526 return FunctionEmissionStatus::OMPDiscarded;
20527 // If we have an explicit value for the device type, or we are in a target
20528 // declare context, we need to emit all extern and used symbols.
20529 if (isInOpenMPDeclareTargetContext() || DevTy)
20530 if (IsEmittedForExternalSymbol())
20531 return FunctionEmissionStatus::Emitted;
20532 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20533 // we'll omit it.
20534 if (Final)
20535 return FunctionEmissionStatus::OMPDiscarded;
20536 } else if (LangOpts.OpenMP > 45) {
20537 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20538 // function. In 5.0, no_host was introduced which might cause a function to
20539 // be ommitted.
20540 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20541 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20542 if (DevTy)
20543 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20544 return FunctionEmissionStatus::OMPDiscarded;
20545 }
20546
20547 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20548 return FunctionEmissionStatus::Emitted;
20549
20550 if (LangOpts.CUDA) {
20551 // When compiling for device, host functions are never emitted. Similarly,
20552 // when compiling for host, device and global functions are never emitted.
20553 // (Technically, we do emit a host-side stub for global functions, but this
20554 // doesn't count for our purposes here.)
20555 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(D: FD);
20556 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20557 return FunctionEmissionStatus::CUDADiscarded;
20558 if (!LangOpts.CUDAIsDevice &&
20559 (T == Sema::CFT_Device || T == Sema::CFT_Global))
20560 return FunctionEmissionStatus::CUDADiscarded;
20561
20562 if (IsEmittedForExternalSymbol())
20563 return FunctionEmissionStatus::Emitted;
20564 }
20565
20566 // Otherwise, the function is known-emitted if it's in our set of
20567 // known-emitted functions.
20568 return FunctionEmissionStatus::Unknown;
20569}
20570
20571bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20572 // Host-side references to a __global__ function refer to the stub, so the
20573 // function itself is never emitted and therefore should not be marked.
20574 // If we have host fn calls kernel fn calls host+device, the HD function
20575 // does not get instantiated on the host. We model this by omitting at the
20576 // call to the kernel from the callgraph. This ensures that, when compiling
20577 // for host, only HD functions actually called from the host get marked as
20578 // known-emitted.
20579 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20580 IdentifyCUDATarget(D: Callee) == CFT_Global;
20581}
20582

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