Debian Codegraph @

clang/lib/Sema/SemaDecl.cpp

raw
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/MangleNumberingContext.h"
27 #include "clang/AST/NonTrivialTypeVisitor.h"
28 #include "clang/AST/Randstruct.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticComment.h"
34 #include "clang/Basic/HLSLRuntime.h"
35 #include "clang/Basic/PartialDiagnostic.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42 #include "clang/Sema/CXXFieldCollector.h"
43 #include "clang/Sema/DeclSpec.h"
44 #include "clang/Sema/DelayedDiagnostic.h"
45 #include "clang/Sema/Initialization.h"
46 #include "clang/Sema/Lookup.h"
47 #include "clang/Sema/ParsedTemplate.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
50 #include "clang/Sema/SemaARM.h"
51 #include "clang/Sema/SemaCUDA.h"
52 #include "clang/Sema/SemaHLSL.h"
53 #include "clang/Sema/SemaInternal.h"
54 #include "clang/Sema/SemaObjC.h"
55 #include "clang/Sema/SemaOpenACC.h"
56 #include "clang/Sema/SemaOpenMP.h"
57 #include "clang/Sema/SemaPPC.h"
58 #include "clang/Sema/SemaRISCV.h"
59 #include "clang/Sema/SemaSYCL.h"
60 #include "clang/Sema/SemaSwift.h"
61 #include "clang/Sema/SemaWasm.h"
62 #include "clang/Sema/Template.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/STLForwardCompat.h"
65 #include "llvm/ADT/ScopeExit.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/SmallString.h"
68 #include "llvm/ADT/StringExtras.h"
69 #include "llvm/ADT/StringRef.h"
70 #include "llvm/Support/SaveAndRestore.h"
71 #include "llvm/TargetParser/Triple.h"
72 #include <algorithm>
73 #include <cstring>
74 #include <optional>
75 #include <unordered_map>
76
77 using namespace clang;
78 using namespace sema;
79
80 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
81 if (OwnedType) {
82 Decl *Group[2] = { OwnedType, Ptr };
83 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
84 }
85
86 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
87 }
88
89 namespace {
90
91 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
92 public:
93 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
94 bool AllowTemplates = false,
95 bool AllowNonTemplates = true)
96 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
97 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
98 WantExpressionKeywords = false;
99 WantCXXNamedCasts = false;
100 WantRemainingKeywords = false;
101 }
102
103 bool ValidateCandidate(const TypoCorrection &candidate) override {
104 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
105 if (!AllowInvalidDecl && ND->isInvalidDecl())
106 return false;
107
108 if (getAsTypeTemplateDecl(ND))
109 return AllowTemplates;
110
111 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
112 if (!IsType)
113 return false;
114
115 if (AllowNonTemplates)
116 return true;
117
118 // An injected-class-name of a class template (specialization) is valid
119 // as a template or as a non-template.
120 if (AllowTemplates) {
121 auto *RD = dyn_cast<CXXRecordDecl>(ND);
122 if (!RD || !RD->isInjectedClassName())
123 return false;
124 RD = cast<CXXRecordDecl>(RD->getDeclContext());
125 return RD->getDescribedClassTemplate() ||
126 isa<ClassTemplateSpecializationDecl>(RD);
127 }
128
129 return false;
130 }
131
132 return !WantClassName && candidate.isKeyword();
133 }
134
135 std::unique_ptr<CorrectionCandidateCallback> clone() override {
136 return std::make_unique<TypeNameValidatorCCC>(*this);
137 }
138
139 private:
140 bool AllowInvalidDecl;
141 bool WantClassName;
142 bool AllowTemplates;
143 bool AllowNonTemplates;
144 };
145
146 } // end anonymous namespace
147
148 void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
149 TypeDecl *TD, SourceLocation NameLoc) {
150 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
151 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
152 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
153 FoundRD->isInjectedClassName() &&
154 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
155 Diag(NameLoc,
156 DCK == DiagCtorKind::Typename
157 ? diag::ext_out_of_line_qualified_id_type_names_constructor
158 : diag::err_out_of_line_qualified_id_type_names_constructor)
159 << TD->getIdentifier() << /*Type=*/1
160 << 0 /*if any keyword was present, it was 'typename'*/;
161 }
162
163 DiagnoseUseOfDecl(TD, NameLoc);
164 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
165 }
166
167 namespace {
168 enum class UnqualifiedTypeNameLookupResult {
169 NotFound,
170 FoundNonType,
171 FoundType
172 };
173 } // end anonymous namespace
174
175 /// Tries to perform unqualified lookup of the type decls in bases for
176 /// dependent class.
177 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
178 /// type decl, \a FoundType if only type decls are found.
179 static UnqualifiedTypeNameLookupResult
180 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
181 SourceLocation NameLoc,
182 const CXXRecordDecl *RD) {
183 if (!RD->hasDefinition())
184 return UnqualifiedTypeNameLookupResult::NotFound;
185 // Look for type decls in base classes.
186 UnqualifiedTypeNameLookupResult FoundTypeDecl =
187 UnqualifiedTypeNameLookupResult::NotFound;
188 for (const auto &Base : RD->bases()) {
189 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
190 if (BaseRD) {
191 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
192 Base.getType().getCanonicalType())) {
193 // Look for type decls in dependent base classes that have known primary
194 // templates.
195 if (!TST->isDependentType())
196 continue;
197 auto *TD = TST->getTemplateName().getAsTemplateDecl();
198 if (!TD)
199 continue;
200 if (auto *BasePrimaryTemplate =
201 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
202 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
203 BaseRD = BasePrimaryTemplate;
204 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
205 if (const ClassTemplatePartialSpecializationDecl *PS =
206 CTD->findPartialSpecialization(Base.getType()))
207 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
208 BaseRD = PS;
209 }
210 }
211 }
212 if (BaseRD) {
213 for (NamedDecl *ND : BaseRD->lookup(&II)) {
214 if (!isa<TypeDecl>(ND))
215 return UnqualifiedTypeNameLookupResult::FoundNonType;
216 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217 }
218 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
219 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
220 case UnqualifiedTypeNameLookupResult::FoundNonType:
221 return UnqualifiedTypeNameLookupResult::FoundNonType;
222 case UnqualifiedTypeNameLookupResult::FoundType:
223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224 break;
225 case UnqualifiedTypeNameLookupResult::NotFound:
226 break;
227 }
228 }
229 }
230 }
231
232 return FoundTypeDecl;
233 }
234
235 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
236 const IdentifierInfo &II,
237 SourceLocation NameLoc) {
238 // Lookup in the parent class template context, if any.
239 const CXXRecordDecl *RD = nullptr;
240 UnqualifiedTypeNameLookupResult FoundTypeDecl =
241 UnqualifiedTypeNameLookupResult::NotFound;
242 for (DeclContext *DC = S.CurContext;
243 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
244 DC = DC->getParent()) {
245 // Look for type decls in dependent base classes that have known primary
246 // templates.
247 RD = dyn_cast<CXXRecordDecl>(DC);
248 if (RD && RD->getDescribedClassTemplate())
249 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
250 }
251 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
252 return nullptr;
253
254 // We found some types in dependent base classes. Recover as if the user
255 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
256 // allowed. We'll fully resolve the lookup during template instantiation.
257 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
258
259 ASTContext &Context = S.Context;
260 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
261 QualType T =
262 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
263
264 CXXScopeSpec SS;
265 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
266
267 TypeLocBuilder Builder;
268 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
269 DepTL.setNameLoc(NameLoc);
270 DepTL.setElaboratedKeywordLoc(SourceLocation());
271 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
272 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
273 }
274
275 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
276 Scope *S, CXXScopeSpec *SS, bool isClassName,
277 bool HasTrailingDot, ParsedType ObjectTypePtr,
278 bool IsCtorOrDtorName,
279 bool WantNontrivialTypeSourceInfo,
280 bool IsClassTemplateDeductionContext,
281 ImplicitTypenameContext AllowImplicitTypename,
282 IdentifierInfo **CorrectedII) {
283 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
284 // FIXME: Consider allowing this outside C++1z mode as an extension.
285 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
287 !HasTrailingDot;
288
289 // Determine where we will perform name lookup.
290 DeclContext *LookupCtx = nullptr;
291 if (ObjectTypePtr) {
292 QualType ObjectType = ObjectTypePtr.get();
293 if (ObjectType->isRecordType())
294 LookupCtx = computeDeclContext(ObjectType);
295 } else if (SS && SS->isNotEmpty()) {
296 LookupCtx = computeDeclContext(*SS, false);
297
298 if (!LookupCtx) {
299 if (isDependentScopeSpecifier(*SS)) {
300 // C++ [temp.res]p3:
301 // A qualified-id that refers to a type and in which the
302 // nested-name-specifier depends on a template-parameter (14.6.2)
303 // shall be prefixed by the keyword typename to indicate that the
304 // qualified-id denotes a type, forming an
305 // elaborated-type-specifier (7.1.5.3).
306 //
307 // We therefore do not perform any name lookup if the result would
308 // refer to a member of an unknown specialization.
309 // In C++2a, in several contexts a 'typename' is not required. Also
310 // allow this as an extension.
311 if (IsImplicitTypename) {
312 if (AllowImplicitTypename == ImplicitTypenameContext::No)
313 return nullptr;
314 SourceLocation QualifiedLoc = SS->getRange().getBegin();
315 // FIXME: Defer the diagnostic after we build the type and use it.
316 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
317 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
318 SS->getScopeRep(), &II);
319 if (!getLangOpts().CPlusPlus20)
320 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
321 }
322
323 // We know from the grammar that this name refers to a type,
324 // so build a dependent node to describe the type.
325 if (WantNontrivialTypeSourceInfo)
326 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
327 (ImplicitTypenameContext)IsImplicitTypename)
328 .get();
329
330 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
331 QualType T = CheckTypenameType(
332 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
333 : ElaboratedTypeKeyword::None,
334 SourceLocation(), QualifierLoc, II, NameLoc);
335 return ParsedType::make(T);
336 }
337
338 return nullptr;
339 }
340
341 if (!LookupCtx->isDependentContext() &&
342 RequireCompleteDeclContext(*SS, LookupCtx))
343 return nullptr;
344 }
345
346 // In the case where we know that the identifier is a class name, we know that
347 // it is a type declaration (struct, class, union or enum) so we can use tag
348 // name lookup.
349 //
350 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
351 // the component name of the type-name or simple-template-id is type-only.
352 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
353 LookupResult Result(*this, &II, NameLoc, Kind);
354 if (LookupCtx) {
355 // Perform "qualified" name lookup into the declaration context we
356 // computed, which is either the type of the base of a member access
357 // expression or the declaration context associated with a prior
358 // nested-name-specifier.
359 LookupQualifiedName(Result, LookupCtx);
360
361 if (ObjectTypePtr && Result.empty()) {
362 // C++ [basic.lookup.classref]p3:
363 // If the unqualified-id is ~type-name, the type-name is looked up
364 // in the context of the entire postfix-expression. If the type T of
365 // the object expression is of a class type C, the type-name is also
366 // looked up in the scope of class C. At least one of the lookups shall
367 // find a name that refers to (possibly cv-qualified) T.
368 LookupName(Result, S);
369 }
370 } else {
371 // Perform unqualified name lookup.
372 LookupName(Result, S);
373
374 // For unqualified lookup in a class template in MSVC mode, look into
375 // dependent base classes where the primary class template is known.
376 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
377 if (ParsedType TypeInBase =
378 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
379 return TypeInBase;
380 }
381 }
382
383 NamedDecl *IIDecl = nullptr;
384 UsingShadowDecl *FoundUsingShadow = nullptr;
385 switch (Result.getResultKind()) {
386 case LookupResultKind::NotFound:
387 if (CorrectedII) {
388 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
389 AllowDeducedTemplate);
390 TypoCorrection Correction =
391 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
392 CorrectTypoKind::ErrorRecovery);
393 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
394 TemplateTy Template;
395 bool MemberOfUnknownSpecialization;
396 UnqualifiedId TemplateName;
397 TemplateName.setIdentifier(NewII, NameLoc);
398 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
399 CXXScopeSpec NewSS, *NewSSPtr = SS;
400 if (SS && NNS) {
401 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
402 NewSSPtr = &NewSS;
403 }
404 if (Correction && (NNS || NewII != &II) &&
405 // Ignore a correction to a template type as the to-be-corrected
406 // identifier is not a template (typo correction for template names
407 // is handled elsewhere).
408 !(getLangOpts().CPlusPlus && NewSSPtr &&
409 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
410 Template, MemberOfUnknownSpecialization))) {
411 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
412 isClassName, HasTrailingDot, ObjectTypePtr,
413 IsCtorOrDtorName,
414 WantNontrivialTypeSourceInfo,
415 IsClassTemplateDeductionContext);
416 if (Ty) {
417 diagnoseTypo(Correction,
418 PDiag(diag::err_unknown_type_or_class_name_suggest)
419 << Result.getLookupName() << isClassName);
420 if (SS && NNS)
421 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
422 *CorrectedII = NewII;
423 return Ty;
424 }
425 }
426 }
427 Result.suppressDiagnostics();
428 return nullptr;
429 case LookupResultKind::NotFoundInCurrentInstantiation:
430 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
431 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
432 SS->getScopeRep(), &II);
433 TypeLocBuilder TLB;
434 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
435 TL.setElaboratedKeywordLoc(SourceLocation());
436 TL.setQualifierLoc(SS->getWithLocInContext(Context));
437 TL.setNameLoc(NameLoc);
438 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
439 }
440 [[fallthrough]];
441 case LookupResultKind::FoundOverloaded:
442 case LookupResultKind::FoundUnresolvedValue:
443 Result.suppressDiagnostics();
444 return nullptr;
445
446 case LookupResultKind::Ambiguous:
447 // Recover from type-hiding ambiguities by hiding the type. We'll
448 // do the lookup again when looking for an object, and we can
449 // diagnose the error then. If we don't do this, then the error
450 // about hiding the type will be immediately followed by an error
451 // that only makes sense if the identifier was treated like a type.
452 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
453 Result.suppressDiagnostics();
454 return nullptr;
455 }
456
457 // Look to see if we have a type anywhere in the list of results.
458 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
459 Res != ResEnd; ++Res) {
460 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
461 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
462 RealRes) ||
463 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
464 if (!IIDecl ||
465 // Make the selection of the recovery decl deterministic.
466 RealRes->getLocation() < IIDecl->getLocation()) {
467 IIDecl = RealRes;
468 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
469 }
470 }
471 }
472
473 if (!IIDecl) {
474 // None of the entities we found is a type, so there is no way
475 // to even assume that the result is a type. In this case, don't
476 // complain about the ambiguity. The parser will either try to
477 // perform this lookup again (e.g., as an object name), which
478 // will produce the ambiguity, or will complain that it expected
479 // a type name.
480 Result.suppressDiagnostics();
481 return nullptr;
482 }
483
484 // We found a type within the ambiguous lookup; diagnose the
485 // ambiguity and then return that type. This might be the right
486 // answer, or it might not be, but it suppresses any attempt to
487 // perform the name lookup again.
488 break;
489
490 case LookupResultKind::Found:
491 IIDecl = Result.getFoundDecl();
492 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
493 break;
494 }
495
496 assert(IIDecl && "Didn't find decl");
497
498 TypeLocBuilder TLB;
499 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
500 checkTypeDeclType(LookupCtx,
501 IsImplicitTypename ? DiagCtorKind::Implicit
502 : DiagCtorKind::None,
503 TD, NameLoc);
504 QualType T;
505 if (FoundUsingShadow) {
506 T = Context.getUsingType(ElaboratedTypeKeyword::None,
507 SS ? SS->getScopeRep() : std::nullopt,
508 FoundUsingShadow);
509 if (!WantNontrivialTypeSourceInfo)
510 return ParsedType::make(T);
511 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
512 SS ? SS->getWithLocInContext(Context)
513 : NestedNameSpecifierLoc(),
514 NameLoc);
515 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
516 T = Context.getTagType(ElaboratedTypeKeyword::None,
517 SS ? SS->getScopeRep() : std::nullopt, Tag,
518 /*OwnsTag=*/false);
519 if (!WantNontrivialTypeSourceInfo)
520 return ParsedType::make(T);
521 auto TL = TLB.push<TagTypeLoc>(T);
522 TL.setElaboratedKeywordLoc(SourceLocation());
523 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
524 : NestedNameSpecifierLoc());
525 TL.setNameLoc(NameLoc);
526 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
527 TN && !isa<ObjCTypeParamDecl>(TN)) {
528 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
529 SS ? SS->getScopeRep() : std::nullopt, TN);
530 if (!WantNontrivialTypeSourceInfo)
531 return ParsedType::make(T);
532 TLB.push<TypedefTypeLoc>(T).set(
533 /*ElaboratedKeywordLoc=*/SourceLocation(),
534 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
535 NameLoc);
536 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
537 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
538 SS ? SS->getScopeRep() : std::nullopt,
539 UD);
540 if (!WantNontrivialTypeSourceInfo)
541 return ParsedType::make(T);
542 TLB.push<UnresolvedUsingTypeLoc>(T).set(
543 /*ElaboratedKeywordLoc=*/SourceLocation(),
544 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
545 NameLoc);
546 } else {
547 T = Context.getTypeDeclType(TD);
548 if (!WantNontrivialTypeSourceInfo)
549 return ParsedType::make(T);
550 if (isa<ObjCTypeParamType>(T))
551 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
552 else
553 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
554 }
555 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
556 }
557 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
558 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
559 if (!HasTrailingDot) {
560 // FIXME: Support UsingType for this case.
561 QualType T = Context.getObjCInterfaceType(IDecl);
562 if (!WantNontrivialTypeSourceInfo)
563 return ParsedType::make(T);
564 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
565 TL.setNameLoc(NameLoc);
566 // FIXME: Pass in this source location.
567 TL.setNameEndLoc(NameLoc);
568 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
569 }
570 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
571 (void)DiagnoseUseOfDecl(UD, NameLoc);
572 // Recover with 'int'
573 return ParsedType::make(Context.IntTy);
574 } else if (AllowDeducedTemplate) {
575 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
576 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
577 // FIXME: Support UsingType here.
578 TemplateName Template = Context.getQualifiedTemplateName(
579 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
580 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
581 QualType T = Context.getDeducedTemplateSpecializationType(
582 ElaboratedTypeKeyword::None, Template, QualType(), false);
583 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
584 TL.setElaboratedKeywordLoc(SourceLocation());
585 TL.setNameLoc(NameLoc);
586 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
587 : NestedNameSpecifierLoc());
588 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
589 }
590 }
591
592 // As it's not plausibly a type, suppress diagnostics.
593 Result.suppressDiagnostics();
594 return nullptr;
595 }
596
597 // Builds a fake NNS for the given decl context.
598 static NestedNameSpecifier
599 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
600 for (;; DC = DC->getLookupParent()) {
601 DC = DC->getPrimaryContext();
602 auto *ND = dyn_cast<NamespaceDecl>(DC);
603 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
604 return NestedNameSpecifier(Context, ND, std::nullopt);
605 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
606 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
607 if (isa<TranslationUnitDecl>(DC))
608 return NestedNameSpecifier::getGlobal();
609 }
610 llvm_unreachable("something isn't in TU scope?");
611 }
612
613 /// Find the parent class with dependent bases of the innermost enclosing method
614 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
615 /// up allowing unqualified dependent type names at class-level, which MSVC
616 /// correctly rejects.
617 static const CXXRecordDecl *
618 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
619 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
620 DC = DC->getPrimaryContext();
621 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
622 if (MD->getParent()->hasAnyDependentBases())
623 return MD->getParent();
624 }
625 return nullptr;
626 }
627
628 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
629 SourceLocation NameLoc,
630 bool IsTemplateTypeArg) {
631 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
632
633 NestedNameSpecifier NNS = std::nullopt;
634 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
635 // If we weren't able to parse a default template argument, delay lookup
636 // until instantiation time by making a non-dependent DependentTypeName. We
637 // pretend we saw a NestedNameSpecifier referring to the current scope, and
638 // lookup is retried.
639 // FIXME: This hurts our diagnostic quality, since we get errors like "no
640 // type named 'Foo' in 'current_namespace'" when the user didn't write any
641 // name specifiers.
642 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
643 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
644 } else if (const CXXRecordDecl *RD =
645 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
646 // Build a DependentNameType that will perform lookup into RD at
647 // instantiation time.
648 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
649
650 // Diagnose that this identifier was undeclared, and retry the lookup during
651 // template instantiation.
652 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
653 << RD;
654 } else {
655 // This is not a situation that we should recover from.
656 return ParsedType();
657 }
658
659 QualType T =
660 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
661
662 // Build type location information. We synthesized the qualifier, so we have
663 // to build a fake NestedNameSpecifierLoc.
664 NestedNameSpecifierLocBuilder NNSLocBuilder;
665 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
666 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
667
668 TypeLocBuilder Builder;
669 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
670 DepTL.setNameLoc(NameLoc);
671 DepTL.setElaboratedKeywordLoc(SourceLocation());
672 DepTL.setQualifierLoc(QualifierLoc);
673 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
674 }
675
676 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
677 // Do a tag name lookup in this scope.
678 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
679 LookupName(R, S, false);
680 R.suppressDiagnostics();
681 if (R.getResultKind() == LookupResultKind::Found)
682 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
683 switch (TD->getTagKind()) {
684 case TagTypeKind::Struct:
685 return DeclSpec::TST_struct;
686 case TagTypeKind::Interface:
687 return DeclSpec::TST_interface;
688 case TagTypeKind::Union:
689 return DeclSpec::TST_union;
690 case TagTypeKind::Class:
691 return DeclSpec::TST_class;
692 case TagTypeKind::Enum:
693 return DeclSpec::TST_enum;
694 }
695 }
696
697 return DeclSpec::TST_unspecified;
698 }
699
700 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
701 if (!CurContext->isRecord())
702 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
703
704 switch (SS->getScopeRep().getKind()) {
705 case NestedNameSpecifier::Kind::MicrosoftSuper:
706 return true;
707 case NestedNameSpecifier::Kind::Type: {
708 QualType T(SS->getScopeRep().getAsType(), 0);
709 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
710 if (Context.hasSameUnqualifiedType(T, Base.getType()))
711 return true;
712 [[fallthrough]];
713 }
714 default:
715 return S->isFunctionPrototypeScope();
716 }
717 }
718
719 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
720 SourceLocation IILoc,
721 Scope *S,
722 CXXScopeSpec *SS,
723 ParsedType &SuggestedType,
724 bool IsTemplateName) {
725 // Don't report typename errors for editor placeholders.
726 if (II->isEditorPlaceholder())
727 return;
728 // We don't have anything to suggest (yet).
729 SuggestedType = nullptr;
730
731 // There may have been a typo in the name of the type. Look up typo
732 // results, in case we have something that we can suggest.
733 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
734 /*AllowTemplates=*/IsTemplateName,
735 /*AllowNonTemplates=*/!IsTemplateName);
736 if (TypoCorrection Corrected =
737 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
738 CCC, CorrectTypoKind::ErrorRecovery)) {
739 // FIXME: Support error recovery for the template-name case.
740 bool CanRecover = !IsTemplateName;
741 if (Corrected.isKeyword()) {
742 // We corrected to a keyword.
743 diagnoseTypo(Corrected,
744 PDiag(IsTemplateName ? diag::err_no_template_suggest
745 : diag::err_unknown_typename_suggest)
746 << II);
747 II = Corrected.getCorrectionAsIdentifierInfo();
748 } else {
749 // We found a similarly-named type or interface; suggest that.
750 if (!SS || !SS->isSet()) {
751 diagnoseTypo(Corrected,
752 PDiag(IsTemplateName ? diag::err_no_template_suggest
753 : diag::err_unknown_typename_suggest)
754 << II, CanRecover);
755 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
756 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
757 bool DroppedSpecifier =
758 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
759 diagnoseTypo(Corrected,
760 PDiag(IsTemplateName
761 ? diag::err_no_member_template_suggest
762 : diag::err_unknown_nested_typename_suggest)
763 << II << DC << DroppedSpecifier << SS->getRange(),
764 CanRecover);
765 } else {
766 llvm_unreachable("could not have corrected a typo here");
767 }
768
769 if (!CanRecover)
770 return;
771
772 CXXScopeSpec tmpSS;
773 if (Corrected.getCorrectionSpecifier())
774 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
775 SourceRange(IILoc));
776 // FIXME: Support class template argument deduction here.
777 SuggestedType =
778 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
779 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
780 /*IsCtorOrDtorName=*/false,
781 /*WantNontrivialTypeSourceInfo=*/true);
782 }
783 return;
784 }
785
786 if (getLangOpts().CPlusPlus && !IsTemplateName) {
787 // See if II is a class template that the user forgot to pass arguments to.
788 UnqualifiedId Name;
789 Name.setIdentifier(II, IILoc);
790 CXXScopeSpec EmptySS;
791 TemplateTy TemplateResult;
792 bool MemberOfUnknownSpecialization;
793 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
794 Name, nullptr, true, TemplateResult,
795 MemberOfUnknownSpecialization) == TNK_Type_template) {
796 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
797 return;
798 }
799 }
800
801 // FIXME: Should we move the logic that tries to recover from a missing tag
802 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
803
804 if (!SS || (!SS->isSet() && !SS->isInvalid()))
805 Diag(IILoc, IsTemplateName ? diag::err_no_template
806 : diag::err_unknown_typename)
807 << II;
808 else if (DeclContext *DC = computeDeclContext(*SS, false))
809 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
810 : diag::err_typename_nested_not_found)
811 << II << DC << SS->getRange();
812 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
813 SuggestedType =
814 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
815 } else if (isDependentScopeSpecifier(*SS)) {
816 unsigned DiagID = diag::err_typename_missing;
817 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
818 DiagID = diag::ext_typename_missing;
819
820 SuggestedType =
821 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
822
823 Diag(SS->getRange().getBegin(), DiagID)
824 << GetTypeFromParser(SuggestedType)
825 << SourceRange(SS->getRange().getBegin(), IILoc)
826 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
827 } else {
828 assert(SS && SS->isInvalid() &&
829 "Invalid scope specifier has already been diagnosed");
830 }
831 }
832
833 /// Determine whether the given result set contains either a type name
834 /// or
835 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
836 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
837 NextToken.is(tok::less);
838
839 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
840 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
841 return true;
842
843 if (CheckTemplate && isa<TemplateDecl>(*I))
844 return true;
845 }
846
847 return false;
848 }
849
850 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
851 Scope *S, CXXScopeSpec &SS,
852 IdentifierInfo *&Name,
853 SourceLocation NameLoc) {
854 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
855 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
856 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
857 StringRef FixItTagName;
858 switch (Tag->getTagKind()) {
859 case TagTypeKind::Class:
860 FixItTagName = "class ";
861 break;
862
863 case TagTypeKind::Enum:
864 FixItTagName = "enum ";
865 break;
866
867 case TagTypeKind::Struct:
868 FixItTagName = "struct ";
869 break;
870
871 case TagTypeKind::Interface:
872 FixItTagName = "__interface ";
873 break;
874
875 case TagTypeKind::Union:
876 FixItTagName = "union ";
877 break;
878 }
879
880 StringRef TagName = FixItTagName.drop_back();
881 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
882 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
883 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
884
885 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
886 I != IEnd; ++I)
887 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
888 << Name << TagName;
889
890 // Replace lookup results with just the tag decl.
891 Result.clear(Sema::LookupTagName);
892 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
893 return true;
894 }
895
896 return false;
897 }
898
899 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
900 IdentifierInfo *&Name,
901 SourceLocation NameLoc,
902 const Token &NextToken,
903 CorrectionCandidateCallback *CCC) {
904 DeclarationNameInfo NameInfo(Name, NameLoc);
905 ObjCMethodDecl *CurMethod = getCurMethodDecl();
906
907 assert(NextToken.isNot(tok::coloncolon) &&
908 "parse nested name specifiers before calling ClassifyName");
909 if (getLangOpts().CPlusPlus && SS.isSet() &&
910 isCurrentClassName(*Name, S, &SS)) {
911 // Per [class.qual]p2, this names the constructors of SS, not the
912 // injected-class-name. We don't have a classification for that.
913 // There's not much point caching this result, since the parser
914 // will reject it later.
915 return NameClassification::Unknown();
916 }
917
918 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
919 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
920 /*AllowBuiltinCreation=*/!CurMethod);
921
922 if (SS.isInvalid())
923 return NameClassification::Error();
924
925 // For unqualified lookup in a class template in MSVC mode, look into
926 // dependent base classes where the primary class template is known.
927 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
928 if (ParsedType TypeInBase =
929 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
930 return TypeInBase;
931 }
932
933 // Perform lookup for Objective-C instance variables (including automatically
934 // synthesized instance variables), if we're in an Objective-C method.
935 // FIXME: This lookup really, really needs to be folded in to the normal
936 // unqualified lookup mechanism.
937 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
938 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
939 if (Ivar.isInvalid())
940 return NameClassification::Error();
941 if (Ivar.isUsable())
942 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
943
944 // We defer builtin creation until after ivar lookup inside ObjC methods.
945 if (Result.empty())
946 LookupBuiltin(Result);
947 }
948
949 bool SecondTry = false;
950 bool IsFilteredTemplateName = false;
951
952 Corrected:
953 switch (Result.getResultKind()) {
954 case LookupResultKind::NotFound:
955 // If an unqualified-id is followed by a '(', then we have a function
956 // call.
957 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
958 // In C++, this is an ADL-only call.
959 // FIXME: Reference?
960 if (getLangOpts().CPlusPlus)
961 return NameClassification::UndeclaredNonType();
962
963 // C90 6.3.2.2:
964 // If the expression that precedes the parenthesized argument list in a
965 // function call consists solely of an identifier, and if no
966 // declaration is visible for this identifier, the identifier is
967 // implicitly declared exactly as if, in the innermost block containing
968 // the function call, the declaration
969 //
970 // extern int identifier ();
971 //
972 // appeared.
973 //
974 // We also allow this in C99 as an extension. However, this is not
975 // allowed in all language modes as functions without prototypes may not
976 // be supported.
977 if (getLangOpts().implicitFunctionsAllowed()) {
978 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
979 return NameClassification::NonType(D);
980 }
981 }
982
983 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
984 // In C++20 onwards, this could be an ADL-only call to a function
985 // template, and we're required to assume that this is a template name.
986 //
987 // FIXME: Find a way to still do typo correction in this case.
988 TemplateName Template =
989 Context.getAssumedTemplateName(NameInfo.getName());
990 return NameClassification::UndeclaredTemplate(Template);
991 }
992
993 // In C, we first see whether there is a tag type by the same name, in
994 // which case it's likely that the user just forgot to write "enum",
995 // "struct", or "union".
996 if (!getLangOpts().CPlusPlus && !SecondTry &&
997 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
998 break;
999 }
1000
1001 // Perform typo correction to determine if there is another name that is
1002 // close to this name.
1003 if (!SecondTry && CCC) {
1004 SecondTry = true;
1005 if (TypoCorrection Corrected =
1006 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1007 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1008 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1009 unsigned QualifiedDiag = diag::err_no_member_suggest;
1010
1011 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1012 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1013 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1014 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1015 UnqualifiedDiag = diag::err_no_template_suggest;
1016 QualifiedDiag = diag::err_no_member_template_suggest;
1017 } else if (UnderlyingFirstDecl &&
1018 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1020 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1021 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1022 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1023 }
1024
1025 if (SS.isEmpty()) {
1026 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1027 } else {// FIXME: is this even reachable? Test it.
1028 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1029 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1030 Name->getName() == CorrectedStr;
1031 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1032 << Name << computeDeclContext(SS, false)
1033 << DroppedSpecifier << SS.getRange());
1034 }
1035
1036 // Update the name, so that the caller has the new name.
1037 Name = Corrected.getCorrectionAsIdentifierInfo();
1038
1039 // Typo correction corrected to a keyword.
1040 if (Corrected.isKeyword())
1041 return Name;
1042
1043 // Also update the LookupResult...
1044 // FIXME: This should probably go away at some point
1045 Result.clear();
1046 Result.setLookupName(Corrected.getCorrection());
1047 if (FirstDecl)
1048 Result.addDecl(FirstDecl);
1049
1050 // If we found an Objective-C instance variable, let
1051 // LookupInObjCMethod build the appropriate expression to
1052 // reference the ivar.
1053 // FIXME: This is a gross hack.
1054 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1055 DeclResult R =
1056 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1057 if (R.isInvalid())
1058 return NameClassification::Error();
1059 if (R.isUsable())
1060 return NameClassification::NonType(Ivar);
1061 }
1062
1063 goto Corrected;
1064 }
1065 }
1066
1067 // We failed to correct; just fall through and let the parser deal with it.
1068 Result.suppressDiagnostics();
1069 return NameClassification::Unknown();
1070
1071 case LookupResultKind::NotFoundInCurrentInstantiation: {
1072 // We performed name lookup into the current instantiation, and there were
1073 // dependent bases, so we treat this result the same way as any other
1074 // dependent nested-name-specifier.
1075
1076 // C++ [temp.res]p2:
1077 // A name used in a template declaration or definition and that is
1078 // dependent on a template-parameter is assumed not to name a type
1079 // unless the applicable name lookup finds a type name or the name is
1080 // qualified by the keyword typename.
1081 //
1082 // FIXME: If the next token is '<', we might want to ask the parser to
1083 // perform some heroics to see if we actually have a
1084 // template-argument-list, which would indicate a missing 'template'
1085 // keyword here.
1086 return NameClassification::DependentNonType();
1087 }
1088
1089 case LookupResultKind::Found:
1090 case LookupResultKind::FoundOverloaded:
1091 case LookupResultKind::FoundUnresolvedValue:
1092 break;
1093
1094 case LookupResultKind::Ambiguous:
1095 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1096 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1097 /*AllowDependent=*/false)) {
1098 // C++ [temp.local]p3:
1099 // A lookup that finds an injected-class-name (10.2) can result in an
1100 // ambiguity in certain cases (for example, if it is found in more than
1101 // one base class). If all of the injected-class-names that are found
1102 // refer to specializations of the same class template, and if the name
1103 // is followed by a template-argument-list, the reference refers to the
1104 // class template itself and not a specialization thereof, and is not
1105 // ambiguous.
1106 //
1107 // This filtering can make an ambiguous result into an unambiguous one,
1108 // so try again after filtering out template names.
1109 FilterAcceptableTemplateNames(Result);
1110 if (!Result.isAmbiguous()) {
1111 IsFilteredTemplateName = true;
1112 break;
1113 }
1114 }
1115
1116 // Diagnose the ambiguity and return an error.
1117 return NameClassification::Error();
1118 }
1119
1120 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1121 (IsFilteredTemplateName ||
1122 hasAnyAcceptableTemplateNames(
1123 Result, /*AllowFunctionTemplates=*/true,
1124 /*AllowDependent=*/false,
1125 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1126 getLangOpts().CPlusPlus20))) {
1127 // C++ [temp.names]p3:
1128 // After name lookup (3.4) finds that a name is a template-name or that
1129 // an operator-function-id or a literal- operator-id refers to a set of
1130 // overloaded functions any member of which is a function template if
1131 // this is followed by a <, the < is always taken as the delimiter of a
1132 // template-argument-list and never as the less-than operator.
1133 // C++2a [temp.names]p2:
1134 // A name is also considered to refer to a template if it is an
1135 // unqualified-id followed by a < and name lookup finds either one
1136 // or more functions or finds nothing.
1137 if (!IsFilteredTemplateName)
1138 FilterAcceptableTemplateNames(Result);
1139
1140 bool IsFunctionTemplate;
1141 bool IsVarTemplate;
1142 TemplateName Template;
1143 if (Result.end() - Result.begin() > 1) {
1144 IsFunctionTemplate = true;
1145 Template = Context.getOverloadedTemplateName(Result.begin(),
1146 Result.end());
1147 } else if (!Result.empty()) {
1148 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1149 *Result.begin(), /*AllowFunctionTemplates=*/true,
1150 /*AllowDependent=*/false));
1151 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1152 IsVarTemplate = isa<VarTemplateDecl>(TD);
1153
1154 UsingShadowDecl *FoundUsingShadow =
1155 dyn_cast<UsingShadowDecl>(*Result.begin());
1156 assert(!FoundUsingShadow ||
1157 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1158 Template = Context.getQualifiedTemplateName(
1159 SS.getScopeRep(),
1160 /*TemplateKeyword=*/false,
1161 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1162 } else {
1163 // All results were non-template functions. This is a function template
1164 // name.
1165 IsFunctionTemplate = true;
1166 Template = Context.getAssumedTemplateName(NameInfo.getName());
1167 }
1168
1169 if (IsFunctionTemplate) {
1170 // Function templates always go through overload resolution, at which
1171 // point we'll perform the various checks (e.g., accessibility) we need
1172 // to based on which function we selected.
1173 Result.suppressDiagnostics();
1174
1175 return NameClassification::FunctionTemplate(Template);
1176 }
1177
1178 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1179 : NameClassification::TypeTemplate(Template);
1180 }
1181
1182 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1183 QualType T;
1184 TypeLocBuilder TLB;
1185 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1186 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1187 USD);
1188 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1189 SS.getWithLocInContext(Context), NameLoc);
1190 } else {
1191 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1192 Type);
1193 if (isa<TagType>(T)) {
1194 auto TTL = TLB.push<TagTypeLoc>(T);
1195 TTL.setElaboratedKeywordLoc(SourceLocation());
1196 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1197 TTL.setNameLoc(NameLoc);
1198 } else if (isa<TypedefType>(T)) {
1199 TLB.push<TypedefTypeLoc>(T).set(
1200 /*ElaboratedKeywordLoc=*/SourceLocation(),
1201 SS.getWithLocInContext(Context), NameLoc);
1202 } else if (isa<UnresolvedUsingType>(T)) {
1203 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1204 /*ElaboratedKeywordLoc=*/SourceLocation(),
1205 SS.getWithLocInContext(Context), NameLoc);
1206 } else {
1207 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1208 }
1209 }
1210 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
1211 };
1212
1213 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1214 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1215 DiagnoseUseOfDecl(Type, NameLoc);
1216 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1217 return BuildTypeFor(Type, *Result.begin());
1218 }
1219
1220 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1221 if (!Class) {
1222 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1223 if (ObjCCompatibleAliasDecl *Alias =
1224 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1225 Class = Alias->getClassInterface();
1226 }
1227
1228 if (Class) {
1229 DiagnoseUseOfDecl(Class, NameLoc);
1230
1231 if (NextToken.is(tok::period)) {
1232 // Interface. <something> is parsed as a property reference expression.
1233 // Just return "unknown" as a fall-through for now.
1234 Result.suppressDiagnostics();
1235 return NameClassification::Unknown();
1236 }
1237
1238 QualType T = Context.getObjCInterfaceType(Class);
1239 return ParsedType::make(T);
1240 }
1241
1242 if (isa<ConceptDecl>(FirstDecl)) {
1243 // We want to preserve the UsingShadowDecl for concepts.
1244 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1245 return NameClassification::Concept(TemplateName(USD));
1246 return NameClassification::Concept(
1247 TemplateName(cast<TemplateDecl>(FirstDecl)));
1248 }
1249
1250 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1251 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1252 return NameClassification::Error();
1253 }
1254
1255 // We can have a type template here if we're classifying a template argument.
1256 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1257 !isa<VarTemplateDecl>(FirstDecl))
1258 return NameClassification::TypeTemplate(
1259 TemplateName(cast<TemplateDecl>(FirstDecl)));
1260
1261 // Check for a tag type hidden by a non-type decl in a few cases where it
1262 // seems likely a type is wanted instead of the non-type that was found.
1263 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1264 if ((NextToken.is(tok::identifier) ||
1265 (NextIsOp &&
1266 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1267 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1268 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1269 DiagnoseUseOfDecl(Type, NameLoc);
1270 return BuildTypeFor(Type, *Result.begin());
1271 }
1272
1273 // If we already know which single declaration is referenced, just annotate
1274 // that declaration directly. Defer resolving even non-overloaded class
1275 // member accesses, as we need to defer certain access checks until we know
1276 // the context.
1277 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1278 if (Result.isSingleResult() && !ADL &&
1279 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1280 return NameClassification::NonType(Result.getRepresentativeDecl());
1281
1282 // Otherwise, this is an overload set that we will need to resolve later.
1283 Result.suppressDiagnostics();
1284 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1285 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1286 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1287 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1288 }
1289
1290 ExprResult
1291 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1292 SourceLocation NameLoc) {
1293 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1294 CXXScopeSpec SS;
1295 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1296 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1297 }
1298
1299 ExprResult
1300 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1301 IdentifierInfo *Name,
1302 SourceLocation NameLoc,
1303 bool IsAddressOfOperand) {
1304 DeclarationNameInfo NameInfo(Name, NameLoc);
1305 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1306 NameInfo, IsAddressOfOperand,
1307 /*TemplateArgs=*/nullptr);
1308 }
1309
1310 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1311 NamedDecl *Found,
1312 SourceLocation NameLoc,
1313 const Token &NextToken) {
1314 if (getCurMethodDecl() && SS.isEmpty())
1315 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1316 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1317
1318 // Reconstruct the lookup result.
1319 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1320 Result.addDecl(Found);
1321 Result.resolveKind();
1322
1323 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1324 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1325 }
1326
1327 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1328 // For an implicit class member access, transform the result into a member
1329 // access expression if necessary.
1330 auto *ULE = cast<UnresolvedLookupExpr>(E);
1331 if ((*ULE->decls_begin())->isCXXClassMember()) {
1332 CXXScopeSpec SS;
1333 SS.Adopt(ULE->getQualifierLoc());
1334
1335 // Reconstruct the lookup result.
1336 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1337 LookupOrdinaryName);
1338 Result.setNamingClass(ULE->getNamingClass());
1339 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1340 Result.addDecl(*I, I.getAccess());
1341 Result.resolveKind();
1342 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1343 nullptr, S);
1344 }
1345
1346 // Otherwise, this is already in the form we needed, and no further checks
1347 // are necessary.
1348 return ULE;
1349 }
1350
1351 Sema::TemplateNameKindForDiagnostics
1352 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1353 auto *TD = Name.getAsTemplateDecl();
1354 if (!TD)
1355 return TemplateNameKindForDiagnostics::DependentTemplate;
1356 if (isa<ClassTemplateDecl>(TD))
1357 return TemplateNameKindForDiagnostics::ClassTemplate;
1358 if (isa<FunctionTemplateDecl>(TD))
1359 return TemplateNameKindForDiagnostics::FunctionTemplate;
1360 if (isa<VarTemplateDecl>(TD))
1361 return TemplateNameKindForDiagnostics::VarTemplate;
1362 if (isa<TypeAliasTemplateDecl>(TD))
1363 return TemplateNameKindForDiagnostics::AliasTemplate;
1364 if (isa<TemplateTemplateParmDecl>(TD))
1365 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1366 if (isa<ConceptDecl>(TD))
1367 return TemplateNameKindForDiagnostics::Concept;
1368 return TemplateNameKindForDiagnostics::DependentTemplate;
1369 }
1370
1371 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1372 assert(DC->getLexicalParent() == CurContext &&
1373 "The next DeclContext should be lexically contained in the current one.");
1374 CurContext = DC;
1375 S->setEntity(DC);
1376 }
1377
1378 void Sema::PopDeclContext() {
1379 assert(CurContext && "DeclContext imbalance!");
1380
1381 CurContext = CurContext->getLexicalParent();
1382 assert(CurContext && "Popped translation unit!");
1383 }
1384
1385 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1386 Decl *D) {
1387 // Unlike PushDeclContext, the context to which we return is not necessarily
1388 // the containing DC of TD, because the new context will be some pre-existing
1389 // TagDecl definition instead of a fresh one.
1390 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1391 CurContext = cast<TagDecl>(D)->getDefinition();
1392 assert(CurContext && "skipping definition of undefined tag");
1393 // Start lookups from the parent of the current context; we don't want to look
1394 // into the pre-existing complete definition.
1395 S->setEntity(CurContext->getLookupParent());
1396 return Result;
1397 }
1398
1399 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1400 CurContext = static_cast<decltype(CurContext)>(Context);
1401 }
1402
1403 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1404 // C++0x [basic.lookup.unqual]p13:
1405 // A name used in the definition of a static data member of class
1406 // X (after the qualified-id of the static member) is looked up as
1407 // if the name was used in a member function of X.
1408 // C++0x [basic.lookup.unqual]p14:
1409 // If a variable member of a namespace is defined outside of the
1410 // scope of its namespace then any name used in the definition of
1411 // the variable member (after the declarator-id) is looked up as
1412 // if the definition of the variable member occurred in its
1413 // namespace.
1414 // Both of these imply that we should push a scope whose context
1415 // is the semantic context of the declaration. We can't use
1416 // PushDeclContext here because that context is not necessarily
1417 // lexically contained in the current context. Fortunately,
1418 // the containing scope should have the appropriate information.
1419
1420 assert(!S->getEntity() && "scope already has entity");
1421
1422 #ifndef NDEBUG
1423 Scope *Ancestor = S->getParent();
1424 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1425 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1426 #endif
1427
1428 CurContext = DC;
1429 S->setEntity(DC);
1430
1431 if (S->getParent()->isTemplateParamScope()) {
1432 // Also set the corresponding entities for all immediately-enclosing
1433 // template parameter scopes.
1434 EnterTemplatedContext(S->getParent(), DC);
1435 }
1436 }
1437
1438 void Sema::ExitDeclaratorContext(Scope *S) {
1439 assert(S->getEntity() == CurContext && "Context imbalance!");
1440
1441 // Switch back to the lexical context. The safety of this is
1442 // enforced by an assert in EnterDeclaratorContext.
1443 Scope *Ancestor = S->getParent();
1444 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1445 CurContext = Ancestor->getEntity();
1446
1447 // We don't need to do anything with the scope, which is going to
1448 // disappear.
1449 }
1450
1451 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1452 assert(S->isTemplateParamScope() &&
1453 "expected to be initializing a template parameter scope");
1454
1455 // C++20 [temp.local]p7:
1456 // In the definition of a member of a class template that appears outside
1457 // of the class template definition, the name of a member of the class
1458 // template hides the name of a template-parameter of any enclosing class
1459 // templates (but not a template-parameter of the member if the member is a
1460 // class or function template).
1461 // C++20 [temp.local]p9:
1462 // In the definition of a class template or in the definition of a member
1463 // of such a template that appears outside of the template definition, for
1464 // each non-dependent base class (13.8.2.1), if the name of the base class
1465 // or the name of a member of the base class is the same as the name of a
1466 // template-parameter, the base class name or member name hides the
1467 // template-parameter name (6.4.10).
1468 //
1469 // This means that a template parameter scope should be searched immediately
1470 // after searching the DeclContext for which it is a template parameter
1471 // scope. For example, for
1472 // template<typename T> template<typename U> template<typename V>
1473 // void N::A<T>::B<U>::f(...)
1474 // we search V then B<U> (and base classes) then U then A<T> (and base
1475 // classes) then T then N then ::.
1476 unsigned ScopeDepth = getTemplateDepth(S);
1477 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1478 DeclContext *SearchDCAfterScope = DC;
1479 for (; DC; DC = DC->getLookupParent()) {
1480 if (const TemplateParameterList *TPL =
1481 cast<Decl>(DC)->getDescribedTemplateParams()) {
1482 unsigned DCDepth = TPL->getDepth() + 1;
1483 if (DCDepth > ScopeDepth)
1484 continue;
1485 if (ScopeDepth == DCDepth)
1486 SearchDCAfterScope = DC = DC->getLookupParent();
1487 break;
1488 }
1489 }
1490 S->setLookupEntity(SearchDCAfterScope);
1491 }
1492 }
1493
1494 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1495 // We assume that the caller has already called
1496 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1497 FunctionDecl *FD = D->getAsFunction();
1498 if (!FD)
1499 return;
1500
1501 // Same implementation as PushDeclContext, but enters the context
1502 // from the lexical parent, rather than the top-level class.
1503 assert(CurContext == FD->getLexicalParent() &&
1504 "The next DeclContext should be lexically contained in the current one.");
1505 CurContext = FD;
1506 S->setEntity(CurContext);
1507
1508 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1509 ParmVarDecl *Param = FD->getParamDecl(P);
1510 // If the parameter has an identifier, then add it to the scope
1511 if (Param->getIdentifier()) {
1512 S->AddDecl(Param);
1513 IdResolver.AddDecl(Param);
1514 }
1515 }
1516 }
1517
1518 void Sema::ActOnExitFunctionContext() {
1519 // Same implementation as PopDeclContext, but returns to the lexical parent,
1520 // rather than the top-level class.
1521 assert(CurContext && "DeclContext imbalance!");
1522 CurContext = CurContext->getLexicalParent();
1523 assert(CurContext && "Popped translation unit!");
1524 }
1525
1526 /// Determine whether overloading is allowed for a new function
1527 /// declaration considering prior declarations of the same name.
1528 ///
1529 /// This routine determines whether overloading is possible, not
1530 /// whether a new declaration actually overloads a previous one.
1531 /// It will return true in C++ (where overloads are always permitted)
1532 /// or, as a C extension, when either the new declaration or a
1533 /// previous one is declared with the 'overloadable' attribute.
1534 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1535 ASTContext &Context,
1536 const FunctionDecl *New) {
1537 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1538 return true;
1539
1540 // Multiversion function declarations are not overloads in the
1541 // usual sense of that term, but lookup will report that an
1542 // overload set was found if more than one multiversion function
1543 // declaration is present for the same name. It is therefore
1544 // inadequate to assume that some prior declaration(s) had
1545 // the overloadable attribute; checking is required. Since one
1546 // declaration is permitted to omit the attribute, it is necessary
1547 // to check at least two; hence the 'any_of' check below. Note that
1548 // the overloadable attribute is implicitly added to declarations
1549 // that were required to have it but did not.
1550 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1551 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1552 return ND->hasAttr<OverloadableAttr>();
1553 });
1554 } else if (Previous.getResultKind() == LookupResultKind::Found)
1555 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1556
1557 return false;
1558 }
1559
1560 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1561 // Move up the scope chain until we find the nearest enclosing
1562 // non-transparent context. The declaration will be introduced into this
1563 // scope.
1564 while (S->getEntity() && S->getEntity()->isTransparentContext())
1565 S = S->getParent();
1566
1567 // Add scoped declarations into their context, so that they can be
1568 // found later. Declarations without a context won't be inserted
1569 // into any context.
1570 if (AddToContext)
1571 CurContext->addDecl(D);
1572
1573 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1574 // are function-local declarations.
1575 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1576 return;
1577
1578 // Template instantiations should also not be pushed into scope.
1579 if (isa<FunctionDecl>(D) &&
1580 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1581 return;
1582
1583 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1584 S->AddDecl(D);
1585 return;
1586 }
1587 // If this replaces anything in the current scope,
1588 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1589 IEnd = IdResolver.end();
1590 for (; I != IEnd; ++I) {
1591 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1592 S->RemoveDecl(*I);
1593 IdResolver.RemoveDecl(*I);
1594
1595 // Should only need to replace one decl.
1596 break;
1597 }
1598 }
1599
1600 S->AddDecl(D);
1601
1602 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1603 // Implicitly-generated labels may end up getting generated in an order that
1604 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1605 // the label at the appropriate place in the identifier chain.
1606 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1607 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1608 if (IDC == CurContext) {
1609 if (!S->isDeclScope(*I))
1610 continue;
1611 } else if (IDC->Encloses(CurContext))
1612 break;
1613 }
1614
1615 IdResolver.InsertDeclAfter(I, D);
1616 } else {
1617 IdResolver.AddDecl(D);
1618 }
1619 warnOnReservedIdentifier(D);
1620 }
1621
1622 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1623 bool AllowInlineNamespace) const {
1624 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1625 }
1626
1627 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1628 DeclContext *TargetDC = DC->getPrimaryContext();
1629 do {
1630 if (DeclContext *ScopeDC = S->getEntity())
1631 if (ScopeDC->getPrimaryContext() == TargetDC)
1632 return S;
1633 } while ((S = S->getParent()));
1634
1635 return nullptr;
1636 }
1637
1638 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1639 DeclContext*,
1640 ASTContext&);
1641
1642 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1643 bool ConsiderLinkage,
1644 bool AllowInlineNamespace) {
1645 LookupResult::Filter F = R.makeFilter();
1646 while (F.hasNext()) {
1647 NamedDecl *D = F.next();
1648
1649 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1650 continue;
1651
1652 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1653 continue;
1654
1655 F.erase();
1656 }
1657
1658 F.done();
1659 }
1660
1661 static bool isImplicitInstantiation(NamedDecl *D) {
1662 if (auto *VD = dyn_cast<VarDecl>(D))
1663 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1664 if (auto *FD = dyn_cast<FunctionDecl>(D))
1665 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1666 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1667 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1668
1669 return false;
1670 }
1671
1672 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1673 // [module.interface]p7:
1674 // A declaration is attached to a module as follows:
1675 // - If the declaration is a non-dependent friend declaration that nominates a
1676 // function with a declarator-id that is a qualified-id or template-id or that
1677 // nominates a class other than with an elaborated-type-specifier with neither
1678 // a nested-name-specifier nor a simple-template-id, it is attached to the
1679 // module to which the friend is attached ([basic.link]).
1680 if (New->getFriendObjectKind() &&
1681 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1682 New->setLocalOwningModule(Old->getOwningModule());
1683 makeMergedDefinitionVisible(New);
1684 return false;
1685 }
1686
1687 // Although we have questions for the module ownership of implicit
1688 // instantiations, it should be sure that we shouldn't diagnose the
1689 // redeclaration of incorrect module ownership for different implicit
1690 // instantiations in different modules. We will diagnose the redeclaration of
1691 // incorrect module ownership for the template itself.
1692 if (isImplicitInstantiation(New) || isImplicitInstantiation(Old))
1693 return false;
1694
1695 Module *NewM = New->getOwningModule();
1696 Module *OldM = Old->getOwningModule();
1697
1698 if (NewM && NewM->isPrivateModule())
1699 NewM = NewM->Parent;
1700 if (OldM && OldM->isPrivateModule())
1701 OldM = OldM->Parent;
1702
1703 if (NewM == OldM)
1704 return false;
1705
1706 if (NewM && OldM) {
1707 // A module implementation unit has visibility of the decls in its
1708 // implicitly imported interface.
1709 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1710 return false;
1711
1712 // Partitions are part of the module, but a partition could import another
1713 // module, so verify that the PMIs agree.
1714 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1715 getASTContext().isInSameModule(NewM, OldM))
1716 return false;
1717 }
1718
1719 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1720 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1721 if (NewIsModuleInterface || OldIsModuleInterface) {
1722 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1723 // if a declaration of D [...] appears in the purview of a module, all
1724 // other such declarations shall appear in the purview of the same module
1725 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1726 << New
1727 << NewIsModuleInterface
1728 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1729 << OldIsModuleInterface
1730 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1731 Diag(Old->getLocation(), diag::note_previous_declaration);
1732 New->setInvalidDecl();
1733 return true;
1734 }
1735
1736 return false;
1737 }
1738
1739 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1740 // [module.interface]p1:
1741 // An export-declaration shall inhabit a namespace scope.
1742 //
1743 // So it is meaningless to talk about redeclaration which is not at namespace
1744 // scope.
1745 if (!New->getLexicalDeclContext()
1746 ->getNonTransparentContext()
1747 ->isFileContext() ||
1748 !Old->getLexicalDeclContext()
1749 ->getNonTransparentContext()
1750 ->isFileContext())
1751 return false;
1752
1753 bool IsNewExported = New->isInExportDeclContext();
1754 bool IsOldExported = Old->isInExportDeclContext();
1755
1756 // It should be irrevelant if both of them are not exported.
1757 if (!IsNewExported && !IsOldExported)
1758 return false;
1759
1760 if (IsOldExported)
1761 return false;
1762
1763 // If the Old declaration are not attached to named modules
1764 // and the New declaration are attached to global module.
1765 // It should be fine to allow the export since it doesn't change
1766 // the linkage of declarations. See
1767 // https://github.com/llvm/llvm-project/issues/98583 for details.
1768 if (!Old->isInNamedModule() && New->getOwningModule() &&
1769 New->getOwningModule()->isImplicitGlobalModule())
1770 return false;
1771
1772 assert(IsNewExported);
1773
1774 auto Lk = Old->getFormalLinkage();
1775 int S = 0;
1776 if (Lk == Linkage::Internal)
1777 S = 1;
1778 else if (Lk == Linkage::Module)
1779 S = 2;
1780 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1781 Diag(Old->getLocation(), diag::note_previous_declaration);
1782 return true;
1783 }
1784
1785 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1786 if (CheckRedeclarationModuleOwnership(New, Old))
1787 return true;
1788
1789 if (CheckRedeclarationExported(New, Old))
1790 return true;
1791
1792 return false;
1793 }
1794
1795 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1796 const NamedDecl *Old) const {
1797 assert(getASTContext().isSameEntity(New, Old) &&
1798 "New and Old are not the same definition, we should diagnostic it "
1799 "immediately instead of checking it.");
1800 assert(const_cast<Sema *>(this)->isReachable(New) &&
1801 const_cast<Sema *>(this)->isReachable(Old) &&
1802 "We shouldn't see unreachable definitions here.");
1803
1804 Module *NewM = New->getOwningModule();
1805 Module *OldM = Old->getOwningModule();
1806
1807 // We only checks for named modules here. The header like modules is skipped.
1808 // FIXME: This is not right if we import the header like modules in the module
1809 // purview.
1810 //
1811 // For example, assuming "header.h" provides definition for `D`.
1812 // ```C++
1813 // //--- M.cppm
1814 // export module M;
1815 // import "header.h"; // or #include "header.h" but import it by clang modules
1816 // actually.
1817 //
1818 // //--- Use.cpp
1819 // import M;
1820 // import "header.h"; // or uses clang modules.
1821 // ```
1822 //
1823 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1824 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1825 // reject it. But the current implementation couldn't detect the case since we
1826 // don't record the information about the importee modules.
1827 //
1828 // But this might not be painful in practice. Since the design of C++20 Named
1829 // Modules suggests us to use headers in global module fragment instead of
1830 // module purview.
1831 if (NewM && NewM->isHeaderLikeModule())
1832 NewM = nullptr;
1833 if (OldM && OldM->isHeaderLikeModule())
1834 OldM = nullptr;
1835
1836 if (!NewM && !OldM)
1837 return true;
1838
1839 // [basic.def.odr]p14.3
1840 // Each such definition shall not be attached to a named module
1841 // ([module.unit]).
1842 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1843 return true;
1844
1845 // Then New and Old lives in the same TU if their share one same module unit.
1846 if (NewM)
1847 NewM = NewM->getTopLevelModule();
1848 if (OldM)
1849 OldM = OldM->getTopLevelModule();
1850 return OldM == NewM;
1851 }
1852
1853 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1854 if (D->getDeclContext()->isFileContext())
1855 return false;
1856
1857 return isa<UsingShadowDecl>(D) ||
1858 isa<UnresolvedUsingTypenameDecl>(D) ||
1859 isa<UnresolvedUsingValueDecl>(D);
1860 }
1861
1862 /// Removes using shadow declarations not at class scope from the lookup
1863 /// results.
1864 static void RemoveUsingDecls(LookupResult &R) {
1865 LookupResult::Filter F = R.makeFilter();
1866 while (F.hasNext())
1867 if (isUsingDeclNotAtClassScope(F.next()))
1868 F.erase();
1869
1870 F.done();
1871 }
1872
1873 /// Check for this common pattern:
1874 /// @code
1875 /// class S {
1876 /// S(const S&); // DO NOT IMPLEMENT
1877 /// void operator=(const S&); // DO NOT IMPLEMENT
1878 /// };
1879 /// @endcode
1880 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1881 // FIXME: Should check for private access too but access is set after we get
1882 // the decl here.
1883 if (D->doesThisDeclarationHaveABody())
1884 return false;
1885
1886 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1887 return CD->isCopyConstructor();
1888 return D->isCopyAssignmentOperator();
1889 }
1890
1891 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1892 const DeclContext *DC = D->getDeclContext();
1893 while (!DC->isTranslationUnit()) {
1894 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1895 if (!RD->hasNameForLinkage())
1896 return true;
1897 }
1898 DC = DC->getParent();
1899 }
1900
1901 return !D->isExternallyVisible();
1902 }
1903
1904 // FIXME: This needs to be refactored; some other isInMainFile users want
1905 // these semantics.
1906 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1907 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1908 return false;
1909 return S.SourceMgr.isInMainFile(Loc);
1910 }
1911
1912 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1913 assert(D);
1914
1915 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1916 return false;
1917
1918 // Ignore all entities declared within templates, and out-of-line definitions
1919 // of members of class templates.
1920 if (D->getDeclContext()->isDependentContext() ||
1921 D->getLexicalDeclContext()->isDependentContext())
1922 return false;
1923
1924 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1925 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1926 return false;
1927 // A non-out-of-line declaration of a member specialization was implicitly
1928 // instantiated; it's the out-of-line declaration that we're interested in.
1929 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1930 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1931 return false;
1932
1933 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1934 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1935 return false;
1936 } else {
1937 // 'static inline' functions are defined in headers; don't warn.
1938 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1939 return false;
1940 }
1941
1942 if (FD->doesThisDeclarationHaveABody() &&
1943 Context.DeclMustBeEmitted(FD))
1944 return false;
1945 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1946 // Constants and utility variables are defined in headers with internal
1947 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1948 // like "inline".)
1949 if (!isMainFileLoc(*this, VD->getLocation()))
1950 return false;
1951
1952 if (Context.DeclMustBeEmitted(VD))
1953 return false;
1954
1955 if (VD->isStaticDataMember() &&
1956 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1957 return false;
1958 if (VD->isStaticDataMember() &&
1959 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1960 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1961 return false;
1962
1963 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1964 return false;
1965 } else {
1966 return false;
1967 }
1968
1969 // Only warn for unused decls internal to the translation unit.
1970 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1971 // for inline functions defined in the main source file, for instance.
1972 return mightHaveNonExternalLinkage(D);
1973 }
1974
1975 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1976 if (!D)
1977 return;
1978
1979 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1980 const FunctionDecl *First = FD->getFirstDecl();
1981 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1982 return; // First should already be in the vector.
1983 }
1984
1985 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1986 const VarDecl *First = VD->getFirstDecl();
1987 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1988 return; // First should already be in the vector.
1989 }
1990
1991 if (ShouldWarnIfUnusedFileScopedDecl(D))
1992 UnusedFileScopedDecls.push_back(D);
1993 }
1994
1995 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1996 const NamedDecl *D) {
1997 if (D->isInvalidDecl())
1998 return false;
1999
2000 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2001 // For a decomposition declaration, warn if none of the bindings are
2002 // referenced, instead of if the variable itself is referenced (which
2003 // it is, by the bindings' expressions).
2004 bool IsAllIgnored = true;
2005 for (const auto *BD : DD->bindings()) {
2006 if (BD->isReferenced())
2007 return false;
2008 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2009 BD->hasAttr<UnusedAttr>());
2010 }
2011 if (IsAllIgnored)
2012 return false;
2013 } else if (!D->getDeclName()) {
2014 return false;
2015 } else if (D->isReferenced() || D->isUsed()) {
2016 return false;
2017 }
2018
2019 if (D->isPlaceholderVar(LangOpts))
2020 return false;
2021
2022 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2023 D->hasAttr<CleanupAttr>())
2024 return false;
2025
2026 if (isa<LabelDecl>(D))
2027 return true;
2028
2029 // Except for labels, we only care about unused decls that are local to
2030 // functions.
2031 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2032 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2033 // For dependent types, the diagnostic is deferred.
2034 WithinFunction =
2035 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2036 if (!WithinFunction)
2037 return false;
2038
2039 if (isa<TypedefNameDecl>(D))
2040 return true;
2041
2042 // White-list anything that isn't a local variable.
2043 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2044 return false;
2045
2046 // Types of valid local variables should be complete, so this should succeed.
2047 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2048
2049 const Expr *Init = VD->getInit();
2050 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2051 Init = Cleanups->getSubExpr();
2052
2053 const auto *Ty = VD->getType().getTypePtr();
2054
2055 // Only look at the outermost level of typedef.
2056 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2057 // Allow anything marked with __attribute__((unused)).
2058 if (TT->getDecl()->hasAttr<UnusedAttr>())
2059 return false;
2060 }
2061
2062 // Warn for reference variables whose initializtion performs lifetime
2063 // extension.
2064 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2065 MTE && MTE->getExtendingDecl()) {
2066 Ty = VD->getType().getNonReferenceType().getTypePtr();
2067 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2068 }
2069
2070 // If we failed to complete the type for some reason, or if the type is
2071 // dependent, don't diagnose the variable.
2072 if (Ty->isIncompleteType() || Ty->isDependentType())
2073 return false;
2074
2075 // Look at the element type to ensure that the warning behaviour is
2076 // consistent for both scalars and arrays.
2077 Ty = Ty->getBaseElementTypeUnsafe();
2078
2079 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2080 if (Tag->hasAttr<UnusedAttr>())
2081 return false;
2082
2083 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2084 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2085 return false;
2086
2087 if (Init) {
2088 const auto *Construct =
2089 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2090 if (Construct && !Construct->isElidable()) {
2091 const CXXConstructorDecl *CD = Construct->getConstructor();
2092 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2093 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2094 return false;
2095 }
2096
2097 // Suppress the warning if we don't know how this is constructed, and
2098 // it could possibly be non-trivial constructor.
2099 if (Init->isTypeDependent()) {
2100 for (const CXXConstructorDecl *Ctor : RD->ctors())
2101 if (!Ctor->isTrivial())
2102 return false;
2103 }
2104
2105 // Suppress the warning if the constructor is unresolved because
2106 // its arguments are dependent.
2107 if (isa<CXXUnresolvedConstructExpr>(Init))
2108 return false;
2109 }
2110 }
2111 }
2112
2113 // TODO: __attribute__((unused)) templates?
2114 }
2115
2116 return true;
2117 }
2118
2119 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2120 FixItHint &Hint) {
2121 if (isa<LabelDecl>(D)) {
2122 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2123 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2124 /*SkipTrailingWhitespaceAndNewline=*/false);
2125 if (AfterColon.isInvalid())
2126 return;
2127 Hint = FixItHint::CreateRemoval(
2128 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2129 }
2130 }
2131
2132 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2133 DiagnoseUnusedNestedTypedefs(
2134 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2135 }
2136
2137 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2138 DiagReceiverTy DiagReceiver) {
2139 if (D->isDependentType())
2140 return;
2141
2142 for (auto *TmpD : D->decls()) {
2143 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2144 DiagnoseUnusedDecl(T, DiagReceiver);
2145 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2146 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2147 }
2148 }
2149
2150 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2151 DiagnoseUnusedDecl(
2152 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2153 }
2154
2155 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2156 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2157 return;
2158
2159 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2160 // typedefs can be referenced later on, so the diagnostics are emitted
2161 // at end-of-translation-unit.
2162 UnusedLocalTypedefNameCandidates.insert(TD);
2163 return;
2164 }
2165
2166 FixItHint Hint;
2167 GenerateFixForUnusedDecl(D, Context, Hint);
2168
2169 unsigned DiagID;
2170 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2171 DiagID = diag::warn_unused_exception_param;
2172 else if (isa<LabelDecl>(D))
2173 DiagID = diag::warn_unused_label;
2174 else
2175 DiagID = diag::warn_unused_variable;
2176
2177 SourceLocation DiagLoc = D->getLocation();
2178 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2179 }
2180
2181 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2182 DiagReceiverTy DiagReceiver) {
2183 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2184 // it's not really unused.
2185 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2186 return;
2187
2188 // In C++, `_` variables behave as if they were maybe_unused
2189 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2190 return;
2191
2192 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2193
2194 if (Ty->isReferenceType() || Ty->isDependentType())
2195 return;
2196
2197 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2198 if (Tag->hasAttr<UnusedAttr>())
2199 return;
2200 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2201 // mimic gcc's behavior.
2202 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2203 RD && !RD->hasAttr<WarnUnusedAttr>())
2204 return;
2205 }
2206
2207 // Don't warn about __block Objective-C pointer variables, as they might
2208 // be assigned in the block but not used elsewhere for the purpose of lifetime
2209 // extension.
2210 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2211 return;
2212
2213 // Don't warn about Objective-C pointer variables with precise lifetime
2214 // semantics; they can be used to ensure ARC releases the object at a known
2215 // time, which may mean assignment but no other references.
2216 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2217 return;
2218
2219 auto iter = RefsMinusAssignments.find(VD);
2220 if (iter == RefsMinusAssignments.end())
2221 return;
2222
2223 assert(iter->getSecond() >= 0 &&
2224 "Found a negative number of references to a VarDecl");
2225 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2226 // Assume the given VarDecl is "used" if its ref count stored in
2227 // `RefMinusAssignments` is positive, with one exception.
2228 //
2229 // For a C++ variable whose decl (with initializer) entirely consist the
2230 // condition expression of a if/while/for construct,
2231 // Clang creates a DeclRefExpr for the condition expression rather than a
2232 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2233 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2234 // used in the body of the if/while/for construct.
2235 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2236 if (!UnusedCXXCondDecl)
2237 return;
2238 }
2239
2240 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2241 : diag::warn_unused_but_set_variable;
2242 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2243 }
2244
2245 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2246 Sema::DiagReceiverTy DiagReceiver) {
2247 // Verify that we have no forward references left. If so, there was a goto
2248 // or address of a label taken, but no definition of it. Label fwd
2249 // definitions are indicated with a null substmt which is also not a resolved
2250 // MS inline assembly label name.
2251 bool Diagnose = false;
2252 if (L->isMSAsmLabel())
2253 Diagnose = !L->isResolvedMSAsmLabel();
2254 else
2255 Diagnose = L->getStmt() == nullptr;
2256 if (Diagnose)
2257 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2258 << L);
2259 }
2260
2261 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2262 S->applyNRVO();
2263
2264 if (S->decl_empty()) return;
2265 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2266 "Scope shouldn't contain decls!");
2267
2268 /// We visit the decls in non-deterministic order, but we want diagnostics
2269 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2270 /// and sort the diagnostics before emitting them, after we visited all decls.
2271 struct LocAndDiag {
2272 SourceLocation Loc;
2273 std::optional<SourceLocation> PreviousDeclLoc;
2274 PartialDiagnostic PD;
2275 };
2276 SmallVector<LocAndDiag, 16> DeclDiags;
2277 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2278 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2279 };
2280 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2281 SourceLocation PreviousDeclLoc,
2282 PartialDiagnostic PD) {
2283 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2284 };
2285
2286 for (auto *TmpD : S->decls()) {
2287 assert(TmpD && "This decl didn't get pushed??");
2288
2289 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2290 NamedDecl *D = cast<NamedDecl>(TmpD);
2291
2292 // Diagnose unused variables in this scope.
2293 if (!S->hasUnrecoverableErrorOccurred()) {
2294 DiagnoseUnusedDecl(D, addDiag);
2295 if (const auto *RD = dyn_cast<RecordDecl>(D))
2296 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2297 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2298 DiagnoseUnusedButSetDecl(VD, addDiag);
2299 RefsMinusAssignments.erase(VD);
2300 }
2301 }
2302
2303 if (!D->getDeclName()) continue;
2304
2305 // If this was a forward reference to a label, verify it was defined.
2306 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2307 CheckPoppedLabel(LD, *this, addDiag);
2308
2309 // Partial translation units that are created in incremental processing must
2310 // not clean up the IdResolver because PTUs should take into account the
2311 // declarations that came from previous PTUs.
2312 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2313 getLangOpts().CPlusPlus)
2314 IdResolver.RemoveDecl(D);
2315
2316 // Warn on it if we are shadowing a declaration.
2317 auto ShadowI = ShadowingDecls.find(D);
2318 if (ShadowI != ShadowingDecls.end()) {
2319 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2320 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2321 PDiag(diag::warn_ctor_parm_shadows_field)
2322 << D << FD << FD->getParent());
2323 }
2324 ShadowingDecls.erase(ShadowI);
2325 }
2326 }
2327
2328 llvm::sort(DeclDiags,
2329 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2330 // The particular order for diagnostics is not important, as long
2331 // as the order is deterministic. Using the raw location is going
2332 // to generally be in source order unless there are macro
2333 // expansions involved.
2334 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2335 });
2336 for (const LocAndDiag &D : DeclDiags) {
2337 Diag(D.Loc, D.PD);
2338 if (D.PreviousDeclLoc)
2339 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2340 }
2341 }
2342
2343 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2344 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2345 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2346 (S->isClassScope() && !getLangOpts().CPlusPlus))
2347 S = S->getParent();
2348 return S;
2349 }
2350
2351 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2352 ASTContext::GetBuiltinTypeError Error) {
2353 switch (Error) {
2354 case ASTContext::GE_None:
2355 return "";
2356 case ASTContext::GE_Missing_type:
2357 return BuiltinInfo.getHeaderName(ID);
2358 case ASTContext::GE_Missing_stdio:
2359 return "stdio.h";
2360 case ASTContext::GE_Missing_setjmp:
2361 return "setjmp.h";
2362 case ASTContext::GE_Missing_ucontext:
2363 return "ucontext.h";
2364 }
2365 llvm_unreachable("unhandled error kind");
2366 }
2367
2368 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2369 unsigned ID, SourceLocation Loc) {
2370 DeclContext *Parent = Context.getTranslationUnitDecl();
2371
2372 if (getLangOpts().CPlusPlus) {
2373 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2374 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2375 CLinkageDecl->setImplicit();
2376 Parent->addDecl(CLinkageDecl);
2377 Parent = CLinkageDecl;
2378 }
2379
2380 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2381 if (Context.BuiltinInfo.isImmediate(ID)) {
2382 assert(getLangOpts().CPlusPlus20 &&
2383 "consteval builtins should only be available in C++20 mode");
2384 ConstexprKind = ConstexprSpecKind::Consteval;
2385 }
2386
2387 FunctionDecl *New = FunctionDecl::Create(
2388 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2389 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2390 Type->isFunctionProtoType(), ConstexprKind);
2391 New->setImplicit();
2392 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2393
2394 // Create Decl objects for each parameter, adding them to the
2395 // FunctionDecl.
2396 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2397 SmallVector<ParmVarDecl *, 16> Params;
2398 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2399 ParmVarDecl *parm = ParmVarDecl::Create(
2400 Context, New, SourceLocation(), SourceLocation(), nullptr,
2401 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2402 parm->setScopeInfo(0, i);
2403 Params.push_back(parm);
2404 }
2405 New->setParams(Params);
2406 }
2407
2408 AddKnownFunctionAttributes(New);
2409 return New;
2410 }
2411
2412 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2413 Scope *S, bool ForRedeclaration,
2414 SourceLocation Loc) {
2415 LookupNecessaryTypesForBuiltin(S, ID);
2416
2417 ASTContext::GetBuiltinTypeError Error;
2418 QualType R = Context.GetBuiltinType(ID, Error);
2419 if (Error) {
2420 if (!ForRedeclaration)
2421 return nullptr;
2422
2423 // If we have a builtin without an associated type we should not emit a
2424 // warning when we were not able to find a type for it.
2425 if (Error == ASTContext::GE_Missing_type ||
2426 Context.BuiltinInfo.allowTypeMismatch(ID))
2427 return nullptr;
2428
2429 // If we could not find a type for setjmp it is because the jmp_buf type was
2430 // not defined prior to the setjmp declaration.
2431 if (Error == ASTContext::GE_Missing_setjmp) {
2432 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2433 << Context.BuiltinInfo.getName(ID);
2434 return nullptr;
2435 }
2436
2437 // Generally, we emit a warning that the declaration requires the
2438 // appropriate header.
2439 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2440 << getHeaderName(Context.BuiltinInfo, ID, Error)
2441 << Context.BuiltinInfo.getName(ID);
2442 return nullptr;
2443 }
2444
2445 if (!ForRedeclaration &&
2446 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2447 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2448 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2449 : diag::ext_implicit_lib_function_decl)
2450 << Context.BuiltinInfo.getName(ID) << R;
2451 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2452 Diag(Loc, diag::note_include_header_or_declare)
2453 << Header << Context.BuiltinInfo.getName(ID);
2454 }
2455
2456 if (R.isNull())
2457 return nullptr;
2458
2459 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2460 RegisterLocallyScopedExternCDecl(New, S);
2461
2462 // TUScope is the translation-unit scope to insert this function into.
2463 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2464 // relate Scopes to DeclContexts, and probably eliminate CurContext
2465 // entirely, but we're not there yet.
2466 DeclContext *SavedContext = CurContext;
2467 CurContext = New->getDeclContext();
2468 PushOnScopeChains(New, TUScope);
2469 CurContext = SavedContext;
2470 return New;
2471 }
2472
2473 /// Typedef declarations don't have linkage, but they still denote the same
2474 /// entity if their types are the same.
2475 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2476 /// isSameEntity.
2477 static void
2478 filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2479 LookupResult &Previous) {
2480 // This is only interesting when modules are enabled.
2481 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2482 return;
2483
2484 // Empty sets are uninteresting.
2485 if (Previous.empty())
2486 return;
2487
2488 LookupResult::Filter Filter = Previous.makeFilter();
2489 while (Filter.hasNext()) {
2490 NamedDecl *Old = Filter.next();
2491
2492 // Non-hidden declarations are never ignored.
2493 if (S.isVisible(Old))
2494 continue;
2495
2496 // Declarations of the same entity are not ignored, even if they have
2497 // different linkages.
2498 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2499 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2500 Decl->getUnderlyingType()))
2501 continue;
2502
2503 // If both declarations give a tag declaration a typedef name for linkage
2504 // purposes, then they declare the same entity.
2505 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2506 Decl->getAnonDeclWithTypedefName())
2507 continue;
2508 }
2509
2510 Filter.erase();
2511 }
2512
2513 Filter.done();
2514 }
2515
2516 bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2517 QualType OldType;
2518 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2519 OldType = OldTypedef->getUnderlyingType();
2520 else
2521 OldType = Context.getTypeDeclType(Old);
2522 QualType NewType = New->getUnderlyingType();
2523
2524 if (NewType->isVariablyModifiedType()) {
2525 // Must not redefine a typedef with a variably-modified type.
2526 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2527 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2528 << Kind << NewType;
2529 if (Old->getLocation().isValid())
2530 notePreviousDefinition(Old, New->getLocation());
2531 New->setInvalidDecl();
2532 return true;
2533 }
2534
2535 if (OldType != NewType &&
2536 !OldType->isDependentType() &&
2537 !NewType->isDependentType() &&
2538 !Context.hasSameType(OldType, NewType)) {
2539 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2540 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2541 << Kind << NewType << OldType;
2542 if (Old->getLocation().isValid())
2543 notePreviousDefinition(Old, New->getLocation());
2544 New->setInvalidDecl();
2545 return true;
2546 }
2547 return false;
2548 }
2549
2550 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2551 LookupResult &OldDecls) {
2552 // If the new decl is known invalid already, don't bother doing any
2553 // merging checks.
2554 if (New->isInvalidDecl()) return;
2555
2556 // Allow multiple definitions for ObjC built-in typedefs.
2557 // FIXME: Verify the underlying types are equivalent!
2558 if (getLangOpts().ObjC) {
2559 const IdentifierInfo *TypeID = New->getIdentifier();
2560 switch (TypeID->getLength()) {
2561 default: break;
2562 case 2:
2563 {
2564 if (!TypeID->isStr("id"))
2565 break;
2566 QualType T = New->getUnderlyingType();
2567 if (!T->isPointerType())
2568 break;
2569 if (!T->isVoidPointerType()) {
2570 QualType PT = T->castAs<PointerType>()->getPointeeType();
2571 if (!PT->isStructureType())
2572 break;
2573 }
2574 Context.setObjCIdRedefinitionType(T);
2575 // Install the built-in type for 'id', ignoring the current definition.
2576 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2577 Context.getObjCIdType());
2578 return;
2579 }
2580 case 5:
2581 if (!TypeID->isStr("Class"))
2582 break;
2583 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2584 // Install the built-in type for 'Class', ignoring the current definition.
2585 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2586 Context.getObjCClassType());
2587 return;
2588 case 3:
2589 if (!TypeID->isStr("SEL"))
2590 break;
2591 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2592 // Install the built-in type for 'SEL', ignoring the current definition.
2593 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2594 Context.getObjCSelType());
2595 return;
2596 }
2597 // Fall through - the typedef name was not a builtin type.
2598 }
2599
2600 // Verify the old decl was also a type.
2601 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2602 if (!Old) {
2603 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2604 << New->getDeclName();
2605
2606 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2607 if (OldD->getLocation().isValid())
2608 notePreviousDefinition(OldD, New->getLocation());
2609
2610 return New->setInvalidDecl();
2611 }
2612
2613 // If the old declaration is invalid, just give up here.
2614 if (Old->isInvalidDecl())
2615 return New->setInvalidDecl();
2616
2617 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2618 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2619 auto *NewTag = New->getAnonDeclWithTypedefName();
2620 NamedDecl *Hidden = nullptr;
2621 if (OldTag && NewTag &&
2622 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2623 !hasVisibleDefinition(OldTag, &Hidden)) {
2624 // There is a definition of this tag, but it is not visible. Use it
2625 // instead of our tag.
2626 if (OldTD->isModed())
2627 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2628 OldTD->getUnderlyingType());
2629 else
2630 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2631
2632 // Make the old tag definition visible.
2633 makeMergedDefinitionVisible(Hidden);
2634
2635 CleanupMergedEnum(S, NewTag);
2636 }
2637 }
2638
2639 // If the typedef types are not identical, reject them in all languages and
2640 // with any extensions enabled.
2641 if (isIncompatibleTypedef(Old, New))
2642 return;
2643
2644 // The types match. Link up the redeclaration chain and merge attributes if
2645 // the old declaration was a typedef.
2646 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2647 New->setPreviousDecl(Typedef);
2648 mergeDeclAttributes(New, Old);
2649 }
2650
2651 if (getLangOpts().MicrosoftExt)
2652 return;
2653
2654 if (getLangOpts().CPlusPlus) {
2655 // C++ [dcl.typedef]p2:
2656 // In a given non-class scope, a typedef specifier can be used to
2657 // redefine the name of any type declared in that scope to refer
2658 // to the type to which it already refers.
2659 if (!isa<CXXRecordDecl>(CurContext))
2660 return;
2661
2662 // C++0x [dcl.typedef]p4:
2663 // In a given class scope, a typedef specifier can be used to redefine
2664 // any class-name declared in that scope that is not also a typedef-name
2665 // to refer to the type to which it already refers.
2666 //
2667 // This wording came in via DR424, which was a correction to the
2668 // wording in DR56, which accidentally banned code like:
2669 //
2670 // struct S {
2671 // typedef struct A { } A;
2672 // };
2673 //
2674 // in the C++03 standard. We implement the C++0x semantics, which
2675 // allow the above but disallow
2676 //
2677 // struct S {
2678 // typedef int I;
2679 // typedef int I;
2680 // };
2681 //
2682 // since that was the intent of DR56.
2683 if (!isa<TypedefNameDecl>(Old))
2684 return;
2685
2686 Diag(New->getLocation(), diag::err_redefinition)
2687 << New->getDeclName();
2688 notePreviousDefinition(Old, New->getLocation());
2689 return New->setInvalidDecl();
2690 }
2691
2692 // Modules always permit redefinition of typedefs, as does C11.
2693 if (getLangOpts().Modules || getLangOpts().C11)
2694 return;
2695
2696 // If we have a redefinition of a typedef in C, emit a warning. This warning
2697 // is normally mapped to an error, but can be controlled with
2698 // -Wtypedef-redefinition. If either the original or the redefinition is
2699 // in a system header, don't emit this for compatibility with GCC.
2700 if (getDiagnostics().getSuppressSystemWarnings() &&
2701 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2702 (Old->isImplicit() ||
2703 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2704 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2705 return;
2706
2707 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2708 << New->getDeclName();
2709 notePreviousDefinition(Old, New->getLocation());
2710 }
2711
2712 void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2713 // If this was an unscoped enumeration, yank all of its enumerators
2714 // out of the scope.
2715 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2716 Scope *EnumScope = getNonFieldDeclScope(S);
2717 for (auto *ECD : ED->enumerators()) {
2718 assert(EnumScope->isDeclScope(ECD));
2719 EnumScope->RemoveDecl(ECD);
2720 IdResolver.RemoveDecl(ECD);
2721 }
2722 }
2723 }
2724
2725 /// DeclhasAttr - returns true if decl Declaration already has the target
2726 /// attribute.
2727 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2728 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2729 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2730 for (const auto *i : D->attrs())
2731 if (i->getKind() == A->getKind()) {
2732 if (Ann) {
2733 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2734 return true;
2735 continue;
2736 }
2737 // FIXME: Don't hardcode this check
2738 if (OA && isa<OwnershipAttr>(i))
2739 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2740 return true;
2741 }
2742
2743 return false;
2744 }
2745
2746 static bool isAttributeTargetADefinition(Decl *D) {
2747 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2748 return VD->isThisDeclarationADefinition();
2749 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2750 return TD->isCompleteDefinition() || TD->isBeingDefined();
2751 return true;
2752 }
2753
2754 /// Merge alignment attributes from \p Old to \p New, taking into account the
2755 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2756 ///
2757 /// \return \c true if any attributes were added to \p New.
2758 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2759 // Look for alignas attributes on Old, and pick out whichever attribute
2760 // specifies the strictest alignment requirement.
2761 AlignedAttr *OldAlignasAttr = nullptr;
2762 AlignedAttr *OldStrictestAlignAttr = nullptr;
2763 unsigned OldAlign = 0;
2764 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2765 // FIXME: We have no way of representing inherited dependent alignments
2766 // in a case like:
2767 // template<int A, int B> struct alignas(A) X;
2768 // template<int A, int B> struct alignas(B) X {};
2769 // For now, we just ignore any alignas attributes which are not on the
2770 // definition in such a case.
2771 if (I->isAlignmentDependent())
2772 return false;
2773
2774 if (I->isAlignas())
2775 OldAlignasAttr = I;
2776
2777 unsigned Align = I->getAlignment(S.Context);
2778 if (Align > OldAlign) {
2779 OldAlign = Align;
2780 OldStrictestAlignAttr = I;
2781 }
2782 }
2783
2784 // Look for alignas attributes on New.
2785 AlignedAttr *NewAlignasAttr = nullptr;
2786 unsigned NewAlign = 0;
2787 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2788 if (I->isAlignmentDependent())
2789 return false;
2790
2791 if (I->isAlignas())
2792 NewAlignasAttr = I;
2793
2794 unsigned Align = I->getAlignment(S.Context);
2795 if (Align > NewAlign)
2796 NewAlign = Align;
2797 }
2798
2799 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2800 // Both declarations have 'alignas' attributes. We require them to match.
2801 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2802 // fall short. (If two declarations both have alignas, they must both match
2803 // every definition, and so must match each other if there is a definition.)
2804
2805 // If either declaration only contains 'alignas(0)' specifiers, then it
2806 // specifies the natural alignment for the type.
2807 if (OldAlign == 0 || NewAlign == 0) {
2808 QualType Ty;
2809 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2810 Ty = VD->getType();
2811 else
2812 Ty = S.Context.getCanonicalTagType(cast<TagDecl>(New));
2813
2814 if (OldAlign == 0)
2815 OldAlign = S.Context.getTypeAlign(Ty);
2816 if (NewAlign == 0)
2817 NewAlign = S.Context.getTypeAlign(Ty);
2818 }
2819
2820 if (OldAlign != NewAlign) {
2821 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2822 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2823 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2824 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2825 }
2826 }
2827
2828 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2829 // C++11 [dcl.align]p6:
2830 // if any declaration of an entity has an alignment-specifier,
2831 // every defining declaration of that entity shall specify an
2832 // equivalent alignment.
2833 // C11 6.7.5/7:
2834 // If the definition of an object does not have an alignment
2835 // specifier, any other declaration of that object shall also
2836 // have no alignment specifier.
2837 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2838 << OldAlignasAttr;
2839 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2840 << OldAlignasAttr;
2841 }
2842
2843 bool AnyAdded = false;
2844
2845 // Ensure we have an attribute representing the strictest alignment.
2846 if (OldAlign > NewAlign) {
2847 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2848 Clone->setInherited(true);
2849 New->addAttr(Clone);
2850 AnyAdded = true;
2851 }
2852
2853 // Ensure we have an alignas attribute if the old declaration had one.
2854 if (OldAlignasAttr && !NewAlignasAttr &&
2855 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2856 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2857 Clone->setInherited(true);
2858 New->addAttr(Clone);
2859 AnyAdded = true;
2860 }
2861
2862 return AnyAdded;
2863 }
2864
2865 #define WANT_DECL_MERGE_LOGIC
2866 #include "clang/Sema/AttrParsedAttrImpl.inc"
2867 #undef WANT_DECL_MERGE_LOGIC
2868
2869 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2870 const InheritableAttr *Attr,
2871 AvailabilityMergeKind AMK) {
2872 // Diagnose any mutual exclusions between the attribute that we want to add
2873 // and attributes that already exist on the declaration.
2874 if (!DiagnoseMutualExclusions(S, D, Attr))
2875 return false;
2876
2877 // This function copies an attribute Attr from a previous declaration to the
2878 // new declaration D if the new declaration doesn't itself have that attribute
2879 // yet or if that attribute allows duplicates.
2880 // If you're adding a new attribute that requires logic different from
2881 // "use explicit attribute on decl if present, else use attribute from
2882 // previous decl", for example if the attribute needs to be consistent
2883 // between redeclarations, you need to call a custom merge function here.
2884 InheritableAttr *NewAttr = nullptr;
2885 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2886 NewAttr = S.mergeAvailabilityAttr(
2887 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2888 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2889 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2890 AA->getPriority(), AA->getEnvironment());
2891 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2892 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2893 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2894 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2895 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2896 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2897 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2898 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2899 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2900 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2901 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2902 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2903 FA->getFirstArg());
2904 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2905 NewAttr = S.mergeFormatMatchesAttr(
2906 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2907 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2908 NewAttr = S.mergeModularFormatAttr(
2909 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2910 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2911 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2912 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2913 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2914 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2915 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2916 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2917 IA->getInheritanceModel());
2918 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2919 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2920 &S.Context.Idents.get(AA->getSpelling()));
2921 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2922 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2923 isa<CUDAGlobalAttr>(Attr))) {
2924 // CUDA target attributes are part of function signature for
2925 // overloading purposes and must not be merged.
2926 return false;
2927 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2928 NewAttr = S.mergeMinSizeAttr(D, *MA);
2929 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2930 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2931 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2932 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2933 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2934 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2935 else if (isa<AlignedAttr>(Attr))
2936 // AlignedAttrs are handled separately, because we need to handle all
2937 // such attributes on a declaration at the same time.
2938 NewAttr = nullptr;
2939 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2940 (AMK == AvailabilityMergeKind::Override ||
2941 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2942 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2943 NewAttr = nullptr;
2944 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2945 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2946 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2947 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2948 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2949 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2950 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2951 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2952 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2953 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2954 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2955 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2956 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2957 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2958 NT->getZ());
2959 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2960 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2961 WS->getPreferred(),
2962 WS->getSpelledArgsCount());
2963 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2964 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2965 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2966 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2967 else if (isa<SuppressAttr>(Attr))
2968 // Do nothing. Each redeclaration should be suppressed separately.
2969 NewAttr = nullptr;
2970 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2971 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2972 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2973 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2974
2975 if (NewAttr) {
2976 NewAttr->setInherited(true);
2977 D->addAttr(NewAttr);
2978 if (isa<MSInheritanceAttr>(NewAttr))
2979 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2980 return true;
2981 }
2982
2983 return false;
2984 }
2985
2986 static const NamedDecl *getDefinition(const Decl *D) {
2987 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2988 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2989 return Def;
2990 return nullptr;
2991 }
2992 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2993 const VarDecl *Def = VD->getDefinition();
2994 if (Def)
2995 return Def;
2996 return VD->getActingDefinition();
2997 }
2998 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2999 const FunctionDecl *Def = nullptr;
3000 if (FD->isDefined(Def, true))
3001 return Def;
3002 }
3003 return nullptr;
3004 }
3005
3006 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3007 for (const auto *Attribute : D->attrs())
3008 if (Attribute->getKind() == Kind)
3009 return true;
3010 return false;
3011 }
3012
3013 /// checkNewAttributesAfterDef - If we already have a definition, check that
3014 /// there are no new attributes in this declaration.
3015 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3016 if (!New->hasAttrs())
3017 return;
3018
3019 const NamedDecl *Def = getDefinition(Old);
3020 if (!Def || Def == New)
3021 return;
3022
3023 AttrVec &NewAttributes = New->getAttrs();
3024 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3025 Attr *NewAttribute = NewAttributes[I];
3026
3027 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3028 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3029 SkipBodyInfo SkipBody;
3030 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3031
3032 // If we're skipping this definition, drop the "alias" attribute.
3033 if (SkipBody.ShouldSkip) {
3034 NewAttributes.erase(NewAttributes.begin() + I);
3035 --E;
3036 continue;
3037 }
3038 } else {
3039 VarDecl *VD = cast<VarDecl>(New);
3040 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3041 VarDecl::TentativeDefinition
3042 ? diag::err_alias_after_tentative
3043 : diag::err_redefinition;
3044 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3045 if (Diag == diag::err_redefinition)
3046 S.notePreviousDefinition(Def, VD->getLocation());
3047 else
3048 S.Diag(Def->getLocation(), diag::note_previous_definition);
3049 VD->setInvalidDecl();
3050 }
3051 ++I;
3052 continue;
3053 }
3054
3055 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3056 // Tentative definitions are only interesting for the alias check above.
3057 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3058 ++I;
3059 continue;
3060 }
3061 }
3062
3063 if (hasAttribute(Def, NewAttribute->getKind())) {
3064 ++I;
3065 continue; // regular attr merging will take care of validating this.
3066 }
3067
3068 if (isa<C11NoReturnAttr>(NewAttribute)) {
3069 // C's _Noreturn is allowed to be added to a function after it is defined.
3070 ++I;
3071 continue;
3072 } else if (isa<UuidAttr>(NewAttribute)) {
3073 // msvc will allow a subsequent definition to add an uuid to a class
3074 ++I;
3075 continue;
3076 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3077 NewAttribute) &&
3078 NewAttribute->isStandardAttributeSyntax()) {
3079 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3080 // deprecated attribute can later be re-declared with the attribute and
3081 // vice-versa.
3082 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3083 // maybe_unused attribute can later be redeclared with the attribute and
3084 // vice versa.
3085 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3086 // nodiscard attribute can later be redeclared with the attribute and
3087 // vice-versa.
3088 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3089 ++I;
3090 continue;
3091 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3092 if (AA->isAlignas()) {
3093 // C++11 [dcl.align]p6:
3094 // if any declaration of an entity has an alignment-specifier,
3095 // every defining declaration of that entity shall specify an
3096 // equivalent alignment.
3097 // C11 6.7.5/7:
3098 // If the definition of an object does not have an alignment
3099 // specifier, any other declaration of that object shall also
3100 // have no alignment specifier.
3101 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3102 << AA;
3103 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3104 << AA;
3105 NewAttributes.erase(NewAttributes.begin() + I);
3106 --E;
3107 continue;
3108 }
3109 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3110 // If there is a C definition followed by a redeclaration with this
3111 // attribute then there are two different definitions. In C++, prefer the
3112 // standard diagnostics.
3113 if (!S.getLangOpts().CPlusPlus) {
3114 S.Diag(NewAttribute->getLocation(),
3115 diag::err_loader_uninitialized_redeclaration);
3116 S.Diag(Def->getLocation(), diag::note_previous_definition);
3117 NewAttributes.erase(NewAttributes.begin() + I);
3118 --E;
3119 continue;
3120 }
3121 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3122 cast<VarDecl>(New)->isInline() &&
3123 !cast<VarDecl>(New)->isInlineSpecified()) {
3124 // Don't warn about applying selectany to implicitly inline variables.
3125 // Older compilers and language modes would require the use of selectany
3126 // to make such variables inline, and it would have no effect if we
3127 // honored it.
3128 ++I;
3129 continue;
3130 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3131 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3132 // declarations after definitions.
3133 ++I;
3134 continue;
3135 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3136 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3137 // error since the definition will have already been created without
3138 // the semantic effects of the attribute having been applied.
3139 S.Diag(NewAttribute->getLocation(),
3140 diag::err_sycl_entry_point_after_definition)
3141 << NewAttribute;
3142 S.Diag(Def->getLocation(), diag::note_previous_definition);
3143 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3144 ++I;
3145 continue;
3146 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3147 // SYCLExternalAttr may be added after a definition.
3148 ++I;
3149 continue;
3150 }
3151
3152 S.Diag(NewAttribute->getLocation(),
3153 diag::warn_attribute_precede_definition);
3154 S.Diag(Def->getLocation(), diag::note_previous_definition);
3155 NewAttributes.erase(NewAttributes.begin() + I);
3156 --E;
3157 }
3158 }
3159
3160 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3161 const ConstInitAttr *CIAttr,
3162 bool AttrBeforeInit) {
3163 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3164
3165 // Figure out a good way to write this specifier on the old declaration.
3166 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3167 // enough of the attribute list spelling information to extract that without
3168 // heroics.
3169 std::string SuitableSpelling;
3170 if (S.getLangOpts().CPlusPlus20)
3171 SuitableSpelling = std::string(
3172 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3173 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3174 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3175 InsertLoc, {tok::l_square, tok::l_square,
3176 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3177 S.PP.getIdentifierInfo("require_constant_initialization"),
3178 tok::r_square, tok::r_square}));
3179 if (SuitableSpelling.empty())
3180 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3181 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3182 S.PP.getIdentifierInfo("require_constant_initialization"),
3183 tok::r_paren, tok::r_paren}));
3184 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3185 SuitableSpelling = "constinit";
3186 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3187 SuitableSpelling = "[[clang::require_constant_initialization]]";
3188 if (SuitableSpelling.empty())
3189 SuitableSpelling = "__attribute__((require_constant_initialization))";
3190 SuitableSpelling += " ";
3191
3192 if (AttrBeforeInit) {
3193 // extern constinit int a;
3194 // int a = 0; // error (missing 'constinit'), accepted as extension
3195 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3196 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3197 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3198 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3199 } else {
3200 // int a = 0;
3201 // constinit extern int a; // error (missing 'constinit')
3202 S.Diag(CIAttr->getLocation(),
3203 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3204 : diag::warn_require_const_init_added_too_late)
3205 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3206 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3207 << CIAttr->isConstinit()
3208 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3209 }
3210 }
3211
3212 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3213 AvailabilityMergeKind AMK) {
3214 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3215 UsedAttr *NewAttr = OldAttr->clone(Context);
3216 NewAttr->setInherited(true);
3217 New->addAttr(NewAttr);
3218 }
3219 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3220 RetainAttr *NewAttr = OldAttr->clone(Context);
3221 NewAttr->setInherited(true);
3222 New->addAttr(NewAttr);
3223 }
3224
3225 if (!Old->hasAttrs() && !New->hasAttrs())
3226 return;
3227
3228 // [dcl.constinit]p1:
3229 // If the [constinit] specifier is applied to any declaration of a
3230 // variable, it shall be applied to the initializing declaration.
3231 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3232 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3233 if (bool(OldConstInit) != bool(NewConstInit)) {
3234 const auto *OldVD = cast<VarDecl>(Old);
3235 auto *NewVD = cast<VarDecl>(New);
3236
3237 // Find the initializing declaration. Note that we might not have linked
3238 // the new declaration into the redeclaration chain yet.
3239 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3240 if (!InitDecl &&
3241 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3242 InitDecl = NewVD;
3243
3244 if (InitDecl == NewVD) {
3245 // This is the initializing declaration. If it would inherit 'constinit',
3246 // that's ill-formed. (Note that we do not apply this to the attribute
3247 // form).
3248 if (OldConstInit && OldConstInit->isConstinit())
3249 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3250 /*AttrBeforeInit=*/true);
3251 } else if (NewConstInit) {
3252 // This is the first time we've been told that this declaration should
3253 // have a constant initializer. If we already saw the initializing
3254 // declaration, this is too late.
3255 if (InitDecl && InitDecl != NewVD) {
3256 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3257 /*AttrBeforeInit=*/false);
3258 NewVD->dropAttr<ConstInitAttr>();
3259 }
3260 }
3261 }
3262
3263 // Attributes declared post-definition are currently ignored.
3264 checkNewAttributesAfterDef(*this, New, Old);
3265
3266 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3267 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3268 if (!OldA->isEquivalent(NewA)) {
3269 // This redeclaration changes __asm__ label.
3270 Diag(New->getLocation(), diag::err_different_asm_label);
3271 Diag(OldA->getLocation(), diag::note_previous_declaration);
3272 }
3273 } else if (Old->isUsed()) {
3274 // This redeclaration adds an __asm__ label to a declaration that has
3275 // already been ODR-used.
3276 Diag(New->getLocation(), diag::err_late_asm_label_name)
3277 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3278 }
3279 }
3280
3281 // Re-declaration cannot add abi_tag's.
3282 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3283 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3284 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3285 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3286 Diag(NewAbiTagAttr->getLocation(),
3287 diag::err_new_abi_tag_on_redeclaration)
3288 << NewTag;
3289 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3290 }
3291 }
3292 } else {
3293 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3294 Diag(Old->getLocation(), diag::note_previous_declaration);
3295 }
3296 }
3297
3298 // This redeclaration adds a section attribute.
3299 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3300 if (auto *VD = dyn_cast<VarDecl>(New)) {
3301 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3302 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3303 Diag(Old->getLocation(), diag::note_previous_declaration);
3304 }
3305 }
3306 }
3307
3308 // Redeclaration adds code-seg attribute.
3309 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3310 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3311 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3312 Diag(New->getLocation(), diag::warn_mismatched_section)
3313 << 0 /*codeseg*/;
3314 Diag(Old->getLocation(), diag::note_previous_declaration);
3315 }
3316
3317 if (!Old->hasAttrs())
3318 return;
3319
3320 bool foundAny = New->hasAttrs();
3321
3322 // Ensure that any moving of objects within the allocated map is done before
3323 // we process them.
3324 if (!foundAny) New->setAttrs(AttrVec());
3325
3326 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3327 // Ignore deprecated/unavailable/availability attributes if requested.
3328 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3329 if (isa<DeprecatedAttr>(I) ||
3330 isa<UnavailableAttr>(I) ||
3331 isa<AvailabilityAttr>(I)) {
3332 switch (AMK) {
3333 case AvailabilityMergeKind::None:
3334 continue;
3335
3336 case AvailabilityMergeKind::Redeclaration:
3337 case AvailabilityMergeKind::Override:
3338 case AvailabilityMergeKind::ProtocolImplementation:
3339 case AvailabilityMergeKind::OptionalProtocolImplementation:
3340 LocalAMK = AMK;
3341 break;
3342 }
3343 }
3344
3345 // Already handled.
3346 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3347 continue;
3348
3349 if (isa<InferredNoReturnAttr>(I)) {
3350 if (auto *FD = dyn_cast<FunctionDecl>(New);
3351 FD &&
3352 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3353 continue; // Don't propagate inferred noreturn attributes to explicit
3354 }
3355
3356 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3357 foundAny = true;
3358 }
3359
3360 if (mergeAlignedAttrs(*this, New, Old))
3361 foundAny = true;
3362
3363 if (!foundAny) New->dropAttrs();
3364 }
3365
3366 void Sema::CheckAttributesOnDeducedType(Decl *D) {
3367 for (const Attr *A : D->attrs())
3368 checkAttrIsTypeDependent(D, A);
3369 }
3370
3371 // Returns the number of added attributes.
3372 template <class T>
3373 static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3374 Sema &S) {
3375 unsigned found = 0;
3376 for (const auto *I : From->specific_attrs<T>()) {
3377 if (!DeclHasAttr(To, I)) {
3378 T *newAttr = cast<T>(I->clone(S.Context));
3379 newAttr->setInherited(true);
3380 To->addAttr(newAttr);
3381 ++found;
3382 }
3383 }
3384 return found;
3385 }
3386
3387 template <class F>
3388 static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3389 F &&propagator) {
3390 if (!From->hasAttrs()) {
3391 return;
3392 }
3393
3394 bool foundAny = To->hasAttrs();
3395
3396 // Ensure that any moving of objects within the allocated map is
3397 // done before we process them.
3398 if (!foundAny)
3399 To->setAttrs(AttrVec());
3400
3401 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3402
3403 if (!foundAny)
3404 To->dropAttrs();
3405 }
3406
3407 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3408 /// to the new one.
3409 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3410 const ParmVarDecl *oldDecl,
3411 Sema &S) {
3412 // C++11 [dcl.attr.depend]p2:
3413 // The first declaration of a function shall specify the
3414 // carries_dependency attribute for its declarator-id if any declaration
3415 // of the function specifies the carries_dependency attribute.
3416 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3417 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3418 S.Diag(CDA->getLocation(),
3419 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3420 // Find the first declaration of the parameter.
3421 // FIXME: Should we build redeclaration chains for function parameters?
3422 const FunctionDecl *FirstFD =
3423 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3424 const ParmVarDecl *FirstVD =
3425 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3426 S.Diag(FirstVD->getLocation(),
3427 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3428 }
3429
3430 propagateAttributes(
3431 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3432 unsigned found = 0;
3433 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3434 // Propagate the lifetimebound attribute from parameters to the
3435 // most recent declaration. Note that this doesn't include the implicit
3436 // 'this' parameter, as the attribute is applied to the function type in
3437 // that case.
3438 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3439 return found;
3440 });
3441 }
3442
3443 static bool EquivalentArrayTypes(QualType Old, QualType New,
3444 const ASTContext &Ctx) {
3445
3446 auto NoSizeInfo = [&Ctx](QualType Ty) {
3447 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3448 return true;
3449 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3450 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3451 return false;
3452 };
3453
3454 // `type[]` is equivalent to `type *` and `type[*]`.
3455 if (NoSizeInfo(Old) && NoSizeInfo(New))
3456 return true;
3457
3458 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3459 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3460 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3461 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3462 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3463 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3464 return false;
3465 return true;
3466 }
3467
3468 // Only compare size, ignore Size modifiers and CVR.
3469 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3470 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3471 Ctx.getAsConstantArrayType(New)->getSize();
3472 }
3473
3474 // Don't try to compare dependent sized array
3475 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3476 return true;
3477 }
3478
3479 return Old == New;
3480 }
3481
3482 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3483 const ParmVarDecl *OldParam,
3484 Sema &S) {
3485 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3486 if (auto Newnullability = NewParam->getType()->getNullability()) {
3487 if (*Oldnullability != *Newnullability) {
3488 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3489 << DiagNullabilityKind(
3490 *Newnullability,
3491 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3492 != 0))
3493 << DiagNullabilityKind(
3494 *Oldnullability,
3495 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3496 != 0));
3497 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3498 }
3499 } else {
3500 QualType NewT = NewParam->getType();
3501 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3502 NewParam->setType(NewT);
3503 }
3504 }
3505 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3506 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3507 if (OldParamDT && NewParamDT &&
3508 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3509 QualType OldParamOT = OldParamDT->getOriginalType();
3510 QualType NewParamOT = NewParamDT->getOriginalType();
3511 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3512 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3513 << NewParam << NewParamOT;
3514 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3515 << OldParamOT;
3516 }
3517 }
3518 }
3519
3520 namespace {
3521
3522 /// Used in MergeFunctionDecl to keep track of function parameters in
3523 /// C.
3524 struct GNUCompatibleParamWarning {
3525 ParmVarDecl *OldParm;
3526 ParmVarDecl *NewParm;
3527 QualType PromotedType;
3528 };
3529
3530 } // end anonymous namespace
3531
3532 // Determine whether the previous declaration was a definition, implicit
3533 // declaration, or a declaration.
3534 template <typename T>
3535 static std::pair<diag::kind, SourceLocation>
3536 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3537 diag::kind PrevDiag;
3538 SourceLocation OldLocation = Old->getLocation();
3539 if (Old->isThisDeclarationADefinition())
3540 PrevDiag = diag::note_previous_definition;
3541 else if (Old->isImplicit()) {
3542 PrevDiag = diag::note_previous_implicit_declaration;
3543 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3544 if (FD->getBuiltinID())
3545 PrevDiag = diag::note_previous_builtin_declaration;
3546 }
3547 if (OldLocation.isInvalid())
3548 OldLocation = New->getLocation();
3549 } else
3550 PrevDiag = diag::note_previous_declaration;
3551 return std::make_pair(PrevDiag, OldLocation);
3552 }
3553
3554 /// canRedefineFunction - checks if a function can be redefined. Currently,
3555 /// only extern inline functions can be redefined, and even then only in
3556 /// GNU89 mode.
3557 static bool canRedefineFunction(const FunctionDecl *FD,
3558 const LangOptions& LangOpts) {
3559 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3560 !LangOpts.CPlusPlus &&
3561 FD->isInlineSpecified() &&
3562 FD->getStorageClass() == SC_Extern);
3563 }
3564
3565 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3566 const AttributedType *AT = T->getAs<AttributedType>();
3567 while (AT && !AT->isCallingConv())
3568 AT = AT->getModifiedType()->getAs<AttributedType>();
3569 return AT;
3570 }
3571
3572 template <typename T>
3573 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3574 const DeclContext *DC = Old->getDeclContext();
3575 if (DC->isRecord())
3576 return false;
3577
3578 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3579 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3580 return true;
3581 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3582 return true;
3583 return false;
3584 }
3585
3586 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3587 static bool isExternC(VarTemplateDecl *) { return false; }
3588 static bool isExternC(FunctionTemplateDecl *) { return false; }
3589
3590 /// Check whether a redeclaration of an entity introduced by a
3591 /// using-declaration is valid, given that we know it's not an overload
3592 /// (nor a hidden tag declaration).
3593 template<typename ExpectedDecl>
3594 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3595 ExpectedDecl *New) {
3596 // C++11 [basic.scope.declarative]p4:
3597 // Given a set of declarations in a single declarative region, each of
3598 // which specifies the same unqualified name,
3599 // -- they shall all refer to the same entity, or all refer to functions
3600 // and function templates; or
3601 // -- exactly one declaration shall declare a class name or enumeration
3602 // name that is not a typedef name and the other declarations shall all
3603 // refer to the same variable or enumerator, or all refer to functions
3604 // and function templates; in this case the class name or enumeration
3605 // name is hidden (3.3.10).
3606
3607 // C++11 [namespace.udecl]p14:
3608 // If a function declaration in namespace scope or block scope has the
3609 // same name and the same parameter-type-list as a function introduced
3610 // by a using-declaration, and the declarations do not declare the same
3611 // function, the program is ill-formed.
3612
3613 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3614 if (Old &&
3615 !Old->getDeclContext()->getRedeclContext()->Equals(
3616 New->getDeclContext()->getRedeclContext()) &&
3617 !(isExternC(Old) && isExternC(New)))
3618 Old = nullptr;
3619
3620 if (!Old) {
3621 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3622 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3623 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3624 return true;
3625 }
3626 return false;
3627 }
3628
3629 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3630 const FunctionDecl *B) {
3631 assert(A->getNumParams() == B->getNumParams());
3632
3633 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3634 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3635 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3636 if (AttrA == AttrB)
3637 return true;
3638 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3639 AttrA->isDynamic() == AttrB->isDynamic();
3640 };
3641
3642 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3643 }
3644
3645 /// If necessary, adjust the semantic declaration context for a qualified
3646 /// declaration to name the correct inline namespace within the qualifier.
3647 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3648 DeclaratorDecl *OldD) {
3649 // The only case where we need to update the DeclContext is when
3650 // redeclaration lookup for a qualified name finds a declaration
3651 // in an inline namespace within the context named by the qualifier:
3652 //
3653 // inline namespace N { int f(); }
3654 // int ::f(); // Sema DC needs adjusting from :: to N::.
3655 //
3656 // For unqualified declarations, the semantic context *can* change
3657 // along the redeclaration chain (for local extern declarations,
3658 // extern "C" declarations, and friend declarations in particular).
3659 if (!NewD->getQualifier())
3660 return;
3661
3662 // NewD is probably already in the right context.
3663 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3664 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3665 if (NamedDC->Equals(SemaDC))
3666 return;
3667
3668 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3669 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3670 "unexpected context for redeclaration");
3671
3672 auto *LexDC = NewD->getLexicalDeclContext();
3673 auto FixSemaDC = [=](NamedDecl *D) {
3674 if (!D)
3675 return;
3676 D->setDeclContext(SemaDC);
3677 D->setLexicalDeclContext(LexDC);
3678 };
3679
3680 FixSemaDC(NewD);
3681 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3682 FixSemaDC(FD->getDescribedFunctionTemplate());
3683 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3684 FixSemaDC(VD->getDescribedVarTemplate());
3685 }
3686
3687 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3688 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3689 // Verify the old decl was also a function.
3690 FunctionDecl *Old = OldD->getAsFunction();
3691 if (!Old) {
3692 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3693 // We don't need to check the using friend pattern from other module unit
3694 // since we should have diagnosed such cases in its unit already.
3695 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3696 Diag(New->getLocation(), diag::err_using_decl_friend);
3697 Diag(Shadow->getTargetDecl()->getLocation(),
3698 diag::note_using_decl_target);
3699 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3700 << 0;
3701 return true;
3702 }
3703
3704 // Check whether the two declarations might declare the same function or
3705 // function template.
3706 if (FunctionTemplateDecl *NewTemplate =
3707 New->getDescribedFunctionTemplate()) {
3708 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3709 NewTemplate))
3710 return true;
3711 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3712 ->getAsFunction();
3713 } else {
3714 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3715 return true;
3716 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3717 }
3718 } else {
3719 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3720 << New->getDeclName();
3721 notePreviousDefinition(OldD, New->getLocation());
3722 return true;
3723 }
3724 }
3725
3726 // If the old declaration was found in an inline namespace and the new
3727 // declaration was qualified, update the DeclContext to match.
3728 adjustDeclContextForDeclaratorDecl(New, Old);
3729
3730 // If the old declaration is invalid, just give up here.
3731 if (Old->isInvalidDecl())
3732 return true;
3733
3734 // Disallow redeclaration of some builtins.
3735 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3736 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3737 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3738 << Old << Old->getType();
3739 return true;
3740 }
3741
3742 diag::kind PrevDiag;
3743 SourceLocation OldLocation;
3744 std::tie(PrevDiag, OldLocation) =
3745 getNoteDiagForInvalidRedeclaration(Old, New);
3746
3747 // Don't complain about this if we're in GNU89 mode and the old function
3748 // is an extern inline function.
3749 // Don't complain about specializations. They are not supposed to have
3750 // storage classes.
3751 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3752 New->getStorageClass() == SC_Static &&
3753 Old->hasExternalFormalLinkage() &&
3754 !New->getTemplateSpecializationInfo() &&
3755 !canRedefineFunction(Old, getLangOpts())) {
3756 if (getLangOpts().MicrosoftExt) {
3757 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3758 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3759 } else {
3760 Diag(New->getLocation(), diag::err_static_non_static) << New;
3761 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3762 return true;
3763 }
3764 }
3765
3766 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3767 if (!Old->hasAttr<InternalLinkageAttr>()) {
3768 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3769 << ILA;
3770 Diag(Old->getLocation(), diag::note_previous_declaration);
3771 New->dropAttr<InternalLinkageAttr>();
3772 }
3773
3774 if (auto *EA = New->getAttr<ErrorAttr>()) {
3775 if (!Old->hasAttr<ErrorAttr>()) {
3776 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3777 Diag(Old->getLocation(), diag::note_previous_declaration);
3778 New->dropAttr<ErrorAttr>();
3779 }
3780 }
3781
3782 if (CheckRedeclarationInModule(New, Old))
3783 return true;
3784
3785 if (!getLangOpts().CPlusPlus) {
3786 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3787 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3788 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3789 << New << OldOvl;
3790
3791 // Try our best to find a decl that actually has the overloadable
3792 // attribute for the note. In most cases (e.g. programs with only one
3793 // broken declaration/definition), this won't matter.
3794 //
3795 // FIXME: We could do this if we juggled some extra state in
3796 // OverloadableAttr, rather than just removing it.
3797 const Decl *DiagOld = Old;
3798 if (OldOvl) {
3799 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3800 const auto *A = D->getAttr<OverloadableAttr>();
3801 return A && !A->isImplicit();
3802 });
3803 // If we've implicitly added *all* of the overloadable attrs to this
3804 // chain, emitting a "previous redecl" note is pointless.
3805 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3806 }
3807
3808 if (DiagOld)
3809 Diag(DiagOld->getLocation(),
3810 diag::note_attribute_overloadable_prev_overload)
3811 << OldOvl;
3812
3813 if (OldOvl)
3814 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3815 else
3816 New->dropAttr<OverloadableAttr>();
3817 }
3818 }
3819
3820 // It is not permitted to redeclare an SME function with different SME
3821 // attributes.
3822 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3823 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3824 << New->getType() << Old->getType();
3825 Diag(OldLocation, diag::note_previous_declaration);
3826 return true;
3827 }
3828
3829 // If a function is first declared with a calling convention, but is later
3830 // declared or defined without one, all following decls assume the calling
3831 // convention of the first.
3832 //
3833 // It's OK if a function is first declared without a calling convention,
3834 // but is later declared or defined with the default calling convention.
3835 //
3836 // To test if either decl has an explicit calling convention, we look for
3837 // AttributedType sugar nodes on the type as written. If they are missing or
3838 // were canonicalized away, we assume the calling convention was implicit.
3839 //
3840 // Note also that we DO NOT return at this point, because we still have
3841 // other tests to run.
3842 QualType OldQType = Context.getCanonicalType(Old->getType());
3843 QualType NewQType = Context.getCanonicalType(New->getType());
3844 const FunctionType *OldType = cast<FunctionType>(OldQType);
3845 const FunctionType *NewType = cast<FunctionType>(NewQType);
3846 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3847 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3848 bool RequiresAdjustment = false;
3849
3850 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3851 FunctionDecl *First = Old->getFirstDecl();
3852 const FunctionType *FT =
3853 First->getType().getCanonicalType()->castAs<FunctionType>();
3854 FunctionType::ExtInfo FI = FT->getExtInfo();
3855 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3856 if (!NewCCExplicit) {
3857 // Inherit the CC from the previous declaration if it was specified
3858 // there but not here.
3859 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3860 RequiresAdjustment = true;
3861 } else if (Old->getBuiltinID()) {
3862 // Builtin attribute isn't propagated to the new one yet at this point,
3863 // so we check if the old one is a builtin.
3864
3865 // Calling Conventions on a Builtin aren't really useful and setting a
3866 // default calling convention and cdecl'ing some builtin redeclarations is
3867 // common, so warn and ignore the calling convention on the redeclaration.
3868 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3869 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3870 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3871 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3872 RequiresAdjustment = true;
3873 } else {
3874 // Calling conventions aren't compatible, so complain.
3875 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3876 Diag(New->getLocation(), diag::err_cconv_change)
3877 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3878 << !FirstCCExplicit
3879 << (!FirstCCExplicit ? "" :
3880 FunctionType::getNameForCallConv(FI.getCC()));
3881
3882 // Put the note on the first decl, since it is the one that matters.
3883 Diag(First->getLocation(), diag::note_previous_declaration);
3884 return true;
3885 }
3886 }
3887
3888 // FIXME: diagnose the other way around?
3889 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3890 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3891 RequiresAdjustment = true;
3892 }
3893
3894 // If the declaration is marked with cfi_unchecked_callee but the definition
3895 // isn't, the definition is also cfi_unchecked_callee.
3896 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3897 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3898 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3899 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3900
3901 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3902 EPI2.CFIUncheckedCallee = true;
3903 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3904 FPT2->getParamTypes(), EPI2);
3905 NewType = cast<FunctionType>(NewQType);
3906 New->setType(NewQType);
3907 }
3908 }
3909 }
3910
3911 // Merge regparm attribute.
3912 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3913 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3914 if (NewTypeInfo.getHasRegParm()) {
3915 Diag(New->getLocation(), diag::err_regparm_mismatch)
3916 << NewType->getRegParmType()
3917 << OldType->getRegParmType();
3918 Diag(OldLocation, diag::note_previous_declaration);
3919 return true;
3920 }
3921
3922 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3923 RequiresAdjustment = true;
3924 }
3925
3926 // Merge ns_returns_retained attribute.
3927 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3928 if (NewTypeInfo.getProducesResult()) {
3929 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3930 << "'ns_returns_retained'";
3931 Diag(OldLocation, diag::note_previous_declaration);
3932 return true;
3933 }
3934
3935 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3936 RequiresAdjustment = true;
3937 }
3938
3939 if (OldTypeInfo.getNoCallerSavedRegs() !=
3940 NewTypeInfo.getNoCallerSavedRegs()) {
3941 if (NewTypeInfo.getNoCallerSavedRegs()) {
3942 AnyX86NoCallerSavedRegistersAttr *Attr =
3943 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3944 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3945 Diag(OldLocation, diag::note_previous_declaration);
3946 return true;
3947 }
3948
3949 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3950 RequiresAdjustment = true;
3951 }
3952
3953 if (RequiresAdjustment) {
3954 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3955 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3956 New->setType(QualType(AdjustedType, 0));
3957 NewQType = Context.getCanonicalType(New->getType());
3958 }
3959
3960 // If this redeclaration makes the function inline, we may need to add it to
3961 // UndefinedButUsed.
3962 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3963 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3964 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3965 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3966 SourceLocation()));
3967
3968 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3969 // about it.
3970 if (New->hasAttr<GNUInlineAttr>() &&
3971 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3972 UndefinedButUsed.erase(Old->getCanonicalDecl());
3973 }
3974
3975 // If pass_object_size params don't match up perfectly, this isn't a valid
3976 // redeclaration.
3977 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3978 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3979 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3980 << New->getDeclName();
3981 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3982 return true;
3983 }
3984
3985 QualType OldQTypeForComparison = OldQType;
3986 if (Context.hasAnyFunctionEffects()) {
3987 const auto OldFX = Old->getFunctionEffects();
3988 const auto NewFX = New->getFunctionEffects();
3989 if (OldFX != NewFX) {
3990 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3991 for (const auto &Diff : Diffs) {
3992 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3993 Diag(New->getLocation(),
3994 diag::warn_mismatched_func_effect_redeclaration)
3995 << Diff.effectName();
3996 Diag(Old->getLocation(), diag::note_previous_declaration);
3997 }
3998 }
3999 // Following a warning, we could skip merging effects from the previous
4000 // declaration, but that would trigger an additional "conflicting types"
4001 // error.
4002 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4003 FunctionEffectSet::Conflicts MergeErrs;
4004 FunctionEffectSet MergedFX =
4005 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4006 if (!MergeErrs.empty())
4007 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4008 Old->getLocation());
4009
4010 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4011 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4012 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4013 NewFPT->getParamTypes(), EPI);
4014
4015 New->setType(ModQT);
4016 NewQType = New->getType();
4017
4018 // Revise OldQTForComparison to include the merged effects,
4019 // so as not to fail due to differences later.
4020 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4021 EPI = OldFPT->getExtProtoInfo();
4022 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4023 OldQTypeForComparison = Context.getFunctionType(
4024 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4025 }
4026 if (OldFX.empty()) {
4027 // A redeclaration may add the attribute to a previously seen function
4028 // body which needs to be verified.
4029 maybeAddDeclWithEffects(Old, MergedFX);
4030 }
4031 }
4032 }
4033 }
4034
4035 if (getLangOpts().CPlusPlus) {
4036 OldQType = Context.getCanonicalType(Old->getType());
4037 NewQType = Context.getCanonicalType(New->getType());
4038
4039 // Go back to the type source info to compare the declared return types,
4040 // per C++1y [dcl.type.auto]p13:
4041 // Redeclarations or specializations of a function or function template
4042 // with a declared return type that uses a placeholder type shall also
4043 // use that placeholder, not a deduced type.
4044 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4045 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4046 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4047 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4048 OldDeclaredReturnType)) {
4049 QualType ResQT;
4050 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4051 OldDeclaredReturnType->isObjCObjectPointerType())
4052 // FIXME: This does the wrong thing for a deduced return type.
4053 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4054 if (ResQT.isNull()) {
4055 if (New->isCXXClassMember() && New->isOutOfLine())
4056 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4057 << New << New->getReturnTypeSourceRange();
4058 else if (Old->isExternC() && New->isExternC() &&
4059 !Old->hasAttr<OverloadableAttr>() &&
4060 !New->hasAttr<OverloadableAttr>())
4061 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4062 else
4063 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4064 << New->getReturnTypeSourceRange();
4065 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4066 << Old->getReturnTypeSourceRange();
4067 return true;
4068 }
4069 else
4070 NewQType = ResQT;
4071 }
4072
4073 QualType OldReturnType = OldType->getReturnType();
4074 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4075 if (OldReturnType != NewReturnType) {
4076 // If this function has a deduced return type and has already been
4077 // defined, copy the deduced value from the old declaration.
4078 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4079 if (OldAT && OldAT->isDeduced()) {
4080 QualType DT = OldAT->getDeducedType();
4081 if (DT.isNull()) {
4082 New->setType(SubstAutoTypeDependent(New->getType()));
4083 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4084 } else {
4085 New->setType(SubstAutoType(New->getType(), DT));
4086 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4087 }
4088 }
4089 }
4090
4091 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4092 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4093 if (OldMethod && NewMethod) {
4094 // Preserve triviality.
4095 NewMethod->setTrivial(OldMethod->isTrivial());
4096
4097 // MSVC allows explicit template specialization at class scope:
4098 // 2 CXXMethodDecls referring to the same function will be injected.
4099 // We don't want a redeclaration error.
4100 bool IsClassScopeExplicitSpecialization =
4101 OldMethod->isFunctionTemplateSpecialization() &&
4102 NewMethod->isFunctionTemplateSpecialization();
4103 bool isFriend = NewMethod->getFriendObjectKind();
4104
4105 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4106 !IsClassScopeExplicitSpecialization) {
4107 // -- Member function declarations with the same name and the
4108 // same parameter types cannot be overloaded if any of them
4109 // is a static member function declaration.
4110 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4111 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4112 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4113 return true;
4114 }
4115
4116 // C++ [class.mem]p1:
4117 // [...] A member shall not be declared twice in the
4118 // member-specification, except that a nested class or member
4119 // class template can be declared and then later defined.
4120 if (!inTemplateInstantiation()) {
4121 unsigned NewDiag;
4122 if (isa<CXXConstructorDecl>(OldMethod))
4123 NewDiag = diag::err_constructor_redeclared;
4124 else if (isa<CXXDestructorDecl>(NewMethod))
4125 NewDiag = diag::err_destructor_redeclared;
4126 else if (isa<CXXConversionDecl>(NewMethod))
4127 NewDiag = diag::err_conv_function_redeclared;
4128 else
4129 NewDiag = diag::err_member_redeclared;
4130
4131 Diag(New->getLocation(), NewDiag);
4132 } else {
4133 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4134 << New << New->getType();
4135 }
4136 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4137 return true;
4138
4139 // Complain if this is an explicit declaration of a special
4140 // member that was initially declared implicitly.
4141 //
4142 // As an exception, it's okay to befriend such methods in order
4143 // to permit the implicit constructor/destructor/operator calls.
4144 } else if (OldMethod->isImplicit()) {
4145 if (isFriend) {
4146 NewMethod->setImplicit();
4147 } else {
4148 Diag(NewMethod->getLocation(),
4149 diag::err_definition_of_implicitly_declared_member)
4150 << New << getSpecialMember(OldMethod);
4151 return true;
4152 }
4153 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4154 Diag(NewMethod->getLocation(),
4155 diag::err_definition_of_explicitly_defaulted_member)
4156 << getSpecialMember(OldMethod);
4157 return true;
4158 }
4159 }
4160
4161 // C++1z [over.load]p2
4162 // Certain function declarations cannot be overloaded:
4163 // -- Function declarations that differ only in the return type,
4164 // the exception specification, or both cannot be overloaded.
4165
4166 // Check the exception specifications match. This may recompute the type of
4167 // both Old and New if it resolved exception specifications, so grab the
4168 // types again after this. Because this updates the type, we do this before
4169 // any of the other checks below, which may update the "de facto" NewQType
4170 // but do not necessarily update the type of New.
4171 if (CheckEquivalentExceptionSpec(Old, New))
4172 return true;
4173
4174 // C++11 [dcl.attr.noreturn]p1:
4175 // The first declaration of a function shall specify the noreturn
4176 // attribute if any declaration of that function specifies the noreturn
4177 // attribute.
4178 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4179 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4180 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4181 << NRA;
4182 Diag(Old->getLocation(), diag::note_previous_declaration);
4183 }
4184
4185 // C++11 [dcl.attr.depend]p2:
4186 // The first declaration of a function shall specify the
4187 // carries_dependency attribute for its declarator-id if any declaration
4188 // of the function specifies the carries_dependency attribute.
4189 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4190 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4191 Diag(CDA->getLocation(),
4192 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4193 Diag(Old->getFirstDecl()->getLocation(),
4194 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4195 }
4196
4197 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4198 // When a function is declared with SYCL_EXTERNAL, that macro must be
4199 // used on the first declaration of that function in the translation unit.
4200 // Redeclarations of the function in the same translation unit may
4201 // optionally use SYCL_EXTERNAL, but this is not required.
4202 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4203 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4204 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4205 << SEA;
4206 Diag(Old->getLocation(), diag::note_previous_declaration);
4207 }
4208
4209 // (C++98 8.3.5p3):
4210 // All declarations for a function shall agree exactly in both the
4211 // return type and the parameter-type-list.
4212 // We also want to respect all the extended bits except noreturn.
4213
4214 // noreturn should now match unless the old type info didn't have it.
4215 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4216 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4217 const FunctionType *OldTypeForComparison
4218 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4219 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4220 assert(OldQTypeForComparison.isCanonical());
4221 }
4222
4223 if (haveIncompatibleLanguageLinkages(Old, New)) {
4224 // As a special case, retain the language linkage from previous
4225 // declarations of a friend function as an extension.
4226 //
4227 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4228 // and is useful because there's otherwise no way to specify language
4229 // linkage within class scope.
4230 //
4231 // Check cautiously as the friend object kind isn't yet complete.
4232 if (New->getFriendObjectKind() != Decl::FOK_None) {
4233 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4234 Diag(OldLocation, PrevDiag);
4235 } else {
4236 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4237 Diag(OldLocation, PrevDiag);
4238 return true;
4239 }
4240 }
4241
4242 // HLSL check parameters for matching ABI specifications.
4243 if (getLangOpts().HLSL) {
4244 if (HLSL().CheckCompatibleParameterABI(New, Old))
4245 return true;
4246
4247 // If no errors are generated when checking parameter ABIs we can check if
4248 // the two declarations have the same type ignoring the ABIs and if so,
4249 // the declarations can be merged. This case for merging is only valid in
4250 // HLSL because there are no valid cases of merging mismatched parameter
4251 // ABIs except the HLSL implicit in and explicit in.
4252 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4253 NewQType))
4254 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4255 // Fall through for conflicting redeclarations and redefinitions.
4256 }
4257
4258 // If the function types are compatible, merge the declarations. Ignore the
4259 // exception specifier because it was already checked above in
4260 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4261 // about incompatible types under -fms-compatibility.
4262 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4263 NewQType))
4264 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4265
4266 // If the types are imprecise (due to dependent constructs in friends or
4267 // local extern declarations), it's OK if they differ. We'll check again
4268 // during instantiation.
4269 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4270 return false;
4271
4272 // Fall through for conflicting redeclarations and redefinitions.
4273 }
4274
4275 // C: Function types need to be compatible, not identical. This handles
4276 // duplicate function decls like "void f(int); void f(enum X);" properly.
4277 if (!getLangOpts().CPlusPlus) {
4278 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4279 // type is specified by a function definition that contains a (possibly
4280 // empty) identifier list, both shall agree in the number of parameters
4281 // and the type of each parameter shall be compatible with the type that
4282 // results from the application of default argument promotions to the
4283 // type of the corresponding identifier. ...
4284 // This cannot be handled by ASTContext::typesAreCompatible() because that
4285 // doesn't know whether the function type is for a definition or not when
4286 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4287 // we need to cover here is that the number of arguments agree as the
4288 // default argument promotion rules were already checked by
4289 // ASTContext::typesAreCompatible().
4290 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4291 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4292 if (Old->hasInheritedPrototype())
4293 Old = Old->getCanonicalDecl();
4294 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4295 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4296 return true;
4297 }
4298
4299 // If we are merging two functions where only one of them has a prototype,
4300 // we may have enough information to decide to issue a diagnostic that the
4301 // function without a prototype will change behavior in C23. This handles
4302 // cases like:
4303 // void i(); void i(int j);
4304 // void i(int j); void i();
4305 // void i(); void i(int j) {}
4306 // See ActOnFinishFunctionBody() for other cases of the behavior change
4307 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4308 // type without a prototype.
4309 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4310 !New->isImplicit() && !Old->isImplicit()) {
4311 const FunctionDecl *WithProto, *WithoutProto;
4312 if (New->hasWrittenPrototype()) {
4313 WithProto = New;
4314 WithoutProto = Old;
4315 } else {
4316 WithProto = Old;
4317 WithoutProto = New;
4318 }
4319
4320 if (WithProto->getNumParams() != 0) {
4321 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4322 // The one without the prototype will be changing behavior in C23, so
4323 // warn about that one so long as it's a user-visible declaration.
4324 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4325 if (WithoutProto == New)
4326 IsWithoutProtoADef = NewDeclIsDefn;
4327 else
4328 IsWithProtoADef = NewDeclIsDefn;
4329 Diag(WithoutProto->getLocation(),
4330 diag::warn_non_prototype_changes_behavior)
4331 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4332 << (WithoutProto == Old) << IsWithProtoADef;
4333
4334 // The reason the one without the prototype will be changing behavior
4335 // is because of the one with the prototype, so note that so long as
4336 // it's a user-visible declaration. There is one exception to this:
4337 // when the new declaration is a definition without a prototype, the
4338 // old declaration with a prototype is not the cause of the issue,
4339 // and that does not need to be noted because the one with a
4340 // prototype will not change behavior in C23.
4341 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4342 !IsWithoutProtoADef)
4343 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4344 }
4345 }
4346 }
4347
4348 if (Context.typesAreCompatible(OldQType, NewQType)) {
4349 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4350 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4351 const FunctionProtoType *OldProto = nullptr;
4352 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4353 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4354 // The old declaration provided a function prototype, but the
4355 // new declaration does not. Merge in the prototype.
4356 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4357 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4358 OldProto->getParamTypes(),
4359 OldProto->getExtProtoInfo());
4360 New->setType(NewQType);
4361 New->setHasInheritedPrototype();
4362
4363 // Synthesize parameters with the same types.
4364 SmallVector<ParmVarDecl *, 16> Params;
4365 for (const auto &ParamType : OldProto->param_types()) {
4366 ParmVarDecl *Param = ParmVarDecl::Create(
4367 Context, New, SourceLocation(), SourceLocation(), nullptr,
4368 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4369 Param->setScopeInfo(0, Params.size());
4370 Param->setImplicit();
4371 Params.push_back(Param);
4372 }
4373
4374 New->setParams(Params);
4375 }
4376
4377 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4378 }
4379 }
4380
4381 // Check if the function types are compatible when pointer size address
4382 // spaces are ignored.
4383 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4384 return false;
4385
4386 // GNU C permits a K&R definition to follow a prototype declaration
4387 // if the declared types of the parameters in the K&R definition
4388 // match the types in the prototype declaration, even when the
4389 // promoted types of the parameters from the K&R definition differ
4390 // from the types in the prototype. GCC then keeps the types from
4391 // the prototype.
4392 //
4393 // If a variadic prototype is followed by a non-variadic K&R definition,
4394 // the K&R definition becomes variadic. This is sort of an edge case, but
4395 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4396 // C99 6.9.1p8.
4397 if (!getLangOpts().CPlusPlus &&
4398 Old->hasPrototype() && !New->hasPrototype() &&
4399 New->getType()->getAs<FunctionProtoType>() &&
4400 Old->getNumParams() == New->getNumParams()) {
4401 SmallVector<QualType, 16> ArgTypes;
4402 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4403 const FunctionProtoType *OldProto
4404 = Old->getType()->getAs<FunctionProtoType>();
4405 const FunctionProtoType *NewProto
4406 = New->getType()->getAs<FunctionProtoType>();
4407
4408 // Determine whether this is the GNU C extension.
4409 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4410 NewProto->getReturnType());
4411 bool LooseCompatible = !MergedReturn.isNull();
4412 for (unsigned Idx = 0, End = Old->getNumParams();
4413 LooseCompatible && Idx != End; ++Idx) {
4414 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4415 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4416 if (Context.typesAreCompatible(OldParm->getType(),
4417 NewProto->getParamType(Idx))) {
4418 ArgTypes.push_back(NewParm->getType());
4419 } else if (Context.typesAreCompatible(OldParm->getType(),
4420 NewParm->getType(),
4421 /*CompareUnqualified=*/true)) {
4422 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4423 NewProto->getParamType(Idx) };
4424 Warnings.push_back(Warn);
4425 ArgTypes.push_back(NewParm->getType());
4426 } else
4427 LooseCompatible = false;
4428 }
4429
4430 if (LooseCompatible) {
4431 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4432 Diag(Warnings[Warn].NewParm->getLocation(),
4433 diag::ext_param_promoted_not_compatible_with_prototype)
4434 << Warnings[Warn].PromotedType
4435 << Warnings[Warn].OldParm->getType();
4436 if (Warnings[Warn].OldParm->getLocation().isValid())
4437 Diag(Warnings[Warn].OldParm->getLocation(),
4438 diag::note_previous_declaration);
4439 }
4440
4441 if (MergeTypeWithOld)
4442 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4443 OldProto->getExtProtoInfo()));
4444 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4445 }
4446
4447 // Fall through to diagnose conflicting types.
4448 }
4449
4450 // A function that has already been declared has been redeclared or
4451 // defined with a different type; show an appropriate diagnostic.
4452
4453 // If the previous declaration was an implicitly-generated builtin
4454 // declaration, then at the very least we should use a specialized note.
4455 unsigned BuiltinID;
4456 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4457 // If it's actually a library-defined builtin function like 'malloc'
4458 // or 'printf', just warn about the incompatible redeclaration.
4459 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4460 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4461 Diag(OldLocation, diag::note_previous_builtin_declaration)
4462 << Old << Old->getType();
4463 return false;
4464 }
4465
4466 PrevDiag = diag::note_previous_builtin_declaration;
4467 }
4468
4469 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4470 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4471 return true;
4472 }
4473
4474 /// Merge lifetimebound attribute on function type (implicit 'this')
4475 /// from Old to New method declaration.
4476 static void mergeLifetimeBoundAttrOnMethod(Sema &S, CXXMethodDecl *New,
4477 const CXXMethodDecl *Old) {
4478 const TypeSourceInfo *OldTSI = Old->getTypeSourceInfo();
4479 const TypeSourceInfo *NewTSI = New->getTypeSourceInfo();
4480
4481 if (!OldTSI || !NewTSI)
4482 return;
4483
4484 const LifetimeBoundAttr *OldLBAttr =
4485 lifetimes::getLifetimeBoundAttrFromFunctionType(*OldTSI);
4486 const LifetimeBoundAttr *NewLBAttr =
4487 lifetimes::getLifetimeBoundAttrFromFunctionType(*NewTSI);
4488
4489 // If Old has lifetimebound but New doesn't, add it to New.
4490 if (OldLBAttr && !NewLBAttr) {
4491 QualType NewMethodType = New->getType();
4492 QualType AttributedType =
4493 S.Context.getAttributedType(OldLBAttr, NewMethodType, NewMethodType);
4494 TypeLocBuilder TLB;
4495 TLB.pushFullCopy(NewTSI->getTypeLoc());
4496 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
4497 TyLoc.setAttr(OldLBAttr);
4498 New->setType(AttributedType);
4499 New->setTypeSourceInfo(TLB.getTypeSourceInfo(S.Context, AttributedType));
4500 }
4501 }
4502
4503 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4504 Scope *S, bool MergeTypeWithOld) {
4505 // Merge the attributes
4506 mergeDeclAttributes(New, Old);
4507
4508 // Merge "pure" flag.
4509 if (Old->isPureVirtual())
4510 New->setIsPureVirtual();
4511
4512 // Merge "used" flag.
4513 if (Old->getMostRecentDecl()->isUsed(false))
4514 New->setIsUsed();
4515
4516 // Merge attributes from the parameters. These can mismatch with K&R
4517 // declarations.
4518 if (New->getNumParams() == Old->getNumParams())
4519 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4520 ParmVarDecl *NewParam = New->getParamDecl(i);
4521 ParmVarDecl *OldParam = Old->getParamDecl(i);
4522 mergeParamDeclAttributes(NewParam, OldParam, *this);
4523 mergeParamDeclTypes(NewParam, OldParam, *this);
4524 }
4525
4526 // Merge function type attributes (e.g., lifetimebound on implicit 'this').
4527 if (auto *NewMethod = dyn_cast<CXXMethodDecl>(New))
4528 mergeLifetimeBoundAttrOnMethod(*this, NewMethod, cast<CXXMethodDecl>(Old));
4529
4530 if (getLangOpts().CPlusPlus)
4531 return MergeCXXFunctionDecl(New, Old, S);
4532
4533 // Merge the function types so the we get the composite types for the return
4534 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4535 // was visible.
4536 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4537 if (!Merged.isNull() && MergeTypeWithOld)
4538 New->setType(Merged);
4539
4540 return false;
4541 }
4542
4543 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4544 ObjCMethodDecl *oldMethod) {
4545 // Merge the attributes, including deprecated/unavailable
4546 AvailabilityMergeKind MergeKind =
4547 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4548 ? (oldMethod->isOptional()
4549 ? AvailabilityMergeKind::OptionalProtocolImplementation
4550 : AvailabilityMergeKind::ProtocolImplementation)
4551 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4552 ? AvailabilityMergeKind::Redeclaration
4553 : AvailabilityMergeKind::Override;
4554
4555 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4556
4557 // Merge attributes from the parameters.
4558 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4559 oe = oldMethod->param_end();
4560 for (ObjCMethodDecl::param_iterator
4561 ni = newMethod->param_begin(), ne = newMethod->param_end();
4562 ni != ne && oi != oe; ++ni, ++oi)
4563 mergeParamDeclAttributes(*ni, *oi, *this);
4564
4565 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4566 }
4567
4568 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4569 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4570
4571 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4572 ? diag::err_redefinition_different_type
4573 : diag::err_redeclaration_different_type)
4574 << New->getDeclName() << New->getType() << Old->getType();
4575
4576 diag::kind PrevDiag;
4577 SourceLocation OldLocation;
4578 std::tie(PrevDiag, OldLocation)
4579 = getNoteDiagForInvalidRedeclaration(Old, New);
4580 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4581 New->setInvalidDecl();
4582 }
4583
4584 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4585 bool MergeTypeWithOld) {
4586 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4587 return;
4588
4589 QualType MergedT;
4590 if (getLangOpts().CPlusPlus) {
4591 if (New->getType()->isUndeducedType()) {
4592 // We don't know what the new type is until the initializer is attached.
4593 return;
4594 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4595 // These could still be something that needs exception specs checked.
4596 return MergeVarDeclExceptionSpecs(New, Old);
4597 }
4598 // C++ [basic.link]p10:
4599 // [...] the types specified by all declarations referring to a given
4600 // object or function shall be identical, except that declarations for an
4601 // array object can specify array types that differ by the presence or
4602 // absence of a major array bound (8.3.4).
4603 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4604 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4605 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4606
4607 // We are merging a variable declaration New into Old. If it has an array
4608 // bound, and that bound differs from Old's bound, we should diagnose the
4609 // mismatch.
4610 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4611 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4612 PrevVD = PrevVD->getPreviousDecl()) {
4613 QualType PrevVDTy = PrevVD->getType();
4614 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4615 continue;
4616
4617 if (!Context.hasSameType(New->getType(), PrevVDTy))
4618 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4619 }
4620 }
4621
4622 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4623 if (Context.hasSameType(OldArray->getElementType(),
4624 NewArray->getElementType()))
4625 MergedT = New->getType();
4626 }
4627 // FIXME: Check visibility. New is hidden but has a complete type. If New
4628 // has no array bound, it should not inherit one from Old, if Old is not
4629 // visible.
4630 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4631 if (Context.hasSameType(OldArray->getElementType(),
4632 NewArray->getElementType()))
4633 MergedT = Old->getType();
4634 }
4635 }
4636 else if (New->getType()->isObjCObjectPointerType() &&
4637 Old->getType()->isObjCObjectPointerType()) {
4638 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4639 Old->getType());
4640 }
4641 } else {
4642 // C 6.2.7p2:
4643 // All declarations that refer to the same object or function shall have
4644 // compatible type.
4645 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4646 }
4647 if (MergedT.isNull()) {
4648 // It's OK if we couldn't merge types if either type is dependent, for a
4649 // block-scope variable. In other cases (static data members of class
4650 // templates, variable templates, ...), we require the types to be
4651 // equivalent.
4652 // FIXME: The C++ standard doesn't say anything about this.
4653 if ((New->getType()->isDependentType() ||
4654 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4655 // If the old type was dependent, we can't merge with it, so the new type
4656 // becomes dependent for now. We'll reproduce the original type when we
4657 // instantiate the TypeSourceInfo for the variable.
4658 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4659 New->setType(Context.DependentTy);
4660 return;
4661 }
4662 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4663 }
4664
4665 // Don't actually update the type on the new declaration if the old
4666 // declaration was an extern declaration in a different scope.
4667 if (MergeTypeWithOld)
4668 New->setType(MergedT);
4669 }
4670
4671 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4672 LookupResult &Previous) {
4673 // C11 6.2.7p4:
4674 // For an identifier with internal or external linkage declared
4675 // in a scope in which a prior declaration of that identifier is
4676 // visible, if the prior declaration specifies internal or
4677 // external linkage, the type of the identifier at the later
4678 // declaration becomes the composite type.
4679 //
4680 // If the variable isn't visible, we do not merge with its type.
4681 if (Previous.isShadowed())
4682 return false;
4683
4684 if (S.getLangOpts().CPlusPlus) {
4685 // C++11 [dcl.array]p3:
4686 // If there is a preceding declaration of the entity in the same
4687 // scope in which the bound was specified, an omitted array bound
4688 // is taken to be the same as in that earlier declaration.
4689 return NewVD->isPreviousDeclInSameBlockScope() ||
4690 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4691 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4692 } else {
4693 // If the old declaration was function-local, don't merge with its
4694 // type unless we're in the same function.
4695 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4696 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4697 }
4698 }
4699
4700 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4701 // If the new decl is already invalid, don't do any other checking.
4702 if (New->isInvalidDecl())
4703 return;
4704
4705 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4706 return;
4707
4708 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4709
4710 // Verify the old decl was also a variable or variable template.
4711 VarDecl *Old = nullptr;
4712 VarTemplateDecl *OldTemplate = nullptr;
4713 if (Previous.isSingleResult()) {
4714 if (NewTemplate) {
4715 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4716 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4717
4718 if (auto *Shadow =
4719 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4720 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4721 return New->setInvalidDecl();
4722 } else {
4723 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4724
4725 if (auto *Shadow =
4726 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4727 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4728 return New->setInvalidDecl();
4729 }
4730 }
4731 if (!Old) {
4732 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4733 << New->getDeclName();
4734 notePreviousDefinition(Previous.getRepresentativeDecl(),
4735 New->getLocation());
4736 return New->setInvalidDecl();
4737 }
4738
4739 // If the old declaration was found in an inline namespace and the new
4740 // declaration was qualified, update the DeclContext to match.
4741 adjustDeclContextForDeclaratorDecl(New, Old);
4742
4743 // Ensure the template parameters are compatible.
4744 if (NewTemplate &&
4745 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4746 OldTemplate->getTemplateParameters(),
4747 /*Complain=*/true, TPL_TemplateMatch))
4748 return New->setInvalidDecl();
4749
4750 // C++ [class.mem]p1:
4751 // A member shall not be declared twice in the member-specification [...]
4752 //
4753 // Here, we need only consider static data members.
4754 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4755 Diag(New->getLocation(), diag::err_duplicate_member)
4756 << New->getIdentifier();
4757 Diag(Old->getLocation(), diag::note_previous_declaration);
4758 New->setInvalidDecl();
4759 }
4760
4761 mergeDeclAttributes(New, Old);
4762 // Warn if an already-defined variable is made a weak_import in a subsequent
4763 // declaration
4764 if (New->hasAttr<WeakImportAttr>())
4765 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4766 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4767 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4768 Diag(D->getLocation(), diag::note_previous_definition);
4769 // Remove weak_import attribute on new declaration.
4770 New->dropAttr<WeakImportAttr>();
4771 break;
4772 }
4773 }
4774
4775 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4776 if (!Old->hasAttr<InternalLinkageAttr>()) {
4777 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4778 << ILA;
4779 Diag(Old->getLocation(), diag::note_previous_declaration);
4780 New->dropAttr<InternalLinkageAttr>();
4781 }
4782
4783 // Merge the types.
4784 VarDecl *MostRecent = Old->getMostRecentDecl();
4785 if (MostRecent != Old) {
4786 MergeVarDeclTypes(New, MostRecent,
4787 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4788 if (New->isInvalidDecl())
4789 return;
4790 }
4791
4792 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4793 if (New->isInvalidDecl())
4794 return;
4795
4796 diag::kind PrevDiag;
4797 SourceLocation OldLocation;
4798 std::tie(PrevDiag, OldLocation) =
4799 getNoteDiagForInvalidRedeclaration(Old, New);
4800
4801 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4802 if (New->getStorageClass() == SC_Static &&
4803 !New->isStaticDataMember() &&
4804 Old->hasExternalFormalLinkage()) {
4805 if (getLangOpts().MicrosoftExt) {
4806 Diag(New->getLocation(), diag::ext_static_non_static)
4807 << New->getDeclName();
4808 Diag(OldLocation, PrevDiag);
4809 } else {
4810 Diag(New->getLocation(), diag::err_static_non_static)
4811 << New->getDeclName();
4812 Diag(OldLocation, PrevDiag);
4813 return New->setInvalidDecl();
4814 }
4815 }
4816 // C99 6.2.2p4:
4817 // For an identifier declared with the storage-class specifier
4818 // extern in a scope in which a prior declaration of that
4819 // identifier is visible,23) if the prior declaration specifies
4820 // internal or external linkage, the linkage of the identifier at
4821 // the later declaration is the same as the linkage specified at
4822 // the prior declaration. If no prior declaration is visible, or
4823 // if the prior declaration specifies no linkage, then the
4824 // identifier has external linkage.
4825 if (New->hasExternalStorage() && Old->hasLinkage())
4826 /* Okay */;
4827 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4828 !New->isStaticDataMember() &&
4829 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4830 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4831 Diag(OldLocation, PrevDiag);
4832 return New->setInvalidDecl();
4833 }
4834
4835 // Check if extern is followed by non-extern and vice-versa.
4836 if (New->hasExternalStorage() &&
4837 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4838 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4839 Diag(OldLocation, PrevDiag);
4840 return New->setInvalidDecl();
4841 }
4842 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4843 !New->hasExternalStorage()) {
4844 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4845 Diag(OldLocation, PrevDiag);
4846 return New->setInvalidDecl();
4847 }
4848
4849 if (CheckRedeclarationInModule(New, Old))
4850 return;
4851
4852 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4853
4854 // FIXME: The test for external storage here seems wrong? We still
4855 // need to check for mismatches.
4856 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4857 // Don't complain about out-of-line definitions of static members.
4858 !(Old->getLexicalDeclContext()->isRecord() &&
4859 !New->getLexicalDeclContext()->isRecord())) {
4860 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4861 Diag(OldLocation, PrevDiag);
4862 return New->setInvalidDecl();
4863 }
4864
4865 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4866 if (VarDecl *Def = Old->getDefinition()) {
4867 // C++1z [dcl.fcn.spec]p4:
4868 // If the definition of a variable appears in a translation unit before
4869 // its first declaration as inline, the program is ill-formed.
4870 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4871 Diag(Def->getLocation(), diag::note_previous_definition);
4872 }
4873 }
4874
4875 // If this redeclaration makes the variable inline, we may need to add it to
4876 // UndefinedButUsed.
4877 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4878 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4879 !Old->isInAnotherModuleUnit())
4880 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4881 SourceLocation()));
4882
4883 if (New->getTLSKind() != Old->getTLSKind()) {
4884 if (!Old->getTLSKind()) {
4885 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4886 Diag(OldLocation, PrevDiag);
4887 } else if (!New->getTLSKind()) {
4888 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4889 Diag(OldLocation, PrevDiag);
4890 } else {
4891 // Do not allow redeclaration to change the variable between requiring
4892 // static and dynamic initialization.
4893 // FIXME: GCC allows this, but uses the TLS keyword on the first
4894 // declaration to determine the kind. Do we need to be compatible here?
4895 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4896 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4897 Diag(OldLocation, PrevDiag);
4898 }
4899 }
4900
4901 // C++ doesn't have tentative definitions, so go right ahead and check here.
4902 if (getLangOpts().CPlusPlus) {
4903 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4904 Old->getCanonicalDecl()->isConstexpr()) {
4905 // This definition won't be a definition any more once it's been merged.
4906 Diag(New->getLocation(),
4907 diag::warn_deprecated_redundant_constexpr_static_def);
4908 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4909 VarDecl *Def = Old->getDefinition();
4910 if (Def && checkVarDeclRedefinition(Def, New))
4911 return;
4912 }
4913 } else {
4914 // C++ may not have a tentative definition rule, but it has a different
4915 // rule about what constitutes a definition in the first place. See
4916 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4917 // contains the extern specifier and doesn't have an initializer, it's fine
4918 // in C++.
4919 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4920 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4921 << New;
4922 Diag(Old->getLocation(), diag::note_previous_declaration);
4923 }
4924 }
4925
4926 if (haveIncompatibleLanguageLinkages(Old, New)) {
4927 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4928 Diag(OldLocation, PrevDiag);
4929 New->setInvalidDecl();
4930 return;
4931 }
4932
4933 // Merge "used" flag.
4934 if (Old->getMostRecentDecl()->isUsed(false))
4935 New->setIsUsed();
4936
4937 // Keep a chain of previous declarations.
4938 New->setPreviousDecl(Old);
4939 if (NewTemplate)
4940 NewTemplate->setPreviousDecl(OldTemplate);
4941
4942 // Inherit access appropriately.
4943 New->setAccess(Old->getAccess());
4944 if (NewTemplate)
4945 NewTemplate->setAccess(New->getAccess());
4946
4947 if (Old->isInline())
4948 New->setImplicitlyInline();
4949 }
4950
4951 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4952 SourceManager &SrcMgr = getSourceManager();
4953 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4954 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4955 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4956 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4957 auto &HSI = PP.getHeaderSearchInfo();
4958 StringRef HdrFilename =
4959 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4960
4961 auto noteFromModuleOrInclude = [&](Module *Mod,
4962 SourceLocation IncLoc) -> bool {
4963 // Redefinition errors with modules are common with non modular mapped
4964 // headers, example: a non-modular header H in module A that also gets
4965 // included directly in a TU. Pointing twice to the same header/definition
4966 // is confusing, try to get better diagnostics when modules is on.
4967 if (IncLoc.isValid()) {
4968 if (Mod) {
4969 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4970 << HdrFilename.str() << Mod->getFullModuleName();
4971 if (!Mod->DefinitionLoc.isInvalid())
4972 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4973 << Mod->getFullModuleName();
4974 } else {
4975 Diag(IncLoc, diag::note_redefinition_include_same_file)
4976 << HdrFilename.str();
4977 }
4978 return true;
4979 }
4980
4981 return false;
4982 };
4983
4984 // Is it the same file and same offset? Provide more information on why
4985 // this leads to a redefinition error.
4986 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4987 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4988 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4989 bool EmittedDiag =
4990 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4991 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4992
4993 // If the header has no guards, emit a note suggesting one.
4994 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4995 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4996
4997 if (EmittedDiag)
4998 return;
4999 }
5000
5001 // Redefinition coming from different files or couldn't do better above.
5002 if (Old->getLocation().isValid())
5003 Diag(Old->getLocation(), diag::note_previous_definition);
5004 }
5005
5006 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5007 if (!hasVisibleDefinition(Old) &&
5008 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5009 isa<VarTemplateSpecializationDecl>(New) ||
5010 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
5011 New->getDeclContext()->isDependentContext() ||
5012 New->hasAttr<SelectAnyAttr>())) {
5013 // The previous definition is hidden, and multiple definitions are
5014 // permitted (in separate TUs). Demote this to a declaration.
5015 New->demoteThisDefinitionToDeclaration();
5016
5017 // Make the canonical definition visible.
5018 if (auto *OldTD = Old->getDescribedVarTemplate())
5019 makeMergedDefinitionVisible(OldTD);
5020 makeMergedDefinitionVisible(Old);
5021 return false;
5022 } else {
5023 Diag(New->getLocation(), diag::err_redefinition) << New;
5024 notePreviousDefinition(Old, New->getLocation());
5025 New->setInvalidDecl();
5026 return true;
5027 }
5028 }
5029
5030 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5031 DeclSpec &DS,
5032 const ParsedAttributesView &DeclAttrs,
5033 RecordDecl *&AnonRecord) {
5034 return ParsedFreeStandingDeclSpec(
5035 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5036 }
5037
5038 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5039 // disambiguate entities defined in different scopes.
5040 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
5041 // compatibility.
5042 // We will pick our mangling number depending on which version of MSVC is being
5043 // targeted.
5044 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5045 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
5046 ? S->getMSCurManglingNumber()
5047 : S->getMSLastManglingNumber();
5048 }
5049
5050 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5051 if (!Context.getLangOpts().CPlusPlus)
5052 return;
5053
5054 if (isa<CXXRecordDecl>(Tag->getParent())) {
5055 // If this tag is the direct child of a class, number it if
5056 // it is anonymous.
5057 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5058 return;
5059 MangleNumberingContext &MCtx =
5060 Context.getManglingNumberContext(Tag->getParent());
5061 Context.setManglingNumber(
5062 Tag, MCtx.getManglingNumber(
5063 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5064 return;
5065 }
5066
5067 // If this tag isn't a direct child of a class, number it if it is local.
5068 MangleNumberingContext *MCtx;
5069 Decl *ManglingContextDecl;
5070 std::tie(MCtx, ManglingContextDecl) =
5071 getCurrentMangleNumberContext(Tag->getDeclContext());
5072 if (MCtx) {
5073 Context.setManglingNumber(
5074 Tag, MCtx->getManglingNumber(
5075 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5076 }
5077 }
5078
5079 namespace {
5080 struct NonCLikeKind {
5081 enum {
5082 None,
5083 BaseClass,
5084 DefaultMemberInit,
5085 Lambda,
5086 Friend,
5087 OtherMember,
5088 Invalid,
5089 } Kind = None;
5090 SourceRange Range;
5091
5092 explicit operator bool() { return Kind != None; }
5093 };
5094 }
5095
5096 /// Determine whether a class is C-like, according to the rules of C++
5097 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
5098 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5099 if (RD->isInvalidDecl())
5100 return {NonCLikeKind::Invalid, {}};
5101
5102 // C++ [dcl.typedef]p9: [P1766R1]
5103 // An unnamed class with a typedef name for linkage purposes shall not
5104 //
5105 // -- have any base classes
5106 if (RD->getNumBases())
5107 return {NonCLikeKind::BaseClass,
5108 SourceRange(RD->bases_begin()->getBeginLoc(),
5109 RD->bases_end()[-1].getEndLoc())};
5110 bool Invalid = false;
5111 for (Decl *D : RD->decls()) {
5112 // Don't complain about things we already diagnosed.
5113 if (D->isInvalidDecl()) {
5114 Invalid = true;
5115 continue;
5116 }
5117
5118 // -- have any [...] default member initializers
5119 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5120 if (FD->hasInClassInitializer()) {
5121 auto *Init = FD->getInClassInitializer();
5122 return {NonCLikeKind::DefaultMemberInit,
5123 Init ? Init->getSourceRange() : D->getSourceRange()};
5124 }
5125 continue;
5126 }
5127
5128 // FIXME: We don't allow friend declarations. This violates the wording of
5129 // P1766, but not the intent.
5130 if (isa<FriendDecl>(D))
5131 return {NonCLikeKind::Friend, D->getSourceRange()};
5132
5133 // -- declare any members other than non-static data members, member
5134 // enumerations, or member classes,
5135 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
5136 isa<EnumDecl>(D))
5137 continue;
5138 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5139 if (!MemberRD) {
5140 if (D->isImplicit())
5141 continue;
5142 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5143 }
5144
5145 // -- contain a lambda-expression,
5146 if (MemberRD->isLambda())
5147 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5148
5149 // and all member classes shall also satisfy these requirements
5150 // (recursively).
5151 if (MemberRD->isThisDeclarationADefinition()) {
5152 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5153 return Kind;
5154 }
5155 }
5156
5157 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5158 }
5159
5160 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5161 TypedefNameDecl *NewTD) {
5162 if (TagFromDeclSpec->isInvalidDecl())
5163 return;
5164
5165 // Do nothing if the tag already has a name for linkage purposes.
5166 if (TagFromDeclSpec->hasNameForLinkage())
5167 return;
5168
5169 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5170 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5171
5172 // The type must match the tag exactly; no qualifiers allowed.
5173 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5174 Context.getCanonicalTagType(TagFromDeclSpec))) {
5175 if (getLangOpts().CPlusPlus)
5176 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5177 return;
5178 }
5179
5180 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5181 // An unnamed class with a typedef name for linkage purposes shall [be
5182 // C-like].
5183 //
5184 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5185 // shouldn't happen, but there are constructs that the language rule doesn't
5186 // disallow for which we can't reasonably avoid computing linkage early.
5187 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5188 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5189 : NonCLikeKind();
5190 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5191 if (NonCLike || ChangesLinkage) {
5192 if (NonCLike.Kind == NonCLikeKind::Invalid)
5193 return;
5194
5195 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5196 if (ChangesLinkage) {
5197 // If the linkage changes, we can't accept this as an extension.
5198 if (NonCLike.Kind == NonCLikeKind::None)
5199 DiagID = diag::err_typedef_changes_linkage;
5200 else
5201 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5202 }
5203
5204 SourceLocation FixitLoc =
5205 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5206 llvm::SmallString<40> TextToInsert;
5207 TextToInsert += ' ';
5208 TextToInsert += NewTD->getIdentifier()->getName();
5209
5210 Diag(FixitLoc, DiagID)
5211 << isa<TypeAliasDecl>(NewTD)
5212 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5213 if (NonCLike.Kind != NonCLikeKind::None) {
5214 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5215 << NonCLike.Kind - 1 << NonCLike.Range;
5216 }
5217 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5218 << NewTD << isa<TypeAliasDecl>(NewTD);
5219
5220 if (ChangesLinkage)
5221 return;
5222 }
5223
5224 // Otherwise, set this as the anon-decl typedef for the tag.
5225 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5226
5227 // Now that we have a name for the tag, process API notes again.
5228 ProcessAPINotes(TagFromDeclSpec);
5229 }
5230
5231 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5232 DeclSpec::TST T = DS.getTypeSpecType();
5233 switch (T) {
5234 case DeclSpec::TST_class:
5235 return 0;
5236 case DeclSpec::TST_struct:
5237 return 1;
5238 case DeclSpec::TST_interface:
5239 return 2;
5240 case DeclSpec::TST_union:
5241 return 3;
5242 case DeclSpec::TST_enum:
5243 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5244 if (ED->isScopedUsingClassTag())
5245 return 5;
5246 if (ED->isScoped())
5247 return 6;
5248 }
5249 return 4;
5250 default:
5251 llvm_unreachable("unexpected type specifier");
5252 }
5253 }
5254
5255 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5256 DeclSpec &DS,
5257 const ParsedAttributesView &DeclAttrs,
5258 MultiTemplateParamsArg TemplateParams,
5259 bool IsExplicitInstantiation,
5260 RecordDecl *&AnonRecord,
5261 SourceLocation EllipsisLoc) {
5262 Decl *TagD = nullptr;
5263 TagDecl *Tag = nullptr;
5264 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5265 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5266 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5267 DS.getTypeSpecType() == DeclSpec::TST_union ||
5268 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5269 TagD = DS.getRepAsDecl();
5270
5271 if (!TagD) // We probably had an error
5272 return nullptr;
5273
5274 // Note that the above type specs guarantee that the
5275 // type rep is a Decl, whereas in many of the others
5276 // it's a Type.
5277 if (isa<TagDecl>(TagD))
5278 Tag = cast<TagDecl>(TagD);
5279 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5280 Tag = CTD->getTemplatedDecl();
5281 }
5282
5283 if (Tag) {
5284 handleTagNumbering(Tag, S);
5285 Tag->setFreeStanding();
5286 if (Tag->isInvalidDecl())
5287 return Tag;
5288 }
5289
5290 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5291 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5292 // or incomplete types shall not be restrict-qualified."
5293 if (TypeQuals & DeclSpec::TQ_restrict)
5294 Diag(DS.getRestrictSpecLoc(),
5295 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5296 << DS.getSourceRange();
5297 }
5298
5299 if (DS.isInlineSpecified())
5300 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5301 << getLangOpts().CPlusPlus17;
5302
5303 if (DS.hasConstexprSpecifier()) {
5304 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5305 // and definitions of functions and variables.
5306 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5307 // the declaration of a function or function template
5308 if (Tag)
5309 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5310 << GetDiagnosticTypeSpecifierID(DS)
5311 << static_cast<int>(DS.getConstexprSpecifier());
5312 else if (getLangOpts().C23)
5313 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5314 else
5315 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5316 << static_cast<int>(DS.getConstexprSpecifier());
5317 // Don't emit warnings after this error.
5318 return TagD;
5319 }
5320
5321 DiagnoseFunctionSpecifiers(DS);
5322
5323 if (DS.isFriendSpecified()) {
5324 // If we're dealing with a decl but not a TagDecl, assume that
5325 // whatever routines created it handled the friendship aspect.
5326 if (TagD && !Tag)
5327 return nullptr;
5328 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5329 }
5330
5331 assert(EllipsisLoc.isInvalid() &&
5332 "Friend ellipsis but not friend-specified?");
5333
5334 // Track whether this decl-specifier declares anything.
5335 bool DeclaresAnything = true;
5336
5337 // Handle anonymous struct definitions.
5338 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5339 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5340 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5341 if (getLangOpts().CPlusPlus ||
5342 Record->getDeclContext()->isRecord()) {
5343 // If CurContext is a DeclContext that can contain statements,
5344 // RecursiveASTVisitor won't visit the decls that
5345 // BuildAnonymousStructOrUnion() will put into CurContext.
5346 // Also store them here so that they can be part of the
5347 // DeclStmt that gets created in this case.
5348 // FIXME: Also return the IndirectFieldDecls created by
5349 // BuildAnonymousStructOr union, for the same reason?
5350 if (CurContext->isFunctionOrMethod())
5351 AnonRecord = Record;
5352 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5353 Context.getPrintingPolicy());
5354 }
5355
5356 DeclaresAnything = false;
5357 }
5358 }
5359
5360 // C11 6.7.2.1p2:
5361 // A struct-declaration that does not declare an anonymous structure or
5362 // anonymous union shall contain a struct-declarator-list.
5363 //
5364 // This rule also existed in C89 and C99; the grammar for struct-declaration
5365 // did not permit a struct-declaration without a struct-declarator-list.
5366 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5367 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5368 // Check for Microsoft C extension: anonymous struct/union member.
5369 // Handle 2 kinds of anonymous struct/union:
5370 // struct STRUCT;
5371 // union UNION;
5372 // and
5373 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5374 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5375 if ((Tag && Tag->getDeclName()) ||
5376 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5377 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5378 : DS.getRepAsType().get()->getAsRecordDecl();
5379 if (Record && getLangOpts().MicrosoftExt) {
5380 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5381 << Record->isUnion() << DS.getSourceRange();
5382 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5383 }
5384
5385 DeclaresAnything = false;
5386 }
5387 }
5388
5389 // Skip all the checks below if we have a type error.
5390 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5391 (TagD && TagD->isInvalidDecl()))
5392 return TagD;
5393
5394 if (getLangOpts().CPlusPlus &&
5395 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5396 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5397 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5398 !Enum->isInvalidDecl())
5399 DeclaresAnything = false;
5400
5401 if (!DS.isMissingDeclaratorOk()) {
5402 // Customize diagnostic for a typedef missing a name.
5403 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5404 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5405 << DS.getSourceRange();
5406 else
5407 DeclaresAnything = false;
5408 }
5409
5410 if (DS.isModulePrivateSpecified() &&
5411 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5412 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5413 << Tag->getTagKind()
5414 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5415
5416 ActOnDocumentableDecl(TagD);
5417
5418 // C 6.7/2:
5419 // A declaration [...] shall declare at least a declarator [...], a tag,
5420 // or the members of an enumeration.
5421 // C++ [dcl.dcl]p3:
5422 // [If there are no declarators], and except for the declaration of an
5423 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5424 // names into the program, or shall redeclare a name introduced by a
5425 // previous declaration.
5426 if (!DeclaresAnything) {
5427 // In C, we allow this as a (popular) extension / bug. Don't bother
5428 // producing further diagnostics for redundant qualifiers after this.
5429 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5430 ? diag::err_no_declarators
5431 : diag::ext_no_declarators)
5432 << DS.getSourceRange();
5433 return TagD;
5434 }
5435
5436 // C++ [dcl.stc]p1:
5437 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5438 // init-declarator-list of the declaration shall not be empty.
5439 // C++ [dcl.fct.spec]p1:
5440 // If a cv-qualifier appears in a decl-specifier-seq, the
5441 // init-declarator-list of the declaration shall not be empty.
5442 //
5443 // Spurious qualifiers here appear to be valid in C.
5444 unsigned DiagID = diag::warn_standalone_specifier;
5445 if (getLangOpts().CPlusPlus)
5446 DiagID = diag::ext_standalone_specifier;
5447
5448 // Note that a linkage-specification sets a storage class, but
5449 // 'extern "C" struct foo;' is actually valid and not theoretically
5450 // useless.
5451 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5452 if (SCS == DeclSpec::SCS_mutable)
5453 // Since mutable is not a viable storage class specifier in C, there is
5454 // no reason to treat it as an extension. Instead, diagnose as an error.
5455 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5456 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5457 Diag(DS.getStorageClassSpecLoc(), DiagID)
5458 << DeclSpec::getSpecifierName(SCS);
5459 }
5460
5461 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5462 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5463 << DeclSpec::getSpecifierName(TSCS);
5464 if (DS.getTypeQualifiers()) {
5465 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5466 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5467 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5468 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5469 // Restrict is covered above.
5470 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5471 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5472 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5473 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5474 }
5475
5476 // Warn about ignored type attributes, for example:
5477 // __attribute__((aligned)) struct A;
5478 // Attributes should be placed after tag to apply to type declaration.
5479 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5480 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5481 if (TypeSpecType == DeclSpec::TST_class ||
5482 TypeSpecType == DeclSpec::TST_struct ||
5483 TypeSpecType == DeclSpec::TST_interface ||
5484 TypeSpecType == DeclSpec::TST_union ||
5485 TypeSpecType == DeclSpec::TST_enum) {
5486
5487 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5488 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5489 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5490 DiagnosticId = diag::warn_attribute_ignored;
5491 else if (AL.isRegularKeywordAttribute())
5492 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5493 else
5494 DiagnosticId = diag::warn_declspec_attribute_ignored;
5495 Diag(AL.getLoc(), DiagnosticId)
5496 << AL << GetDiagnosticTypeSpecifierID(DS);
5497 };
5498
5499 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5500 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5501 }
5502 }
5503
5504 return TagD;
5505 }
5506
5507 /// We are trying to inject an anonymous member into the given scope;
5508 /// check if there's an existing declaration that can't be overloaded.
5509 ///
5510 /// \return true if this is a forbidden redeclaration
5511 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5512 DeclContext *Owner,
5513 DeclarationName Name,
5514 SourceLocation NameLoc, bool IsUnion,
5515 StorageClass SC) {
5516 LookupResult R(SemaRef, Name, NameLoc,
5517 Owner->isRecord() ? Sema::LookupMemberName
5518 : Sema::LookupOrdinaryName,
5519 RedeclarationKind::ForVisibleRedeclaration);
5520 if (!SemaRef.LookupName(R, S)) return false;
5521
5522 // Pick a representative declaration.
5523 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5524 assert(PrevDecl && "Expected a non-null Decl");
5525
5526 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5527 return false;
5528
5529 if (SC == StorageClass::SC_None &&
5530 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5531 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5532 if (!Owner->isRecord())
5533 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5534 return false;
5535 }
5536
5537 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5538 << IsUnion << Name;
5539 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5540
5541 return true;
5542 }
5543
5544 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5545 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5546 DiagPlaceholderFieldDeclDefinitions(RD);
5547 }
5548
5549 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5550 if (!getLangOpts().CPlusPlus)
5551 return;
5552
5553 // This function can be parsed before we have validated the
5554 // structure as an anonymous struct
5555 if (Record->isAnonymousStructOrUnion())
5556 return;
5557
5558 const NamedDecl *First = 0;
5559 for (const Decl *D : Record->decls()) {
5560 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5561 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5562 continue;
5563 if (!First)
5564 First = ND;
5565 else
5566 DiagPlaceholderVariableDefinition(ND->getLocation());
5567 }
5568 }
5569
5570 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5571 /// anonymous struct or union AnonRecord into the owning context Owner
5572 /// and scope S. This routine will be invoked just after we realize
5573 /// that an unnamed union or struct is actually an anonymous union or
5574 /// struct, e.g.,
5575 ///
5576 /// @code
5577 /// union {
5578 /// int i;
5579 /// float f;
5580 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5581 /// // f into the surrounding scope.x
5582 /// @endcode
5583 ///
5584 /// This routine is recursive, injecting the names of nested anonymous
5585 /// structs/unions into the owning context and scope as well.
5586 static bool
5587 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5588 RecordDecl *AnonRecord, AccessSpecifier AS,
5589 StorageClass SC,
5590 SmallVectorImpl<NamedDecl *> &Chaining) {
5591 bool Invalid = false;
5592
5593 // Look every FieldDecl and IndirectFieldDecl with a name.
5594 for (auto *D : AnonRecord->decls()) {
5595 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5596 cast<NamedDecl>(D)->getDeclName()) {
5597 ValueDecl *VD = cast<ValueDecl>(D);
5598 // C++ [class.union]p2:
5599 // The names of the members of an anonymous union shall be
5600 // distinct from the names of any other entity in the
5601 // scope in which the anonymous union is declared.
5602
5603 bool FieldInvalid = CheckAnonMemberRedeclaration(
5604 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5605 AnonRecord->isUnion(), SC);
5606 if (FieldInvalid)
5607 Invalid = true;
5608
5609 // Inject the IndirectFieldDecl even if invalid, because later
5610 // diagnostics may depend on it being present, see findDefaultInitializer.
5611
5612 // C++ [class.union]p2:
5613 // For the purpose of name lookup, after the anonymous union
5614 // definition, the members of the anonymous union are
5615 // considered to have been defined in the scope in which the
5616 // anonymous union is declared.
5617 unsigned OldChainingSize = Chaining.size();
5618 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5619 Chaining.append(IF->chain_begin(), IF->chain_end());
5620 else
5621 Chaining.push_back(VD);
5622
5623 assert(Chaining.size() >= 2);
5624 NamedDecl **NamedChain =
5625 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5626 for (unsigned i = 0; i < Chaining.size(); i++)
5627 NamedChain[i] = Chaining[i];
5628
5629 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5630 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5631 VD->getType(), {NamedChain, Chaining.size()});
5632
5633 for (const auto *Attr : VD->attrs())
5634 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5635
5636 IndirectField->setAccess(AS);
5637 IndirectField->setImplicit();
5638 IndirectField->setInvalidDecl(FieldInvalid);
5639 SemaRef.PushOnScopeChains(IndirectField, S);
5640
5641 // That includes picking up the appropriate access specifier.
5642 if (AS != AS_none)
5643 IndirectField->setAccess(AS);
5644
5645 Chaining.resize(OldChainingSize);
5646 }
5647 }
5648
5649 return Invalid;
5650 }
5651
5652 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5653 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5654 /// illegal input values are mapped to SC_None.
5655 static StorageClass
5656 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5657 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5658 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5659 "Parser allowed 'typedef' as storage class VarDecl.");
5660 switch (StorageClassSpec) {
5661 case DeclSpec::SCS_unspecified: return SC_None;
5662 case DeclSpec::SCS_extern:
5663 if (DS.isExternInLinkageSpec())
5664 return SC_None;
5665 return SC_Extern;
5666 case DeclSpec::SCS_static: return SC_Static;
5667 case DeclSpec::SCS_auto: return SC_Auto;
5668 case DeclSpec::SCS_register: return SC_Register;
5669 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5670 // Illegal SCSs map to None: error reporting is up to the caller.
5671 case DeclSpec::SCS_mutable: // Fall through.
5672 case DeclSpec::SCS_typedef: return SC_None;
5673 }
5674 llvm_unreachable("unknown storage class specifier");
5675 }
5676
5677 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5678 assert(Record->hasInClassInitializer());
5679
5680 for (const auto *I : Record->decls()) {
5681 const auto *FD = dyn_cast<FieldDecl>(I);
5682 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5683 FD = IFD->getAnonField();
5684 if (FD && FD->hasInClassInitializer())
5685 return FD->getLocation();
5686 }
5687
5688 llvm_unreachable("couldn't find in-class initializer");
5689 }
5690
5691 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5692 SourceLocation DefaultInitLoc) {
5693 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5694 return;
5695
5696 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5697 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5698 }
5699
5700 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5701 CXXRecordDecl *AnonUnion) {
5702 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5703 return;
5704
5705 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5706 }
5707
5708 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5709 AccessSpecifier AS,
5710 RecordDecl *Record,
5711 const PrintingPolicy &Policy) {
5712 DeclContext *Owner = Record->getDeclContext();
5713
5714 // Diagnose whether this anonymous struct/union is an extension.
5715 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5716 Diag(Record->getLocation(), diag::ext_anonymous_union);
5717 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5718 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5719 else if (!Record->isUnion() && !getLangOpts().C11)
5720 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5721
5722 // C and C++ require different kinds of checks for anonymous
5723 // structs/unions.
5724 bool Invalid = false;
5725 if (getLangOpts().CPlusPlus) {
5726 const char *PrevSpec = nullptr;
5727 if (Record->isUnion()) {
5728 // C++ [class.union]p6:
5729 // C++17 [class.union.anon]p2:
5730 // Anonymous unions declared in a named namespace or in the
5731 // global namespace shall be declared static.
5732 unsigned DiagID;
5733 DeclContext *OwnerScope = Owner->getRedeclContext();
5734 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5735 (OwnerScope->isTranslationUnit() ||
5736 (OwnerScope->isNamespace() &&
5737 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5738 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5739 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5740
5741 // Recover by adding 'static'.
5742 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5743 PrevSpec, DiagID, Policy);
5744 }
5745 // C++ [class.union]p6:
5746 // A storage class is not allowed in a declaration of an
5747 // anonymous union in a class scope.
5748 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5749 isa<RecordDecl>(Owner)) {
5750 Diag(DS.getStorageClassSpecLoc(),
5751 diag::err_anonymous_union_with_storage_spec)
5752 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5753
5754 // Recover by removing the storage specifier.
5755 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5756 SourceLocation(),
5757 PrevSpec, DiagID, Context.getPrintingPolicy());
5758 }
5759 }
5760
5761 // Ignore const/volatile/restrict qualifiers.
5762 if (DS.getTypeQualifiers()) {
5763 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5764 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5765 << Record->isUnion() << "const"
5766 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5767 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5768 Diag(DS.getVolatileSpecLoc(),
5769 diag::ext_anonymous_struct_union_qualified)
5770 << Record->isUnion() << "volatile"
5771 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5772 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5773 Diag(DS.getRestrictSpecLoc(),
5774 diag::ext_anonymous_struct_union_qualified)
5775 << Record->isUnion() << "restrict"
5776 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5777 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5778 Diag(DS.getAtomicSpecLoc(),
5779 diag::ext_anonymous_struct_union_qualified)
5780 << Record->isUnion() << "_Atomic"
5781 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5782 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5783 Diag(DS.getUnalignedSpecLoc(),
5784 diag::ext_anonymous_struct_union_qualified)
5785 << Record->isUnion() << "__unaligned"
5786 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5787
5788 DS.ClearTypeQualifiers();
5789 }
5790
5791 // C++ [class.union]p2:
5792 // The member-specification of an anonymous union shall only
5793 // define non-static data members. [Note: nested types and
5794 // functions cannot be declared within an anonymous union. ]
5795 for (auto *Mem : Record->decls()) {
5796 // Ignore invalid declarations; we already diagnosed them.
5797 if (Mem->isInvalidDecl())
5798 continue;
5799
5800 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5801 // C++ [class.union]p3:
5802 // An anonymous union shall not have private or protected
5803 // members (clause 11).
5804 assert(FD->getAccess() != AS_none);
5805 if (FD->getAccess() != AS_public) {
5806 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5807 << Record->isUnion() << (FD->getAccess() == AS_protected);
5808 Invalid = true;
5809 }
5810
5811 // C++ [class.union]p1
5812 // An object of a class with a non-trivial constructor, a non-trivial
5813 // copy constructor, a non-trivial destructor, or a non-trivial copy
5814 // assignment operator cannot be a member of a union, nor can an
5815 // array of such objects.
5816 if (CheckNontrivialField(FD))
5817 Invalid = true;
5818 } else if (Mem->isImplicit()) {
5819 // Any implicit members are fine.
5820 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5821 // This is a type that showed up in an
5822 // elaborated-type-specifier inside the anonymous struct or
5823 // union, but which actually declares a type outside of the
5824 // anonymous struct or union. It's okay.
5825 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5826 if (!MemRecord->isAnonymousStructOrUnion() &&
5827 MemRecord->getDeclName()) {
5828 // Visual C++ allows type definition in anonymous struct or union.
5829 if (getLangOpts().MicrosoftExt)
5830 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5831 << Record->isUnion();
5832 else {
5833 // This is a nested type declaration.
5834 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5835 << Record->isUnion();
5836 Invalid = true;
5837 }
5838 } else {
5839 // This is an anonymous type definition within another anonymous type.
5840 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5841 // not part of standard C++.
5842 Diag(MemRecord->getLocation(),
5843 diag::ext_anonymous_record_with_anonymous_type)
5844 << Record->isUnion();
5845 }
5846 } else if (isa<AccessSpecDecl>(Mem)) {
5847 // Any access specifier is fine.
5848 } else if (isa<StaticAssertDecl>(Mem)) {
5849 // In C++1z, static_assert declarations are also fine.
5850 } else {
5851 // We have something that isn't a non-static data
5852 // member. Complain about it.
5853 unsigned DK = diag::err_anonymous_record_bad_member;
5854 if (isa<TypeDecl>(Mem))
5855 DK = diag::err_anonymous_record_with_type;
5856 else if (isa<FunctionDecl>(Mem))
5857 DK = diag::err_anonymous_record_with_function;
5858 else if (isa<VarDecl>(Mem))
5859 DK = diag::err_anonymous_record_with_static;
5860
5861 // Visual C++ allows type definition in anonymous struct or union.
5862 if (getLangOpts().MicrosoftExt &&
5863 DK == diag::err_anonymous_record_with_type)
5864 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5865 << Record->isUnion();
5866 else {
5867 Diag(Mem->getLocation(), DK) << Record->isUnion();
5868 Invalid = true;
5869 }
5870 }
5871 }
5872
5873 // C++11 [class.union]p8 (DR1460):
5874 // At most one variant member of a union may have a
5875 // brace-or-equal-initializer.
5876 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5877 Owner->isRecord())
5878 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5879 cast<CXXRecordDecl>(Record));
5880 }
5881
5882 if (!Record->isUnion() && !Owner->isRecord()) {
5883 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5884 << getLangOpts().CPlusPlus;
5885 Invalid = true;
5886 }
5887
5888 // C++ [dcl.dcl]p3:
5889 // [If there are no declarators], and except for the declaration of an
5890 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5891 // names into the program
5892 // C++ [class.mem]p2:
5893 // each such member-declaration shall either declare at least one member
5894 // name of the class or declare at least one unnamed bit-field
5895 //
5896 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5897 if (getLangOpts().CPlusPlus && Record->field_empty())
5898 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5899
5900 // Mock up a declarator.
5901 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5902 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5903 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5904 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5905
5906 // Create a declaration for this anonymous struct/union.
5907 NamedDecl *Anon = nullptr;
5908 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5909 Anon = FieldDecl::Create(
5910 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5911 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5912 /*BitWidth=*/nullptr, /*Mutable=*/false,
5913 /*InitStyle=*/ICIS_NoInit);
5914 Anon->setAccess(AS);
5915 ProcessDeclAttributes(S, Anon, Dc);
5916
5917 if (getLangOpts().CPlusPlus)
5918 FieldCollector->Add(cast<FieldDecl>(Anon));
5919 } else {
5920 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5921 if (SCSpec == DeclSpec::SCS_mutable) {
5922 // mutable can only appear on non-static class members, so it's always
5923 // an error here
5924 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5925 Invalid = true;
5926 SC = SC_None;
5927 }
5928
5929 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5930 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5931 Context.getCanonicalTagType(Record), TInfo, SC);
5932 if (Invalid)
5933 Anon->setInvalidDecl();
5934
5935 ProcessDeclAttributes(S, Anon, Dc);
5936
5937 // Default-initialize the implicit variable. This initialization will be
5938 // trivial in almost all cases, except if a union member has an in-class
5939 // initializer:
5940 // union { int n = 0; };
5941 ActOnUninitializedDecl(Anon);
5942 }
5943 Anon->setImplicit();
5944
5945 // Mark this as an anonymous struct/union type.
5946 Record->setAnonymousStructOrUnion(true);
5947
5948 // Add the anonymous struct/union object to the current
5949 // context. We'll be referencing this object when we refer to one of
5950 // its members.
5951 Owner->addDecl(Anon);
5952
5953 // Inject the members of the anonymous struct/union into the owning
5954 // context and into the identifier resolver chain for name lookup
5955 // purposes.
5956 SmallVector<NamedDecl*, 2> Chain;
5957 Chain.push_back(Anon);
5958
5959 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5960 Chain))
5961 Invalid = true;
5962
5963 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5964 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5965 MangleNumberingContext *MCtx;
5966 Decl *ManglingContextDecl;
5967 std::tie(MCtx, ManglingContextDecl) =
5968 getCurrentMangleNumberContext(NewVD->getDeclContext());
5969 if (MCtx) {
5970 Context.setManglingNumber(
5971 NewVD, MCtx->getManglingNumber(
5972 NewVD, getMSManglingNumber(getLangOpts(), S)));
5973 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5974 }
5975 }
5976 }
5977
5978 if (Invalid)
5979 Anon->setInvalidDecl();
5980
5981 return Anon;
5982 }
5983
5984 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5985 RecordDecl *Record) {
5986 assert(Record && "expected a record!");
5987
5988 // Mock up a declarator.
5989 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5990 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5991 assert(TInfo && "couldn't build declarator info for anonymous struct");
5992
5993 auto *ParentDecl = cast<RecordDecl>(CurContext);
5994 CanQualType RecTy = Context.getCanonicalTagType(Record);
5995
5996 // Create a declaration for this anonymous struct.
5997 NamedDecl *Anon =
5998 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5999 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6000 /*BitWidth=*/nullptr, /*Mutable=*/false,
6001 /*InitStyle=*/ICIS_NoInit);
6002 Anon->setImplicit();
6003
6004 // Add the anonymous struct object to the current context.
6005 CurContext->addDecl(Anon);
6006
6007 // Inject the members of the anonymous struct into the current
6008 // context and into the identifier resolver chain for name lookup
6009 // purposes.
6010 SmallVector<NamedDecl*, 2> Chain;
6011 Chain.push_back(Anon);
6012
6013 RecordDecl *RecordDef = Record->getDefinition();
6014 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6015 diag::err_field_incomplete_or_sizeless) ||
6016 InjectAnonymousStructOrUnionMembers(
6017 *this, S, CurContext, RecordDef, AS_none,
6018 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
6019 Anon->setInvalidDecl();
6020 ParentDecl->setInvalidDecl();
6021 }
6022
6023 return Anon;
6024 }
6025
6026 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6027 return GetNameFromUnqualifiedId(D.getName());
6028 }
6029
6030 DeclarationNameInfo
6031 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6032 DeclarationNameInfo NameInfo;
6033 NameInfo.setLoc(Name.StartLocation);
6034
6035 switch (Name.getKind()) {
6036
6037 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6038 case UnqualifiedIdKind::IK_Identifier:
6039 NameInfo.setName(Name.Identifier);
6040 return NameInfo;
6041
6042 case UnqualifiedIdKind::IK_DeductionGuideName: {
6043 // C++ [temp.deduct.guide]p3:
6044 // The simple-template-id shall name a class template specialization.
6045 // The template-name shall be the same identifier as the template-name
6046 // of the simple-template-id.
6047 // These together intend to imply that the template-name shall name a
6048 // class template.
6049 // FIXME: template<typename T> struct X {};
6050 // template<typename T> using Y = X<T>;
6051 // Y(int) -> Y<int>;
6052 // satisfies these rules but does not name a class template.
6053 TemplateName TN = Name.TemplateName.get().get();
6054 auto *Template = TN.getAsTemplateDecl();
6055 if (!Template || !isa<ClassTemplateDecl>(Template)) {
6056 Diag(Name.StartLocation,
6057 diag::err_deduction_guide_name_not_class_template)
6058 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6059 if (Template)
6060 NoteTemplateLocation(*Template);
6061 return DeclarationNameInfo();
6062 }
6063
6064 NameInfo.setName(
6065 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6066 return NameInfo;
6067 }
6068
6069 case UnqualifiedIdKind::IK_OperatorFunctionId:
6070 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6071 Name.OperatorFunctionId.Operator));
6072 NameInfo.setCXXOperatorNameRange(SourceRange(
6073 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6074 return NameInfo;
6075
6076 case UnqualifiedIdKind::IK_LiteralOperatorId:
6077 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6078 Name.Identifier));
6079 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6080 return NameInfo;
6081
6082 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6083 TypeSourceInfo *TInfo;
6084 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
6085 if (Ty.isNull())
6086 return DeclarationNameInfo();
6087 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6088 Context.getCanonicalType(Ty)));
6089 NameInfo.setNamedTypeInfo(TInfo);
6090 return NameInfo;
6091 }
6092
6093 case UnqualifiedIdKind::IK_ConstructorName: {
6094 TypeSourceInfo *TInfo;
6095 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6096 if (Ty.isNull())
6097 return DeclarationNameInfo();
6098 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6099 Context.getCanonicalType(Ty)));
6100 NameInfo.setNamedTypeInfo(TInfo);
6101 return NameInfo;
6102 }
6103
6104 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6105 // In well-formed code, we can only have a constructor
6106 // template-id that refers to the current context, so go there
6107 // to find the actual type being constructed.
6108 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6109 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6110 return DeclarationNameInfo();
6111
6112 // Determine the type of the class being constructed.
6113 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6114
6115 // FIXME: Check two things: that the template-id names the same type as
6116 // CurClassType, and that the template-id does not occur when the name
6117 // was qualified.
6118
6119 NameInfo.setName(
6120 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6121 // FIXME: should we retrieve TypeSourceInfo?
6122 NameInfo.setNamedTypeInfo(nullptr);
6123 return NameInfo;
6124 }
6125
6126 case UnqualifiedIdKind::IK_DestructorName: {
6127 TypeSourceInfo *TInfo;
6128 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6129 if (Ty.isNull())
6130 return DeclarationNameInfo();
6131 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6132 Context.getCanonicalType(Ty)));
6133 NameInfo.setNamedTypeInfo(TInfo);
6134 return NameInfo;
6135 }
6136
6137 case UnqualifiedIdKind::IK_TemplateId: {
6138 TemplateName TName = Name.TemplateId->Template.get();
6139 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6140 return Context.getNameForTemplate(TName, TNameLoc);
6141 }
6142
6143 } // switch (Name.getKind())
6144
6145 llvm_unreachable("Unknown name kind");
6146 }
6147
6148 static QualType getCoreType(QualType Ty) {
6149 do {
6150 if (Ty->isPointerOrReferenceType())
6151 Ty = Ty->getPointeeType();
6152 else if (Ty->isArrayType())
6153 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6154 else
6155 return Ty.withoutLocalFastQualifiers();
6156 } while (true);
6157 }
6158
6159 /// hasSimilarParameters - Determine whether the C++ functions Declaration
6160 /// and Definition have "nearly" matching parameters. This heuristic is
6161 /// used to improve diagnostics in the case where an out-of-line function
6162 /// definition doesn't match any declaration within the class or namespace.
6163 /// Also sets Params to the list of indices to the parameters that differ
6164 /// between the declaration and the definition. If hasSimilarParameters
6165 /// returns true and Params is empty, then all of the parameters match.
6166 static bool hasSimilarParameters(ASTContext &Context,
6167 FunctionDecl *Declaration,
6168 FunctionDecl *Definition,
6169 SmallVectorImpl<unsigned> &Params) {
6170 Params.clear();
6171 if (Declaration->param_size() != Definition->param_size())
6172 return false;
6173 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6174 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6175 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6176
6177 // The parameter types are identical
6178 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6179 continue;
6180
6181 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6182 QualType DefParamBaseTy = getCoreType(DefParamTy);
6183 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6184 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6185
6186 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6187 (DeclTyName && DeclTyName == DefTyName))
6188 Params.push_back(Idx);
6189 else // The two parameters aren't even close
6190 return false;
6191 }
6192
6193 return true;
6194 }
6195
6196 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6197 /// declarator needs to be rebuilt in the current instantiation.
6198 /// Any bits of declarator which appear before the name are valid for
6199 /// consideration here. That's specifically the type in the decl spec
6200 /// and the base type in any member-pointer chunks.
6201 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6202 DeclarationName Name) {
6203 // The types we specifically need to rebuild are:
6204 // - typenames, typeofs, and decltypes
6205 // - types which will become injected class names
6206 // Of course, we also need to rebuild any type referencing such a
6207 // type. It's safest to just say "dependent", but we call out a
6208 // few cases here.
6209
6210 DeclSpec &DS = D.getMutableDeclSpec();
6211 switch (DS.getTypeSpecType()) {
6212 case DeclSpec::TST_typename:
6213 case DeclSpec::TST_typeofType:
6214 case DeclSpec::TST_typeof_unqualType:
6215 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6216 #include "clang/Basic/TransformTypeTraits.def"
6217 case DeclSpec::TST_atomic: {
6218 // Grab the type from the parser.
6219 TypeSourceInfo *TSI = nullptr;
6220 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6221 if (T.isNull() || !T->isInstantiationDependentType()) break;
6222
6223 // Make sure there's a type source info. This isn't really much
6224 // of a waste; most dependent types should have type source info
6225 // attached already.
6226 if (!TSI)
6227 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6228
6229 // Rebuild the type in the current instantiation.
6230 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6231 if (!TSI) return true;
6232
6233 // Store the new type back in the decl spec.
6234 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6235 DS.UpdateTypeRep(LocType);
6236 break;
6237 }
6238
6239 case DeclSpec::TST_decltype:
6240 case DeclSpec::TST_typeof_unqualExpr:
6241 case DeclSpec::TST_typeofExpr: {
6242 Expr *E = DS.getRepAsExpr();
6243 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6244 if (Result.isInvalid()) return true;
6245 DS.UpdateExprRep(Result.get());
6246 break;
6247 }
6248
6249 default:
6250 // Nothing to do for these decl specs.
6251 break;
6252 }
6253
6254 // It doesn't matter what order we do this in.
6255 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6256 DeclaratorChunk &Chunk = D.getTypeObject(I);
6257
6258 // The only type information in the declarator which can come
6259 // before the declaration name is the base type of a member
6260 // pointer.
6261 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6262 continue;
6263
6264 // Rebuild the scope specifier in-place.
6265 CXXScopeSpec &SS = Chunk.Mem.Scope();
6266 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6267 return true;
6268 }
6269
6270 return false;
6271 }
6272
6273 /// Returns true if the declaration is declared in a system header or from a
6274 /// system macro.
6275 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6276 return SM.isInSystemHeader(D->getLocation()) ||
6277 SM.isInSystemMacro(D->getLocation());
6278 }
6279
6280 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6281 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6282 // of system decl.
6283 if (D->getPreviousDecl() || D->isImplicit())
6284 return;
6285 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6286 if (Status != ReservedIdentifierStatus::NotReserved &&
6287 !isFromSystemHeader(Context.getSourceManager(), D)) {
6288 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6289 << D << static_cast<int>(Status);
6290 }
6291 }
6292
6293 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6294 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6295
6296 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6297 // declaration only if the `bind_to_declaration` extension is set.
6298 SmallVector<FunctionDecl *, 4> Bases;
6299 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6300 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6301 llvm::omp::TraitProperty::
6302 implementation_extension_bind_to_declaration))
6303 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6304 S, D, MultiTemplateParamsArg(), Bases);
6305
6306 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6307
6308 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6309 Dcl && Dcl->getDeclContext()->isFileContext())
6310 Dcl->setTopLevelDeclInObjCContainer();
6311
6312 if (!Bases.empty())
6313 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
6314 Bases);
6315
6316 return Dcl;
6317 }
6318
6319 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6320 DeclarationNameInfo NameInfo) {
6321 DeclarationName Name = NameInfo.getName();
6322
6323 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6324 while (Record && Record->isAnonymousStructOrUnion())
6325 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6326 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6327 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6328 return true;
6329 }
6330
6331 return false;
6332 }
6333
6334 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6335 DeclarationName Name,
6336 SourceLocation Loc,
6337 TemplateIdAnnotation *TemplateId,
6338 bool IsMemberSpecialization) {
6339 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6340 "without nested-name-specifier");
6341 DeclContext *Cur = CurContext;
6342 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6343 Cur = Cur->getParent();
6344
6345 // If the user provided a superfluous scope specifier that refers back to the
6346 // class in which the entity is already declared, diagnose and ignore it.
6347 //
6348 // class X {
6349 // void X::f();
6350 // };
6351 //
6352 // Note, it was once ill-formed to give redundant qualification in all
6353 // contexts, but that rule was removed by DR482.
6354 if (Cur->Equals(DC)) {
6355 if (Cur->isRecord()) {
6356 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6357 : diag::err_member_extra_qualification)
6358 << Name << FixItHint::CreateRemoval(SS.getRange());
6359 SS.clear();
6360 } else {
6361 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6362 }
6363 return false;
6364 }
6365
6366 // Check whether the qualifying scope encloses the scope of the original
6367 // declaration. For a template-id, we perform the checks in
6368 // CheckTemplateSpecializationScope.
6369 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6370 if (Cur->isRecord())
6371 Diag(Loc, diag::err_member_qualification)
6372 << Name << SS.getRange();
6373 else if (isa<TranslationUnitDecl>(DC))
6374 Diag(Loc, diag::err_invalid_declarator_global_scope)
6375 << Name << SS.getRange();
6376 else if (isa<FunctionDecl>(Cur))
6377 Diag(Loc, diag::err_invalid_declarator_in_function)
6378 << Name << SS.getRange();
6379 else if (isa<BlockDecl>(Cur))
6380 Diag(Loc, diag::err_invalid_declarator_in_block)
6381 << Name << SS.getRange();
6382 else if (isa<ExportDecl>(Cur)) {
6383 if (!isa<NamespaceDecl>(DC))
6384 Diag(Loc, diag::err_export_non_namespace_scope_name)
6385 << Name << SS.getRange();
6386 else
6387 // The cases that DC is not NamespaceDecl should be handled in
6388 // CheckRedeclarationExported.
6389 return false;
6390 } else
6391 Diag(Loc, diag::err_invalid_declarator_scope)
6392 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6393
6394 return true;
6395 }
6396
6397 if (Cur->isRecord()) {
6398 // Cannot qualify members within a class.
6399 Diag(Loc, diag::err_member_qualification)
6400 << Name << SS.getRange();
6401 SS.clear();
6402
6403 // C++ constructors and destructors with incorrect scopes can break
6404 // our AST invariants by having the wrong underlying types. If
6405 // that's the case, then drop this declaration entirely.
6406 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6407 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6408 !Context.hasSameType(
6409 Name.getCXXNameType(),
6410 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6411 return true;
6412
6413 return false;
6414 }
6415
6416 // C++23 [temp.names]p5:
6417 // The keyword template shall not appear immediately after a declarative
6418 // nested-name-specifier.
6419 //
6420 // First check the template-id (if any), and then check each component of the
6421 // nested-name-specifier in reverse order.
6422 //
6423 // FIXME: nested-name-specifiers in friend declarations are declarative,
6424 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6425 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6426 Diag(Loc, diag::ext_template_after_declarative_nns)
6427 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6428
6429 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6430 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6431 TL = std::exchange(NextTL, TypeLoc())) {
6432 SourceLocation TemplateKeywordLoc;
6433 switch (TL.getTypeLocClass()) {
6434 case TypeLoc::TemplateSpecialization: {
6435 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6436 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6437 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6438 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6439 << TST.getLocalSourceRange();
6440 break;
6441 }
6442 case TypeLoc::Decltype:
6443 case TypeLoc::PackIndexing: {
6444 const Type *T = TL.getTypePtr();
6445 // C++23 [expr.prim.id.qual]p2:
6446 // [...] A declarative nested-name-specifier shall not have a
6447 // computed-type-specifier.
6448 //
6449 // CWG2858 changed this from 'decltype-specifier' to
6450 // 'computed-type-specifier'.
6451 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6452 << T->isDecltypeType() << TL.getSourceRange();
6453 break;
6454 }
6455 case TypeLoc::DependentName:
6456 NextTL =
6457 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6458 break;
6459 default:
6460 break;
6461 }
6462 if (TemplateKeywordLoc.isValid())
6463 Diag(Loc, diag::ext_template_after_declarative_nns)
6464 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6465 }
6466
6467 return false;
6468 }
6469
6470 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6471 MultiTemplateParamsArg TemplateParamLists) {
6472 // TODO: consider using NameInfo for diagnostic.
6473 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6474 DeclarationName Name = NameInfo.getName();
6475
6476 // All of these full declarators require an identifier. If it doesn't have
6477 // one, the ParsedFreeStandingDeclSpec action should be used.
6478 if (D.isDecompositionDeclarator()) {
6479 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6480 } else if (!Name) {
6481 if (!D.isInvalidType()) // Reject this if we think it is valid.
6482 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6483 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6484 return nullptr;
6485 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6486 return nullptr;
6487
6488 DeclContext *DC = CurContext;
6489 if (D.getCXXScopeSpec().isInvalid())
6490 D.setInvalidType();
6491 else if (D.getCXXScopeSpec().isSet()) {
6492 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6493 UPPC_DeclarationQualifier))
6494 return nullptr;
6495
6496 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6497 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6498 if (!DC || isa<EnumDecl>(DC)) {
6499 // If we could not compute the declaration context, it's because the
6500 // declaration context is dependent but does not refer to a class,
6501 // class template, or class template partial specialization. Complain
6502 // and return early, to avoid the coming semantic disaster.
6503 Diag(D.getIdentifierLoc(),
6504 diag::err_template_qualified_declarator_no_match)
6505 << D.getCXXScopeSpec().getScopeRep()
6506 << D.getCXXScopeSpec().getRange();
6507 return nullptr;
6508 }
6509 bool IsDependentContext = DC->isDependentContext();
6510
6511 if (!IsDependentContext &&
6512 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6513 return nullptr;
6514
6515 // If a class is incomplete, do not parse entities inside it.
6516 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6517 Diag(D.getIdentifierLoc(),
6518 diag::err_member_def_undefined_record)
6519 << Name << DC << D.getCXXScopeSpec().getRange();
6520 return nullptr;
6521 }
6522 if (!D.getDeclSpec().isFriendSpecified()) {
6523 TemplateIdAnnotation *TemplateId =
6524 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6525 ? D.getName().TemplateId
6526 : nullptr;
6527 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6528 D.getIdentifierLoc(), TemplateId,
6529 /*IsMemberSpecialization=*/false)) {
6530 if (DC->isRecord())
6531 return nullptr;
6532
6533 D.setInvalidType();
6534 }
6535 }
6536
6537 // Check whether we need to rebuild the type of the given
6538 // declaration in the current instantiation.
6539 if (EnteringContext && IsDependentContext &&
6540 TemplateParamLists.size() != 0) {
6541 ContextRAII SavedContext(*this, DC);
6542 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6543 D.setInvalidType();
6544 }
6545 }
6546
6547 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6548 QualType R = TInfo->getType();
6549
6550 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6551 UPPC_DeclarationType))
6552 D.setInvalidType();
6553
6554 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6555 forRedeclarationInCurContext());
6556
6557 // See if this is a redefinition of a variable in the same scope.
6558 if (!D.getCXXScopeSpec().isSet()) {
6559 bool IsLinkageLookup = false;
6560 bool CreateBuiltins = false;
6561
6562 // If the declaration we're planning to build will be a function
6563 // or object with linkage, then look for another declaration with
6564 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6565 //
6566 // If the declaration we're planning to build will be declared with
6567 // external linkage in the translation unit, create any builtin with
6568 // the same name.
6569 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6570 /* Do nothing*/;
6571 else if (CurContext->isFunctionOrMethod() &&
6572 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6573 R->isFunctionType())) {
6574 IsLinkageLookup = true;
6575 CreateBuiltins =
6576 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6577 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6578 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6579 CreateBuiltins = true;
6580
6581 if (IsLinkageLookup) {
6582 Previous.clear(LookupRedeclarationWithLinkage);
6583 Previous.setRedeclarationKind(
6584 RedeclarationKind::ForExternalRedeclaration);
6585 }
6586
6587 LookupName(Previous, S, CreateBuiltins);
6588 } else { // Something like "int foo::x;"
6589 LookupQualifiedName(Previous, DC);
6590
6591 // C++ [dcl.meaning]p1:
6592 // When the declarator-id is qualified, the declaration shall refer to a
6593 // previously declared member of the class or namespace to which the
6594 // qualifier refers (or, in the case of a namespace, of an element of the
6595 // inline namespace set of that namespace (7.3.1)) or to a specialization
6596 // thereof; [...]
6597 //
6598 // Note that we already checked the context above, and that we do not have
6599 // enough information to make sure that Previous contains the declaration
6600 // we want to match. For example, given:
6601 //
6602 // class X {
6603 // void f();
6604 // void f(float);
6605 // };
6606 //
6607 // void X::f(int) { } // ill-formed
6608 //
6609 // In this case, Previous will point to the overload set
6610 // containing the two f's declared in X, but neither of them
6611 // matches.
6612
6613 RemoveUsingDecls(Previous);
6614 }
6615
6616 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6617 TPD && TPD->isTemplateParameter()) {
6618 // Older versions of clang allowed the names of function/variable templates
6619 // to shadow the names of their template parameters. For the compatibility
6620 // purposes we detect such cases and issue a default-to-error warning that
6621 // can be disabled with -Wno-strict-primary-template-shadow.
6622 if (!D.isInvalidType()) {
6623 bool AllowForCompatibility = false;
6624 if (Scope *DeclParent = S->getDeclParent();
6625 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6626 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6627 TemplateParamParent->isDeclScope(TPD);
6628 }
6629 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6630 AllowForCompatibility);
6631 }
6632
6633 // Just pretend that we didn't see the previous declaration.
6634 Previous.clear();
6635 }
6636
6637 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6638 // Forget that the previous declaration is the injected-class-name.
6639 Previous.clear();
6640
6641 // In C++, the previous declaration we find might be a tag type
6642 // (class or enum). In this case, the new declaration will hide the
6643 // tag type. Note that this applies to functions, function templates, and
6644 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6645 if (Previous.isSingleTagDecl() &&
6646 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6647 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6648 Previous.clear();
6649
6650 // Check that there are no default arguments other than in the parameters
6651 // of a function declaration (C++ only).
6652 if (getLangOpts().CPlusPlus)
6653 CheckExtraCXXDefaultArguments(D);
6654
6655 /// Get the innermost enclosing declaration scope.
6656 S = S->getDeclParent();
6657
6658 NamedDecl *New;
6659
6660 bool AddToScope = true;
6661 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6662 if (TemplateParamLists.size()) {
6663 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6664 return nullptr;
6665 }
6666
6667 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6668 } else if (R->isFunctionType()) {
6669 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6670 TemplateParamLists,
6671 AddToScope);
6672 } else {
6673 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6674 AddToScope);
6675 }
6676
6677 if (!New)
6678 return nullptr;
6679
6680 warnOnCTypeHiddenInCPlusPlus(New);
6681
6682 // If this has an identifier and is not a function template specialization,
6683 // add it to the scope stack.
6684 if (New->getDeclName() && AddToScope)
6685 PushOnScopeChains(New, S);
6686
6687 if (OpenMP().isInOpenMPDeclareTargetContext())
6688 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6689
6690 return New;
6691 }
6692
6693 /// Helper method to turn variable array types into constant array
6694 /// types in certain situations which would otherwise be errors (for
6695 /// GCC compatibility).
6696 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6697 ASTContext &Context,
6698 bool &SizeIsNegative,
6699 llvm::APSInt &Oversized) {
6700 // This method tries to turn a variable array into a constant
6701 // array even when the size isn't an ICE. This is necessary
6702 // for compatibility with code that depends on gcc's buggy
6703 // constant expression folding, like struct {char x[(int)(char*)2];}
6704 SizeIsNegative = false;
6705 Oversized = 0;
6706
6707 if (T->isDependentType())
6708 return QualType();
6709
6710 QualifierCollector Qs;
6711 const Type *Ty = Qs.strip(T);
6712
6713 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6714 QualType Pointee = PTy->getPointeeType();
6715 QualType FixedType =
6716 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6717 Oversized);
6718 if (FixedType.isNull()) return FixedType;
6719 FixedType = Context.getPointerType(FixedType);
6720 return Qs.apply(Context, FixedType);
6721 }
6722 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6723 QualType Inner = PTy->getInnerType();
6724 QualType FixedType =
6725 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6726 Oversized);
6727 if (FixedType.isNull()) return FixedType;
6728 FixedType = Context.getParenType(FixedType);
6729 return Qs.apply(Context, FixedType);
6730 }
6731
6732 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6733 if (!VLATy)
6734 return QualType();
6735
6736 QualType ElemTy = VLATy->getElementType();
6737 if (ElemTy->isVariablyModifiedType()) {
6738 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6739 SizeIsNegative, Oversized);
6740 if (ElemTy.isNull())
6741 return QualType();
6742 }
6743
6744 Expr::EvalResult Result;
6745 if (!VLATy->getSizeExpr() ||
6746 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6747 return QualType();
6748
6749 llvm::APSInt Res = Result.Val.getInt();
6750
6751 // Check whether the array size is negative.
6752 if (Res.isSigned() && Res.isNegative()) {
6753 SizeIsNegative = true;
6754 return QualType();
6755 }
6756
6757 // Check whether the array is too large to be addressed.
6758 unsigned ActiveSizeBits =
6759 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6760 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6761 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6762 : Res.getActiveBits();
6763 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6764 Oversized = Res;
6765 return QualType();
6766 }
6767
6768 QualType FoldedArrayType = Context.getConstantArrayType(
6769 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6770 return Qs.apply(Context, FoldedArrayType);
6771 }
6772
6773 static void
6774 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6775 SrcTL = SrcTL.getUnqualifiedLoc();
6776 DstTL = DstTL.getUnqualifiedLoc();
6777 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6778 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6779 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6780 DstPTL.getPointeeLoc());
6781 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6782 return;
6783 }
6784 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6785 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6786 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6787 DstPTL.getInnerLoc());
6788 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6789 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6790 return;
6791 }
6792 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6793 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6794 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6795 TypeLoc DstElemTL = DstATL.getElementLoc();
6796 if (VariableArrayTypeLoc SrcElemATL =
6797 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6798 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6799 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6800 } else {
6801 DstElemTL.initializeFullCopy(SrcElemTL);
6802 }
6803 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6804 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6805 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6806 }
6807
6808 /// Helper method to turn variable array types into constant array
6809 /// types in certain situations which would otherwise be errors (for
6810 /// GCC compatibility).
6811 static TypeSourceInfo*
6812 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6813 ASTContext &Context,
6814 bool &SizeIsNegative,
6815 llvm::APSInt &Oversized) {
6816 QualType FixedTy
6817 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6818 SizeIsNegative, Oversized);
6819 if (FixedTy.isNull())
6820 return nullptr;
6821 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6822 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6823 FixedTInfo->getTypeLoc());
6824 return FixedTInfo;
6825 }
6826
6827 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6828 QualType &T, SourceLocation Loc,
6829 unsigned FailedFoldDiagID) {
6830 bool SizeIsNegative;
6831 llvm::APSInt Oversized;
6832 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6833 TInfo, Context, SizeIsNegative, Oversized);
6834 if (FixedTInfo) {
6835 Diag(Loc, diag::ext_vla_folded_to_constant);
6836 TInfo = FixedTInfo;
6837 T = FixedTInfo->getType();
6838 return true;
6839 }
6840
6841 if (SizeIsNegative)
6842 Diag(Loc, diag::err_typecheck_negative_array_size);
6843 else if (Oversized.getBoolValue())
6844 Diag(Loc, diag::err_array_too_large) << toString(
6845 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6846 /*UpperCase=*/false, /*InsertSeparators=*/true);
6847 else if (FailedFoldDiagID)
6848 Diag(Loc, FailedFoldDiagID);
6849 return false;
6850 }
6851
6852 void
6853 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6854 if (!getLangOpts().CPlusPlus &&
6855 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6856 // Don't need to track declarations in the TU in C.
6857 return;
6858
6859 // Note that we have a locally-scoped external with this name.
6860 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6861 }
6862
6863 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6864 // FIXME: We can have multiple results via __attribute__((overloadable)).
6865 auto Result = Context.getExternCContextDecl()->lookup(Name);
6866 return Result.empty() ? nullptr : *Result.begin();
6867 }
6868
6869 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6870 // FIXME: We should probably indicate the identifier in question to avoid
6871 // confusion for constructs like "virtual int a(), b;"
6872 if (DS.isVirtualSpecified())
6873 Diag(DS.getVirtualSpecLoc(),
6874 diag::err_virtual_non_function);
6875
6876 if (DS.hasExplicitSpecifier())
6877 Diag(DS.getExplicitSpecLoc(),
6878 diag::err_explicit_non_function);
6879
6880 if (DS.isNoreturnSpecified())
6881 Diag(DS.getNoreturnSpecLoc(),
6882 diag::err_noreturn_non_function);
6883 }
6884
6885 NamedDecl*
6886 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6887 TypeSourceInfo *TInfo, LookupResult &Previous) {
6888 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6889 if (D.getCXXScopeSpec().isSet()) {
6890 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6891 << D.getCXXScopeSpec().getRange();
6892 D.setInvalidType();
6893 // Pretend we didn't see the scope specifier.
6894 DC = CurContext;
6895 Previous.clear();
6896 }
6897
6898 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6899
6900 if (D.getDeclSpec().isInlineSpecified())
6901 Diag(D.getDeclSpec().getInlineSpecLoc(),
6902 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6903 ? diag::warn_ms_inline_non_function
6904 : diag::err_inline_non_function)
6905 << getLangOpts().CPlusPlus17;
6906 if (D.getDeclSpec().hasConstexprSpecifier())
6907 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6908 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6909
6910 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6911 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6912 Diag(D.getName().StartLocation,
6913 diag::err_deduction_guide_invalid_specifier)
6914 << "typedef";
6915 else
6916 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6917 << D.getName().getSourceRange();
6918 return nullptr;
6919 }
6920
6921 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6922 if (!NewTD) return nullptr;
6923
6924 // Handle attributes prior to checking for duplicates in MergeVarDecl
6925 ProcessDeclAttributes(S, NewTD, D);
6926
6927 CheckTypedefForVariablyModifiedType(S, NewTD);
6928
6929 bool Redeclaration = D.isRedeclaration();
6930 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6931 D.setRedeclaration(Redeclaration);
6932 return ND;
6933 }
6934
6935 void
6936 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6937 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6938 // then it shall have block scope.
6939 // Note that variably modified types must be fixed before merging the decl so
6940 // that redeclarations will match.
6941 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6942 QualType T = TInfo->getType();
6943 if (T->isVariablyModifiedType()) {
6944 setFunctionHasBranchProtectedScope();
6945
6946 if (S->getFnParent() == nullptr) {
6947 bool SizeIsNegative;
6948 llvm::APSInt Oversized;
6949 TypeSourceInfo *FixedTInfo =
6950 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6951 SizeIsNegative,
6952 Oversized);
6953 if (FixedTInfo) {
6954 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6955 NewTD->setTypeSourceInfo(FixedTInfo);
6956 } else {
6957 if (SizeIsNegative)
6958 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6959 else if (T->isVariableArrayType())
6960 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6961 else if (Oversized.getBoolValue())
6962 Diag(NewTD->getLocation(), diag::err_array_too_large)
6963 << toString(Oversized, 10);
6964 else
6965 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6966 NewTD->setInvalidDecl();
6967 }
6968 }
6969 }
6970 }
6971
6972 NamedDecl*
6973 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6974 LookupResult &Previous, bool &Redeclaration) {
6975
6976 // Find the shadowed declaration before filtering for scope.
6977 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6978
6979 // Merge the decl with the existing one if appropriate. If the decl is
6980 // in an outer scope, it isn't the same thing.
6981 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6982 /*AllowInlineNamespace*/false);
6983 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6984 if (!Previous.empty()) {
6985 Redeclaration = true;
6986 MergeTypedefNameDecl(S, NewTD, Previous);
6987 } else {
6988 inferGslPointerAttribute(NewTD);
6989 }
6990
6991 if (ShadowedDecl && !Redeclaration)
6992 CheckShadow(NewTD, ShadowedDecl, Previous);
6993
6994 // If this is the C FILE type, notify the AST context.
6995 if (IdentifierInfo *II = NewTD->getIdentifier())
6996 if (!NewTD->isInvalidDecl() &&
6997 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6998 switch (II->getNotableIdentifierID()) {
6999 case tok::NotableIdentifierKind::FILE:
7000 Context.setFILEDecl(NewTD);
7001 break;
7002 case tok::NotableIdentifierKind::jmp_buf:
7003 Context.setjmp_bufDecl(NewTD);
7004 break;
7005 case tok::NotableIdentifierKind::sigjmp_buf:
7006 Context.setsigjmp_bufDecl(NewTD);
7007 break;
7008 case tok::NotableIdentifierKind::ucontext_t:
7009 Context.setucontext_tDecl(NewTD);
7010 break;
7011 case tok::NotableIdentifierKind::float_t:
7012 case tok::NotableIdentifierKind::double_t:
7013 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7014 break;
7015 default:
7016 break;
7017 }
7018 }
7019
7020 return NewTD;
7021 }
7022
7023 /// Determines whether the given declaration is an out-of-scope
7024 /// previous declaration.
7025 ///
7026 /// This routine should be invoked when name lookup has found a
7027 /// previous declaration (PrevDecl) that is not in the scope where a
7028 /// new declaration by the same name is being introduced. If the new
7029 /// declaration occurs in a local scope, previous declarations with
7030 /// linkage may still be considered previous declarations (C99
7031 /// 6.2.2p4-5, C++ [basic.link]p6).
7032 ///
7033 /// \param PrevDecl the previous declaration found by name
7034 /// lookup
7035 ///
7036 /// \param DC the context in which the new declaration is being
7037 /// declared.
7038 ///
7039 /// \returns true if PrevDecl is an out-of-scope previous declaration
7040 /// for a new delcaration with the same name.
7041 static bool
7042 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7043 ASTContext &Context) {
7044 if (!PrevDecl)
7045 return false;
7046
7047 if (!PrevDecl->hasLinkage())
7048 return false;
7049
7050 if (Context.getLangOpts().CPlusPlus) {
7051 // C++ [basic.link]p6:
7052 // If there is a visible declaration of an entity with linkage
7053 // having the same name and type, ignoring entities declared
7054 // outside the innermost enclosing namespace scope, the block
7055 // scope declaration declares that same entity and receives the
7056 // linkage of the previous declaration.
7057 DeclContext *OuterContext = DC->getRedeclContext();
7058 if (!OuterContext->isFunctionOrMethod())
7059 // This rule only applies to block-scope declarations.
7060 return false;
7061
7062 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7063 if (PrevOuterContext->isRecord())
7064 // We found a member function: ignore it.
7065 return false;
7066
7067 // Find the innermost enclosing namespace for the new and
7068 // previous declarations.
7069 OuterContext = OuterContext->getEnclosingNamespaceContext();
7070 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7071
7072 // The previous declaration is in a different namespace, so it
7073 // isn't the same function.
7074 if (!OuterContext->Equals(PrevOuterContext))
7075 return false;
7076 }
7077
7078 return true;
7079 }
7080
7081 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7082 CXXScopeSpec &SS = D.getCXXScopeSpec();
7083 if (!SS.isSet()) return;
7084 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
7085 }
7086
7087 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
7088 if (Decl->getType().hasAddressSpace())
7089 return;
7090 if (Decl->getType()->isDependentType())
7091 return;
7092 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7093 QualType Type = Var->getType();
7094 if (Type->isSamplerT() || Type->isVoidType())
7095 return;
7096 LangAS ImplAS = LangAS::opencl_private;
7097 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7098 // __opencl_c_program_scope_global_variables feature, the address space
7099 // for a variable at program scope or a static or extern variable inside
7100 // a function are inferred to be __global.
7101 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7102 Var->hasGlobalStorage())
7103 ImplAS = LangAS::opencl_global;
7104 // If the original type from a decayed type is an array type and that array
7105 // type has no address space yet, deduce it now.
7106 if (auto DT = dyn_cast<DecayedType>(Type)) {
7107 auto OrigTy = DT->getOriginalType();
7108 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7109 // Add the address space to the original array type and then propagate
7110 // that to the element type through `getAsArrayType`.
7111 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7112 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7113 // Re-generate the decayed type.
7114 Type = Context.getDecayedType(OrigTy);
7115 }
7116 }
7117 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7118 // Apply any qualifiers (including address space) from the array type to
7119 // the element type. This implements C99 6.7.3p8: "If the specification of
7120 // an array type includes any type qualifiers, the element type is so
7121 // qualified, not the array type."
7122 if (Type->isArrayType())
7123 Type = QualType(Context.getAsArrayType(Type), 0);
7124 Decl->setType(Type);
7125 }
7126 }
7127
7128 static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7129 // 'weak' only applies to declarations with external linkage.
7130 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7131 if (!ND.isExternallyVisible()) {
7132 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7133 ND.dropAttr<WeakAttr>();
7134 }
7135 }
7136 }
7137
7138 static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7139 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7140 if (ND.isExternallyVisible()) {
7141 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7142 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7143 }
7144 }
7145 }
7146
7147 static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7148 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7149 if (VD->hasInit()) {
7150 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7151 assert(VD->isThisDeclarationADefinition() &&
7152 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7153 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7154 VD->dropAttr<AliasAttr>();
7155 }
7156 }
7157 }
7158 }
7159
7160 static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7161 // 'selectany' only applies to externally visible variable declarations.
7162 // It does not apply to functions.
7163 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7164 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7165 S.Diag(Attr->getLocation(),
7166 diag::err_attribute_selectany_non_extern_data);
7167 ND.dropAttr<SelectAnyAttr>();
7168 }
7169 }
7170 }
7171
7172 static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7173 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7174 if (!ND.isExternallyVisible())
7175 S.Diag(Attr->getLocation(),
7176 diag::warn_attribute_hybrid_patchable_non_extern);
7177 }
7178 }
7179
7180 static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7181 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7182 auto *VD = dyn_cast<VarDecl>(&ND);
7183 bool IsAnonymousNS = false;
7184 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7185 if (VD) {
7186 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7187 while (NS && !IsAnonymousNS) {
7188 IsAnonymousNS = NS->isAnonymousNamespace();
7189 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7190 }
7191 }
7192 // dll attributes require external linkage. Static locals may have external
7193 // linkage but still cannot be explicitly imported or exported.
7194 // In Microsoft mode, a variable defined in anonymous namespace must have
7195 // external linkage in order to be exported.
7196 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7197 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7198 (!AnonNSInMicrosoftMode &&
7199 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7200 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7201 << &ND << Attr;
7202 ND.setInvalidDecl();
7203 }
7204 }
7205 }
7206
7207 static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7208 // Check the attributes on the function type and function params, if any.
7209 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7210 FD = FD->getMostRecentDecl();
7211 // Don't declare this variable in the second operand of the for-statement;
7212 // GCC miscompiles that by ending its lifetime before evaluating the
7213 // third operand. See gcc.gnu.org/PR86769.
7214 AttributedTypeLoc ATL;
7215 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7216 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7217 TL = ATL.getModifiedLoc()) {
7218 // The [[lifetimebound]] attribute can be applied to the implicit object
7219 // parameter of a non-static member function (other than a ctor or dtor)
7220 // by applying it to the function type.
7221 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7222 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7223 int NoImplicitObjectError = -1;
7224 if (!MD)
7225 NoImplicitObjectError = 0;
7226 else if (MD->isStatic())
7227 NoImplicitObjectError = 1;
7228 else if (MD->isExplicitObjectMemberFunction())
7229 NoImplicitObjectError = 2;
7230 if (NoImplicitObjectError != -1) {
7231 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7232 << NoImplicitObjectError << A->getRange();
7233 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7234 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7235 << isa<CXXDestructorDecl>(MD) << A->getRange();
7236 } else if (MD->getReturnType()->isVoidType()) {
7237 S.Diag(
7238 MD->getLocation(),
7239 diag::
7240 err_lifetimebound_implicit_object_parameter_void_return_type);
7241 }
7242 }
7243 }
7244
7245 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7246 const ParmVarDecl *P = FD->getParamDecl(I);
7247
7248 // The [[lifetimebound]] attribute can be applied to a function parameter
7249 // only if the function returns a value.
7250 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7251 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7252 S.Diag(A->getLocation(),
7253 diag::err_lifetimebound_parameter_void_return_type);
7254 }
7255 }
7256 }
7257 }
7258 }
7259
7260 static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7261 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7262 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7263 }
7264
7265 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7266 // Ensure that an auto decl is deduced otherwise the checks below might cache
7267 // the wrong linkage.
7268 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7269
7270 checkWeakAttr(S, ND);
7271 checkWeakRefAttr(S, ND);
7272 checkAliasAttr(S, ND);
7273 checkSelectAnyAttr(S, ND);
7274 checkHybridPatchableAttr(S, ND);
7275 checkInheritableAttr(S, ND);
7276 checkLifetimeBoundAttr(S, ND);
7277 checkModularFormatAttr(S, ND);
7278 }
7279
7280 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7281 NamedDecl *NewDecl,
7282 bool IsSpecialization,
7283 bool IsDefinition) {
7284 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7285 return;
7286
7287 bool IsTemplate = false;
7288 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7289 OldDecl = OldTD->getTemplatedDecl();
7290 IsTemplate = true;
7291 if (!IsSpecialization)
7292 IsDefinition = false;
7293 }
7294 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7295 NewDecl = NewTD->getTemplatedDecl();
7296 IsTemplate = true;
7297 }
7298
7299 if (!OldDecl || !NewDecl)
7300 return;
7301
7302 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7303 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7304 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7305 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7306
7307 // dllimport and dllexport are inheritable attributes so we have to exclude
7308 // inherited attribute instances.
7309 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7310 (NewExportAttr && !NewExportAttr->isInherited());
7311
7312 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7313 // the only exception being explicit specializations.
7314 // Implicitly generated declarations are also excluded for now because there
7315 // is no other way to switch these to use dllimport or dllexport.
7316 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7317
7318 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7319 // Allow with a warning for free functions and global variables.
7320 bool JustWarn = false;
7321 if (!OldDecl->isCXXClassMember()) {
7322 auto *VD = dyn_cast<VarDecl>(OldDecl);
7323 if (VD && !VD->getDescribedVarTemplate())
7324 JustWarn = true;
7325 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7326 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7327 JustWarn = true;
7328 }
7329
7330 // We cannot change a declaration that's been used because IR has already
7331 // been emitted. Dllimported functions will still work though (modulo
7332 // address equality) as they can use the thunk.
7333 if (OldDecl->isUsed())
7334 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7335 JustWarn = false;
7336
7337 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7338 : diag::err_attribute_dll_redeclaration;
7339 S.Diag(NewDecl->getLocation(), DiagID)
7340 << NewDecl
7341 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7342 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7343 if (!JustWarn) {
7344 NewDecl->setInvalidDecl();
7345 return;
7346 }
7347 }
7348
7349 // A redeclaration is not allowed to drop a dllimport attribute, the only
7350 // exceptions being inline function definitions (except for function
7351 // templates), local extern declarations, qualified friend declarations or
7352 // special MSVC extension: in the last case, the declaration is treated as if
7353 // it were marked dllexport.
7354 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7355 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7356 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7357 // Ignore static data because out-of-line definitions are diagnosed
7358 // separately.
7359 IsStaticDataMember = VD->isStaticDataMember();
7360 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7361 VarDecl::DeclarationOnly;
7362 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7363 IsInline = FD->isInlined();
7364 IsQualifiedFriend = FD->getQualifier() &&
7365 FD->getFriendObjectKind() == Decl::FOK_Declared;
7366 }
7367
7368 if (OldImportAttr && !HasNewAttr &&
7369 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7370 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7371 if (IsMicrosoftABI && IsDefinition) {
7372 if (IsSpecialization) {
7373 S.Diag(
7374 NewDecl->getLocation(),
7375 diag::err_attribute_dllimport_function_specialization_definition);
7376 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7377 NewDecl->dropAttr<DLLImportAttr>();
7378 } else {
7379 S.Diag(NewDecl->getLocation(),
7380 diag::warn_redeclaration_without_import_attribute)
7381 << NewDecl;
7382 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7383 NewDecl->dropAttr<DLLImportAttr>();
7384 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7385 S.Context, NewImportAttr->getRange()));
7386 }
7387 } else if (IsMicrosoftABI && IsSpecialization) {
7388 assert(!IsDefinition);
7389 // MSVC allows this. Keep the inherited attribute.
7390 } else {
7391 S.Diag(NewDecl->getLocation(),
7392 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7393 << NewDecl << OldImportAttr;
7394 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7395 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7396 OldDecl->dropAttr<DLLImportAttr>();
7397 NewDecl->dropAttr<DLLImportAttr>();
7398 }
7399 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7400 // In MinGW, seeing a function declared inline drops the dllimport
7401 // attribute.
7402 OldDecl->dropAttr<DLLImportAttr>();
7403 NewDecl->dropAttr<DLLImportAttr>();
7404 S.Diag(NewDecl->getLocation(),
7405 diag::warn_dllimport_dropped_from_inline_function)
7406 << NewDecl << OldImportAttr;
7407 }
7408
7409 // A specialization of a class template member function is processed here
7410 // since it's a redeclaration. If the parent class is dllexport, the
7411 // specialization inherits that attribute. This doesn't happen automatically
7412 // since the parent class isn't instantiated until later.
7413 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7414 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7415 !NewImportAttr && !NewExportAttr) {
7416 if (const DLLExportAttr *ParentExportAttr =
7417 MD->getParent()->getAttr<DLLExportAttr>()) {
7418 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7419 NewAttr->setInherited(true);
7420 NewDecl->addAttr(NewAttr);
7421 }
7422 }
7423 }
7424 }
7425
7426 /// Given that we are within the definition of the given function,
7427 /// will that definition behave like C99's 'inline', where the
7428 /// definition is discarded except for optimization purposes?
7429 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7430 // Try to avoid calling GetGVALinkageForFunction.
7431
7432 // All cases of this require the 'inline' keyword.
7433 if (!FD->isInlined()) return false;
7434
7435 // This is only possible in C++ with the gnu_inline attribute.
7436 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7437 return false;
7438
7439 // Okay, go ahead and call the relatively-more-expensive function.
7440 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7441 }
7442
7443 /// Determine whether a variable is extern "C" prior to attaching
7444 /// an initializer. We can't just call isExternC() here, because that
7445 /// will also compute and cache whether the declaration is externally
7446 /// visible, which might change when we attach the initializer.
7447 ///
7448 /// This can only be used if the declaration is known to not be a
7449 /// redeclaration of an internal linkage declaration.
7450 ///
7451 /// For instance:
7452 ///
7453 /// auto x = []{};
7454 ///
7455 /// Attaching the initializer here makes this declaration not externally
7456 /// visible, because its type has internal linkage.
7457 ///
7458 /// FIXME: This is a hack.
7459 template<typename T>
7460 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7461 if (S.getLangOpts().CPlusPlus) {
7462 // In C++, the overloadable attribute negates the effects of extern "C".
7463 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7464 return false;
7465
7466 // So do CUDA's host/device attributes.
7467 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7468 D->template hasAttr<CUDAHostAttr>()))
7469 return false;
7470 }
7471 return D->isExternC();
7472 }
7473
7474 static bool shouldConsiderLinkage(const VarDecl *VD) {
7475 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7476 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7477 isa<OMPDeclareMapperDecl>(DC))
7478 return VD->hasExternalStorage();
7479 if (DC->isFileContext())
7480 return true;
7481 if (DC->isRecord())
7482 return false;
7483 if (DC->getDeclKind() == Decl::HLSLBuffer)
7484 return false;
7485
7486 if (isa<RequiresExprBodyDecl>(DC))
7487 return false;
7488 llvm_unreachable("Unexpected context");
7489 }
7490
7491 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7492 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7493 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7494 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7495 return true;
7496 if (DC->isRecord())
7497 return false;
7498 llvm_unreachable("Unexpected context");
7499 }
7500
7501 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7502 ParsedAttr::Kind Kind) {
7503 // Check decl attributes on the DeclSpec.
7504 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7505 return true;
7506
7507 // Walk the declarator structure, checking decl attributes that were in a type
7508 // position to the decl itself.
7509 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7510 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7511 return true;
7512 }
7513
7514 // Finally, check attributes on the decl itself.
7515 return PD.getAttributes().hasAttribute(Kind) ||
7516 PD.getDeclarationAttributes().hasAttribute(Kind);
7517 }
7518
7519 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7520 if (!DC->isFunctionOrMethod())
7521 return false;
7522
7523 // If this is a local extern function or variable declared within a function
7524 // template, don't add it into the enclosing namespace scope until it is
7525 // instantiated; it might have a dependent type right now.
7526 if (DC->isDependentContext())
7527 return true;
7528
7529 // C++11 [basic.link]p7:
7530 // When a block scope declaration of an entity with linkage is not found to
7531 // refer to some other declaration, then that entity is a member of the
7532 // innermost enclosing namespace.
7533 //
7534 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7535 // semantically-enclosing namespace, not a lexically-enclosing one.
7536 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7537 DC = DC->getParent();
7538 return true;
7539 }
7540
7541 /// Returns true if given declaration has external C language linkage.
7542 static bool isDeclExternC(const Decl *D) {
7543 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7544 return FD->isExternC();
7545 if (const auto *VD = dyn_cast<VarDecl>(D))
7546 return VD->isExternC();
7547
7548 llvm_unreachable("Unknown type of decl!");
7549 }
7550
7551 /// Returns true if there hasn't been any invalid type diagnosed.
7552 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7553 DeclContext *DC = NewVD->getDeclContext();
7554 QualType R = NewVD->getType();
7555
7556 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7557 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7558 // argument.
7559 if (R->isImageType() || R->isPipeType()) {
7560 Se.Diag(NewVD->getLocation(),
7561 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7562 << R;
7563 NewVD->setInvalidDecl();
7564 return false;
7565 }
7566
7567 // OpenCL v1.2 s6.9.r:
7568 // The event type cannot be used to declare a program scope variable.
7569 // OpenCL v2.0 s6.9.q:
7570 // The clk_event_t and reserve_id_t types cannot be declared in program
7571 // scope.
7572 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7573 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7574 Se.Diag(NewVD->getLocation(),
7575 diag::err_invalid_type_for_program_scope_var)
7576 << R;
7577 NewVD->setInvalidDecl();
7578 return false;
7579 }
7580 }
7581
7582 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7583 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7584 Se.getLangOpts())) {
7585 QualType NR = R.getCanonicalType();
7586 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7587 NR->isReferenceType()) {
7588 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7589 NR->isFunctionReferenceType()) {
7590 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7591 << NR->isReferenceType();
7592 NewVD->setInvalidDecl();
7593 return false;
7594 }
7595 NR = NR->getPointeeType();
7596 }
7597 }
7598
7599 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7600 Se.getLangOpts())) {
7601 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7602 // half array type (unless the cl_khr_fp16 extension is enabled).
7603 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7604 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7605 NewVD->setInvalidDecl();
7606 return false;
7607 }
7608 }
7609
7610 // OpenCL v1.2 s6.9.r:
7611 // The event type cannot be used with the __local, __constant and __global
7612 // address space qualifiers.
7613 if (R->isEventT()) {
7614 if (R.getAddressSpace() != LangAS::opencl_private) {
7615 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7616 NewVD->setInvalidDecl();
7617 return false;
7618 }
7619 }
7620
7621 if (R->isSamplerT()) {
7622 // OpenCL v1.2 s6.9.b p4:
7623 // The sampler type cannot be used with the __local and __global address
7624 // space qualifiers.
7625 if (R.getAddressSpace() == LangAS::opencl_local ||
7626 R.getAddressSpace() == LangAS::opencl_global) {
7627 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7628 NewVD->setInvalidDecl();
7629 }
7630
7631 // OpenCL v1.2 s6.12.14.1:
7632 // A global sampler must be declared with either the constant address
7633 // space qualifier or with the const qualifier.
7634 if (DC->isTranslationUnit() &&
7635 !(R.getAddressSpace() == LangAS::opencl_constant ||
7636 R.isConstQualified())) {
7637 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7638 NewVD->setInvalidDecl();
7639 }
7640 if (NewVD->isInvalidDecl())
7641 return false;
7642 }
7643
7644 return true;
7645 }
7646
7647 template <typename AttrTy>
7648 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7649 const TypedefNameDecl *TND = TT->getDecl();
7650 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7651 AttrTy *Clone = Attribute->clone(S.Context);
7652 Clone->setInherited(true);
7653 D->addAttr(Clone);
7654 }
7655 }
7656
7657 // This function emits warning and a corresponding note based on the
7658 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7659 // declarations of an annotated type must be const qualified.
7660 static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7661 QualType VarType = VD->getType().getCanonicalType();
7662
7663 // Ignore local declarations (for now) and those with const qualification.
7664 // TODO: Local variables should not be allowed if their type declaration has
7665 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7666 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7667 return;
7668
7669 if (VarType->isArrayType()) {
7670 // Retrieve element type for array declarations.
7671 VarType = S.getASTContext().getBaseElementType(VarType);
7672 }
7673
7674 const RecordDecl *RD = VarType->getAsRecordDecl();
7675
7676 // Check if the record declaration is present and if it has any attributes.
7677 if (RD == nullptr)
7678 return;
7679
7680 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7681 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7682 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7683 return;
7684 }
7685 }
7686
7687 // Checks if VD is declared at global scope or with C language linkage.
7688 static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7689 return Name.getAsIdentifierInfo() &&
7690 Name.getAsIdentifierInfo()->isStr("main") &&
7691 !VD->getDescribedVarTemplate() &&
7692 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7693 VD->isExternC());
7694 }
7695
7696 void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7697 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7698
7699 // Quickly return if the function does not have an `asm` attribute.
7700 if (E == nullptr)
7701 return;
7702
7703 // The parser guarantees this is a string.
7704 StringLiteral *SE = cast<StringLiteral>(E);
7705 StringRef Label = SE->getString();
7706 QualType R = TInfo->getType();
7707 if (S->getFnParent() != nullptr) {
7708 switch (SC) {
7709 case SC_None:
7710 case SC_Auto:
7711 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7712 break;
7713 case SC_Register:
7714 // Local Named register
7715 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7716 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7717 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7718 break;
7719 case SC_Static:
7720 case SC_Extern:
7721 case SC_PrivateExtern:
7722 break;
7723 }
7724 } else if (SC == SC_Register) {
7725 // Global Named register
7726 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7727 const auto &TI = Context.getTargetInfo();
7728 bool HasSizeMismatch;
7729
7730 if (!TI.isValidGCCRegisterName(Label))
7731 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7732 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7733 HasSizeMismatch))
7734 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7735 else if (HasSizeMismatch)
7736 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7737 }
7738
7739 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7740 Diag(TInfo->getTypeLoc().getBeginLoc(),
7741 diag::err_asm_unsupported_register_type)
7742 << TInfo->getTypeLoc().getSourceRange();
7743 NewVD->setInvalidDecl(true);
7744 }
7745 }
7746 }
7747
7748 NamedDecl *Sema::ActOnVariableDeclarator(
7749 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7750 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7751 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7752 QualType R = TInfo->getType();
7753 DeclarationName Name = GetNameForDeclarator(D).getName();
7754
7755 IdentifierInfo *II = Name.getAsIdentifierInfo();
7756 bool IsPlaceholderVariable = false;
7757
7758 if (D.isDecompositionDeclarator()) {
7759 // Take the name of the first declarator as our name for diagnostic
7760 // purposes.
7761 auto &Decomp = D.getDecompositionDeclarator();
7762 if (!Decomp.bindings().empty()) {
7763 II = Decomp.bindings()[0].Name;
7764 Name = II;
7765 }
7766 } else if (!II) {
7767 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7768 return nullptr;
7769 }
7770
7771
7772 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7773 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7774 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7775 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7776
7777 IsPlaceholderVariable = true;
7778
7779 if (!Previous.empty()) {
7780 NamedDecl *PrevDecl = *Previous.begin();
7781 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7782 DC->getRedeclContext());
7783 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7784 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7785 if (IsPlaceholderVariable)
7786 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7787 }
7788 }
7789 }
7790
7791 // dllimport globals without explicit storage class are treated as extern. We
7792 // have to change the storage class this early to get the right DeclContext.
7793 if (SC == SC_None && !DC->isRecord() &&
7794 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7795 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7796 SC = SC_Extern;
7797
7798 DeclContext *OriginalDC = DC;
7799 bool IsLocalExternDecl = SC == SC_Extern &&
7800 adjustContextForLocalExternDecl(DC);
7801
7802 if (SCSpec == DeclSpec::SCS_mutable) {
7803 // mutable can only appear on non-static class members, so it's always
7804 // an error here
7805 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7806 D.setInvalidType();
7807 SC = SC_None;
7808 }
7809
7810 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7811 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7812 D.getDeclSpec().getStorageClassSpecLoc())) {
7813 // In C++11, the 'register' storage class specifier is deprecated.
7814 // Suppress the warning in system macros, it's used in macros in some
7815 // popular C system headers, such as in glibc's htonl() macro.
7816 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7817 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7818 : diag::warn_deprecated_register)
7819 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7820 }
7821
7822 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7823
7824 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7825 // C99 6.9p2: The storage-class specifiers auto and register shall not
7826 // appear in the declaration specifiers in an external declaration.
7827 // Global Register+Asm is a GNU extension we support.
7828 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7829 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7830 D.setInvalidType();
7831 }
7832 }
7833
7834 // If this variable has a VLA type and an initializer, try to
7835 // fold to a constant-sized type. This is otherwise invalid.
7836 if (D.hasInitializer() && R->isVariableArrayType())
7837 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7838 /*DiagID=*/0);
7839
7840 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7841 const AutoType *AT = TL.getTypePtr();
7842 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7843 }
7844
7845 bool IsMemberSpecialization = false;
7846 bool IsVariableTemplateSpecialization = false;
7847 bool IsPartialSpecialization = false;
7848 bool IsVariableTemplate = false;
7849 VarDecl *NewVD = nullptr;
7850 VarTemplateDecl *NewTemplate = nullptr;
7851 TemplateParameterList *TemplateParams = nullptr;
7852 if (!getLangOpts().CPlusPlus) {
7853 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7854 II, R, TInfo, SC);
7855
7856 if (R->getContainedDeducedType())
7857 ParsingInitForAutoVars.insert(NewVD);
7858
7859 if (D.isInvalidType())
7860 NewVD->setInvalidDecl();
7861
7862 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7863 NewVD->hasLocalStorage())
7864 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7865 NonTrivialCUnionContext::AutoVar, NTCUK_Destruct);
7866 } else {
7867 bool Invalid = false;
7868 // Match up the template parameter lists with the scope specifier, then
7869 // determine whether we have a template or a template specialization.
7870 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7871 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7872 D.getCXXScopeSpec(),
7873 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7874 ? D.getName().TemplateId
7875 : nullptr,
7876 TemplateParamLists,
7877 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7878
7879 if (TemplateParams) {
7880 if (DC->isDependentContext()) {
7881 ContextRAII SavedContext(*this, DC);
7882 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7883 Invalid = true;
7884 }
7885
7886 if (!TemplateParams->size() &&
7887 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7888 // There is an extraneous 'template<>' for this variable. Complain
7889 // about it, but allow the declaration of the variable.
7890 Diag(TemplateParams->getTemplateLoc(),
7891 diag::err_template_variable_noparams)
7892 << II
7893 << SourceRange(TemplateParams->getTemplateLoc(),
7894 TemplateParams->getRAngleLoc());
7895 TemplateParams = nullptr;
7896 } else {
7897 // Check that we can declare a template here.
7898 if (CheckTemplateDeclScope(S, TemplateParams))
7899 return nullptr;
7900
7901 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7902 // This is an explicit specialization or a partial specialization.
7903 IsVariableTemplateSpecialization = true;
7904 IsPartialSpecialization = TemplateParams->size() > 0;
7905 } else { // if (TemplateParams->size() > 0)
7906 // This is a template declaration.
7907 IsVariableTemplate = true;
7908
7909 // Only C++1y supports variable templates (N3651).
7910 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7911 }
7912 }
7913 } else {
7914 // Check that we can declare a member specialization here.
7915 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7916 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7917 return nullptr;
7918 assert((Invalid ||
7919 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7920 "should have a 'template<>' for this decl");
7921 }
7922
7923 bool IsExplicitSpecialization =
7924 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7925
7926 // C++ [temp.expl.spec]p2:
7927 // The declaration in an explicit-specialization shall not be an
7928 // export-declaration. An explicit specialization shall not use a
7929 // storage-class-specifier other than thread_local.
7930 //
7931 // We use the storage-class-specifier from DeclSpec because we may have
7932 // added implicit 'extern' for declarations with __declspec(dllimport)!
7933 if (SCSpec != DeclSpec::SCS_unspecified &&
7934 (IsExplicitSpecialization || IsMemberSpecialization)) {
7935 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7936 diag::ext_explicit_specialization_storage_class)
7937 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7938 }
7939
7940 if (CurContext->isRecord()) {
7941 if (SC == SC_Static) {
7942 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7943 // Walk up the enclosing DeclContexts to check for any that are
7944 // incompatible with static data members.
7945 const DeclContext *FunctionOrMethod = nullptr;
7946 const CXXRecordDecl *AnonStruct = nullptr;
7947 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7948 if (Ctxt->isFunctionOrMethod()) {
7949 FunctionOrMethod = Ctxt;
7950 break;
7951 }
7952 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7953 if (ParentDecl && !ParentDecl->getDeclName()) {
7954 AnonStruct = ParentDecl;
7955 break;
7956 }
7957 }
7958 if (FunctionOrMethod) {
7959 // C++ [class.static.data]p5: A local class shall not have static
7960 // data members.
7961 Diag(D.getIdentifierLoc(),
7962 diag::err_static_data_member_not_allowed_in_local_class)
7963 << Name << RD->getDeclName() << RD->getTagKind();
7964 } else if (AnonStruct) {
7965 // C++ [class.static.data]p4: Unnamed classes and classes contained
7966 // directly or indirectly within unnamed classes shall not contain
7967 // static data members.
7968 Diag(D.getIdentifierLoc(),
7969 diag::err_static_data_member_not_allowed_in_anon_struct)
7970 << Name << AnonStruct->getTagKind();
7971 Invalid = true;
7972 } else if (RD->isUnion()) {
7973 // C++98 [class.union]p1: If a union contains a static data member,
7974 // the program is ill-formed. C++11 drops this restriction.
7975 DiagCompat(D.getIdentifierLoc(),
7976 diag_compat::static_data_member_in_union)
7977 << Name;
7978 }
7979 }
7980 } else if (IsVariableTemplate || IsPartialSpecialization) {
7981 // There is no such thing as a member field template.
7982 Diag(D.getIdentifierLoc(), diag::err_template_member)
7983 << II << TemplateParams->getSourceRange();
7984 // Recover by pretending this is a static data member template.
7985 SC = SC_Static;
7986 }
7987 } else if (DC->isRecord()) {
7988 // This is an out-of-line definition of a static data member.
7989 switch (SC) {
7990 case SC_None:
7991 break;
7992 case SC_Static:
7993 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7994 diag::err_static_out_of_line)
7995 << FixItHint::CreateRemoval(
7996 D.getDeclSpec().getStorageClassSpecLoc());
7997 break;
7998 case SC_Auto:
7999 case SC_Register:
8000 case SC_Extern:
8001 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8002 // to names of variables declared in a block or to function parameters.
8003 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8004 // of class members
8005
8006 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8007 diag::err_storage_class_for_static_member)
8008 << FixItHint::CreateRemoval(
8009 D.getDeclSpec().getStorageClassSpecLoc());
8010 break;
8011 case SC_PrivateExtern:
8012 llvm_unreachable("C storage class in c++!");
8013 }
8014 }
8015
8016 if (IsVariableTemplateSpecialization) {
8017 SourceLocation TemplateKWLoc =
8018 TemplateParamLists.size() > 0
8019 ? TemplateParamLists[0]->getTemplateLoc()
8020 : SourceLocation();
8021 DeclResult Res = ActOnVarTemplateSpecialization(
8022 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8023 IsPartialSpecialization);
8024 if (Res.isInvalid())
8025 return nullptr;
8026 NewVD = cast<VarDecl>(Res.get());
8027 AddToScope = false;
8028 } else if (D.isDecompositionDeclarator()) {
8029 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
8030 D.getIdentifierLoc(), R, TInfo, SC,
8031 Bindings);
8032 } else
8033 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8034 D.getIdentifierLoc(), II, R, TInfo, SC);
8035
8036 // If this is supposed to be a variable template, create it as such.
8037 if (IsVariableTemplate) {
8038 NewTemplate =
8039 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
8040 TemplateParams, NewVD);
8041 NewVD->setDescribedVarTemplate(NewTemplate);
8042 }
8043
8044 // If this decl has an auto type in need of deduction, make a note of the
8045 // Decl so we can diagnose uses of it in its own initializer.
8046 if (R->getContainedDeducedType())
8047 ParsingInitForAutoVars.insert(NewVD);
8048
8049 if (D.isInvalidType() || Invalid) {
8050 NewVD->setInvalidDecl();
8051 if (NewTemplate)
8052 NewTemplate->setInvalidDecl();
8053 }
8054
8055 SetNestedNameSpecifier(*this, NewVD, D);
8056
8057 // If we have any template parameter lists that don't directly belong to
8058 // the variable (matching the scope specifier), store them.
8059 // An explicit variable template specialization does not own any template
8060 // parameter lists.
8061 unsigned VDTemplateParamLists =
8062 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8063 if (TemplateParamLists.size() > VDTemplateParamLists)
8064 NewVD->setTemplateParameterListsInfo(
8065 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8066 }
8067
8068 if (D.getDeclSpec().isInlineSpecified()) {
8069 if (!getLangOpts().CPlusPlus) {
8070 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8071 << 0;
8072 } else if (CurContext->isFunctionOrMethod()) {
8073 // 'inline' is not allowed on block scope variable declaration.
8074 Diag(D.getDeclSpec().getInlineSpecLoc(),
8075 diag::err_inline_declaration_block_scope) << Name
8076 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8077 } else {
8078 Diag(D.getDeclSpec().getInlineSpecLoc(),
8079 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8080 : diag::compat_pre_cxx17_inline_variable);
8081 NewVD->setInlineSpecified();
8082 }
8083 }
8084
8085 // Set the lexical context. If the declarator has a C++ scope specifier, the
8086 // lexical context will be different from the semantic context.
8087 NewVD->setLexicalDeclContext(CurContext);
8088 if (NewTemplate)
8089 NewTemplate->setLexicalDeclContext(CurContext);
8090
8091 if (IsLocalExternDecl) {
8092 if (D.isDecompositionDeclarator())
8093 for (auto *B : Bindings)
8094 B->setLocalExternDecl();
8095 else
8096 NewVD->setLocalExternDecl();
8097 }
8098
8099 bool EmitTLSUnsupportedError = false;
8100 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8101 // C++11 [dcl.stc]p4:
8102 // When thread_local is applied to a variable of block scope the
8103 // storage-class-specifier static is implied if it does not appear
8104 // explicitly.
8105 // Core issue: 'static' is not implied if the variable is declared
8106 // 'extern'.
8107 if (NewVD->hasLocalStorage() &&
8108 (SCSpec != DeclSpec::SCS_unspecified ||
8109 TSCS != DeclSpec::TSCS_thread_local ||
8110 !DC->isFunctionOrMethod()))
8111 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8112 diag::err_thread_non_global)
8113 << DeclSpec::getSpecifierName(TSCS);
8114 else if (!Context.getTargetInfo().isTLSSupported()) {
8115 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8116 // Postpone error emission until we've collected attributes required to
8117 // figure out whether it's a host or device variable and whether the
8118 // error should be ignored.
8119 EmitTLSUnsupportedError = true;
8120 // We still need to mark the variable as TLS so it shows up in AST with
8121 // proper storage class for other tools to use even if we're not going
8122 // to emit any code for it.
8123 NewVD->setTSCSpec(TSCS);
8124 } else
8125 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8126 diag::err_thread_unsupported);
8127 } else
8128 NewVD->setTSCSpec(TSCS);
8129 }
8130
8131 switch (D.getDeclSpec().getConstexprSpecifier()) {
8132 case ConstexprSpecKind::Unspecified:
8133 break;
8134
8135 case ConstexprSpecKind::Consteval:
8136 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8137 diag::err_constexpr_wrong_decl_kind)
8138 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8139 [[fallthrough]];
8140
8141 case ConstexprSpecKind::Constexpr:
8142 NewVD->setConstexpr(true);
8143 // C++1z [dcl.spec.constexpr]p1:
8144 // A static data member declared with the constexpr specifier is
8145 // implicitly an inline variable.
8146 if (NewVD->isStaticDataMember() &&
8147 (getLangOpts().CPlusPlus17 ||
8148 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8149 NewVD->setImplicitlyInline();
8150 break;
8151
8152 case ConstexprSpecKind::Constinit:
8153 if (!NewVD->hasGlobalStorage())
8154 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8155 diag::err_constinit_local_variable);
8156 else
8157 NewVD->addAttr(
8158 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8159 ConstInitAttr::Keyword_constinit));
8160 break;
8161 }
8162
8163 // C99 6.7.4p3
8164 // An inline definition of a function with external linkage shall
8165 // not contain a definition of a modifiable object with static or
8166 // thread storage duration...
8167 // We only apply this when the function is required to be defined
8168 // elsewhere, i.e. when the function is not 'extern inline'. Note
8169 // that a local variable with thread storage duration still has to
8170 // be marked 'static'. Also note that it's possible to get these
8171 // semantics in C++ using __attribute__((gnu_inline)).
8172 if (SC == SC_Static && S->getFnParent() != nullptr &&
8173 !NewVD->getType().isConstQualified()) {
8174 FunctionDecl *CurFD = getCurFunctionDecl();
8175 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8176 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8177 diag::warn_static_local_in_extern_inline);
8178 MaybeSuggestAddingStaticToDecl(CurFD);
8179 }
8180 }
8181
8182 if (D.getDeclSpec().isModulePrivateSpecified()) {
8183 if (IsVariableTemplateSpecialization)
8184 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8185 << (IsPartialSpecialization ? 1 : 0)
8186 << FixItHint::CreateRemoval(
8187 D.getDeclSpec().getModulePrivateSpecLoc());
8188 else if (IsMemberSpecialization)
8189 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8190 << 2
8191 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8192 else if (NewVD->hasLocalStorage())
8193 Diag(NewVD->getLocation(), diag::err_module_private_local)
8194 << 0 << NewVD
8195 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8196 << FixItHint::CreateRemoval(
8197 D.getDeclSpec().getModulePrivateSpecLoc());
8198 else {
8199 NewVD->setModulePrivate();
8200 if (NewTemplate)
8201 NewTemplate->setModulePrivate();
8202 for (auto *B : Bindings)
8203 B->setModulePrivate();
8204 }
8205 }
8206
8207 if (getLangOpts().OpenCL) {
8208 deduceOpenCLAddressSpace(NewVD);
8209
8210 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8211 if (TSC != TSCS_unspecified) {
8212 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8213 diag::err_opencl_unknown_type_specifier)
8214 << getLangOpts().getOpenCLVersionString()
8215 << DeclSpec::getSpecifierName(TSC) << 1;
8216 NewVD->setInvalidDecl();
8217 }
8218 }
8219
8220 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8221 // address space if the table has local storage (semantic checks elsewhere
8222 // will produce an error anyway).
8223 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8224 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8225 !NewVD->hasLocalStorage()) {
8226 QualType Type = Context.getAddrSpaceQualType(
8227 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8228 NewVD->setType(Type);
8229 }
8230 }
8231
8232 if (Expr *E = D.getAsmLabel()) {
8233 // The parser guarantees this is a string.
8234 StringLiteral *SE = cast<StringLiteral>(E);
8235 StringRef Label = SE->getString();
8236
8237 // Insert the asm attribute.
8238 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8239 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8240 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8241 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8242 if (I != ExtnameUndeclaredIdentifiers.end()) {
8243 if (isDeclExternC(NewVD)) {
8244 NewVD->addAttr(I->second);
8245 ExtnameUndeclaredIdentifiers.erase(I);
8246 } else
8247 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8248 << /*Variable*/ 1 << NewVD;
8249 }
8250 }
8251
8252 // Handle attributes prior to checking for duplicates in MergeVarDecl
8253 ProcessDeclAttributes(S, NewVD, D);
8254
8255 if (getLangOpts().HLSL)
8256 HLSL().ActOnVariableDeclarator(NewVD);
8257
8258 if (getLangOpts().OpenACC)
8259 OpenACC().ActOnVariableDeclarator(NewVD);
8260
8261 // FIXME: This is probably the wrong location to be doing this and we should
8262 // probably be doing this for more attributes (especially for function
8263 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8264 // the code to copy attributes would be generated by TableGen.
8265 if (R->isFunctionPointerType())
8266 if (const auto *TT = R->getAs<TypedefType>())
8267 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8268
8269 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8270 if (EmitTLSUnsupportedError &&
8271 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
8272 (getLangOpts().OpenMPIsTargetDevice &&
8273 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8274 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8275 diag::err_thread_unsupported);
8276
8277 if (EmitTLSUnsupportedError &&
8278 (LangOpts.SYCLIsDevice ||
8279 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8280 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8281 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8282 // storage [duration]."
8283 if (SC == SC_None && S->getFnParent() != nullptr &&
8284 (NewVD->hasAttr<CUDASharedAttr>() ||
8285 NewVD->hasAttr<CUDAConstantAttr>())) {
8286 NewVD->setStorageClass(SC_Static);
8287 }
8288 }
8289
8290 // Ensure that dllimport globals without explicit storage class are treated as
8291 // extern. The storage class is set above using parsed attributes. Now we can
8292 // check the VarDecl itself.
8293 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8294 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8295 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8296
8297 // In auto-retain/release, infer strong retension for variables of
8298 // retainable type.
8299 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8300 NewVD->setInvalidDecl();
8301
8302 // Check the ASM label here, as we need to know all other attributes of the
8303 // Decl first. Otherwise, we can't know if the asm label refers to the
8304 // host or device in a CUDA context. The device has other registers than
8305 // host and we must know where the function will be placed.
8306 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8307
8308 // Find the shadowed declaration before filtering for scope.
8309 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8310 ? getShadowedDeclaration(NewVD, Previous)
8311 : nullptr;
8312
8313 // Don't consider existing declarations that are in a different
8314 // scope and are out-of-semantic-context declarations (if the new
8315 // declaration has linkage).
8316 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8317 D.getCXXScopeSpec().isNotEmpty() ||
8318 IsMemberSpecialization ||
8319 IsVariableTemplateSpecialization);
8320
8321 // Check whether the previous declaration is in the same block scope. This
8322 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8323 if (getLangOpts().CPlusPlus &&
8324 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8325 NewVD->setPreviousDeclInSameBlockScope(
8326 Previous.isSingleResult() && !Previous.isShadowed() &&
8327 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8328
8329 if (!getLangOpts().CPlusPlus) {
8330 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8331 } else {
8332 // If this is an explicit specialization of a static data member, check it.
8333 if (IsMemberSpecialization && !IsVariableTemplate &&
8334 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8335 CheckMemberSpecialization(NewVD, Previous))
8336 NewVD->setInvalidDecl();
8337
8338 // Merge the decl with the existing one if appropriate.
8339 if (!Previous.empty()) {
8340 if (Previous.isSingleResult() &&
8341 isa<FieldDecl>(Previous.getFoundDecl()) &&
8342 D.getCXXScopeSpec().isSet()) {
8343 // The user tried to define a non-static data member
8344 // out-of-line (C++ [dcl.meaning]p1).
8345 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8346 << D.getCXXScopeSpec().getRange();
8347 Previous.clear();
8348 NewVD->setInvalidDecl();
8349 }
8350 } else if (D.getCXXScopeSpec().isSet() &&
8351 !IsVariableTemplateSpecialization) {
8352 // No previous declaration in the qualifying scope.
8353 Diag(D.getIdentifierLoc(), diag::err_no_member)
8354 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8355 << D.getCXXScopeSpec().getRange();
8356 NewVD->setInvalidDecl();
8357 }
8358
8359 if (!IsPlaceholderVariable)
8360 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8361
8362 // CheckVariableDeclaration will set NewVD as invalid if something is in
8363 // error like WebAssembly tables being declared as arrays with a non-zero
8364 // size, but then parsing continues and emits further errors on that line.
8365 // To avoid that we check here if it happened and return nullptr.
8366 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8367 return nullptr;
8368
8369 if (NewTemplate) {
8370 VarTemplateDecl *PrevVarTemplate =
8371 NewVD->getPreviousDecl()
8372 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8373 : nullptr;
8374
8375 // Check the template parameter list of this declaration, possibly
8376 // merging in the template parameter list from the previous variable
8377 // template declaration.
8378 if (CheckTemplateParameterList(
8379 TemplateParams,
8380 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8381 : nullptr,
8382 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8383 DC->isDependentContext())
8384 ? TPC_ClassTemplateMember
8385 : TPC_Other))
8386 NewVD->setInvalidDecl();
8387
8388 // If we are providing an explicit specialization of a static variable
8389 // template, make a note of that.
8390 if (PrevVarTemplate &&
8391 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8392 PrevVarTemplate->setMemberSpecialization();
8393 }
8394 }
8395
8396 // Diagnose shadowed variables iff this isn't a redeclaration.
8397 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8398 CheckShadow(NewVD, ShadowedDecl, Previous);
8399
8400 ProcessPragmaWeak(S, NewVD);
8401
8402 // If this is the first declaration of an extern C variable, update
8403 // the map of such variables.
8404 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8405 isIncompleteDeclExternC(*this, NewVD))
8406 RegisterLocallyScopedExternCDecl(NewVD, S);
8407
8408 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8409 MangleNumberingContext *MCtx;
8410 Decl *ManglingContextDecl;
8411 std::tie(MCtx, ManglingContextDecl) =
8412 getCurrentMangleNumberContext(NewVD->getDeclContext());
8413 if (MCtx) {
8414 Context.setManglingNumber(
8415 NewVD, MCtx->getManglingNumber(
8416 NewVD, getMSManglingNumber(getLangOpts(), S)));
8417 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8418 }
8419 }
8420
8421 // Special handling of variable named 'main'.
8422 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8423 // C++ [basic.start.main]p3:
8424 // A program that declares
8425 // - a variable main at global scope, or
8426 // - an entity named main with C language linkage (in any namespace)
8427 // is ill-formed
8428 if (getLangOpts().CPlusPlus)
8429 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8430 << NewVD->isExternC();
8431
8432 // In C, and external-linkage variable named main results in undefined
8433 // behavior.
8434 else if (NewVD->hasExternalFormalLinkage())
8435 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8436 }
8437
8438 if (D.isRedeclaration() && !Previous.empty()) {
8439 NamedDecl *Prev = Previous.getRepresentativeDecl();
8440 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8441 D.isFunctionDefinition());
8442 }
8443
8444 if (NewTemplate) {
8445 if (NewVD->isInvalidDecl())
8446 NewTemplate->setInvalidDecl();
8447 ActOnDocumentableDecl(NewTemplate);
8448 return NewTemplate;
8449 }
8450
8451 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8452 CompleteMemberSpecialization(NewVD, Previous);
8453
8454 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8455
8456 return NewVD;
8457 }
8458
8459 /// Enum describing the %select options in diag::warn_decl_shadow.
8460 enum ShadowedDeclKind {
8461 SDK_Local,
8462 SDK_Global,
8463 SDK_StaticMember,
8464 SDK_Field,
8465 SDK_Typedef,
8466 SDK_Using,
8467 SDK_StructuredBinding
8468 };
8469
8470 /// Determine what kind of declaration we're shadowing.
8471 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8472 const DeclContext *OldDC) {
8473 if (isa<TypeAliasDecl>(ShadowedDecl))
8474 return SDK_Using;
8475 else if (isa<TypedefDecl>(ShadowedDecl))
8476 return SDK_Typedef;
8477 else if (isa<BindingDecl>(ShadowedDecl))
8478 return SDK_StructuredBinding;
8479 else if (isa<RecordDecl>(OldDC))
8480 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8481
8482 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8483 }
8484
8485 /// Return the location of the capture if the given lambda captures the given
8486 /// variable \p VD, or an invalid source location otherwise.
8487 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8488 const ValueDecl *VD) {
8489 for (const Capture &Capture : LSI->Captures) {
8490 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8491 return Capture.getLocation();
8492 }
8493 return SourceLocation();
8494 }
8495
8496 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8497 const LookupResult &R) {
8498 // Only diagnose if we're shadowing an unambiguous field or variable.
8499 if (R.getResultKind() != LookupResultKind::Found)
8500 return false;
8501
8502 // Return false if warning is ignored.
8503 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8504 }
8505
8506 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8507 const LookupResult &R) {
8508 if (!shouldWarnIfShadowedDecl(Diags, R))
8509 return nullptr;
8510
8511 // Don't diagnose declarations at file scope.
8512 if (D->hasGlobalStorage() && !D->isStaticLocal())
8513 return nullptr;
8514
8515 NamedDecl *ShadowedDecl = R.getFoundDecl();
8516 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8517 : nullptr;
8518 }
8519
8520 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8521 const LookupResult &R) {
8522 // Don't warn if typedef declaration is part of a class
8523 if (D->getDeclContext()->isRecord())
8524 return nullptr;
8525
8526 if (!shouldWarnIfShadowedDecl(Diags, R))
8527 return nullptr;
8528
8529 NamedDecl *ShadowedDecl = R.getFoundDecl();
8530 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8531 }
8532
8533 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8534 const LookupResult &R) {
8535 if (!shouldWarnIfShadowedDecl(Diags, R))
8536 return nullptr;
8537
8538 NamedDecl *ShadowedDecl = R.getFoundDecl();
8539 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8540 : nullptr;
8541 }
8542
8543 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8544 const LookupResult &R) {
8545 DeclContext *NewDC = D->getDeclContext();
8546
8547 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8548 if (const auto *MD =
8549 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8550 // Fields aren't shadowed in C++ static members or in member functions
8551 // with an explicit object parameter.
8552 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8553 return;
8554 }
8555 // Fields shadowed by constructor parameters are a special case. Usually
8556 // the constructor initializes the field with the parameter.
8557 if (isa<CXXConstructorDecl>(NewDC))
8558 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8559 // Remember that this was shadowed so we can either warn about its
8560 // modification or its existence depending on warning settings.
8561 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8562 return;
8563 }
8564 }
8565
8566 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8567 if (shadowedVar->isExternC()) {
8568 // For shadowing external vars, make sure that we point to the global
8569 // declaration, not a locally scoped extern declaration.
8570 for (auto *I : shadowedVar->redecls())
8571 if (I->isFileVarDecl()) {
8572 ShadowedDecl = I;
8573 break;
8574 }
8575 }
8576
8577 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8578
8579 unsigned WarningDiag = diag::warn_decl_shadow;
8580 SourceLocation CaptureLoc;
8581 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8582 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8583 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8584 // Handle both VarDecl and BindingDecl in lambda contexts
8585 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8586 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8587 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8588 if (RD->getLambdaCaptureDefault() == LCD_None) {
8589 // Try to avoid warnings for lambdas with an explicit capture
8590 // list. Warn only when the lambda captures the shadowed decl
8591 // explicitly.
8592 CaptureLoc = getCaptureLocation(LSI, VD);
8593 if (CaptureLoc.isInvalid())
8594 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8595 } else {
8596 // Remember that this was shadowed so we can avoid the warning if
8597 // the shadowed decl isn't captured and the warning settings allow
8598 // it.
8599 cast<LambdaScopeInfo>(getCurFunction())
8600 ->ShadowingDecls.push_back({D, VD});
8601 return;
8602 }
8603 }
8604 if (isa<FieldDecl>(ShadowedDecl)) {
8605 // If lambda can capture this, then emit default shadowing warning,
8606 // Otherwise it is not really a shadowing case since field is not
8607 // available in lambda's body.
8608 // At this point we don't know that lambda can capture this, so
8609 // remember that this was shadowed and delay until we know.
8610 cast<LambdaScopeInfo>(getCurFunction())
8611 ->ShadowingDecls.push_back({D, ShadowedDecl});
8612 return;
8613 }
8614 }
8615 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8616 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8617 bool HasLocalStorage = false;
8618 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8619 HasLocalStorage = VD->hasLocalStorage();
8620 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8621 HasLocalStorage =
8622 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8623
8624 if (HasLocalStorage) {
8625 // A variable can't shadow a local variable or binding in an enclosing
8626 // scope, if they are separated by a non-capturing declaration
8627 // context.
8628 for (DeclContext *ParentDC = NewDC;
8629 ParentDC && !ParentDC->Equals(OldDC);
8630 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8631 // Only block literals, captured statements, and lambda expressions
8632 // can capture; other scopes don't.
8633 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8634 !isLambdaCallOperator(ParentDC))
8635 return;
8636 }
8637 }
8638 }
8639 }
8640 }
8641
8642 // Never warn about shadowing a placeholder variable.
8643 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8644 return;
8645
8646 // Only warn about certain kinds of shadowing for class members.
8647 if (NewDC) {
8648 // In particular, don't warn about shadowing non-class members.
8649 if (NewDC->isRecord() && !OldDC->isRecord())
8650 return;
8651
8652 // Skip shadowing check if we're in a class scope, dealing with an enum
8653 // constant in a different context.
8654 DeclContext *ReDC = NewDC->getRedeclContext();
8655 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8656 return;
8657
8658 // TODO: should we warn about static data members shadowing
8659 // static data members from base classes?
8660
8661 // TODO: don't diagnose for inaccessible shadowed members.
8662 // This is hard to do perfectly because we might friend the
8663 // shadowing context, but that's just a false negative.
8664 }
8665
8666 DeclarationName Name = R.getLookupName();
8667
8668 // Emit warning and note.
8669 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8670 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8671 if (!CaptureLoc.isInvalid())
8672 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8673 << Name << /*explicitly*/ 1;
8674 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8675 }
8676
8677 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8678 for (const auto &Shadow : LSI->ShadowingDecls) {
8679 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8680 // Try to avoid the warning when the shadowed decl isn't captured.
8681 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8682 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8683 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8684 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8685 Diag(Shadow.VD->getLocation(),
8686 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8687 : diag::warn_decl_shadow)
8688 << Shadow.VD->getDeclName()
8689 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8690 if (CaptureLoc.isValid())
8691 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8692 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8693 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8694 } else if (isa<FieldDecl>(ShadowedDecl)) {
8695 Diag(Shadow.VD->getLocation(),
8696 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8697 : diag::warn_decl_shadow_uncaptured_local)
8698 << Shadow.VD->getDeclName()
8699 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8700 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8701 }
8702 }
8703 }
8704
8705 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8706 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8707 return;
8708
8709 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8710 Sema::LookupOrdinaryName,
8711 RedeclarationKind::ForVisibleRedeclaration);
8712 LookupName(R, S);
8713 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8714 CheckShadow(D, ShadowedDecl, R);
8715 }
8716
8717 /// Check if 'E', which is an expression that is about to be modified, refers
8718 /// to a constructor parameter that shadows a field.
8719 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8720 // Quickly ignore expressions that can't be shadowing ctor parameters.
8721 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8722 return;
8723 E = E->IgnoreParenImpCasts();
8724 auto *DRE = dyn_cast<DeclRefExpr>(E);
8725 if (!DRE)
8726 return;
8727 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8728 auto I = ShadowingDecls.find(D);
8729 if (I == ShadowingDecls.end())
8730 return;
8731 const NamedDecl *ShadowedDecl = I->second;
8732 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8733 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8734 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8735 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8736
8737 // Avoid issuing multiple warnings about the same decl.
8738 ShadowingDecls.erase(I);
8739 }
8740
8741 /// Check for conflict between this global or extern "C" declaration and
8742 /// previous global or extern "C" declarations. This is only used in C++.
8743 template<typename T>
8744 static bool checkGlobalOrExternCConflict(
8745 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8746 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8747 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8748
8749 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8750 // The common case: this global doesn't conflict with any extern "C"
8751 // declaration.
8752 return false;
8753 }
8754
8755 if (Prev) {
8756 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8757 // Both the old and new declarations have C language linkage. This is a
8758 // redeclaration.
8759 Previous.clear();
8760 Previous.addDecl(Prev);
8761 return true;
8762 }
8763
8764 // This is a global, non-extern "C" declaration, and there is a previous
8765 // non-global extern "C" declaration. Diagnose if this is a variable
8766 // declaration.
8767 if (!isa<VarDecl>(ND))
8768 return false;
8769 } else {
8770 // The declaration is extern "C". Check for any declaration in the
8771 // translation unit which might conflict.
8772 if (IsGlobal) {
8773 // We have already performed the lookup into the translation unit.
8774 IsGlobal = false;
8775 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8776 I != E; ++I) {
8777 if (isa<VarDecl>(*I)) {
8778 Prev = *I;
8779 break;
8780 }
8781 }
8782 } else {
8783 DeclContext::lookup_result R =
8784 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8785 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8786 I != E; ++I) {
8787 if (isa<VarDecl>(*I)) {
8788 Prev = *I;
8789 break;
8790 }
8791 // FIXME: If we have any other entity with this name in global scope,
8792 // the declaration is ill-formed, but that is a defect: it breaks the
8793 // 'stat' hack, for instance. Only variables can have mangled name
8794 // clashes with extern "C" declarations, so only they deserve a
8795 // diagnostic.
8796 }
8797 }
8798
8799 if (!Prev)
8800 return false;
8801 }
8802
8803 // Use the first declaration's location to ensure we point at something which
8804 // is lexically inside an extern "C" linkage-spec.
8805 assert(Prev && "should have found a previous declaration to diagnose");
8806 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8807 Prev = FD->getFirstDecl();
8808 else
8809 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8810
8811 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8812 << IsGlobal << ND;
8813 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8814 << IsGlobal;
8815 return false;
8816 }
8817
8818 /// Apply special rules for handling extern "C" declarations. Returns \c true
8819 /// if we have found that this is a redeclaration of some prior entity.
8820 ///
8821 /// Per C++ [dcl.link]p6:
8822 /// Two declarations [for a function or variable] with C language linkage
8823 /// with the same name that appear in different scopes refer to the same
8824 /// [entity]. An entity with C language linkage shall not be declared with
8825 /// the same name as an entity in global scope.
8826 template<typename T>
8827 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8828 LookupResult &Previous) {
8829 if (!S.getLangOpts().CPlusPlus) {
8830 // In C, when declaring a global variable, look for a corresponding 'extern'
8831 // variable declared in function scope. We don't need this in C++, because
8832 // we find local extern decls in the surrounding file-scope DeclContext.
8833 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8834 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8835 Previous.clear();
8836 Previous.addDecl(Prev);
8837 return true;
8838 }
8839 }
8840 return false;
8841 }
8842
8843 // A declaration in the translation unit can conflict with an extern "C"
8844 // declaration.
8845 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8846 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8847
8848 // An extern "C" declaration can conflict with a declaration in the
8849 // translation unit or can be a redeclaration of an extern "C" declaration
8850 // in another scope.
8851 if (isIncompleteDeclExternC(S,ND))
8852 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8853
8854 // Neither global nor extern "C": nothing to do.
8855 return false;
8856 }
8857
8858 static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8859 QualType T) {
8860 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8861 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8862 // any of its members, even recursively, shall not have an atomic type, or a
8863 // variably modified type, or a type that is volatile or restrict qualified.
8864 if (CanonT->isVariablyModifiedType()) {
8865 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8866 return true;
8867 }
8868
8869 // Arrays are qualified by their element type, so get the base type (this
8870 // works on non-arrays as well).
8871 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8872
8873 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8874 CanonT.isRestrictQualified()) {
8875 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8876 return true;
8877 }
8878
8879 if (CanonT->isRecordType()) {
8880 const RecordDecl *RD = CanonT->getAsRecordDecl();
8881 if (!RD->isInvalidDecl() &&
8882 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8883 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8884 }))
8885 return true;
8886 }
8887
8888 return false;
8889 }
8890
8891 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8892 // If the decl is already known invalid, don't check it.
8893 if (NewVD->isInvalidDecl())
8894 return;
8895
8896 QualType T = NewVD->getType();
8897
8898 // Defer checking an 'auto' type until its initializer is attached.
8899 if (T->isUndeducedType())
8900 return;
8901
8902 if (NewVD->hasAttrs())
8903 CheckAlignasUnderalignment(NewVD);
8904
8905 if (T->isObjCObjectType()) {
8906 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8907 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8908 T = Context.getObjCObjectPointerType(T);
8909 NewVD->setType(T);
8910 }
8911
8912 // Emit an error if an address space was applied to decl with local storage.
8913 // This includes arrays of objects with address space qualifiers, but not
8914 // automatic variables that point to other address spaces.
8915 // ISO/IEC TR 18037 S5.1.2
8916 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8917 T.getAddressSpace() != LangAS::Default) {
8918 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8919 NewVD->setInvalidDecl();
8920 return;
8921 }
8922
8923 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8924 // scope.
8925 if (getLangOpts().OpenCLVersion == 120 &&
8926 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8927 getLangOpts()) &&
8928 NewVD->isStaticLocal()) {
8929 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8930 NewVD->setInvalidDecl();
8931 return;
8932 }
8933
8934 if (getLangOpts().OpenCL) {
8935 if (!diagnoseOpenCLTypes(*this, NewVD))
8936 return;
8937
8938 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8939 if (NewVD->hasAttr<BlocksAttr>()) {
8940 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8941 return;
8942 }
8943
8944 if (T->isBlockPointerType()) {
8945 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8946 // can't use 'extern' storage class.
8947 if (!T.isConstQualified()) {
8948 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8949 << 0 /*const*/;
8950 NewVD->setInvalidDecl();
8951 return;
8952 }
8953 if (NewVD->hasExternalStorage()) {
8954 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8955 NewVD->setInvalidDecl();
8956 return;
8957 }
8958 }
8959
8960 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8961 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8962 NewVD->hasExternalStorage()) {
8963 if (!T->isSamplerT() && !T->isDependentType() &&
8964 !(T.getAddressSpace() == LangAS::opencl_constant ||
8965 (T.getAddressSpace() == LangAS::opencl_global &&
8966 getOpenCLOptions().areProgramScopeVariablesSupported(
8967 getLangOpts())))) {
8968 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8969 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8970 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8971 << Scope << "global or constant";
8972 else
8973 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8974 << Scope << "constant";
8975 NewVD->setInvalidDecl();
8976 return;
8977 }
8978 } else {
8979 if (T.getAddressSpace() == LangAS::opencl_global) {
8980 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8981 << 1 /*is any function*/ << "global";
8982 NewVD->setInvalidDecl();
8983 return;
8984 }
8985 if (T.getAddressSpace() == LangAS::opencl_constant ||
8986 T.getAddressSpace() == LangAS::opencl_local) {
8987 FunctionDecl *FD = getCurFunctionDecl();
8988 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8989 // in functions.
8990 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8991 if (T.getAddressSpace() == LangAS::opencl_constant)
8992 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8993 << 0 /*non-kernel only*/ << "constant";
8994 else
8995 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8996 << 0 /*non-kernel only*/ << "local";
8997 NewVD->setInvalidDecl();
8998 return;
8999 }
9000 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9001 // in the outermost scope of a kernel function.
9002 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9003 if (!getCurScope()->isFunctionScope()) {
9004 if (T.getAddressSpace() == LangAS::opencl_constant)
9005 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9006 << "constant";
9007 else
9008 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9009 << "local";
9010 NewVD->setInvalidDecl();
9011 return;
9012 }
9013 }
9014 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9015 // If we are parsing a template we didn't deduce an addr
9016 // space yet.
9017 T.getAddressSpace() != LangAS::Default) {
9018 // Do not allow other address spaces on automatic variable.
9019 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9020 NewVD->setInvalidDecl();
9021 return;
9022 }
9023 }
9024 }
9025
9026 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9027 && !NewVD->hasAttr<BlocksAttr>()) {
9028 if (getLangOpts().getGC() != LangOptions::NonGC)
9029 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9030 else {
9031 assert(!getLangOpts().ObjCAutoRefCount);
9032 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9033 }
9034 }
9035
9036 // WebAssembly tables must be static with a zero length and can't be
9037 // declared within functions.
9038 if (T->isWebAssemblyTableType()) {
9039 if (getCurScope()->getParent()) { // Parent is null at top-level
9040 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9041 NewVD->setInvalidDecl();
9042 return;
9043 }
9044 if (NewVD->getStorageClass() != SC_Static) {
9045 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9046 NewVD->setInvalidDecl();
9047 return;
9048 }
9049 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9050 if (!ATy || ATy->getZExtSize() != 0) {
9051 Diag(NewVD->getLocation(),
9052 diag::err_typecheck_wasm_table_must_have_zero_length);
9053 NewVD->setInvalidDecl();
9054 return;
9055 }
9056 }
9057
9058 // zero sized static arrays are not allowed in HIP device functions
9059 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9060 if (FunctionDecl *FD = getCurFunctionDecl();
9061 FD &&
9062 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9063 if (const ConstantArrayType *ArrayT =
9064 getASTContext().getAsConstantArrayType(T);
9065 ArrayT && ArrayT->isZeroSize()) {
9066 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9067 }
9068 }
9069 }
9070
9071 bool isVM = T->isVariablyModifiedType();
9072 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9073 NewVD->hasAttr<BlocksAttr>())
9074 setFunctionHasBranchProtectedScope();
9075
9076 if ((isVM && NewVD->hasLinkage()) ||
9077 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9078 bool SizeIsNegative;
9079 llvm::APSInt Oversized;
9080 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9081 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9082 QualType FixedT;
9083 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9084 FixedT = FixedTInfo->getType();
9085 else if (FixedTInfo) {
9086 // Type and type-as-written are canonically different. We need to fix up
9087 // both types separately.
9088 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9089 Oversized);
9090 }
9091 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9092 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9093 // FIXME: This won't give the correct result for
9094 // int a[10][n];
9095 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9096
9097 if (NewVD->isFileVarDecl())
9098 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9099 << SizeRange;
9100 else if (NewVD->isStaticLocal())
9101 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9102 << SizeRange;
9103 else
9104 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9105 << SizeRange;
9106 NewVD->setInvalidDecl();
9107 return;
9108 }
9109
9110 if (!FixedTInfo) {
9111 if (NewVD->isFileVarDecl())
9112 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9113 else
9114 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9115 NewVD->setInvalidDecl();
9116 return;
9117 }
9118
9119 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9120 NewVD->setType(FixedT);
9121 NewVD->setTypeSourceInfo(FixedTInfo);
9122 }
9123
9124 if (T->isVoidType()) {
9125 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9126 // of objects and functions.
9127 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9128 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9129 << T;
9130 NewVD->setInvalidDecl();
9131 return;
9132 }
9133 }
9134
9135 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9136 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9137 NewVD->setInvalidDecl();
9138 return;
9139 }
9140
9141 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9142 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9143 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9144 NewVD->setInvalidDecl();
9145 return;
9146 }
9147
9148 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9149 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9150 NewVD->setInvalidDecl();
9151 return;
9152 }
9153
9154 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9155 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9156 NewVD->setInvalidDecl();
9157 return;
9158 }
9159
9160 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9161 !T->isDependentType() &&
9162 RequireLiteralType(NewVD->getLocation(), T,
9163 diag::err_constexpr_var_non_literal)) {
9164 NewVD->setInvalidDecl();
9165 return;
9166 }
9167
9168 // PPC MMA non-pointer types are not allowed as non-local variable types.
9169 if (Context.getTargetInfo().getTriple().isPPC64() &&
9170 !NewVD->isLocalVarDecl() &&
9171 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9172 NewVD->setInvalidDecl();
9173 return;
9174 }
9175
9176 // Check that SVE types are only used in functions with SVE available.
9177 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9178 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
9179 llvm::StringMap<bool> CallerFeatureMap;
9180 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9181 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9182 CallerFeatureMap)) {
9183 NewVD->setInvalidDecl();
9184 return;
9185 }
9186 }
9187
9188 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9189 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
9190 llvm::StringMap<bool> CallerFeatureMap;
9191 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9192 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
9193 CallerFeatureMap);
9194 }
9195 }
9196
9197 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9198 CheckVariableDeclarationType(NewVD);
9199
9200 // If the decl is already known invalid, don't check it.
9201 if (NewVD->isInvalidDecl())
9202 return false;
9203
9204 // If we did not find anything by this name, look for a non-visible
9205 // extern "C" declaration with the same name.
9206 if (Previous.empty() &&
9207 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
9208 Previous.setShadowed();
9209
9210 if (!Previous.empty()) {
9211 MergeVarDecl(NewVD, Previous);
9212 return true;
9213 }
9214 return false;
9215 }
9216
9217 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9218 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9219
9220 // Look for methods in base classes that this method might override.
9221 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9222 /*DetectVirtual=*/false);
9223 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9224 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9225 DeclarationName Name = MD->getDeclName();
9226
9227 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9228 // We really want to find the base class destructor here.
9229 Name = Context.DeclarationNames.getCXXDestructorName(
9230 Context.getCanonicalTagType(BaseRecord));
9231 }
9232
9233 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9234 CXXMethodDecl *BaseMD =
9235 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9236 if (!BaseMD || !BaseMD->isVirtual() ||
9237 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9238 /*ConsiderCudaAttrs=*/true))
9239 continue;
9240 if (!CheckExplicitObjectOverride(MD, BaseMD))
9241 continue;
9242 if (Overridden.insert(BaseMD).second) {
9243 MD->addOverriddenMethod(BaseMD);
9244 CheckOverridingFunctionReturnType(MD, BaseMD);
9245 CheckOverridingFunctionAttributes(MD, BaseMD);
9246 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
9247 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
9248 }
9249
9250 // A method can only override one function from each base class. We
9251 // don't track indirectly overridden methods from bases of bases.
9252 return true;
9253 }
9254
9255 return false;
9256 };
9257
9258 DC->lookupInBases(VisitBase, Paths);
9259 return !Overridden.empty();
9260 }
9261
9262 namespace {
9263 // Struct for holding all of the extra arguments needed by
9264 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9265 struct ActOnFDArgs {
9266 Scope *S;
9267 Declarator &D;
9268 MultiTemplateParamsArg TemplateParamLists;
9269 bool AddToScope;
9270 };
9271 } // end anonymous namespace
9272
9273 namespace {
9274
9275 // Callback to only accept typo corrections that have a non-zero edit distance.
9276 // Also only accept corrections that have the same parent decl.
9277 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9278 public:
9279 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9280 CXXRecordDecl *Parent)
9281 : Context(Context), OriginalFD(TypoFD),
9282 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9283
9284 bool ValidateCandidate(const TypoCorrection &candidate) override {
9285 if (candidate.getEditDistance() == 0)
9286 return false;
9287
9288 SmallVector<unsigned, 1> MismatchedParams;
9289 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9290 CDeclEnd = candidate.end();
9291 CDecl != CDeclEnd; ++CDecl) {
9292 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9293
9294 if (FD && !FD->hasBody() &&
9295 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9296 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9297 CXXRecordDecl *Parent = MD->getParent();
9298 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9299 return true;
9300 } else if (!ExpectedParent) {
9301 return true;
9302 }
9303 }
9304 }
9305
9306 return false;
9307 }
9308
9309 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9310 return std::make_unique<DifferentNameValidatorCCC>(*this);
9311 }
9312
9313 private:
9314 ASTContext &Context;
9315 FunctionDecl *OriginalFD;
9316 CXXRecordDecl *ExpectedParent;
9317 };
9318
9319 } // end anonymous namespace
9320
9321 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9322 TypoCorrectedFunctionDefinitions.insert(F);
9323 }
9324
9325 /// Generate diagnostics for an invalid function redeclaration.
9326 ///
9327 /// This routine handles generating the diagnostic messages for an invalid
9328 /// function redeclaration, including finding possible similar declarations
9329 /// or performing typo correction if there are no previous declarations with
9330 /// the same name.
9331 ///
9332 /// Returns a NamedDecl iff typo correction was performed and substituting in
9333 /// the new declaration name does not cause new errors.
9334 static NamedDecl *DiagnoseInvalidRedeclaration(
9335 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9336 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9337 DeclarationName Name = NewFD->getDeclName();
9338 DeclContext *NewDC = NewFD->getDeclContext();
9339 SmallVector<unsigned, 1> MismatchedParams;
9340 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9341 TypoCorrection Correction;
9342 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9343 unsigned DiagMsg =
9344 IsLocalFriend ? diag::err_no_matching_local_friend :
9345 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9346 diag::err_member_decl_does_not_match;
9347 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9348 IsLocalFriend ? Sema::LookupLocalFriendName
9349 : Sema::LookupOrdinaryName,
9350 RedeclarationKind::ForVisibleRedeclaration);
9351
9352 NewFD->setInvalidDecl();
9353 if (IsLocalFriend)
9354 SemaRef.LookupName(Prev, S);
9355 else
9356 SemaRef.LookupQualifiedName(Prev, NewDC);
9357 assert(!Prev.isAmbiguous() &&
9358 "Cannot have an ambiguity in previous-declaration lookup");
9359 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9360 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9361 MD ? MD->getParent() : nullptr);
9362 if (!Prev.empty()) {
9363 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9364 Func != FuncEnd; ++Func) {
9365 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9366 if (FD &&
9367 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9368 // Add 1 to the index so that 0 can mean the mismatch didn't
9369 // involve a parameter
9370 unsigned ParamNum =
9371 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9372 NearMatches.push_back(std::make_pair(FD, ParamNum));
9373 }
9374 }
9375 // If the qualified name lookup yielded nothing, try typo correction
9376 } else if ((Correction = SemaRef.CorrectTypo(
9377 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9378 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9379 CorrectTypoKind::ErrorRecovery,
9380 IsLocalFriend ? nullptr : NewDC))) {
9381 // Set up everything for the call to ActOnFunctionDeclarator
9382 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9383 ExtraArgs.D.getIdentifierLoc());
9384 Previous.clear();
9385 Previous.setLookupName(Correction.getCorrection());
9386 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9387 CDeclEnd = Correction.end();
9388 CDecl != CDeclEnd; ++CDecl) {
9389 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9390 if (FD && !FD->hasBody() &&
9391 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9392 Previous.addDecl(FD);
9393 }
9394 }
9395 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9396
9397 NamedDecl *Result;
9398 // Retry building the function declaration with the new previous
9399 // declarations, and with errors suppressed.
9400 {
9401 // Trap errors.
9402 Sema::SFINAETrap Trap(SemaRef);
9403
9404 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9405 // pieces need to verify the typo-corrected C++ declaration and hopefully
9406 // eliminate the need for the parameter pack ExtraArgs.
9407 Result = SemaRef.ActOnFunctionDeclarator(
9408 ExtraArgs.S, ExtraArgs.D,
9409 Correction.getCorrectionDecl()->getDeclContext(),
9410 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9411 ExtraArgs.AddToScope);
9412
9413 if (Trap.hasErrorOccurred())
9414 Result = nullptr;
9415 }
9416
9417 if (Result) {
9418 // Determine which correction we picked.
9419 Decl *Canonical = Result->getCanonicalDecl();
9420 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9421 I != E; ++I)
9422 if ((*I)->getCanonicalDecl() == Canonical)
9423 Correction.setCorrectionDecl(*I);
9424
9425 // Let Sema know about the correction.
9426 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9427 SemaRef.diagnoseTypo(
9428 Correction,
9429 SemaRef.PDiag(IsLocalFriend
9430 ? diag::err_no_matching_local_friend_suggest
9431 : diag::err_member_decl_does_not_match_suggest)
9432 << Name << NewDC << IsDefinition);
9433 return Result;
9434 }
9435
9436 // Pretend the typo correction never occurred
9437 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9438 ExtraArgs.D.getIdentifierLoc());
9439 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9440 Previous.clear();
9441 Previous.setLookupName(Name);
9442 }
9443
9444 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9445 << Name << NewDC << IsDefinition << NewFD->getLocation();
9446
9447 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9448 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9449 CXXRecordDecl *RD = NewMD->getParent();
9450 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9451 << RD->getName() << RD->getLocation();
9452 }
9453
9454 bool NewFDisConst = NewMD && NewMD->isConst();
9455
9456 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9457 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9458 NearMatch != NearMatchEnd; ++NearMatch) {
9459 FunctionDecl *FD = NearMatch->first;
9460 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9461 bool FDisConst = MD && MD->isConst();
9462 bool IsMember = MD || !IsLocalFriend;
9463
9464 // FIXME: These notes are poorly worded for the local friend case.
9465 if (unsigned Idx = NearMatch->second) {
9466 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9467 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9468 if (Loc.isInvalid()) Loc = FD->getLocation();
9469 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9470 : diag::note_local_decl_close_param_match)
9471 << Idx << FDParam->getType()
9472 << NewFD->getParamDecl(Idx - 1)->getType();
9473 } else if (FDisConst != NewFDisConst) {
9474 auto DB = SemaRef.Diag(FD->getLocation(),
9475 diag::note_member_def_close_const_match)
9476 << NewFDisConst << FD->getSourceRange().getEnd();
9477 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9478 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9479 " const");
9480 else if (FTI.hasMethodTypeQualifiers() &&
9481 FTI.getConstQualifierLoc().isValid())
9482 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9483 } else {
9484 SemaRef.Diag(FD->getLocation(),
9485 IsMember ? diag::note_member_def_close_match
9486 : diag::note_local_decl_close_match);
9487 }
9488 }
9489 return nullptr;
9490 }
9491
9492 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9493 switch (D.getDeclSpec().getStorageClassSpec()) {
9494 default: llvm_unreachable("Unknown storage class!");
9495 case DeclSpec::SCS_auto:
9496 case DeclSpec::SCS_register:
9497 case DeclSpec::SCS_mutable:
9498 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9499 diag::err_typecheck_sclass_func);
9500 D.getMutableDeclSpec().ClearStorageClassSpecs();
9501 D.setInvalidType();
9502 break;
9503 case DeclSpec::SCS_unspecified: break;
9504 case DeclSpec::SCS_extern:
9505 if (D.getDeclSpec().isExternInLinkageSpec())
9506 return SC_None;
9507 return SC_Extern;
9508 case DeclSpec::SCS_static: {
9509 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9510 // C99 6.7.1p5:
9511 // The declaration of an identifier for a function that has
9512 // block scope shall have no explicit storage-class specifier
9513 // other than extern
9514 // See also (C++ [dcl.stc]p4).
9515 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9516 diag::err_static_block_func);
9517 break;
9518 } else
9519 return SC_Static;
9520 }
9521 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9522 }
9523
9524 // No explicit storage class has already been returned
9525 return SC_None;
9526 }
9527
9528 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9529 DeclContext *DC, QualType &R,
9530 TypeSourceInfo *TInfo,
9531 StorageClass SC,
9532 bool &IsVirtualOkay) {
9533 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9534 DeclarationName Name = NameInfo.getName();
9535
9536 FunctionDecl *NewFD = nullptr;
9537 bool isInline = D.getDeclSpec().isInlineSpecified();
9538
9539 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9540 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9541 (SemaRef.getLangOpts().C23 &&
9542 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9543
9544 if (SemaRef.getLangOpts().C23)
9545 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9546 diag::err_c23_constexpr_not_variable);
9547 else
9548 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9549 diag::err_constexpr_wrong_decl_kind)
9550 << static_cast<int>(ConstexprKind);
9551 ConstexprKind = ConstexprSpecKind::Unspecified;
9552 D.getMutableDeclSpec().ClearConstexprSpec();
9553 }
9554
9555 if (!SemaRef.getLangOpts().CPlusPlus) {
9556 // Determine whether the function was written with a prototype. This is
9557 // true when:
9558 // - there is a prototype in the declarator, or
9559 // - the type R of the function is some kind of typedef or other non-
9560 // attributed reference to a type name (which eventually refers to a
9561 // function type). Note, we can't always look at the adjusted type to
9562 // check this case because attributes may cause a non-function
9563 // declarator to still have a function type. e.g.,
9564 // typedef void func(int a);
9565 // __attribute__((noreturn)) func other_func; // This has a prototype
9566 bool HasPrototype =
9567 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9568 (D.getDeclSpec().isTypeRep() &&
9569 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9570 ->isFunctionProtoType()) ||
9571 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9572 assert(
9573 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9574 "Strict prototypes are required");
9575
9576 NewFD = FunctionDecl::Create(
9577 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9578 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9579 ConstexprSpecKind::Unspecified,
9580 /*TrailingRequiresClause=*/{});
9581 if (D.isInvalidType())
9582 NewFD->setInvalidDecl();
9583
9584 return NewFD;
9585 }
9586
9587 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9588 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9589
9590 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9591
9592 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9593 // This is a C++ constructor declaration.
9594 assert(DC->isRecord() &&
9595 "Constructors can only be declared in a member context");
9596
9597 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9598 return CXXConstructorDecl::Create(
9599 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9600 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9601 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9602 InheritedConstructor(), TrailingRequiresClause);
9603
9604 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9605 // This is a C++ destructor declaration.
9606 if (DC->isRecord()) {
9607 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9608 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9609 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9610 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9611 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9612 /*isImplicitlyDeclared=*/false, ConstexprKind,
9613 TrailingRequiresClause);
9614 // User defined destructors start as not selected if the class definition is still
9615 // not done.
9616 if (Record->isBeingDefined())
9617 NewDD->setIneligibleOrNotSelected(true);
9618
9619 // If the destructor needs an implicit exception specification, set it
9620 // now. FIXME: It'd be nice to be able to create the right type to start
9621 // with, but the type needs to reference the destructor declaration.
9622 if (SemaRef.getLangOpts().CPlusPlus11)
9623 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9624
9625 IsVirtualOkay = true;
9626 return NewDD;
9627
9628 } else {
9629 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9630 D.setInvalidType();
9631
9632 // Create a FunctionDecl to satisfy the function definition parsing
9633 // code path.
9634 return FunctionDecl::Create(
9635 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9636 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9637 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9638 }
9639
9640 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9641 if (!DC->isRecord()) {
9642 SemaRef.Diag(D.getIdentifierLoc(),
9643 diag::err_conv_function_not_member);
9644 return nullptr;
9645 }
9646
9647 SemaRef.CheckConversionDeclarator(D, R, SC);
9648 if (D.isInvalidType())
9649 return nullptr;
9650
9651 IsVirtualOkay = true;
9652 return CXXConversionDecl::Create(
9653 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9654 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9655 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9656 TrailingRequiresClause);
9657
9658 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9659 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9660 return nullptr;
9661 return CXXDeductionGuideDecl::Create(
9662 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9663 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9664 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9665 } else if (DC->isRecord()) {
9666 // If the name of the function is the same as the name of the record,
9667 // then this must be an invalid constructor that has a return type.
9668 // (The parser checks for a return type and makes the declarator a
9669 // constructor if it has no return type).
9670 if (Name.getAsIdentifierInfo() &&
9671 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9672 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9673 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9674 << SourceRange(D.getIdentifierLoc());
9675 return nullptr;
9676 }
9677
9678 // This is a C++ method declaration.
9679 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9680 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9681 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9682 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9683 IsVirtualOkay = !Ret->isStatic();
9684 return Ret;
9685 } else {
9686 bool isFriend =
9687 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9688 if (!isFriend && SemaRef.CurContext->isRecord())
9689 return nullptr;
9690
9691 // Determine whether the function was written with a
9692 // prototype. This true when:
9693 // - we're in C++ (where every function has a prototype),
9694 return FunctionDecl::Create(
9695 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9696 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9697 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9698 }
9699 }
9700
9701 enum OpenCLParamType {
9702 ValidKernelParam,
9703 PtrPtrKernelParam,
9704 PtrKernelParam,
9705 InvalidAddrSpacePtrKernelParam,
9706 InvalidKernelParam,
9707 RecordKernelParam
9708 };
9709
9710 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9711 // Size dependent types are just typedefs to normal integer types
9712 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9713 // integers other than by their names.
9714 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9715
9716 // Remove typedefs one by one until we reach a typedef
9717 // for a size dependent type.
9718 QualType DesugaredTy = Ty;
9719 do {
9720 ArrayRef<StringRef> Names(SizeTypeNames);
9721 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9722 if (Names.end() != Match)
9723 return true;
9724
9725 Ty = DesugaredTy;
9726 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9727 } while (DesugaredTy != Ty);
9728
9729 return false;
9730 }
9731
9732 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9733 if (PT->isDependentType())
9734 return InvalidKernelParam;
9735
9736 if (PT->isPointerOrReferenceType()) {
9737 QualType PointeeType = PT->getPointeeType();
9738 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9739 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9740 PointeeType.getAddressSpace() == LangAS::Default)
9741 return InvalidAddrSpacePtrKernelParam;
9742
9743 if (PointeeType->isPointerType()) {
9744 // This is a pointer to pointer parameter.
9745 // Recursively check inner type.
9746 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9747 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9748 ParamKind == InvalidKernelParam)
9749 return ParamKind;
9750
9751 // OpenCL v3.0 s6.11.a:
9752 // A restriction to pass pointers to pointers only applies to OpenCL C
9753 // v1.2 or below.
9754 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9755 return ValidKernelParam;
9756
9757 return PtrPtrKernelParam;
9758 }
9759
9760 // C++ for OpenCL v1.0 s2.4:
9761 // Moreover the types used in parameters of the kernel functions must be:
9762 // Standard layout types for pointer parameters. The same applies to
9763 // reference if an implementation supports them in kernel parameters.
9764 if (S.getLangOpts().OpenCLCPlusPlus &&
9765 !S.getOpenCLOptions().isAvailableOption(
9766 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9767 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9768 bool IsStandardLayoutType = true;
9769 if (CXXRec) {
9770 // If template type is not ODR-used its definition is only available
9771 // in the template definition not its instantiation.
9772 // FIXME: This logic doesn't work for types that depend on template
9773 // parameter (PR58590).
9774 if (!CXXRec->hasDefinition())
9775 CXXRec = CXXRec->getTemplateInstantiationPattern();
9776 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9777 IsStandardLayoutType = false;
9778 }
9779 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9780 !IsStandardLayoutType)
9781 return InvalidKernelParam;
9782 }
9783
9784 // OpenCL v1.2 s6.9.p:
9785 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9786 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9787 return ValidKernelParam;
9788
9789 return PtrKernelParam;
9790 }
9791
9792 // OpenCL v1.2 s6.9.k:
9793 // Arguments to kernel functions in a program cannot be declared with the
9794 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9795 // uintptr_t or a struct and/or union that contain fields declared to be one
9796 // of these built-in scalar types.
9797 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9798 return InvalidKernelParam;
9799
9800 if (PT->isImageType())
9801 return PtrKernelParam;
9802
9803 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9804 return InvalidKernelParam;
9805
9806 // OpenCL extension spec v1.2 s9.5:
9807 // This extension adds support for half scalar and vector types as built-in
9808 // types that can be used for arithmetic operations, conversions etc.
9809 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9810 PT->isHalfType())
9811 return InvalidKernelParam;
9812
9813 // Look into an array argument to check if it has a forbidden type.
9814 if (PT->isArrayType()) {
9815 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9816 // Call ourself to check an underlying type of an array. Since the
9817 // getPointeeOrArrayElementType returns an innermost type which is not an
9818 // array, this recursive call only happens once.
9819 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9820 }
9821
9822 // C++ for OpenCL v1.0 s2.4:
9823 // Moreover the types used in parameters of the kernel functions must be:
9824 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9825 // types) for parameters passed by value;
9826 if (S.getLangOpts().OpenCLCPlusPlus &&
9827 !S.getOpenCLOptions().isAvailableOption(
9828 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9829 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9830 return InvalidKernelParam;
9831
9832 if (PT->isRecordType())
9833 return RecordKernelParam;
9834
9835 return ValidKernelParam;
9836 }
9837
9838 static void checkIsValidOpenCLKernelParameter(
9839 Sema &S,
9840 Declarator &D,
9841 ParmVarDecl *Param,
9842 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9843 QualType PT = Param->getType();
9844
9845 // Cache the valid types we encounter to avoid rechecking structs that are
9846 // used again
9847 if (ValidTypes.count(PT.getTypePtr()))
9848 return;
9849
9850 switch (getOpenCLKernelParameterType(S, PT)) {
9851 case PtrPtrKernelParam:
9852 // OpenCL v3.0 s6.11.a:
9853 // A kernel function argument cannot be declared as a pointer to a pointer
9854 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9855 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9856 D.setInvalidType();
9857 return;
9858
9859 case InvalidAddrSpacePtrKernelParam:
9860 // OpenCL v1.0 s6.5:
9861 // __kernel function arguments declared to be a pointer of a type can point
9862 // to one of the following address spaces only : __global, __local or
9863 // __constant.
9864 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9865 D.setInvalidType();
9866 return;
9867
9868 // OpenCL v1.2 s6.9.k:
9869 // Arguments to kernel functions in a program cannot be declared with the
9870 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9871 // uintptr_t or a struct and/or union that contain fields declared to be
9872 // one of these built-in scalar types.
9873
9874 case InvalidKernelParam:
9875 // OpenCL v1.2 s6.8 n:
9876 // A kernel function argument cannot be declared
9877 // of event_t type.
9878 // Do not diagnose half type since it is diagnosed as invalid argument
9879 // type for any function elsewhere.
9880 if (!PT->isHalfType()) {
9881 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9882
9883 // Explain what typedefs are involved.
9884 const TypedefType *Typedef = nullptr;
9885 while ((Typedef = PT->getAs<TypedefType>())) {
9886 SourceLocation Loc = Typedef->getDecl()->getLocation();
9887 // SourceLocation may be invalid for a built-in type.
9888 if (Loc.isValid())
9889 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9890 PT = Typedef->desugar();
9891 }
9892 }
9893
9894 D.setInvalidType();
9895 return;
9896
9897 case PtrKernelParam:
9898 case ValidKernelParam:
9899 ValidTypes.insert(PT.getTypePtr());
9900 return;
9901
9902 case RecordKernelParam:
9903 break;
9904 }
9905
9906 // Track nested structs we will inspect
9907 SmallVector<const Decl *, 4> VisitStack;
9908
9909 // Track where we are in the nested structs. Items will migrate from
9910 // VisitStack to HistoryStack as we do the DFS for bad field.
9911 SmallVector<const FieldDecl *, 4> HistoryStack;
9912 HistoryStack.push_back(nullptr);
9913
9914 // At this point we already handled everything except of a RecordType.
9915 assert(PT->isRecordType() && "Unexpected type.");
9916 const auto *PD = PT->castAsRecordDecl();
9917 VisitStack.push_back(PD);
9918 assert(VisitStack.back() && "First decl null?");
9919
9920 do {
9921 const Decl *Next = VisitStack.pop_back_val();
9922 if (!Next) {
9923 assert(!HistoryStack.empty());
9924 // Found a marker, we have gone up a level
9925 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9926 ValidTypes.insert(Hist->getType().getTypePtr());
9927
9928 continue;
9929 }
9930
9931 // Adds everything except the original parameter declaration (which is not a
9932 // field itself) to the history stack.
9933 const RecordDecl *RD;
9934 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9935 HistoryStack.push_back(Field);
9936
9937 QualType FieldTy = Field->getType();
9938 // Other field types (known to be valid or invalid) are handled while we
9939 // walk around RecordDecl::fields().
9940 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9941 "Unexpected type.");
9942 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9943
9944 RD = FieldRecTy->castAsRecordDecl();
9945 } else {
9946 RD = cast<RecordDecl>(Next);
9947 }
9948
9949 // Add a null marker so we know when we've gone back up a level
9950 VisitStack.push_back(nullptr);
9951
9952 for (const auto *FD : RD->fields()) {
9953 QualType QT = FD->getType();
9954
9955 if (ValidTypes.count(QT.getTypePtr()))
9956 continue;
9957
9958 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9959 if (ParamType == ValidKernelParam)
9960 continue;
9961
9962 if (ParamType == RecordKernelParam) {
9963 VisitStack.push_back(FD);
9964 continue;
9965 }
9966
9967 // OpenCL v1.2 s6.9.p:
9968 // Arguments to kernel functions that are declared to be a struct or union
9969 // do not allow OpenCL objects to be passed as elements of the struct or
9970 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9971 // of SVM.
9972 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9973 ParamType == InvalidAddrSpacePtrKernelParam) {
9974 S.Diag(Param->getLocation(),
9975 diag::err_record_with_pointers_kernel_param)
9976 << PT->isUnionType()
9977 << PT;
9978 } else {
9979 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9980 }
9981
9982 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9983 << PD->getDeclName();
9984
9985 // We have an error, now let's go back up through history and show where
9986 // the offending field came from
9987 for (ArrayRef<const FieldDecl *>::const_iterator
9988 I = HistoryStack.begin() + 1,
9989 E = HistoryStack.end();
9990 I != E; ++I) {
9991 const FieldDecl *OuterField = *I;
9992 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9993 << OuterField->getType();
9994 }
9995
9996 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9997 << QT->isPointerType()
9998 << QT;
9999 D.setInvalidType();
10000 return;
10001 }
10002 } while (!VisitStack.empty());
10003 }
10004
10005 /// Find the DeclContext in which a tag is implicitly declared if we see an
10006 /// elaborated type specifier in the specified context, and lookup finds
10007 /// nothing.
10008 static DeclContext *getTagInjectionContext(DeclContext *DC) {
10009 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10010 DC = DC->getParent();
10011 return DC;
10012 }
10013
10014 /// Find the Scope in which a tag is implicitly declared if we see an
10015 /// elaborated type specifier in the specified context, and lookup finds
10016 /// nothing.
10017 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10018 while (S->isClassScope() ||
10019 (LangOpts.CPlusPlus &&
10020 S->isFunctionPrototypeScope()) ||
10021 ((S->getFlags() & Scope::DeclScope) == 0) ||
10022 (S->getEntity() && S->getEntity()->isTransparentContext()))
10023 S = S->getParent();
10024 return S;
10025 }
10026
10027 /// Determine whether a declaration matches a known function in namespace std.
10028 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10029 unsigned BuiltinID) {
10030 switch (BuiltinID) {
10031 case Builtin::BI__GetExceptionInfo:
10032 // No type checking whatsoever.
10033 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10034
10035 case Builtin::BIaddressof:
10036 case Builtin::BI__addressof:
10037 case Builtin::BIforward:
10038 case Builtin::BIforward_like:
10039 case Builtin::BImove:
10040 case Builtin::BImove_if_noexcept:
10041 case Builtin::BIas_const: {
10042 // Ensure that we don't treat the algorithm
10043 // OutputIt std::move(InputIt, InputIt, OutputIt)
10044 // as the builtin std::move.
10045 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10046 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10047 }
10048
10049 default:
10050 return false;
10051 }
10052 }
10053
10054 NamedDecl*
10055 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10056 TypeSourceInfo *TInfo, LookupResult &Previous,
10057 MultiTemplateParamsArg TemplateParamListsRef,
10058 bool &AddToScope) {
10059 QualType R = TInfo->getType();
10060
10061 assert(R->isFunctionType());
10062 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10063 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10064
10065 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10066 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10067 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10068 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10069 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10070 TemplateParamLists.back() = Invented;
10071 else
10072 TemplateParamLists.push_back(Invented);
10073 }
10074
10075 // TODO: consider using NameInfo for diagnostic.
10076 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10077 DeclarationName Name = NameInfo.getName();
10078 StorageClass SC = getFunctionStorageClass(*this, D);
10079
10080 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10081 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
10082 diag::err_invalid_thread)
10083 << DeclSpec::getSpecifierName(TSCS);
10084
10085 if (D.isFirstDeclarationOfMember())
10086 adjustMemberFunctionCC(
10087 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10088 D.isCtorOrDtor(), D.getIdentifierLoc());
10089
10090 bool isFriend = false;
10091 FunctionTemplateDecl *FunctionTemplate = nullptr;
10092 bool isMemberSpecialization = false;
10093 bool isFunctionTemplateSpecialization = false;
10094
10095 bool HasExplicitTemplateArgs = false;
10096 TemplateArgumentListInfo TemplateArgs;
10097
10098 bool isVirtualOkay = false;
10099
10100 DeclContext *OriginalDC = DC;
10101 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10102
10103 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10104 isVirtualOkay);
10105 if (!NewFD) return nullptr;
10106
10107 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10108 NewFD->setTopLevelDeclInObjCContainer();
10109
10110 // Set the lexical context. If this is a function-scope declaration, or has a
10111 // C++ scope specifier, or is the object of a friend declaration, the lexical
10112 // context will be different from the semantic context.
10113 NewFD->setLexicalDeclContext(CurContext);
10114
10115 if (IsLocalExternDecl)
10116 NewFD->setLocalExternDecl();
10117
10118 if (getLangOpts().CPlusPlus) {
10119 // The rules for implicit inlines changed in C++20 for methods and friends
10120 // with an in-class definition (when such a definition is not attached to
10121 // the global module). This does not affect declarations that are already
10122 // inline (whether explicitly or implicitly by being declared constexpr,
10123 // consteval, etc).
10124 // FIXME: We need a better way to separate C++ standard and clang modules.
10125 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10126 !NewFD->getOwningModule() ||
10127 NewFD->isFromGlobalModule() ||
10128 NewFD->getOwningModule()->isHeaderLikeModule();
10129 bool isInline = D.getDeclSpec().isInlineSpecified();
10130 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10131 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10132 isFriend = D.getDeclSpec().isFriendSpecified();
10133 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10134 // Pre-C++20 [class.friend]p5
10135 // A function can be defined in a friend declaration of a
10136 // class . . . . Such a function is implicitly inline.
10137 // Post C++20 [class.friend]p7
10138 // Such a function is implicitly an inline function if it is attached
10139 // to the global module.
10140 NewFD->setImplicitlyInline();
10141 }
10142
10143 // If this is a method defined in an __interface, and is not a constructor
10144 // or an overloaded operator, then set the pure flag (isVirtual will already
10145 // return true).
10146 if (const CXXRecordDecl *Parent =
10147 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10148 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10149 NewFD->setIsPureVirtual(true);
10150
10151 // C++ [class.union]p2
10152 // A union can have member functions, but not virtual functions.
10153 if (isVirtual && Parent->isUnion()) {
10154 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10155 NewFD->setInvalidDecl();
10156 }
10157 if ((Parent->isClass() || Parent->isStruct()) &&
10158 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10159 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10160 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10161 if (auto *Def = Parent->getDefinition())
10162 Def->setInitMethod(true);
10163 }
10164 }
10165
10166 SetNestedNameSpecifier(*this, NewFD, D);
10167 isMemberSpecialization = false;
10168 isFunctionTemplateSpecialization = false;
10169 if (D.isInvalidType())
10170 NewFD->setInvalidDecl();
10171
10172 // Match up the template parameter lists with the scope specifier, then
10173 // determine whether we have a template or a template specialization.
10174 bool Invalid = false;
10175 TemplateIdAnnotation *TemplateId =
10176 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10177 ? D.getName().TemplateId
10178 : nullptr;
10179 TemplateParameterList *TemplateParams =
10180 MatchTemplateParametersToScopeSpecifier(
10181 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
10182 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10183 isMemberSpecialization, Invalid);
10184 if (TemplateParams) {
10185 // Check that we can declare a template here.
10186 if (CheckTemplateDeclScope(S, TemplateParams))
10187 NewFD->setInvalidDecl();
10188
10189 if (TemplateParams->size() > 0) {
10190 // This is a function template
10191
10192 // A destructor cannot be a template.
10193 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10194 Diag(NewFD->getLocation(), diag::err_destructor_template);
10195 NewFD->setInvalidDecl();
10196 // Function template with explicit template arguments.
10197 } else if (TemplateId) {
10198 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10199 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10200 NewFD->setInvalidDecl();
10201 }
10202
10203 // If we're adding a template to a dependent context, we may need to
10204 // rebuilding some of the types used within the template parameter list,
10205 // now that we know what the current instantiation is.
10206 if (DC->isDependentContext()) {
10207 ContextRAII SavedContext(*this, DC);
10208 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
10209 Invalid = true;
10210 }
10211
10212 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
10213 NewFD->getLocation(),
10214 Name, TemplateParams,
10215 NewFD);
10216 FunctionTemplate->setLexicalDeclContext(CurContext);
10217 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10218
10219 // For source fidelity, store the other template param lists.
10220 if (TemplateParamLists.size() > 1) {
10221 NewFD->setTemplateParameterListsInfo(Context,
10222 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10223 .drop_back(1));
10224 }
10225 } else {
10226 // This is a function template specialization.
10227 isFunctionTemplateSpecialization = true;
10228 // For source fidelity, store all the template param lists.
10229 if (TemplateParamLists.size() > 0)
10230 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10231
10232 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10233 if (isFriend) {
10234 // We want to remove the "template<>", found here.
10235 SourceRange RemoveRange = TemplateParams->getSourceRange();
10236
10237 // If we remove the template<> and the name is not a
10238 // template-id, we're actually silently creating a problem:
10239 // the friend declaration will refer to an untemplated decl,
10240 // and clearly the user wants a template specialization. So
10241 // we need to insert '<>' after the name.
10242 SourceLocation InsertLoc;
10243 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10244 InsertLoc = D.getName().getSourceRange().getEnd();
10245 InsertLoc = getLocForEndOfToken(InsertLoc);
10246 }
10247
10248 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10249 << Name << RemoveRange
10250 << FixItHint::CreateRemoval(RemoveRange)
10251 << FixItHint::CreateInsertion(InsertLoc, "<>");
10252 Invalid = true;
10253
10254 // Recover by faking up an empty template argument list.
10255 HasExplicitTemplateArgs = true;
10256 TemplateArgs.setLAngleLoc(InsertLoc);
10257 TemplateArgs.setRAngleLoc(InsertLoc);
10258 }
10259 }
10260 } else {
10261 // Check that we can declare a template here.
10262 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10263 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10264 NewFD->setInvalidDecl();
10265
10266 // All template param lists were matched against the scope specifier:
10267 // this is NOT (an explicit specialization of) a template.
10268 if (TemplateParamLists.size() > 0)
10269 // For source fidelity, store all the template param lists.
10270 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10271
10272 // "friend void foo<>(int);" is an implicit specialization decl.
10273 if (isFriend && TemplateId)
10274 isFunctionTemplateSpecialization = true;
10275 }
10276
10277 // If this is a function template specialization and the unqualified-id of
10278 // the declarator-id is a template-id, convert the template argument list
10279 // into our AST format and check for unexpanded packs.
10280 if (isFunctionTemplateSpecialization && TemplateId) {
10281 HasExplicitTemplateArgs = true;
10282
10283 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10284 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10285 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10286 TemplateId->NumArgs);
10287 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10288
10289 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10290 // declaration of a function template partial specialization? Should we
10291 // consider the unexpanded pack context to be a partial specialization?
10292 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10293 if (DiagnoseUnexpandedParameterPack(
10294 ArgLoc, isFriend ? UPPC_FriendDeclaration
10295 : UPPC_ExplicitSpecialization))
10296 NewFD->setInvalidDecl();
10297 }
10298 }
10299
10300 if (Invalid) {
10301 NewFD->setInvalidDecl();
10302 if (FunctionTemplate)
10303 FunctionTemplate->setInvalidDecl();
10304 }
10305
10306 // C++ [dcl.fct.spec]p5:
10307 // The virtual specifier shall only be used in declarations of
10308 // nonstatic class member functions that appear within a
10309 // member-specification of a class declaration; see 10.3.
10310 //
10311 if (isVirtual && !NewFD->isInvalidDecl()) {
10312 if (!isVirtualOkay) {
10313 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10314 diag::err_virtual_non_function);
10315 } else if (!CurContext->isRecord()) {
10316 // 'virtual' was specified outside of the class.
10317 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10318 diag::err_virtual_out_of_class)
10319 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10320 } else if (NewFD->getDescribedFunctionTemplate()) {
10321 // C++ [temp.mem]p3:
10322 // A member function template shall not be virtual.
10323 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10324 diag::err_virtual_member_function_template)
10325 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10326 } else {
10327 // Okay: Add virtual to the method.
10328 NewFD->setVirtualAsWritten(true);
10329 }
10330
10331 if (getLangOpts().CPlusPlus14 &&
10332 NewFD->getReturnType()->isUndeducedType())
10333 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10334 }
10335
10336 // C++ [dcl.fct.spec]p3:
10337 // The inline specifier shall not appear on a block scope function
10338 // declaration.
10339 if (isInline && !NewFD->isInvalidDecl()) {
10340 if (CurContext->isFunctionOrMethod()) {
10341 // 'inline' is not allowed on block scope function declaration.
10342 Diag(D.getDeclSpec().getInlineSpecLoc(),
10343 diag::err_inline_declaration_block_scope) << Name
10344 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10345 }
10346 }
10347
10348 // C++ [dcl.fct.spec]p6:
10349 // The explicit specifier shall be used only in the declaration of a
10350 // constructor or conversion function within its class definition;
10351 // see 12.3.1 and 12.3.2.
10352 if (hasExplicit && !NewFD->isInvalidDecl() &&
10353 !isa<CXXDeductionGuideDecl>(NewFD)) {
10354 if (!CurContext->isRecord()) {
10355 // 'explicit' was specified outside of the class.
10356 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10357 diag::err_explicit_out_of_class)
10358 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10359 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10360 !isa<CXXConversionDecl>(NewFD)) {
10361 // 'explicit' was specified on a function that wasn't a constructor
10362 // or conversion function.
10363 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10364 diag::err_explicit_non_ctor_or_conv_function)
10365 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10366 }
10367 }
10368
10369 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10370 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10371 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10372 // are implicitly inline.
10373 NewFD->setImplicitlyInline();
10374
10375 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10376 // be either constructors or to return a literal type. Therefore,
10377 // destructors cannot be declared constexpr.
10378 if (isa<CXXDestructorDecl>(NewFD) &&
10379 (!getLangOpts().CPlusPlus20 ||
10380 ConstexprKind == ConstexprSpecKind::Consteval)) {
10381 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10382 << static_cast<int>(ConstexprKind);
10383 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10384 ? ConstexprSpecKind::Unspecified
10385 : ConstexprSpecKind::Constexpr);
10386 }
10387 // C++20 [dcl.constexpr]p2: An allocation function, or a
10388 // deallocation function shall not be declared with the consteval
10389 // specifier.
10390 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10391 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10392 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10393 diag::err_invalid_consteval_decl_kind)
10394 << NewFD;
10395 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10396 }
10397 }
10398
10399 // If __module_private__ was specified, mark the function accordingly.
10400 if (D.getDeclSpec().isModulePrivateSpecified()) {
10401 if (isFunctionTemplateSpecialization) {
10402 SourceLocation ModulePrivateLoc
10403 = D.getDeclSpec().getModulePrivateSpecLoc();
10404 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10405 << 0
10406 << FixItHint::CreateRemoval(ModulePrivateLoc);
10407 } else {
10408 NewFD->setModulePrivate();
10409 if (FunctionTemplate)
10410 FunctionTemplate->setModulePrivate();
10411 }
10412 }
10413
10414 if (isFriend) {
10415 if (FunctionTemplate) {
10416 FunctionTemplate->setObjectOfFriendDecl();
10417 FunctionTemplate->setAccess(AS_public);
10418 }
10419 NewFD->setObjectOfFriendDecl();
10420 NewFD->setAccess(AS_public);
10421 }
10422
10423 // If a function is defined as defaulted or deleted, mark it as such now.
10424 // We'll do the relevant checks on defaulted / deleted functions later.
10425 switch (D.getFunctionDefinitionKind()) {
10426 case FunctionDefinitionKind::Declaration:
10427 case FunctionDefinitionKind::Definition:
10428 break;
10429
10430 case FunctionDefinitionKind::Defaulted:
10431 NewFD->setDefaulted();
10432 break;
10433
10434 case FunctionDefinitionKind::Deleted:
10435 NewFD->setDeletedAsWritten();
10436 break;
10437 }
10438
10439 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10440 D.isFunctionDefinition()) {
10441 // Pre C++20 [class.mfct]p2:
10442 // A member function may be defined (8.4) in its class definition, in
10443 // which case it is an inline member function (7.1.2)
10444 // Post C++20 [class.mfct]p1:
10445 // If a member function is attached to the global module and is defined
10446 // in its class definition, it is inline.
10447 NewFD->setImplicitlyInline();
10448 }
10449
10450 if (!isFriend && SC != SC_None) {
10451 // C++ [temp.expl.spec]p2:
10452 // The declaration in an explicit-specialization shall not be an
10453 // export-declaration. An explicit specialization shall not use a
10454 // storage-class-specifier other than thread_local.
10455 //
10456 // We diagnose friend declarations with storage-class-specifiers
10457 // elsewhere.
10458 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10459 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10460 diag::ext_explicit_specialization_storage_class)
10461 << FixItHint::CreateRemoval(
10462 D.getDeclSpec().getStorageClassSpecLoc());
10463 }
10464
10465 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10466 assert(isa<CXXMethodDecl>(NewFD) &&
10467 "Out-of-line member function should be a CXXMethodDecl");
10468 // C++ [class.static]p1:
10469 // A data or function member of a class may be declared static
10470 // in a class definition, in which case it is a static member of
10471 // the class.
10472
10473 // Complain about the 'static' specifier if it's on an out-of-line
10474 // member function definition.
10475
10476 // MSVC permits the use of a 'static' storage specifier on an
10477 // out-of-line member function template declaration and class member
10478 // template declaration (MSVC versions before 2015), warn about this.
10479 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10480 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10481 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10482 (getLangOpts().MSVCCompat &&
10483 NewFD->getDescribedFunctionTemplate()))
10484 ? diag::ext_static_out_of_line
10485 : diag::err_static_out_of_line)
10486 << FixItHint::CreateRemoval(
10487 D.getDeclSpec().getStorageClassSpecLoc());
10488 }
10489 }
10490
10491 // C++11 [except.spec]p15:
10492 // A deallocation function with no exception-specification is treated
10493 // as if it were specified with noexcept(true).
10494 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10495 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10496 !FPT->hasExceptionSpec())
10497 NewFD->setType(Context.getFunctionType(
10498 FPT->getReturnType(), FPT->getParamTypes(),
10499 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10500
10501 // C++20 [dcl.inline]/7
10502 // If an inline function or variable that is attached to a named module
10503 // is declared in a definition domain, it shall be defined in that
10504 // domain.
10505 // So, if the current declaration does not have a definition, we must
10506 // check at the end of the TU (or when the PMF starts) to see that we
10507 // have a definition at that point.
10508 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10509 NewFD->isInNamedModule()) {
10510 PendingInlineFuncDecls.insert(NewFD);
10511 }
10512 }
10513
10514 // Filter out previous declarations that don't match the scope.
10515 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10516 D.getCXXScopeSpec().isNotEmpty() ||
10517 isMemberSpecialization ||
10518 isFunctionTemplateSpecialization);
10519
10520 // Handle GNU asm-label extension (encoded as an attribute).
10521 if (Expr *E = D.getAsmLabel()) {
10522 // The parser guarantees this is a string.
10523 StringLiteral *SE = cast<StringLiteral>(E);
10524 NewFD->addAttr(
10525 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10526 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10527 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10528 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10529 if (I != ExtnameUndeclaredIdentifiers.end()) {
10530 if (isDeclExternC(NewFD)) {
10531 NewFD->addAttr(I->second);
10532 ExtnameUndeclaredIdentifiers.erase(I);
10533 } else
10534 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10535 << /*Variable*/0 << NewFD;
10536 }
10537 }
10538
10539 // Copy the parameter declarations from the declarator D to the function
10540 // declaration NewFD, if they are available. First scavenge them into Params.
10541 SmallVector<ParmVarDecl*, 16> Params;
10542 unsigned FTIIdx;
10543 if (D.isFunctionDeclarator(FTIIdx)) {
10544 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10545
10546 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10547 // function that takes no arguments, not a function that takes a
10548 // single void argument.
10549 // We let through "const void" here because Sema::GetTypeForDeclarator
10550 // already checks for that case.
10551 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10552 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10553 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10554 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10555 Param->setDeclContext(NewFD);
10556 Params.push_back(Param);
10557
10558 if (Param->isInvalidDecl())
10559 NewFD->setInvalidDecl();
10560 }
10561 }
10562
10563 if (!getLangOpts().CPlusPlus) {
10564 // In C, find all the tag declarations from the prototype and move them
10565 // into the function DeclContext. Remove them from the surrounding tag
10566 // injection context of the function, which is typically but not always
10567 // the TU.
10568 DeclContext *PrototypeTagContext =
10569 getTagInjectionContext(NewFD->getLexicalDeclContext());
10570 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10571 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10572
10573 // We don't want to reparent enumerators. Look at their parent enum
10574 // instead.
10575 if (!TD) {
10576 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10577 TD = cast<EnumDecl>(ECD->getDeclContext());
10578 }
10579 if (!TD)
10580 continue;
10581 DeclContext *TagDC = TD->getLexicalDeclContext();
10582 if (!TagDC->containsDecl(TD))
10583 continue;
10584 TagDC->removeDecl(TD);
10585 TD->setDeclContext(NewFD);
10586 NewFD->addDecl(TD);
10587
10588 // Preserve the lexical DeclContext if it is not the surrounding tag
10589 // injection context of the FD. In this example, the semantic context of
10590 // E will be f and the lexical context will be S, while both the
10591 // semantic and lexical contexts of S will be f:
10592 // void f(struct S { enum E { a } f; } s);
10593 if (TagDC != PrototypeTagContext)
10594 TD->setLexicalDeclContext(TagDC);
10595 }
10596 }
10597 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10598 // When we're declaring a function with a typedef, typeof, etc as in the
10599 // following example, we'll need to synthesize (unnamed)
10600 // parameters for use in the declaration.
10601 //
10602 // @code
10603 // typedef void fn(int);
10604 // fn f;
10605 // @endcode
10606
10607 // Synthesize a parameter for each argument type.
10608 for (const auto &AI : FT->param_types()) {
10609 ParmVarDecl *Param =
10610 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10611 Param->setScopeInfo(0, Params.size());
10612 Params.push_back(Param);
10613 }
10614 } else {
10615 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10616 "Should not need args for typedef of non-prototype fn");
10617 }
10618
10619 // Finally, we know we have the right number of parameters, install them.
10620 NewFD->setParams(Params);
10621
10622 // If this declarator is a declaration and not a definition, its parameters
10623 // will not be pushed onto a scope chain. That means we will not issue any
10624 // reserved identifier warnings for the declaration, but we will for the
10625 // definition. Handle those here.
10626 if (!D.isFunctionDefinition()) {
10627 for (const ParmVarDecl *PVD : Params)
10628 warnOnReservedIdentifier(PVD);
10629 }
10630
10631 if (D.getDeclSpec().isNoreturnSpecified())
10632 NewFD->addAttr(
10633 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10634
10635 // Functions returning a variably modified type violate C99 6.7.5.2p2
10636 // because all functions have linkage.
10637 if (!NewFD->isInvalidDecl() &&
10638 NewFD->getReturnType()->isVariablyModifiedType()) {
10639 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10640 NewFD->setInvalidDecl();
10641 }
10642
10643 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10644 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10645 !NewFD->hasAttr<SectionAttr>())
10646 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10647 Context, PragmaClangTextSection.SectionName,
10648 PragmaClangTextSection.PragmaLocation));
10649
10650 // Apply an implicit SectionAttr if #pragma code_seg is active.
10651 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10652 !NewFD->hasAttr<SectionAttr>()) {
10653 NewFD->addAttr(SectionAttr::CreateImplicit(
10654 Context, CodeSegStack.CurrentValue->getString(),
10655 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10656 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10657 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10658 ASTContext::PSF_Read,
10659 NewFD))
10660 NewFD->dropAttr<SectionAttr>();
10661 }
10662
10663 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10664 // active.
10665 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10666 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10667 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10668 Context, PragmaClangTextSection.PragmaLocation));
10669
10670 // Apply an implicit CodeSegAttr from class declspec or
10671 // apply an implicit SectionAttr from #pragma code_seg if active.
10672 if (!NewFD->hasAttr<CodeSegAttr>()) {
10673 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10674 D.isFunctionDefinition())) {
10675 NewFD->addAttr(SAttr);
10676 }
10677 }
10678
10679 // Handle attributes.
10680 ProcessDeclAttributes(S, NewFD, D);
10681 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10682 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10683 !NewTVA->isDefaultVersion() &&
10684 !Context.getTargetInfo().hasFeature("fmv")) {
10685 // Don't add to scope fmv functions declarations if fmv disabled
10686 AddToScope = false;
10687 return NewFD;
10688 }
10689
10690 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10691 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10692 // type.
10693 //
10694 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10695 // type declaration will generate a compilation error.
10696 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10697 if (AddressSpace != LangAS::Default) {
10698 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10699 NewFD->setInvalidDecl();
10700 }
10701 }
10702
10703 if (!getLangOpts().CPlusPlus) {
10704 // Perform semantic checking on the function declaration.
10705 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10706 CheckMain(NewFD, D.getDeclSpec());
10707
10708 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10709 CheckMSVCRTEntryPoint(NewFD);
10710
10711 if (!NewFD->isInvalidDecl())
10712 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10713 isMemberSpecialization,
10714 D.isFunctionDefinition()));
10715 else if (!Previous.empty())
10716 // Recover gracefully from an invalid redeclaration.
10717 D.setRedeclaration(true);
10718 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10719 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10720 "previous declaration set still overloaded");
10721
10722 // Diagnose no-prototype function declarations with calling conventions that
10723 // don't support variadic calls. Only do this in C and do it after merging
10724 // possibly prototyped redeclarations.
10725 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10726 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10727 CallingConv CC = FT->getExtInfo().getCC();
10728 if (!supportsVariadicCall(CC)) {
10729 // Windows system headers sometimes accidentally use stdcall without
10730 // (void) parameters, so we relax this to a warning.
10731 int DiagID =
10732 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10733 Diag(NewFD->getLocation(), DiagID)
10734 << FunctionType::getNameForCallConv(CC);
10735 }
10736 }
10737
10738 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10739 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10740 checkNonTrivialCUnion(
10741 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10742 NonTrivialCUnionContext::FunctionReturn, NTCUK_Destruct | NTCUK_Copy);
10743 } else {
10744 // C++11 [replacement.functions]p3:
10745 // The program's definitions shall not be specified as inline.
10746 //
10747 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10748 //
10749 // Suppress the diagnostic if the function is __attribute__((used)), since
10750 // that forces an external definition to be emitted.
10751 if (D.getDeclSpec().isInlineSpecified() &&
10752 NewFD->isReplaceableGlobalAllocationFunction() &&
10753 !NewFD->hasAttr<UsedAttr>())
10754 Diag(D.getDeclSpec().getInlineSpecLoc(),
10755 diag::ext_operator_new_delete_declared_inline)
10756 << NewFD->getDeclName();
10757
10758 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10759 // C++20 [dcl.decl.general]p4:
10760 // The optional requires-clause in an init-declarator or
10761 // member-declarator shall be present only if the declarator declares a
10762 // templated function.
10763 //
10764 // C++20 [temp.pre]p8:
10765 // An entity is templated if it is
10766 // - a template,
10767 // - an entity defined or created in a templated entity,
10768 // - a member of a templated entity,
10769 // - an enumerator for an enumeration that is a templated entity, or
10770 // - the closure type of a lambda-expression appearing in the
10771 // declaration of a templated entity.
10772 //
10773 // [Note 6: A local class, a local or block variable, or a friend
10774 // function defined in a templated entity is a templated entity.
10775 // — end note]
10776 //
10777 // A templated function is a function template or a function that is
10778 // templated. A templated class is a class template or a class that is
10779 // templated. A templated variable is a variable template or a variable
10780 // that is templated.
10781 if (!FunctionTemplate) {
10782 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10783 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10784 // An explicit specialization shall not have a trailing
10785 // requires-clause unless it declares a function template.
10786 //
10787 // Since a friend function template specialization cannot be
10788 // definition, and since a non-template friend declaration with a
10789 // trailing requires-clause must be a definition, we diagnose
10790 // friend function template specializations with trailing
10791 // requires-clauses on the same path as explicit specializations
10792 // even though they aren't necessarily prohibited by the same
10793 // language rule.
10794 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10795 << isFriend;
10796 } else if (isFriend && NewFD->isTemplated() &&
10797 !D.isFunctionDefinition()) {
10798 // C++ [temp.friend]p9:
10799 // A non-template friend declaration with a requires-clause shall be
10800 // a definition.
10801 Diag(NewFD->getBeginLoc(),
10802 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10803 NewFD->setInvalidDecl();
10804 } else if (!NewFD->isTemplated() ||
10805 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10806 Diag(TRC->getBeginLoc(),
10807 diag::err_constrained_non_templated_function);
10808 }
10809 }
10810 }
10811
10812 // We do not add HD attributes to specializations here because
10813 // they may have different constexpr-ness compared to their
10814 // templates and, after maybeAddHostDeviceAttrs() is applied,
10815 // may end up with different effective targets. Instead, a
10816 // specialization inherits its target attributes from its template
10817 // in the CheckFunctionTemplateSpecialization() call below.
10818 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10819 CUDA().maybeAddHostDeviceAttrs(NewFD, Previous);
10820
10821 // Handle explicit specializations of function templates
10822 // and friend function declarations with an explicit
10823 // template argument list.
10824 if (isFunctionTemplateSpecialization) {
10825 bool isDependentSpecialization = false;
10826 if (isFriend) {
10827 // For friend function specializations, this is a dependent
10828 // specialization if its semantic context is dependent, its
10829 // type is dependent, or if its template-id is dependent.
10830 isDependentSpecialization =
10831 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10832 (HasExplicitTemplateArgs &&
10833 TemplateSpecializationType::
10834 anyInstantiationDependentTemplateArguments(
10835 TemplateArgs.arguments()));
10836 assert((!isDependentSpecialization ||
10837 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10838 "dependent friend function specialization without template "
10839 "args");
10840 } else {
10841 // For class-scope explicit specializations of function templates,
10842 // if the lexical context is dependent, then the specialization
10843 // is dependent.
10844 isDependentSpecialization =
10845 CurContext->isRecord() && CurContext->isDependentContext();
10846 }
10847
10848 TemplateArgumentListInfo *ExplicitTemplateArgs =
10849 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10850 if (isDependentSpecialization) {
10851 // If it's a dependent specialization, it may not be possible
10852 // to determine the primary template (for explicit specializations)
10853 // or befriended declaration (for friends) until the enclosing
10854 // template is instantiated. In such cases, we store the declarations
10855 // found by name lookup and defer resolution until instantiation.
10856 if (CheckDependentFunctionTemplateSpecialization(
10857 NewFD, ExplicitTemplateArgs, Previous))
10858 NewFD->setInvalidDecl();
10859 } else if (!NewFD->isInvalidDecl()) {
10860 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10861 Previous))
10862 NewFD->setInvalidDecl();
10863 }
10864 } else if (isMemberSpecialization && !FunctionTemplate) {
10865 if (CheckMemberSpecialization(NewFD, Previous))
10866 NewFD->setInvalidDecl();
10867 }
10868
10869 // Perform semantic checking on the function declaration.
10870 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10871 CheckMain(NewFD, D.getDeclSpec());
10872
10873 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10874 CheckMSVCRTEntryPoint(NewFD);
10875
10876 if (!NewFD->isInvalidDecl())
10877 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10878 isMemberSpecialization,
10879 D.isFunctionDefinition()));
10880 else if (!Previous.empty())
10881 // Recover gracefully from an invalid redeclaration.
10882 D.setRedeclaration(true);
10883
10884 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10885 !D.isRedeclaration() ||
10886 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10887 "previous declaration set still overloaded");
10888
10889 NamedDecl *PrincipalDecl = (FunctionTemplate
10890 ? cast<NamedDecl>(FunctionTemplate)
10891 : NewFD);
10892
10893 if (isFriend && NewFD->getPreviousDecl()) {
10894 AccessSpecifier Access = AS_public;
10895 if (!NewFD->isInvalidDecl())
10896 Access = NewFD->getPreviousDecl()->getAccess();
10897
10898 NewFD->setAccess(Access);
10899 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10900 }
10901
10902 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10903 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10904 PrincipalDecl->setNonMemberOperator();
10905
10906 // If we have a function template, check the template parameter
10907 // list. This will check and merge default template arguments.
10908 if (FunctionTemplate) {
10909 FunctionTemplateDecl *PrevTemplate =
10910 FunctionTemplate->getPreviousDecl();
10911 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10912 PrevTemplate ? PrevTemplate->getTemplateParameters()
10913 : nullptr,
10914 D.getDeclSpec().isFriendSpecified()
10915 ? (D.isFunctionDefinition()
10916 ? TPC_FriendFunctionTemplateDefinition
10917 : TPC_FriendFunctionTemplate)
10918 : (D.getCXXScopeSpec().isSet() &&
10919 DC && DC->isRecord() &&
10920 DC->isDependentContext())
10921 ? TPC_ClassTemplateMember
10922 : TPC_FunctionTemplate);
10923 }
10924
10925 if (NewFD->isInvalidDecl()) {
10926 // Ignore all the rest of this.
10927 } else if (!D.isRedeclaration()) {
10928 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10929 AddToScope };
10930 // Fake up an access specifier if it's supposed to be a class member.
10931 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10932 NewFD->setAccess(AS_public);
10933
10934 // Qualified decls generally require a previous declaration.
10935 if (D.getCXXScopeSpec().isSet()) {
10936 // ...with the major exception of templated-scope or
10937 // dependent-scope friend declarations.
10938
10939 // TODO: we currently also suppress this check in dependent
10940 // contexts because (1) the parameter depth will be off when
10941 // matching friend templates and (2) we might actually be
10942 // selecting a friend based on a dependent factor. But there
10943 // are situations where these conditions don't apply and we
10944 // can actually do this check immediately.
10945 //
10946 // Unless the scope is dependent, it's always an error if qualified
10947 // redeclaration lookup found nothing at all. Diagnose that now;
10948 // nothing will diagnose that error later.
10949 if (isFriend &&
10950 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10951 (!Previous.empty() && CurContext->isDependentContext()))) {
10952 // ignore these
10953 } else if (NewFD->isCPUDispatchMultiVersion() ||
10954 NewFD->isCPUSpecificMultiVersion()) {
10955 // ignore this, we allow the redeclaration behavior here to create new
10956 // versions of the function.
10957 } else {
10958 // The user tried to provide an out-of-line definition for a
10959 // function that is a member of a class or namespace, but there
10960 // was no such member function declared (C++ [class.mfct]p2,
10961 // C++ [namespace.memdef]p2). For example:
10962 //
10963 // class X {
10964 // void f() const;
10965 // };
10966 //
10967 // void X::f() { } // ill-formed
10968 //
10969 // Complain about this problem, and attempt to suggest close
10970 // matches (e.g., those that differ only in cv-qualifiers and
10971 // whether the parameter types are references).
10972
10973 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10974 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10975 AddToScope = ExtraArgs.AddToScope;
10976 return Result;
10977 }
10978 }
10979
10980 // Unqualified local friend declarations are required to resolve
10981 // to something.
10982 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10983 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10984 *this, Previous, NewFD, ExtraArgs, true, S)) {
10985 AddToScope = ExtraArgs.AddToScope;
10986 return Result;
10987 }
10988 }
10989 } else if (!D.isFunctionDefinition() &&
10990 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10991 !isFriend && !isFunctionTemplateSpecialization &&
10992 !isMemberSpecialization) {
10993 // An out-of-line member function declaration must also be a
10994 // definition (C++ [class.mfct]p2).
10995 // Note that this is not the case for explicit specializations of
10996 // function templates or member functions of class templates, per
10997 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10998 // extension for compatibility with old SWIG code which likes to
10999 // generate them.
11000 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11001 << D.getCXXScopeSpec().getRange();
11002 }
11003 }
11004
11005 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11006 // Any top level function could potentially be specified as an entry.
11007 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11008 HLSL().ActOnTopLevelFunction(NewFD);
11009
11010 if (NewFD->hasAttr<HLSLShaderAttr>())
11011 HLSL().CheckEntryPoint(NewFD);
11012 }
11013
11014 // If this is the first declaration of a library builtin function, add
11015 // attributes as appropriate.
11016 if (!D.isRedeclaration()) {
11017 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11018 if (unsigned BuiltinID = II->getBuiltinID()) {
11019 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11020 if (!InStdNamespace &&
11021 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11022 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11023 // Validate the type matches unless this builtin is specified as
11024 // matching regardless of its declared type.
11025 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11026 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11027 } else {
11028 ASTContext::GetBuiltinTypeError Error;
11029 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11030 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11031
11032 if (!Error && !BuiltinType.isNull() &&
11033 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11034 NewFD->getType(), BuiltinType))
11035 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11036 }
11037 }
11038 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11039 isStdBuiltin(Context, NewFD, BuiltinID)) {
11040 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11041 }
11042 }
11043 }
11044 }
11045
11046 ProcessPragmaWeak(S, NewFD);
11047 checkAttributesAfterMerging(*this, *NewFD);
11048
11049 AddKnownFunctionAttributes(NewFD);
11050
11051 if (NewFD->hasAttr<OverloadableAttr>() &&
11052 !NewFD->getType()->getAs<FunctionProtoType>()) {
11053 Diag(NewFD->getLocation(),
11054 diag::err_attribute_overloadable_no_prototype)
11055 << NewFD;
11056 NewFD->dropAttr<OverloadableAttr>();
11057 }
11058
11059 // If there's a #pragma GCC visibility in scope, and this isn't a class
11060 // member, set the visibility of this function.
11061 if (!DC->isRecord() && NewFD->isExternallyVisible())
11062 AddPushedVisibilityAttribute(NewFD);
11063
11064 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11065 // marking the function.
11066 ObjC().AddCFAuditedAttribute(NewFD);
11067
11068 // If this is a function definition, check if we have to apply any
11069 // attributes (i.e. optnone and no_builtin) due to a pragma.
11070 if (D.isFunctionDefinition()) {
11071 AddRangeBasedOptnone(NewFD);
11072 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
11073 AddSectionMSAllocText(NewFD);
11074 ModifyFnAttributesMSPragmaOptimize(NewFD);
11075 }
11076
11077 // If this is the first declaration of an extern C variable, update
11078 // the map of such variables.
11079 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11080 isIncompleteDeclExternC(*this, NewFD))
11081 RegisterLocallyScopedExternCDecl(NewFD, S);
11082
11083 // Set this FunctionDecl's range up to the right paren.
11084 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11085
11086 if (D.isRedeclaration() && !Previous.empty()) {
11087 NamedDecl *Prev = Previous.getRepresentativeDecl();
11088 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11089 isMemberSpecialization ||
11090 isFunctionTemplateSpecialization,
11091 D.isFunctionDefinition());
11092 }
11093
11094 if (getLangOpts().CUDA) {
11095 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11096 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11097 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11098 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11099 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11100 << CUDA().getConfigureFuncName();
11101 Context.setcudaConfigureCallDecl(NewFD);
11102 }
11103 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11104 !NewFD->isInvalidDecl() &&
11105 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11106 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11107 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11108 << CUDA().getConfigureFuncName();
11109 Context.setcudaGetParameterBufferDecl(NewFD);
11110 }
11111 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11112 !NewFD->isInvalidDecl() &&
11113 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11114 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11115 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11116 << CUDA().getConfigureFuncName();
11117 Context.setcudaLaunchDeviceDecl(NewFD);
11118 }
11119 }
11120 }
11121
11122 MarkUnusedFileScopedDecl(NewFD);
11123
11124 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11125 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11126 if (SC == SC_Static) {
11127 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11128 D.setInvalidType();
11129 }
11130
11131 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11132 if (!NewFD->getReturnType()->isVoidType()) {
11133 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11134 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11135 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11136 : FixItHint());
11137 D.setInvalidType();
11138 }
11139
11140 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11141 for (auto *Param : NewFD->parameters())
11142 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11143
11144 if (getLangOpts().OpenCLCPlusPlus) {
11145 if (DC->isRecord()) {
11146 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11147 D.setInvalidType();
11148 }
11149 if (FunctionTemplate) {
11150 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11151 D.setInvalidType();
11152 }
11153 }
11154 }
11155
11156 if (getLangOpts().CPlusPlus) {
11157 // Precalculate whether this is a friend function template with a constraint
11158 // that depends on an enclosing template, per [temp.friend]p9.
11159 if (isFriend && FunctionTemplate &&
11160 FriendConstraintsDependOnEnclosingTemplate(NewFD)) {
11161 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11162
11163 // C++ [temp.friend]p9:
11164 // A friend function template with a constraint that depends on a
11165 // template parameter from an enclosing template shall be a definition.
11166 if (!D.isFunctionDefinition()) {
11167 Diag(NewFD->getBeginLoc(),
11168 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11169 NewFD->setInvalidDecl();
11170 }
11171 }
11172
11173 if (FunctionTemplate) {
11174 if (NewFD->isInvalidDecl())
11175 FunctionTemplate->setInvalidDecl();
11176 return FunctionTemplate;
11177 }
11178
11179 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11180 CompleteMemberSpecialization(NewFD, Previous);
11181 }
11182
11183 for (const ParmVarDecl *Param : NewFD->parameters()) {
11184 QualType PT = Param->getType();
11185
11186 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11187 // types.
11188 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11189 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11190 QualType ElemTy = PipeTy->getElementType();
11191 if (ElemTy->isPointerOrReferenceType()) {
11192 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11193 D.setInvalidType();
11194 }
11195 }
11196 }
11197 // WebAssembly tables can't be used as function parameters.
11198 if (Context.getTargetInfo().getTriple().isWasm()) {
11199 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11200 Diag(Param->getTypeSpecStartLoc(),
11201 diag::err_wasm_table_as_function_parameter);
11202 D.setInvalidType();
11203 }
11204 }
11205 }
11206
11207 // Diagnose availability attributes. Availability cannot be used on functions
11208 // that are run during load/unload.
11209 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11210 if (NewFD->hasAttr<ConstructorAttr>()) {
11211 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11212 << 1;
11213 NewFD->dropAttr<AvailabilityAttr>();
11214 }
11215 if (NewFD->hasAttr<DestructorAttr>()) {
11216 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11217 << 2;
11218 NewFD->dropAttr<AvailabilityAttr>();
11219 }
11220 }
11221
11222 // Diagnose no_builtin attribute on function declaration that are not a
11223 // definition.
11224 // FIXME: We should really be doing this in
11225 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11226 // the FunctionDecl and at this point of the code
11227 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11228 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11229 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11230 switch (D.getFunctionDefinitionKind()) {
11231 case FunctionDefinitionKind::Defaulted:
11232 case FunctionDefinitionKind::Deleted:
11233 Diag(NBA->getLocation(),
11234 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11235 << NBA->getSpelling();
11236 break;
11237 case FunctionDefinitionKind::Declaration:
11238 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11239 << NBA->getSpelling();
11240 break;
11241 case FunctionDefinitionKind::Definition:
11242 break;
11243 }
11244
11245 // Similar to no_builtin logic above, at this point of the code
11246 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11247 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11248 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11249 !NewFD->isInvalidDecl() &&
11250 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11251 ExternalDeclarations.push_back(NewFD);
11252
11253 // Used for a warning on the 'next' declaration when used with a
11254 // `routine(name)`.
11255 if (getLangOpts().OpenACC)
11256 OpenACC().ActOnFunctionDeclarator(NewFD);
11257
11258 return NewFD;
11259 }
11260
11261 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
11262 /// when __declspec(code_seg) "is applied to a class, all member functions of
11263 /// the class and nested classes -- this includes compiler-generated special
11264 /// member functions -- are put in the specified segment."
11265 /// The actual behavior is a little more complicated. The Microsoft compiler
11266 /// won't check outer classes if there is an active value from #pragma code_seg.
11267 /// The CodeSeg is always applied from the direct parent but only from outer
11268 /// classes when the #pragma code_seg stack is empty. See:
11269 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11270 /// available since MS has removed the page.
11271 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11272 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11273 if (!Method)
11274 return nullptr;
11275 const CXXRecordDecl *Parent = Method->getParent();
11276 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11277 Attr *NewAttr = SAttr->clone(S.getASTContext());
11278 NewAttr->setImplicit(true);
11279 return NewAttr;
11280 }
11281
11282 // The Microsoft compiler won't check outer classes for the CodeSeg
11283 // when the #pragma code_seg stack is active.
11284 if (S.CodeSegStack.CurrentValue)
11285 return nullptr;
11286
11287 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11288 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11289 Attr *NewAttr = SAttr->clone(S.getASTContext());
11290 NewAttr->setImplicit(true);
11291 return NewAttr;
11292 }
11293 }
11294 return nullptr;
11295 }
11296
11297 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11298 bool IsDefinition) {
11299 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11300 return A;
11301 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11302 CodeSegStack.CurrentValue)
11303 return SectionAttr::CreateImplicit(
11304 getASTContext(), CodeSegStack.CurrentValue->getString(),
11305 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11306 return nullptr;
11307 }
11308
11309 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11310 QualType NewT, QualType OldT) {
11311 if (!NewD->getLexicalDeclContext()->isDependentContext())
11312 return true;
11313
11314 // For dependently-typed local extern declarations and friends, we can't
11315 // perform a correct type check in general until instantiation:
11316 //
11317 // int f();
11318 // template<typename T> void g() { T f(); }
11319 //
11320 // (valid if g() is only instantiated with T = int).
11321 if (NewT->isDependentType() &&
11322 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11323 return false;
11324
11325 // Similarly, if the previous declaration was a dependent local extern
11326 // declaration, we don't really know its type yet.
11327 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11328 return false;
11329
11330 return true;
11331 }
11332
11333 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11334 if (!D->getLexicalDeclContext()->isDependentContext())
11335 return true;
11336
11337 // Don't chain dependent friend function definitions until instantiation, to
11338 // permit cases like
11339 //
11340 // void func();
11341 // template<typename T> class C1 { friend void func() {} };
11342 // template<typename T> class C2 { friend void func() {} };
11343 //
11344 // ... which is valid if only one of C1 and C2 is ever instantiated.
11345 //
11346 // FIXME: This need only apply to function definitions. For now, we proxy
11347 // this by checking for a file-scope function. We do not want this to apply
11348 // to friend declarations nominating member functions, because that gets in
11349 // the way of access checks.
11350 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11351 return false;
11352
11353 auto *VD = dyn_cast<ValueDecl>(D);
11354 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11355 return !VD || !PrevVD ||
11356 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11357 PrevVD->getType());
11358 }
11359
11360 /// Check the target or target_version attribute of the function for
11361 /// MultiVersion validity.
11362 ///
11363 /// Returns true if there was an error, false otherwise.
11364 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11365 const auto *TA = FD->getAttr<TargetAttr>();
11366 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11367
11368 assert((TA || TVA) && "Expecting target or target_version attribute");
11369
11370 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11371 enum ErrType { Feature = 0, Architecture = 1 };
11372
11373 if (TA) {
11374 ParsedTargetAttr ParseInfo =
11375 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11376 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11377 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11378 << Architecture << ParseInfo.CPU;
11379 return true;
11380 }
11381 for (const auto &Feat : ParseInfo.Features) {
11382 auto BareFeat = StringRef{Feat}.substr(1);
11383 if (Feat[0] == '-') {
11384 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11385 << Feature << ("no-" + BareFeat).str();
11386 return true;
11387 }
11388
11389 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11390 !TargetInfo.isValidFeatureName(BareFeat) ||
11391 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11392 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11393 << Feature << BareFeat;
11394 return true;
11395 }
11396 }
11397 }
11398
11399 if (TVA) {
11400 llvm::SmallVector<StringRef, 8> Feats;
11401 ParsedTargetAttr ParseInfo;
11402 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11403 ParseInfo =
11404 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11405 for (auto &Feat : ParseInfo.Features)
11406 Feats.push_back(StringRef{Feat}.substr(1));
11407 } else {
11408 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11409 TVA->getFeatures(Feats);
11410 }
11411 for (const auto &Feat : Feats) {
11412 if (!TargetInfo.validateCpuSupports(Feat)) {
11413 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11414 << Feature << Feat;
11415 return true;
11416 }
11417 }
11418 }
11419 return false;
11420 }
11421
11422 // Provide a white-list of attributes that are allowed to be combined with
11423 // multiversion functions.
11424 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11425 MultiVersionKind MVKind) {
11426 // Note: this list/diagnosis must match the list in
11427 // checkMultiversionAttributesAllSame.
11428 switch (Kind) {
11429 default:
11430 return false;
11431 case attr::ArmLocallyStreaming:
11432 return MVKind == MultiVersionKind::TargetVersion ||
11433 MVKind == MultiVersionKind::TargetClones;
11434 case attr::Used:
11435 return MVKind == MultiVersionKind::Target;
11436 case attr::NonNull:
11437 case attr::NoThrow:
11438 return true;
11439 }
11440 }
11441
11442 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11443 const FunctionDecl *FD,
11444 const FunctionDecl *CausedFD,
11445 MultiVersionKind MVKind) {
11446 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11447 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11448 << static_cast<unsigned>(MVKind) << A;
11449 if (CausedFD)
11450 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11451 return true;
11452 };
11453
11454 for (const Attr *A : FD->attrs()) {
11455 switch (A->getKind()) {
11456 case attr::CPUDispatch:
11457 case attr::CPUSpecific:
11458 if (MVKind != MultiVersionKind::CPUDispatch &&
11459 MVKind != MultiVersionKind::CPUSpecific)
11460 return Diagnose(S, A);
11461 break;
11462 case attr::Target:
11463 if (MVKind != MultiVersionKind::Target)
11464 return Diagnose(S, A);
11465 break;
11466 case attr::TargetVersion:
11467 if (MVKind != MultiVersionKind::TargetVersion &&
11468 MVKind != MultiVersionKind::TargetClones)
11469 return Diagnose(S, A);
11470 break;
11471 case attr::TargetClones:
11472 if (MVKind != MultiVersionKind::TargetClones &&
11473 MVKind != MultiVersionKind::TargetVersion)
11474 return Diagnose(S, A);
11475 break;
11476 default:
11477 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11478 return Diagnose(S, A);
11479 break;
11480 }
11481 }
11482 return false;
11483 }
11484
11485 bool Sema::areMultiversionVariantFunctionsCompatible(
11486 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11487 const PartialDiagnostic &NoProtoDiagID,
11488 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11489 const PartialDiagnosticAt &NoSupportDiagIDAt,
11490 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11491 bool ConstexprSupported, bool CLinkageMayDiffer) {
11492 enum DoesntSupport {
11493 FuncTemplates = 0,
11494 VirtFuncs = 1,
11495 DeducedReturn = 2,
11496 Constructors = 3,
11497 Destructors = 4,
11498 DeletedFuncs = 5,
11499 DefaultedFuncs = 6,
11500 ConstexprFuncs = 7,
11501 ConstevalFuncs = 8,
11502 Lambda = 9,
11503 };
11504 enum Different {
11505 CallingConv = 0,
11506 ReturnType = 1,
11507 ConstexprSpec = 2,
11508 InlineSpec = 3,
11509 Linkage = 4,
11510 LanguageLinkage = 5,
11511 };
11512
11513 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11514 !OldFD->getType()->getAs<FunctionProtoType>()) {
11515 Diag(OldFD->getLocation(), NoProtoDiagID);
11516 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11517 return true;
11518 }
11519
11520 if (NoProtoDiagID.getDiagID() != 0 &&
11521 !NewFD->getType()->getAs<FunctionProtoType>())
11522 return Diag(NewFD->getLocation(), NoProtoDiagID);
11523
11524 if (!TemplatesSupported &&
11525 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11526 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11527 << FuncTemplates;
11528
11529 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11530 if (NewCXXFD->isVirtual())
11531 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11532 << VirtFuncs;
11533
11534 if (isa<CXXConstructorDecl>(NewCXXFD))
11535 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11536 << Constructors;
11537
11538 if (isa<CXXDestructorDecl>(NewCXXFD))
11539 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11540 << Destructors;
11541 }
11542
11543 if (NewFD->isDeleted())
11544 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11545 << DeletedFuncs;
11546
11547 if (NewFD->isDefaulted())
11548 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11549 << DefaultedFuncs;
11550
11551 if (!ConstexprSupported && NewFD->isConstexpr())
11552 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11553 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11554
11555 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11556 const auto *NewType = cast<FunctionType>(NewQType);
11557 QualType NewReturnType = NewType->getReturnType();
11558
11559 if (NewReturnType->isUndeducedType())
11560 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11561 << DeducedReturn;
11562
11563 // Ensure the return type is identical.
11564 if (OldFD) {
11565 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11566 const auto *OldType = cast<FunctionType>(OldQType);
11567 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11568 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11569
11570 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11571 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11572
11573 bool ArmStreamingCCMismatched = false;
11574 if (OldFPT && NewFPT) {
11575 unsigned Diff =
11576 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11577 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11578 // cannot be mixed.
11579 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11580 FunctionType::SME_PStateSMCompatibleMask))
11581 ArmStreamingCCMismatched = true;
11582 }
11583
11584 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11585 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11586
11587 QualType OldReturnType = OldType->getReturnType();
11588
11589 if (OldReturnType != NewReturnType)
11590 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11591
11592 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11593 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11594
11595 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11596 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11597
11598 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11599 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11600
11601 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11602 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11603
11604 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11605 NewFD->getLocation()))
11606 return true;
11607 }
11608 return false;
11609 }
11610
11611 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11612 const FunctionDecl *NewFD,
11613 bool CausesMV,
11614 MultiVersionKind MVKind) {
11615 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11616 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11617 if (OldFD)
11618 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11619 return true;
11620 }
11621
11622 bool IsCPUSpecificCPUDispatchMVKind =
11623 MVKind == MultiVersionKind::CPUDispatch ||
11624 MVKind == MultiVersionKind::CPUSpecific;
11625
11626 if (CausesMV && OldFD &&
11627 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11628 return true;
11629
11630 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11631 return true;
11632
11633 // Only allow transition to MultiVersion if it hasn't been used.
11634 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11635 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11636 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11637 return true;
11638 }
11639
11640 return S.areMultiversionVariantFunctionsCompatible(
11641 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11642 PartialDiagnosticAt(NewFD->getLocation(),
11643 S.PDiag(diag::note_multiversioning_caused_here)),
11644 PartialDiagnosticAt(NewFD->getLocation(),
11645 S.PDiag(diag::err_multiversion_doesnt_support)
11646 << static_cast<unsigned>(MVKind)),
11647 PartialDiagnosticAt(NewFD->getLocation(),
11648 S.PDiag(diag::err_multiversion_diff)),
11649 /*TemplatesSupported=*/false,
11650 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11651 /*CLinkageMayDiffer=*/false);
11652 }
11653
11654 /// Check the validity of a multiversion function declaration that is the
11655 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11656 ///
11657 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11658 ///
11659 /// Returns true if there was an error, false otherwise.
11660 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11661 MultiVersionKind MVKind = FD->getMultiVersionKind();
11662 assert(MVKind != MultiVersionKind::None &&
11663 "Function lacks multiversion attribute");
11664 const auto *TA = FD->getAttr<TargetAttr>();
11665 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11666 // The target attribute only causes MV if this declaration is the default,
11667 // otherwise it is treated as a normal function.
11668 if (TA && !TA->isDefaultVersion())
11669 return false;
11670
11671 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11672 FD->setInvalidDecl();
11673 return true;
11674 }
11675
11676 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11677 FD->setInvalidDecl();
11678 return true;
11679 }
11680
11681 FD->setIsMultiVersion();
11682 return false;
11683 }
11684
11685 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11686 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11687 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11688 return true;
11689 }
11690
11691 return false;
11692 }
11693
11694 static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11695 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11696 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11697 return;
11698
11699 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11700 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11701
11702 if (MVKindTo == MultiVersionKind::None &&
11703 (MVKindFrom == MultiVersionKind::TargetVersion ||
11704 MVKindFrom == MultiVersionKind::TargetClones))
11705 To->addAttr(TargetVersionAttr::CreateImplicit(
11706 To->getASTContext(), "default", To->getSourceRange()));
11707 }
11708
11709 static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11710 FunctionDecl *NewFD,
11711 bool &Redeclaration,
11712 NamedDecl *&OldDecl,
11713 LookupResult &Previous) {
11714 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11715
11716 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11717 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11718 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11719 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11720
11721 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11722
11723 // The definitions should be allowed in any order. If we have discovered
11724 // a new target version and the preceeding was the default, then add the
11725 // corresponding attribute to it.
11726 patchDefaultTargetVersion(NewFD, OldFD);
11727
11728 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11729 // to change, this is a simple redeclaration.
11730 if (NewTA && !NewTA->isDefaultVersion() &&
11731 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11732 return false;
11733
11734 // Otherwise, this decl causes MultiVersioning.
11735 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11736 NewTVA ? MultiVersionKind::TargetVersion
11737 : MultiVersionKind::Target)) {
11738 NewFD->setInvalidDecl();
11739 return true;
11740 }
11741
11742 if (CheckMultiVersionValue(S, NewFD)) {
11743 NewFD->setInvalidDecl();
11744 return true;
11745 }
11746
11747 // If this is 'default', permit the forward declaration.
11748 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11749 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11750 Redeclaration = true;
11751 OldDecl = OldFD;
11752 OldFD->setIsMultiVersion();
11753 NewFD->setIsMultiVersion();
11754 return false;
11755 }
11756
11757 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11758 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11759 NewFD->setInvalidDecl();
11760 return true;
11761 }
11762
11763 if (NewTA) {
11764 ParsedTargetAttr OldParsed =
11765 S.getASTContext().getTargetInfo().parseTargetAttr(
11766 OldTA->getFeaturesStr());
11767 llvm::sort(OldParsed.Features);
11768 ParsedTargetAttr NewParsed =
11769 S.getASTContext().getTargetInfo().parseTargetAttr(
11770 NewTA->getFeaturesStr());
11771 // Sort order doesn't matter, it just needs to be consistent.
11772 llvm::sort(NewParsed.Features);
11773 if (OldParsed == NewParsed) {
11774 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11775 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11776 NewFD->setInvalidDecl();
11777 return true;
11778 }
11779 }
11780
11781 for (const auto *FD : OldFD->redecls()) {
11782 const auto *CurTA = FD->getAttr<TargetAttr>();
11783 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11784 // We allow forward declarations before ANY multiversioning attributes, but
11785 // nothing after the fact.
11786 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11787 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11788 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11789 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11790 << (NewTA ? 0 : 2);
11791 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11792 NewFD->setInvalidDecl();
11793 return true;
11794 }
11795 }
11796
11797 OldFD->setIsMultiVersion();
11798 NewFD->setIsMultiVersion();
11799 Redeclaration = false;
11800 OldDecl = nullptr;
11801 Previous.clear();
11802 return false;
11803 }
11804
11805 static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11806 MultiVersionKind OldKind = Old->getMultiVersionKind();
11807 MultiVersionKind NewKind = New->getMultiVersionKind();
11808
11809 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11810 NewKind == MultiVersionKind::None)
11811 return true;
11812
11813 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11814 switch (OldKind) {
11815 case MultiVersionKind::TargetVersion:
11816 return NewKind == MultiVersionKind::TargetClones;
11817 case MultiVersionKind::TargetClones:
11818 return NewKind == MultiVersionKind::TargetVersion;
11819 default:
11820 return false;
11821 }
11822 } else {
11823 switch (OldKind) {
11824 case MultiVersionKind::CPUDispatch:
11825 return NewKind == MultiVersionKind::CPUSpecific;
11826 case MultiVersionKind::CPUSpecific:
11827 return NewKind == MultiVersionKind::CPUDispatch;
11828 default:
11829 return false;
11830 }
11831 }
11832 }
11833
11834 /// Check the validity of a new function declaration being added to an existing
11835 /// multiversioned declaration collection.
11836 static bool CheckMultiVersionAdditionalDecl(
11837 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11838 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11839 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11840 LookupResult &Previous) {
11841
11842 // Disallow mixing of multiversioning types.
11843 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11844 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11845 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11846 NewFD->setInvalidDecl();
11847 return true;
11848 }
11849
11850 // Add the default target_version attribute if it's missing.
11851 patchDefaultTargetVersion(OldFD, NewFD);
11852 patchDefaultTargetVersion(NewFD, OldFD);
11853
11854 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11855 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11856 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11857 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11858
11859 ParsedTargetAttr NewParsed;
11860 if (NewTA) {
11861 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11862 NewTA->getFeaturesStr());
11863 llvm::sort(NewParsed.Features);
11864 }
11865 llvm::SmallVector<StringRef, 8> NewFeats;
11866 if (NewTVA) {
11867 NewTVA->getFeatures(NewFeats);
11868 llvm::sort(NewFeats);
11869 }
11870
11871 bool UseMemberUsingDeclRules =
11872 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11873
11874 bool MayNeedOverloadableChecks =
11875 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11876
11877 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11878 // of a previous member of the MultiVersion set.
11879 for (NamedDecl *ND : Previous) {
11880 FunctionDecl *CurFD = ND->getAsFunction();
11881 if (!CurFD || CurFD->isInvalidDecl())
11882 continue;
11883 if (MayNeedOverloadableChecks &&
11884 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11885 continue;
11886
11887 switch (NewMVKind) {
11888 case MultiVersionKind::None:
11889 assert(OldMVKind == MultiVersionKind::TargetClones &&
11890 "Only target_clones can be omitted in subsequent declarations");
11891 break;
11892 case MultiVersionKind::Target: {
11893 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11894 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11895 NewFD->setIsMultiVersion();
11896 Redeclaration = true;
11897 OldDecl = ND;
11898 return false;
11899 }
11900
11901 ParsedTargetAttr CurParsed =
11902 S.getASTContext().getTargetInfo().parseTargetAttr(
11903 CurTA->getFeaturesStr());
11904 llvm::sort(CurParsed.Features);
11905 if (CurParsed == NewParsed) {
11906 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11907 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11908 NewFD->setInvalidDecl();
11909 return true;
11910 }
11911 break;
11912 }
11913 case MultiVersionKind::TargetVersion: {
11914 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11915 if (CurTVA->getName() == NewTVA->getName()) {
11916 NewFD->setIsMultiVersion();
11917 Redeclaration = true;
11918 OldDecl = ND;
11919 return false;
11920 }
11921 llvm::SmallVector<StringRef, 8> CurFeats;
11922 CurTVA->getFeatures(CurFeats);
11923 llvm::sort(CurFeats);
11924
11925 if (CurFeats == NewFeats) {
11926 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11927 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11928 NewFD->setInvalidDecl();
11929 return true;
11930 }
11931 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11932 // Default
11933 if (NewFeats.empty())
11934 break;
11935
11936 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11937 llvm::SmallVector<StringRef, 8> CurFeats;
11938 CurClones->getFeatures(CurFeats, I);
11939 llvm::sort(CurFeats);
11940
11941 if (CurFeats == NewFeats) {
11942 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11943 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11944 NewFD->setInvalidDecl();
11945 return true;
11946 }
11947 }
11948 }
11949 break;
11950 }
11951 case MultiVersionKind::TargetClones: {
11952 assert(NewClones && "MultiVersionKind does not match attribute type");
11953 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11954 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11955 !std::equal(CurClones->featuresStrs_begin(),
11956 CurClones->featuresStrs_end(),
11957 NewClones->featuresStrs_begin())) {
11958 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11959 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11960 NewFD->setInvalidDecl();
11961 return true;
11962 }
11963 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11964 llvm::SmallVector<StringRef, 8> CurFeats;
11965 CurTVA->getFeatures(CurFeats);
11966 llvm::sort(CurFeats);
11967
11968 // Default
11969 if (CurFeats.empty())
11970 break;
11971
11972 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11973 NewFeats.clear();
11974 NewClones->getFeatures(NewFeats, I);
11975 llvm::sort(NewFeats);
11976
11977 if (CurFeats == NewFeats) {
11978 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11979 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11980 NewFD->setInvalidDecl();
11981 return true;
11982 }
11983 }
11984 break;
11985 }
11986 Redeclaration = true;
11987 OldDecl = CurFD;
11988 NewFD->setIsMultiVersion();
11989 return false;
11990 }
11991 case MultiVersionKind::CPUSpecific:
11992 case MultiVersionKind::CPUDispatch: {
11993 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11994 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11995 // Handle CPUDispatch/CPUSpecific versions.
11996 // Only 1 CPUDispatch function is allowed, this will make it go through
11997 // the redeclaration errors.
11998 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11999 CurFD->hasAttr<CPUDispatchAttr>()) {
12000 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12001 std::equal(
12002 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12003 NewCPUDisp->cpus_begin(),
12004 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12005 return Cur->getName() == New->getName();
12006 })) {
12007 NewFD->setIsMultiVersion();
12008 Redeclaration = true;
12009 OldDecl = ND;
12010 return false;
12011 }
12012
12013 // If the declarations don't match, this is an error condition.
12014 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12015 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12016 NewFD->setInvalidDecl();
12017 return true;
12018 }
12019 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12020 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12021 std::equal(
12022 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12023 NewCPUSpec->cpus_begin(),
12024 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12025 return Cur->getName() == New->getName();
12026 })) {
12027 NewFD->setIsMultiVersion();
12028 Redeclaration = true;
12029 OldDecl = ND;
12030 return false;
12031 }
12032
12033 // Only 1 version of CPUSpecific is allowed for each CPU.
12034 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12035 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12036 if (CurII == NewII) {
12037 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12038 << NewII;
12039 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12040 NewFD->setInvalidDecl();
12041 return true;
12042 }
12043 }
12044 }
12045 }
12046 break;
12047 }
12048 }
12049 }
12050
12051 // Redeclarations of a target_clones function may omit the attribute, in which
12052 // case it will be inherited during declaration merging.
12053 if (NewMVKind == MultiVersionKind::None &&
12054 OldMVKind == MultiVersionKind::TargetClones) {
12055 NewFD->setIsMultiVersion();
12056 Redeclaration = true;
12057 OldDecl = OldFD;
12058 return false;
12059 }
12060
12061 // Else, this is simply a non-redecl case. Checking the 'value' is only
12062 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12063 // handled in the attribute adding step.
12064 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12065 NewFD->setInvalidDecl();
12066 return true;
12067 }
12068
12069 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12070 !OldFD->isMultiVersion(), NewMVKind)) {
12071 NewFD->setInvalidDecl();
12072 return true;
12073 }
12074
12075 // Permit forward declarations in the case where these two are compatible.
12076 if (!OldFD->isMultiVersion()) {
12077 OldFD->setIsMultiVersion();
12078 NewFD->setIsMultiVersion();
12079 Redeclaration = true;
12080 OldDecl = OldFD;
12081 return false;
12082 }
12083
12084 NewFD->setIsMultiVersion();
12085 Redeclaration = false;
12086 OldDecl = nullptr;
12087 Previous.clear();
12088 return false;
12089 }
12090
12091 /// Check the validity of a mulitversion function declaration.
12092 /// Also sets the multiversion'ness' of the function itself.
12093 ///
12094 /// This sets NewFD->isInvalidDecl() to true if there was an error.
12095 ///
12096 /// Returns true if there was an error, false otherwise.
12097 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12098 bool &Redeclaration, NamedDecl *&OldDecl,
12099 LookupResult &Previous) {
12100 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12101
12102 // Check if FMV is disabled.
12103 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12104 return false;
12105
12106 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12107 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12108 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12109 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12110 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12111 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12112
12113 // Main isn't allowed to become a multiversion function, however it IS
12114 // permitted to have 'main' be marked with the 'target' optimization hint,
12115 // for 'target_version' only default is allowed.
12116 if (NewFD->isMain()) {
12117 if (MVKind != MultiVersionKind::None &&
12118 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12119 !(MVKind == MultiVersionKind::TargetVersion &&
12120 NewTVA->isDefaultVersion())) {
12121 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12122 NewFD->setInvalidDecl();
12123 return true;
12124 }
12125 return false;
12126 }
12127
12128 // Target attribute on AArch64 is not used for multiversioning
12129 if (NewTA && TI.getTriple().isAArch64())
12130 return false;
12131
12132 // Target attribute on RISCV is not used for multiversioning
12133 if (NewTA && TI.getTriple().isRISCV())
12134 return false;
12135
12136 if (!OldDecl || !OldDecl->getAsFunction() ||
12137 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12138 NewFD->getDeclContext()->getRedeclContext())) {
12139 // If there's no previous declaration, AND this isn't attempting to cause
12140 // multiversioning, this isn't an error condition.
12141 if (MVKind == MultiVersionKind::None)
12142 return false;
12143 return CheckMultiVersionFirstFunction(S, NewFD);
12144 }
12145
12146 FunctionDecl *OldFD = OldDecl->getAsFunction();
12147
12148 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12149 return false;
12150
12151 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12152 // for target_clones and target_version.
12153 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12154 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12155 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12156 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12157 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12158 NewFD->setInvalidDecl();
12159 return true;
12160 }
12161
12162 if (!OldFD->isMultiVersion()) {
12163 switch (MVKind) {
12164 case MultiVersionKind::Target:
12165 case MultiVersionKind::TargetVersion:
12166 return CheckDeclarationCausesMultiVersioning(
12167 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12168 case MultiVersionKind::TargetClones:
12169 if (OldFD->isUsed(false)) {
12170 NewFD->setInvalidDecl();
12171 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12172 }
12173 OldFD->setIsMultiVersion();
12174 break;
12175
12176 case MultiVersionKind::CPUDispatch:
12177 case MultiVersionKind::CPUSpecific:
12178 case MultiVersionKind::None:
12179 break;
12180 }
12181 }
12182
12183 // At this point, we have a multiversion function decl (in OldFD) AND an
12184 // appropriate attribute in the current function decl (unless it's allowed to
12185 // omit the attribute). Resolve that these are still compatible with previous
12186 // declarations.
12187 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12188 NewCPUSpec, NewClones, Redeclaration,
12189 OldDecl, Previous);
12190 }
12191
12192 static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12193 bool IsPure = NewFD->hasAttr<PureAttr>();
12194 bool IsConst = NewFD->hasAttr<ConstAttr>();
12195
12196 // If there are no pure or const attributes, there's nothing to check.
12197 if (!IsPure && !IsConst)
12198 return;
12199
12200 // If the function is marked both pure and const, we retain the const
12201 // attribute because it makes stronger guarantees than the pure attribute, and
12202 // we drop the pure attribute explicitly to prevent later confusion about
12203 // semantics.
12204 if (IsPure && IsConst) {
12205 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12206 NewFD->dropAttrs<PureAttr>();
12207 }
12208
12209 // Constructors and destructors are functions which return void, so are
12210 // handled here as well.
12211 if (NewFD->getReturnType()->isVoidType()) {
12212 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12213 << IsConst;
12214 NewFD->dropAttrs<PureAttr, ConstAttr>();
12215 }
12216 }
12217
12218 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12219 LookupResult &Previous,
12220 bool IsMemberSpecialization,
12221 bool DeclIsDefn) {
12222 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12223 "Variably modified return types are not handled here");
12224
12225 // Determine whether the type of this function should be merged with
12226 // a previous visible declaration. This never happens for functions in C++,
12227 // and always happens in C if the previous declaration was visible.
12228 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12229 !Previous.isShadowed();
12230
12231 bool Redeclaration = false;
12232 NamedDecl *OldDecl = nullptr;
12233 bool MayNeedOverloadableChecks = false;
12234
12235 inferLifetimeCaptureByAttribute(NewFD);
12236 // Merge or overload the declaration with an existing declaration of
12237 // the same name, if appropriate.
12238 if (!Previous.empty()) {
12239 // Determine whether NewFD is an overload of PrevDecl or
12240 // a declaration that requires merging. If it's an overload,
12241 // there's no more work to do here; we'll just add the new
12242 // function to the scope.
12243 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
12244 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12245 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12246 Redeclaration = true;
12247 OldDecl = Candidate;
12248 }
12249 } else {
12250 MayNeedOverloadableChecks = true;
12251 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12252 /*NewIsUsingDecl*/ false)) {
12253 case OverloadKind::Match:
12254 Redeclaration = true;
12255 break;
12256
12257 case OverloadKind::NonFunction:
12258 Redeclaration = true;
12259 break;
12260
12261 case OverloadKind::Overload:
12262 Redeclaration = false;
12263 break;
12264 }
12265 }
12266 }
12267
12268 // Check for a previous extern "C" declaration with this name.
12269 if (!Redeclaration &&
12270 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
12271 if (!Previous.empty()) {
12272 // This is an extern "C" declaration with the same name as a previous
12273 // declaration, and thus redeclares that entity...
12274 Redeclaration = true;
12275 OldDecl = Previous.getFoundDecl();
12276 MergeTypeWithPrevious = false;
12277
12278 // ... except in the presence of __attribute__((overloadable)).
12279 if (OldDecl->hasAttr<OverloadableAttr>() ||
12280 NewFD->hasAttr<OverloadableAttr>()) {
12281 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12282 MayNeedOverloadableChecks = true;
12283 Redeclaration = false;
12284 OldDecl = nullptr;
12285 }
12286 }
12287 }
12288 }
12289
12290 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12291 return Redeclaration;
12292
12293 // PPC MMA non-pointer types are not allowed as function return types.
12294 if (Context.getTargetInfo().getTriple().isPPC64() &&
12295 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12296 NewFD->setInvalidDecl();
12297 }
12298
12299 CheckConstPureAttributesUsage(*this, NewFD);
12300
12301 // C++ [dcl.spec.auto.general]p12:
12302 // Return type deduction for a templated function with a placeholder in its
12303 // declared type occurs when the definition is instantiated even if the
12304 // function body contains a return statement with a non-type-dependent
12305 // operand.
12306 //
12307 // C++ [temp.dep.expr]p3:
12308 // An id-expression is type-dependent if it is a template-id that is not a
12309 // concept-id and is dependent; or if its terminal name is:
12310 // - [...]
12311 // - associated by name lookup with one or more declarations of member
12312 // functions of a class that is the current instantiation declared with a
12313 // return type that contains a placeholder type,
12314 // - [...]
12315 //
12316 // If this is a templated function with a placeholder in its return type,
12317 // make the placeholder type dependent since it won't be deduced until the
12318 // definition is instantiated. We do this here because it needs to happen
12319 // for implicitly instantiated member functions/member function templates.
12320 if (getLangOpts().CPlusPlus14 &&
12321 (NewFD->isDependentContext() &&
12322 NewFD->getReturnType()->isUndeducedType())) {
12323 const FunctionProtoType *FPT =
12324 NewFD->getType()->castAs<FunctionProtoType>();
12325 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12326 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12327 FPT->getExtProtoInfo()));
12328 }
12329
12330 // C++11 [dcl.constexpr]p8:
12331 // A constexpr specifier for a non-static member function that is not
12332 // a constructor declares that member function to be const.
12333 //
12334 // This needs to be delayed until we know whether this is an out-of-line
12335 // definition of a static member function.
12336 //
12337 // This rule is not present in C++1y, so we produce a backwards
12338 // compatibility warning whenever it happens in C++11.
12339 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12340 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12341 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12342 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12343 CXXMethodDecl *OldMD = nullptr;
12344 if (OldDecl)
12345 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12346 if (!OldMD || !OldMD->isStatic()) {
12347 const FunctionProtoType *FPT =
12348 MD->getType()->castAs<FunctionProtoType>();
12349 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12350 EPI.TypeQuals.addConst();
12351 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12352 FPT->getParamTypes(), EPI));
12353
12354 // Warn that we did this, if we're not performing template instantiation.
12355 // In that case, we'll have warned already when the template was defined.
12356 if (!inTemplateInstantiation()) {
12357 SourceLocation AddConstLoc;
12358 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12359 .IgnoreParens().getAs<FunctionTypeLoc>())
12360 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12361
12362 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12363 << FixItHint::CreateInsertion(AddConstLoc, " const");
12364 }
12365 }
12366 }
12367
12368 if (Redeclaration) {
12369 // NewFD and OldDecl represent declarations that need to be
12370 // merged.
12371 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12372 DeclIsDefn)) {
12373 NewFD->setInvalidDecl();
12374 return Redeclaration;
12375 }
12376
12377 Previous.clear();
12378 Previous.addDecl(OldDecl);
12379
12380 if (FunctionTemplateDecl *OldTemplateDecl =
12381 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12382 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12383 FunctionTemplateDecl *NewTemplateDecl
12384 = NewFD->getDescribedFunctionTemplate();
12385 assert(NewTemplateDecl && "Template/non-template mismatch");
12386
12387 // The call to MergeFunctionDecl above may have created some state in
12388 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12389 // can add it as a redeclaration.
12390 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12391
12392 NewFD->setPreviousDeclaration(OldFD);
12393 if (NewFD->isCXXClassMember()) {
12394 NewFD->setAccess(OldTemplateDecl->getAccess());
12395 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12396 }
12397
12398 // If this is an explicit specialization of a member that is a function
12399 // template, mark it as a member specialization.
12400 if (IsMemberSpecialization &&
12401 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12402 NewTemplateDecl->setMemberSpecialization();
12403 assert(OldTemplateDecl->isMemberSpecialization());
12404 // Explicit specializations of a member template do not inherit deleted
12405 // status from the parent member template that they are specializing.
12406 if (OldFD->isDeleted()) {
12407 // FIXME: This assert will not hold in the presence of modules.
12408 assert(OldFD->getCanonicalDecl() == OldFD);
12409 // FIXME: We need an update record for this AST mutation.
12410 OldFD->setDeletedAsWritten(false);
12411 }
12412 }
12413
12414 } else {
12415 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12416 auto *OldFD = cast<FunctionDecl>(OldDecl);
12417 // This needs to happen first so that 'inline' propagates.
12418 NewFD->setPreviousDeclaration(OldFD);
12419 if (NewFD->isCXXClassMember())
12420 NewFD->setAccess(OldFD->getAccess());
12421 }
12422 }
12423 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12424 !NewFD->getAttr<OverloadableAttr>()) {
12425 assert((Previous.empty() ||
12426 llvm::any_of(Previous,
12427 [](const NamedDecl *ND) {
12428 return ND->hasAttr<OverloadableAttr>();
12429 })) &&
12430 "Non-redecls shouldn't happen without overloadable present");
12431
12432 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12433 const auto *FD = dyn_cast<FunctionDecl>(ND);
12434 return FD && !FD->hasAttr<OverloadableAttr>();
12435 });
12436
12437 if (OtherUnmarkedIter != Previous.end()) {
12438 Diag(NewFD->getLocation(),
12439 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12440 Diag((*OtherUnmarkedIter)->getLocation(),
12441 diag::note_attribute_overloadable_prev_overload)
12442 << false;
12443
12444 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12445 }
12446 }
12447
12448 if (LangOpts.OpenMP)
12449 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12450
12451 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12452 SYCL().CheckSYCLEntryPointFunctionDecl(NewFD);
12453
12454 if (NewFD->hasAttr<SYCLExternalAttr>())
12455 SYCL().CheckSYCLExternalFunctionDecl(NewFD);
12456
12457 // Semantic checking for this function declaration (in isolation).
12458
12459 if (getLangOpts().CPlusPlus) {
12460 // C++-specific checks.
12461 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12462 CheckConstructor(Constructor);
12463 } else if (CXXDestructorDecl *Destructor =
12464 dyn_cast<CXXDestructorDecl>(NewFD)) {
12465 // We check here for invalid destructor names.
12466 // If we have a friend destructor declaration that is dependent, we can't
12467 // diagnose right away because cases like this are still valid:
12468 // template <class T> struct A { friend T::X::~Y(); };
12469 // struct B { struct Y { ~Y(); }; using X = Y; };
12470 // template struct A<B>;
12471 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12472 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12473 CanQualType ClassType =
12474 Context.getCanonicalTagType(Destructor->getParent());
12475
12476 DeclarationName Name =
12477 Context.DeclarationNames.getCXXDestructorName(ClassType);
12478 if (NewFD->getDeclName() != Name) {
12479 Diag(NewFD->getLocation(), diag::err_destructor_name);
12480 NewFD->setInvalidDecl();
12481 return Redeclaration;
12482 }
12483 }
12484 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12485 if (auto *TD = Guide->getDescribedFunctionTemplate())
12486 CheckDeductionGuideTemplate(TD);
12487
12488 // A deduction guide is not on the list of entities that can be
12489 // explicitly specialized.
12490 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12491 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12492 << /*explicit specialization*/ 1;
12493 }
12494
12495 // Find any virtual functions that this function overrides.
12496 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12497 if (!Method->isFunctionTemplateSpecialization() &&
12498 !Method->getDescribedFunctionTemplate() &&
12499 Method->isCanonicalDecl()) {
12500 AddOverriddenMethods(Method->getParent(), Method);
12501 }
12502 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12503 // C++2a [class.virtual]p6
12504 // A virtual method shall not have a requires-clause.
12505 Diag(NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12506 diag::err_constrained_virtual_method);
12507
12508 if (Method->isStatic())
12509 checkThisInStaticMemberFunctionType(Method);
12510 }
12511
12512 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12513 ActOnConversionDeclarator(Conversion);
12514
12515 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12516 if (NewFD->isOverloadedOperator() &&
12517 CheckOverloadedOperatorDeclaration(NewFD)) {
12518 NewFD->setInvalidDecl();
12519 return Redeclaration;
12520 }
12521
12522 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12523 if (NewFD->getLiteralIdentifier() &&
12524 CheckLiteralOperatorDeclaration(NewFD)) {
12525 NewFD->setInvalidDecl();
12526 return Redeclaration;
12527 }
12528
12529 // In C++, check default arguments now that we have merged decls. Unless
12530 // the lexical context is the class, because in this case this is done
12531 // during delayed parsing anyway.
12532 if (!CurContext->isRecord())
12533 CheckCXXDefaultArguments(NewFD);
12534
12535 // If this function is declared as being extern "C", then check to see if
12536 // the function returns a UDT (class, struct, or union type) that is not C
12537 // compatible, and if it does, warn the user.
12538 // But, issue any diagnostic on the first declaration only.
12539 if (Previous.empty() && NewFD->isExternC()) {
12540 QualType R = NewFD->getReturnType();
12541 if (R->isIncompleteType() && !R->isVoidType())
12542 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12543 << NewFD << R;
12544 else if (!R.isPODType(Context) && !R->isVoidType() &&
12545 !R->isObjCObjectPointerType())
12546 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12547 }
12548
12549 // C++1z [dcl.fct]p6:
12550 // [...] whether the function has a non-throwing exception-specification
12551 // [is] part of the function type
12552 //
12553 // This results in an ABI break between C++14 and C++17 for functions whose
12554 // declared type includes an exception-specification in a parameter or
12555 // return type. (Exception specifications on the function itself are OK in
12556 // most cases, and exception specifications are not permitted in most other
12557 // contexts where they could make it into a mangling.)
12558 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12559 auto HasNoexcept = [&](QualType T) -> bool {
12560 // Strip off declarator chunks that could be between us and a function
12561 // type. We don't need to look far, exception specifications are very
12562 // restricted prior to C++17.
12563 if (auto *RT = T->getAs<ReferenceType>())
12564 T = RT->getPointeeType();
12565 else if (T->isAnyPointerType())
12566 T = T->getPointeeType();
12567 else if (auto *MPT = T->getAs<MemberPointerType>())
12568 T = MPT->getPointeeType();
12569 if (auto *FPT = T->getAs<FunctionProtoType>())
12570 if (FPT->isNothrow())
12571 return true;
12572 return false;
12573 };
12574
12575 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12576 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12577 for (QualType T : FPT->param_types())
12578 AnyNoexcept |= HasNoexcept(T);
12579 if (AnyNoexcept)
12580 Diag(NewFD->getLocation(),
12581 diag::warn_cxx17_compat_exception_spec_in_signature)
12582 << NewFD;
12583 }
12584
12585 if (!Redeclaration && LangOpts.CUDA) {
12586 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12587 for (auto *Parm : NewFD->parameters()) {
12588 if (!Parm->getType()->isDependentType() &&
12589 Parm->hasAttr<CUDAGridConstantAttr>() &&
12590 !(IsKernel && Parm->getType().isConstQualified()))
12591 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12592 diag::err_cuda_grid_constant_not_allowed);
12593 }
12594 CUDA().checkTargetOverload(NewFD, Previous);
12595 }
12596 }
12597
12598 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12599 ARM().CheckSMEFunctionDefAttributes(NewFD);
12600
12601 return Redeclaration;
12602 }
12603
12604 void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12605 // [basic.start.main]p3
12606 // The main function shall not be declared with C linkage-specification.
12607 if (FD->isExternCContext())
12608 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12609
12610 // C++11 [basic.start.main]p3:
12611 // A program that [...] declares main to be inline, static or
12612 // constexpr is ill-formed.
12613 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12614 // appear in a declaration of main.
12615 // static main is not an error under C99, but we should warn about it.
12616 // We accept _Noreturn main as an extension.
12617 if (FD->getStorageClass() == SC_Static)
12618 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12619 ? diag::err_static_main : diag::warn_static_main)
12620 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12621 if (FD->isInlineSpecified())
12622 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12623 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12624 if (DS.isNoreturnSpecified()) {
12625 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12626 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12627 Diag(NoreturnLoc, diag::ext_noreturn_main);
12628 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12629 << FixItHint::CreateRemoval(NoreturnRange);
12630 }
12631 if (FD->isConstexpr()) {
12632 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12633 << FD->isConsteval()
12634 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12635 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12636 }
12637
12638 if (getLangOpts().OpenCL) {
12639 Diag(FD->getLocation(), diag::err_opencl_no_main)
12640 << FD->hasAttr<DeviceKernelAttr>();
12641 FD->setInvalidDecl();
12642 return;
12643 }
12644
12645 if (FD->hasAttr<SYCLExternalAttr>()) {
12646 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12647 << FD->getAttr<SYCLExternalAttr>();
12648 FD->setInvalidDecl();
12649 return;
12650 }
12651
12652 // Functions named main in hlsl are default entries, but don't have specific
12653 // signatures they are required to conform to.
12654 if (getLangOpts().HLSL)
12655 return;
12656
12657 QualType T = FD->getType();
12658 assert(T->isFunctionType() && "function decl is not of function type");
12659 const FunctionType* FT = T->castAs<FunctionType>();
12660
12661 // Set default calling convention for main()
12662 if (FT->getCallConv() != CC_C) {
12663 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12664 FD->setType(QualType(FT, 0));
12665 T = Context.getCanonicalType(FD->getType());
12666 }
12667
12668 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12669 // In C with GNU extensions we allow main() to have non-integer return
12670 // type, but we should warn about the extension, and we disable the
12671 // implicit-return-zero rule.
12672
12673 // GCC in C mode accepts qualified 'int'.
12674 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12675 FD->setHasImplicitReturnZero(true);
12676 else {
12677 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12678 SourceRange RTRange = FD->getReturnTypeSourceRange();
12679 if (RTRange.isValid())
12680 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12681 << FixItHint::CreateReplacement(RTRange, "int");
12682 }
12683 } else {
12684 // In C and C++, main magically returns 0 if you fall off the end;
12685 // set the flag which tells us that.
12686 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12687
12688 // All the standards say that main() should return 'int'.
12689 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12690 FD->setHasImplicitReturnZero(true);
12691 else {
12692 // Otherwise, this is just a flat-out error.
12693 SourceRange RTRange = FD->getReturnTypeSourceRange();
12694 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12695 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12696 : FixItHint());
12697 FD->setInvalidDecl(true);
12698 }
12699
12700 // [basic.start.main]p3:
12701 // A program that declares a function main that belongs to the global scope
12702 // and is attached to a named module is ill-formed.
12703 if (FD->isInNamedModule()) {
12704 const SourceLocation start = FD->getTypeSpecStartLoc();
12705 Diag(start, diag::warn_main_in_named_module)
12706 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12707 }
12708 }
12709
12710 // Treat protoless main() as nullary.
12711 if (isa<FunctionNoProtoType>(FT)) return;
12712
12713 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12714 unsigned nparams = FTP->getNumParams();
12715 assert(FD->getNumParams() == nparams);
12716
12717 bool HasExtraParameters = (nparams > 3);
12718
12719 if (FTP->isVariadic()) {
12720 Diag(FD->getLocation(), diag::ext_variadic_main);
12721 // FIXME: if we had information about the location of the ellipsis, we
12722 // could add a FixIt hint to remove it as a parameter.
12723 }
12724
12725 // Darwin passes an undocumented fourth argument of type char**. If
12726 // other platforms start sprouting these, the logic below will start
12727 // getting shifty.
12728 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12729 HasExtraParameters = false;
12730
12731 if (HasExtraParameters) {
12732 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12733 FD->setInvalidDecl(true);
12734 nparams = 3;
12735 }
12736
12737 // FIXME: a lot of the following diagnostics would be improved
12738 // if we had some location information about types.
12739
12740 QualType CharPP =
12741 Context.getPointerType(Context.getPointerType(Context.CharTy));
12742 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12743
12744 for (unsigned i = 0; i < nparams; ++i) {
12745 QualType AT = FTP->getParamType(i);
12746
12747 bool mismatch = true;
12748
12749 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12750 mismatch = false;
12751 else if (Expected[i] == CharPP) {
12752 // As an extension, the following forms are okay:
12753 // char const **
12754 // char const * const *
12755 // char * const *
12756
12757 QualifierCollector qs;
12758 const PointerType* PT;
12759 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12760 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12761 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12762 Context.CharTy)) {
12763 qs.removeConst();
12764 mismatch = !qs.empty();
12765 }
12766 }
12767
12768 if (mismatch) {
12769 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12770 // TODO: suggest replacing given type with expected type
12771 FD->setInvalidDecl(true);
12772 }
12773 }
12774
12775 if (nparams == 1 && !FD->isInvalidDecl()) {
12776 Diag(FD->getLocation(), diag::warn_main_one_arg);
12777 }
12778
12779 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12780 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12781 FD->setInvalidDecl();
12782 }
12783 }
12784
12785 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12786
12787 // Default calling convention for main and wmain is __cdecl
12788 if (FD->getName() == "main" || FD->getName() == "wmain")
12789 return false;
12790
12791 // Default calling convention for MinGW and Cygwin is __cdecl
12792 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12793 if (T.isOSCygMing())
12794 return false;
12795
12796 // Default calling convention for WinMain, wWinMain and DllMain
12797 // is __stdcall on 32 bit Windows
12798 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12799 return true;
12800
12801 return false;
12802 }
12803
12804 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12805 QualType T = FD->getType();
12806 assert(T->isFunctionType() && "function decl is not of function type");
12807 const FunctionType *FT = T->castAs<FunctionType>();
12808
12809 // Set an implicit return of 'zero' if the function can return some integral,
12810 // enumeration, pointer or nullptr type.
12811 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12812 FT->getReturnType()->isAnyPointerType() ||
12813 FT->getReturnType()->isNullPtrType())
12814 // DllMain is exempt because a return value of zero means it failed.
12815 if (FD->getName() != "DllMain")
12816 FD->setHasImplicitReturnZero(true);
12817
12818 // Explicitly specified calling conventions are applied to MSVC entry points
12819 if (!hasExplicitCallingConv(T)) {
12820 if (isDefaultStdCall(FD, *this)) {
12821 if (FT->getCallConv() != CC_X86StdCall) {
12822 FT = Context.adjustFunctionType(
12823 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12824 FD->setType(QualType(FT, 0));
12825 }
12826 } else if (FT->getCallConv() != CC_C) {
12827 FT = Context.adjustFunctionType(FT,
12828 FT->getExtInfo().withCallingConv(CC_C));
12829 FD->setType(QualType(FT, 0));
12830 }
12831 }
12832
12833 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12834 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12835 FD->setInvalidDecl();
12836 }
12837 }
12838
12839 bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12840 // FIXME: Need strict checking. In C89, we need to check for
12841 // any assignment, increment, decrement, function-calls, or
12842 // commas outside of a sizeof. In C99, it's the same list,
12843 // except that the aforementioned are allowed in unevaluated
12844 // expressions. Everything else falls under the
12845 // "may accept other forms of constant expressions" exception.
12846 //
12847 // Regular C++ code will not end up here (exceptions: language extensions,
12848 // OpenCL C++ etc), so the constant expression rules there don't matter.
12849 if (Init->isValueDependent()) {
12850 assert(Init->containsErrors() &&
12851 "Dependent code should only occur in error-recovery path.");
12852 return true;
12853 }
12854 const Expr *Culprit;
12855 if (Init->isConstantInitializer(Context, false, &Culprit))
12856 return false;
12857 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12858 return true;
12859 }
12860
12861 namespace {
12862 // Visits an initialization expression to see if OrigDecl is evaluated in
12863 // its own initialization and throws a warning if it does.
12864 class SelfReferenceChecker
12865 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12866 Sema &S;
12867 Decl *OrigDecl;
12868 bool isRecordType;
12869 bool isPODType;
12870 bool isReferenceType;
12871 bool isInCXXOperatorCall;
12872
12873 bool isInitList;
12874 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12875
12876 public:
12877 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12878
12879 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12880 S(S), OrigDecl(OrigDecl) {
12881 isPODType = false;
12882 isRecordType = false;
12883 isReferenceType = false;
12884 isInCXXOperatorCall = false;
12885 isInitList = false;
12886 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12887 isPODType = VD->getType().isPODType(S.Context);
12888 isRecordType = VD->getType()->isRecordType();
12889 isReferenceType = VD->getType()->isReferenceType();
12890 }
12891 }
12892
12893 // For most expressions, just call the visitor. For initializer lists,
12894 // track the index of the field being initialized since fields are
12895 // initialized in order allowing use of previously initialized fields.
12896 void CheckExpr(Expr *E) {
12897 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12898 if (!InitList) {
12899 Visit(E);
12900 return;
12901 }
12902
12903 // Track and increment the index here.
12904 isInitList = true;
12905 InitFieldIndex.push_back(0);
12906 for (auto *Child : InitList->children()) {
12907 CheckExpr(cast<Expr>(Child));
12908 ++InitFieldIndex.back();
12909 }
12910 InitFieldIndex.pop_back();
12911 }
12912
12913 // Returns true if MemberExpr is checked and no further checking is needed.
12914 // Returns false if additional checking is required.
12915 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12916 llvm::SmallVector<FieldDecl*, 4> Fields;
12917 Expr *Base = E;
12918 bool ReferenceField = false;
12919
12920 // Get the field members used.
12921 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12922 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12923 if (!FD)
12924 return false;
12925 Fields.push_back(FD);
12926 if (FD->getType()->isReferenceType())
12927 ReferenceField = true;
12928 Base = ME->getBase()->IgnoreParenImpCasts();
12929 }
12930
12931 // Keep checking only if the base Decl is the same.
12932 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12933 if (!DRE || DRE->getDecl() != OrigDecl)
12934 return false;
12935
12936 // A reference field can be bound to an unininitialized field.
12937 if (CheckReference && !ReferenceField)
12938 return true;
12939
12940 // Convert FieldDecls to their index number.
12941 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12942 for (const FieldDecl *I : llvm::reverse(Fields))
12943 UsedFieldIndex.push_back(I->getFieldIndex());
12944
12945 // See if a warning is needed by checking the first difference in index
12946 // numbers. If field being used has index less than the field being
12947 // initialized, then the use is safe.
12948 for (auto UsedIter = UsedFieldIndex.begin(),
12949 UsedEnd = UsedFieldIndex.end(),
12950 OrigIter = InitFieldIndex.begin(),
12951 OrigEnd = InitFieldIndex.end();
12952 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12953 if (*UsedIter < *OrigIter)
12954 return true;
12955 if (*UsedIter > *OrigIter)
12956 break;
12957 }
12958
12959 // TODO: Add a different warning which will print the field names.
12960 HandleDeclRefExpr(DRE);
12961 return true;
12962 }
12963
12964 // For most expressions, the cast is directly above the DeclRefExpr.
12965 // For conditional operators, the cast can be outside the conditional
12966 // operator if both expressions are DeclRefExpr's.
12967 void HandleValue(Expr *E) {
12968 E = E->IgnoreParens();
12969 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12970 HandleDeclRefExpr(DRE);
12971 return;
12972 }
12973
12974 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12975 Visit(CO->getCond());
12976 HandleValue(CO->getTrueExpr());
12977 HandleValue(CO->getFalseExpr());
12978 return;
12979 }
12980
12981 if (BinaryConditionalOperator *BCO =
12982 dyn_cast<BinaryConditionalOperator>(E)) {
12983 Visit(BCO->getCond());
12984 HandleValue(BCO->getFalseExpr());
12985 return;
12986 }
12987
12988 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12989 if (Expr *SE = OVE->getSourceExpr())
12990 HandleValue(SE);
12991 return;
12992 }
12993
12994 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12995 if (BO->getOpcode() == BO_Comma) {
12996 Visit(BO->getLHS());
12997 HandleValue(BO->getRHS());
12998 return;
12999 }
13000 }
13001
13002 if (isa<MemberExpr>(E)) {
13003 if (isInitList) {
13004 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13005 false /*CheckReference*/))
13006 return;
13007 }
13008
13009 Expr *Base = E->IgnoreParenImpCasts();
13010 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13011 // Check for static member variables and don't warn on them.
13012 if (!isa<FieldDecl>(ME->getMemberDecl()))
13013 return;
13014 Base = ME->getBase()->IgnoreParenImpCasts();
13015 }
13016 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13017 HandleDeclRefExpr(DRE);
13018 return;
13019 }
13020
13021 Visit(E);
13022 }
13023
13024 // Reference types not handled in HandleValue are handled here since all
13025 // uses of references are bad, not just r-value uses.
13026 void VisitDeclRefExpr(DeclRefExpr *E) {
13027 if (isReferenceType)
13028 HandleDeclRefExpr(E);
13029 }
13030
13031 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13032 if (E->getCastKind() == CK_LValueToRValue) {
13033 HandleValue(E->getSubExpr());
13034 return;
13035 }
13036
13037 Inherited::VisitImplicitCastExpr(E);
13038 }
13039
13040 void VisitMemberExpr(MemberExpr *E) {
13041 if (isInitList) {
13042 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13043 return;
13044 }
13045
13046 // Don't warn on arrays since they can be treated as pointers.
13047 if (E->getType()->canDecayToPointerType()) return;
13048
13049 // Warn when a non-static method call is followed by non-static member
13050 // field accesses, which is followed by a DeclRefExpr.
13051 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13052 bool Warn = (MD && !MD->isStatic());
13053 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13054 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13055 if (!isa<FieldDecl>(ME->getMemberDecl()))
13056 Warn = false;
13057 Base = ME->getBase()->IgnoreParenImpCasts();
13058 }
13059
13060 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13061 if (Warn)
13062 HandleDeclRefExpr(DRE);
13063 return;
13064 }
13065
13066 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13067 // Visit that expression.
13068 Visit(Base);
13069 }
13070
13071 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13072 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13073 Expr *Callee = E->getCallee();
13074
13075 if (isa<UnresolvedLookupExpr>(Callee))
13076 return Inherited::VisitCXXOperatorCallExpr(E);
13077
13078 Visit(Callee);
13079 for (auto Arg: E->arguments())
13080 HandleValue(Arg->IgnoreParenImpCasts());
13081 }
13082
13083 void VisitLambdaExpr(LambdaExpr *E) {
13084 if (!isInCXXOperatorCall) {
13085 Inherited::VisitLambdaExpr(E);
13086 return;
13087 }
13088
13089 for (Expr *Init : E->capture_inits())
13090 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13091 HandleDeclRefExpr(DRE);
13092 else if (Init)
13093 Visit(Init);
13094 }
13095
13096 void VisitUnaryOperator(UnaryOperator *E) {
13097 // For POD record types, addresses of its own members are well-defined.
13098 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13099 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
13100 if (!isPODType)
13101 HandleValue(E->getSubExpr());
13102 return;
13103 }
13104
13105 if (E->isIncrementDecrementOp()) {
13106 HandleValue(E->getSubExpr());
13107 return;
13108 }
13109
13110 Inherited::VisitUnaryOperator(E);
13111 }
13112
13113 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13114
13115 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13116 if (E->getConstructor()->isCopyConstructor()) {
13117 Expr *ArgExpr = E->getArg(0);
13118 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13119 if (ILE->getNumInits() == 1)
13120 ArgExpr = ILE->getInit(0);
13121 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13122 if (ICE->getCastKind() == CK_NoOp)
13123 ArgExpr = ICE->getSubExpr();
13124 HandleValue(ArgExpr);
13125 return;
13126 }
13127 Inherited::VisitCXXConstructExpr(E);
13128 }
13129
13130 void VisitCallExpr(CallExpr *E) {
13131 // Treat std::move as a use.
13132 if (E->isCallToStdMove()) {
13133 HandleValue(E->getArg(0));
13134 return;
13135 }
13136
13137 Inherited::VisitCallExpr(E);
13138 }
13139
13140 void VisitBinaryOperator(BinaryOperator *E) {
13141 if (E->isCompoundAssignmentOp()) {
13142 HandleValue(E->getLHS());
13143 Visit(E->getRHS());
13144 return;
13145 }
13146
13147 Inherited::VisitBinaryOperator(E);
13148 }
13149
13150 // A custom visitor for BinaryConditionalOperator is needed because the
13151 // regular visitor would check the condition and true expression separately
13152 // but both point to the same place giving duplicate diagnostics.
13153 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13154 Visit(E->getCond());
13155 Visit(E->getFalseExpr());
13156 }
13157
13158 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13159 Decl* ReferenceDecl = DRE->getDecl();
13160 if (OrigDecl != ReferenceDecl) return;
13161 unsigned diag;
13162 if (isReferenceType) {
13163 diag = diag::warn_uninit_self_reference_in_reference_init;
13164 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13165 diag = diag::warn_static_self_reference_in_init;
13166 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13167 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13168 DRE->getDecl()->getType()->isRecordType()) {
13169 diag = diag::warn_uninit_self_reference_in_init;
13170 } else {
13171 // Local variables will be handled by the CFG analysis.
13172 return;
13173 }
13174
13175 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13176 S.PDiag(diag)
13177 << DRE->getDecl() << OrigDecl->getLocation()
13178 << DRE->getSourceRange());
13179 }
13180 };
13181
13182 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13183 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13184 bool DirectInit) {
13185 // Parameters arguments are occassionially constructed with itself,
13186 // for instance, in recursive functions. Skip them.
13187 if (isa<ParmVarDecl>(OrigDecl))
13188 return;
13189
13190 // Skip checking for file-scope constexpr variables - constant evaluation
13191 // will produce appropriate errors without needing runtime diagnostics.
13192 // Local constexpr should still emit runtime warnings.
13193 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13194 VD && VD->isConstexpr() && VD->isFileVarDecl())
13195 return;
13196
13197 E = E->IgnoreParens();
13198
13199 // Skip checking T a = a where T is not a record or reference type.
13200 // Doing so is a way to silence uninitialized warnings.
13201 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13202 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13203 if (ICE->getCastKind() == CK_LValueToRValue)
13204 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13205 if (DRE->getDecl() == OrigDecl)
13206 return;
13207
13208 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13209 }
13210 } // end anonymous namespace
13211
13212 namespace {
13213 // Simple wrapper to add the name of a variable or (if no variable is
13214 // available) a DeclarationName into a diagnostic.
13215 struct VarDeclOrName {
13216 VarDecl *VDecl;
13217 DeclarationName Name;
13218
13219 friend const Sema::SemaDiagnosticBuilder &
13220 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13221 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13222 }
13223 };
13224 } // end anonymous namespace
13225
13226 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13227 DeclarationName Name, QualType Type,
13228 TypeSourceInfo *TSI,
13229 SourceRange Range, bool DirectInit,
13230 Expr *Init) {
13231 bool IsInitCapture = !VDecl;
13232 assert((!VDecl || !VDecl->isInitCapture()) &&
13233 "init captures are expected to be deduced prior to initialization");
13234
13235 VarDeclOrName VN{VDecl, Name};
13236
13237 DeducedType *Deduced = Type->getContainedDeducedType();
13238 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13239
13240 // Diagnose auto array declarations in C23, unless it's a supported extension.
13241 if (getLangOpts().C23 && Type->isArrayType() &&
13242 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13243 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13244 << (int)Deduced->getContainedAutoType()->getKeyword()
13245 << /*in array decl*/ 23 << Range;
13246 return QualType();
13247 }
13248
13249 // C++11 [dcl.spec.auto]p3
13250 if (!Init) {
13251 assert(VDecl && "no init for init capture deduction?");
13252
13253 // Except for class argument deduction, and then for an initializing
13254 // declaration only, i.e. no static at class scope or extern.
13255 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
13256 VDecl->hasExternalStorage() ||
13257 VDecl->isStaticDataMember()) {
13258 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13259 << VDecl->getDeclName() << Type;
13260 return QualType();
13261 }
13262 }
13263
13264 ArrayRef<Expr*> DeduceInits;
13265 if (Init)
13266 DeduceInits = Init;
13267
13268 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13269 if (DirectInit && PL)
13270 DeduceInits = PL->exprs();
13271
13272 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
13273 assert(VDecl && "non-auto type for init capture deduction?");
13274 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13275 InitializationKind Kind = InitializationKind::CreateForInit(
13276 VDecl->getLocation(), DirectInit, Init);
13277 // FIXME: Initialization should not be taking a mutable list of inits.
13278 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13279 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13280 InitsCopy);
13281 }
13282
13283 if (DirectInit) {
13284 if (auto *IL = dyn_cast<InitListExpr>(Init))
13285 DeduceInits = IL->inits();
13286 }
13287
13288 // Deduction only works if we have exactly one source expression.
13289 if (DeduceInits.empty()) {
13290 // It isn't possible to write this directly, but it is possible to
13291 // end up in this situation with "auto x(some_pack...);"
13292 Diag(Init->getBeginLoc(), IsInitCapture
13293 ? diag::err_init_capture_no_expression
13294 : diag::err_auto_var_init_no_expression)
13295 << VN << Type << Range;
13296 return QualType();
13297 }
13298
13299 if (DeduceInits.size() > 1) {
13300 Diag(DeduceInits[1]->getBeginLoc(),
13301 IsInitCapture ? diag::err_init_capture_multiple_expressions
13302 : diag::err_auto_var_init_multiple_expressions)
13303 << VN << Type << Range;
13304 return QualType();
13305 }
13306
13307 Expr *DeduceInit = DeduceInits[0];
13308 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13309 Diag(Init->getBeginLoc(), IsInitCapture
13310 ? diag::err_init_capture_paren_braces
13311 : diag::err_auto_var_init_paren_braces)
13312 << isa<InitListExpr>(Init) << VN << Type << Range;
13313 return QualType();
13314 }
13315
13316 // Expressions default to 'id' when we're in a debugger.
13317 bool DefaultedAnyToId = false;
13318 if (getLangOpts().DebuggerCastResultToId &&
13319 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13320 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13321 if (Result.isInvalid()) {
13322 return QualType();
13323 }
13324 Init = Result.get();
13325 DefaultedAnyToId = true;
13326 }
13327
13328 // C++ [dcl.decomp]p1:
13329 // If the assignment-expression [...] has array type A and no ref-qualifier
13330 // is present, e has type cv A
13331 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13332 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13333 DeduceInit->getType()->isConstantArrayType())
13334 return Context.getQualifiedType(DeduceInit->getType(),
13335 Type.getQualifiers());
13336
13337 QualType DeducedType;
13338 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13339 TemplateDeductionResult Result =
13340 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13341 if (Result != TemplateDeductionResult::Success &&
13342 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13343 if (!IsInitCapture)
13344 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13345 else if (isa<InitListExpr>(Init))
13346 Diag(Range.getBegin(),
13347 diag::err_init_capture_deduction_failure_from_init_list)
13348 << VN
13349 << (DeduceInit->getType().isNull() ? TSI->getType()
13350 : DeduceInit->getType())
13351 << DeduceInit->getSourceRange();
13352 else
13353 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13354 << VN << TSI->getType()
13355 << (DeduceInit->getType().isNull() ? TSI->getType()
13356 : DeduceInit->getType())
13357 << DeduceInit->getSourceRange();
13358 }
13359
13360 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13361 // 'id' instead of a specific object type prevents most of our usual
13362 // checks.
13363 // We only want to warn outside of template instantiations, though:
13364 // inside a template, the 'id' could have come from a parameter.
13365 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13366 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13367 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13368 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13369 }
13370
13371 return DeducedType;
13372 }
13373
13374 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13375 Expr *Init) {
13376 assert(!Init || !Init->containsErrors());
13377 QualType DeducedType = deduceVarTypeFromInitializer(
13378 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13379 VDecl->getSourceRange(), DirectInit, Init);
13380 if (DeducedType.isNull()) {
13381 VDecl->setInvalidDecl();
13382 return true;
13383 }
13384
13385 VDecl->setType(DeducedType);
13386 assert(VDecl->isLinkageValid());
13387
13388 // In ARC, infer lifetime.
13389 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13390 VDecl->setInvalidDecl();
13391
13392 if (getLangOpts().OpenCL)
13393 deduceOpenCLAddressSpace(VDecl);
13394
13395 if (getLangOpts().HLSL)
13396 HLSL().deduceAddressSpace(VDecl);
13397
13398 // If this is a redeclaration, check that the type we just deduced matches
13399 // the previously declared type.
13400 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13401 // We never need to merge the type, because we cannot form an incomplete
13402 // array of auto, nor deduce such a type.
13403 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13404 }
13405
13406 // Check the deduced type is valid for a variable declaration.
13407 CheckVariableDeclarationType(VDecl);
13408 return VDecl->isInvalidDecl();
13409 }
13410
13411 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13412 SourceLocation Loc) {
13413 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13414 Init = EWC->getSubExpr();
13415
13416 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13417 Init = CE->getSubExpr();
13418
13419 QualType InitType = Init->getType();
13420 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13421 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13422 "shouldn't be called if type doesn't have a non-trivial C struct");
13423 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13424 for (auto *I : ILE->inits()) {
13425 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13426 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13427 continue;
13428 SourceLocation SL = I->getExprLoc();
13429 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13430 }
13431 return;
13432 }
13433
13434 if (isa<ImplicitValueInitExpr>(Init)) {
13435 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13436 checkNonTrivialCUnion(InitType, Loc,
13437 NonTrivialCUnionContext::DefaultInitializedObject,
13438 NTCUK_Init);
13439 } else {
13440 // Assume all other explicit initializers involving copying some existing
13441 // object.
13442 // TODO: ignore any explicit initializers where we can guarantee
13443 // copy-elision.
13444 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13445 checkNonTrivialCUnion(InitType, Loc, NonTrivialCUnionContext::CopyInit,
13446 NTCUK_Copy);
13447 }
13448 }
13449
13450 namespace {
13451
13452 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13453 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13454 // in the source code or implicitly by the compiler if it is in a union
13455 // defined in a system header and has non-trivial ObjC ownership
13456 // qualifications. We don't want those fields to participate in determining
13457 // whether the containing union is non-trivial.
13458 return FD->hasAttr<UnavailableAttr>();
13459 }
13460
13461 struct DiagNonTrivalCUnionDefaultInitializeVisitor
13462 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13463 void> {
13464 using Super =
13465 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13466 void>;
13467
13468 DiagNonTrivalCUnionDefaultInitializeVisitor(
13469 QualType OrigTy, SourceLocation OrigLoc,
13470 NonTrivialCUnionContext UseContext, Sema &S)
13471 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13472
13473 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13474 const FieldDecl *FD, bool InNonTrivialUnion) {
13475 if (const auto *AT = S.Context.getAsArrayType(QT))
13476 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13477 InNonTrivialUnion);
13478 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13479 }
13480
13481 void visitARCStrong(QualType QT, const FieldDecl *FD,
13482 bool InNonTrivialUnion) {
13483 if (InNonTrivialUnion)
13484 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13485 << 1 << 0 << QT << FD->getName();
13486 }
13487
13488 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13489 if (InNonTrivialUnion)
13490 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13491 << 1 << 0 << QT << FD->getName();
13492 }
13493
13494 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13495 const auto *RD = QT->castAsRecordDecl();
13496 if (RD->isUnion()) {
13497 if (OrigLoc.isValid()) {
13498 bool IsUnion = false;
13499 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13500 IsUnion = OrigRD->isUnion();
13501 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13502 << 0 << OrigTy << IsUnion << UseContext;
13503 // Reset OrigLoc so that this diagnostic is emitted only once.
13504 OrigLoc = SourceLocation();
13505 }
13506 InNonTrivialUnion = true;
13507 }
13508
13509 if (InNonTrivialUnion)
13510 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13511 << 0 << 0 << QT.getUnqualifiedType() << "";
13512
13513 for (const FieldDecl *FD : RD->fields())
13514 if (!shouldIgnoreForRecordTriviality(FD))
13515 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13516 }
13517
13518 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13519
13520 // The non-trivial C union type or the struct/union type that contains a
13521 // non-trivial C union.
13522 QualType OrigTy;
13523 SourceLocation OrigLoc;
13524 NonTrivialCUnionContext UseContext;
13525 Sema &S;
13526 };
13527
13528 struct DiagNonTrivalCUnionDestructedTypeVisitor
13529 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13530 using Super =
13531 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13532
13533 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13534 SourceLocation OrigLoc,
13535 NonTrivialCUnionContext UseContext,
13536 Sema &S)
13537 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13538
13539 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13540 const FieldDecl *FD, bool InNonTrivialUnion) {
13541 if (const auto *AT = S.Context.getAsArrayType(QT))
13542 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13543 InNonTrivialUnion);
13544 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13545 }
13546
13547 void visitARCStrong(QualType QT, const FieldDecl *FD,
13548 bool InNonTrivialUnion) {
13549 if (InNonTrivialUnion)
13550 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13551 << 1 << 1 << QT << FD->getName();
13552 }
13553
13554 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13555 if (InNonTrivialUnion)
13556 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13557 << 1 << 1 << QT << FD->getName();
13558 }
13559
13560 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13561 const auto *RD = QT->castAsRecordDecl();
13562 if (RD->isUnion()) {
13563 if (OrigLoc.isValid()) {
13564 bool IsUnion = false;
13565 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13566 IsUnion = OrigRD->isUnion();
13567 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13568 << 1 << OrigTy << IsUnion << UseContext;
13569 // Reset OrigLoc so that this diagnostic is emitted only once.
13570 OrigLoc = SourceLocation();
13571 }
13572 InNonTrivialUnion = true;
13573 }
13574
13575 if (InNonTrivialUnion)
13576 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13577 << 0 << 1 << QT.getUnqualifiedType() << "";
13578
13579 for (const FieldDecl *FD : RD->fields())
13580 if (!shouldIgnoreForRecordTriviality(FD))
13581 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13582 }
13583
13584 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13585 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13586 bool InNonTrivialUnion) {}
13587
13588 // The non-trivial C union type or the struct/union type that contains a
13589 // non-trivial C union.
13590 QualType OrigTy;
13591 SourceLocation OrigLoc;
13592 NonTrivialCUnionContext UseContext;
13593 Sema &S;
13594 };
13595
13596 struct DiagNonTrivalCUnionCopyVisitor
13597 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13598 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13599
13600 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13601 NonTrivialCUnionContext UseContext, Sema &S)
13602 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13603
13604 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13605 const FieldDecl *FD, bool InNonTrivialUnion) {
13606 if (const auto *AT = S.Context.getAsArrayType(QT))
13607 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13608 InNonTrivialUnion);
13609 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13610 }
13611
13612 void visitARCStrong(QualType QT, const FieldDecl *FD,
13613 bool InNonTrivialUnion) {
13614 if (InNonTrivialUnion)
13615 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13616 << 1 << 2 << QT << FD->getName();
13617 }
13618
13619 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13620 if (InNonTrivialUnion)
13621 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13622 << 1 << 2 << QT << FD->getName();
13623 }
13624
13625 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13626 const auto *RD = QT->castAsRecordDecl();
13627 if (RD->isUnion()) {
13628 if (OrigLoc.isValid()) {
13629 bool IsUnion = false;
13630 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13631 IsUnion = OrigRD->isUnion();
13632 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13633 << 2 << OrigTy << IsUnion << UseContext;
13634 // Reset OrigLoc so that this diagnostic is emitted only once.
13635 OrigLoc = SourceLocation();
13636 }
13637 InNonTrivialUnion = true;
13638 }
13639
13640 if (InNonTrivialUnion)
13641 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13642 << 0 << 2 << QT.getUnqualifiedType() << "";
13643
13644 for (const FieldDecl *FD : RD->fields())
13645 if (!shouldIgnoreForRecordTriviality(FD))
13646 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13647 }
13648
13649 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13650 if (InNonTrivialUnion)
13651 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13652 << 1 << 2 << QT << FD->getName();
13653 }
13654
13655 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13656 const FieldDecl *FD, bool InNonTrivialUnion) {}
13657 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13658 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13659 bool InNonTrivialUnion) {}
13660
13661 // The non-trivial C union type or the struct/union type that contains a
13662 // non-trivial C union.
13663 QualType OrigTy;
13664 SourceLocation OrigLoc;
13665 NonTrivialCUnionContext UseContext;
13666 Sema &S;
13667 };
13668
13669 } // namespace
13670
13671 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13672 NonTrivialCUnionContext UseContext,
13673 unsigned NonTrivialKind) {
13674 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13675 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13676 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13677 "shouldn't be called if type doesn't have a non-trivial C union");
13678
13679 if ((NonTrivialKind & NTCUK_Init) &&
13680 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13681 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13682 .visit(QT, nullptr, false);
13683 if ((NonTrivialKind & NTCUK_Destruct) &&
13684 QT.hasNonTrivialToPrimitiveDestructCUnion())
13685 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13686 .visit(QT, nullptr, false);
13687 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13688 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13689 .visit(QT, nullptr, false);
13690 }
13691
13692 bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13693 const VarDecl *Dcl) {
13694 if (!getLangOpts().CPlusPlus)
13695 return false;
13696
13697 // We only need to warn if the definition is in a header file, so wait to
13698 // diagnose until we've seen the definition.
13699 if (!Dcl->isThisDeclarationADefinition())
13700 return false;
13701
13702 // If an object is defined in a source file, its definition can't get
13703 // duplicated since it will never appear in more than one TU.
13704 if (Dcl->getASTContext().getSourceManager().isInMainFile(Dcl->getLocation()))
13705 return false;
13706
13707 // If the variable we're looking at is a static local, then we actually care
13708 // about the properties of the function containing it.
13709 const ValueDecl *Target = Dcl;
13710 // VarDecls and FunctionDecls have different functions for checking
13711 // inline-ness, and whether they were originally templated, so we have to
13712 // call the appropriate functions manually.
13713 bool TargetIsInline = Dcl->isInline();
13714 bool TargetWasTemplated =
13715 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13716
13717 // Update the Target and TargetIsInline property if necessary
13718 if (Dcl->isStaticLocal()) {
13719 const DeclContext *Ctx = Dcl->getDeclContext();
13720 if (!Ctx)
13721 return false;
13722
13723 const FunctionDecl *FunDcl =
13724 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13725 if (!FunDcl)
13726 return false;
13727
13728 Target = FunDcl;
13729 // IsInlined() checks for the C++ inline property
13730 TargetIsInline = FunDcl->isInlined();
13731 TargetWasTemplated =
13732 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13733 }
13734
13735 // Non-inline functions/variables can only legally appear in one TU
13736 // unless they were part of a template. Unfortunately, making complex
13737 // template instantiations visible is infeasible in practice, since
13738 // everything the template depends on also has to be visible. To avoid
13739 // giving impractical-to-fix warnings, don't warn if we're inside
13740 // something that was templated, even on inline stuff.
13741 if (!TargetIsInline || TargetWasTemplated)
13742 return false;
13743
13744 // If the object isn't hidden, the dynamic linker will prevent duplication.
13745 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13746
13747 // The target is "hidden" (from the dynamic linker) if:
13748 // 1. On posix, it has hidden visibility, or
13749 // 2. On windows, it has no import/export annotation, and neither does the
13750 // class which directly contains it.
13751 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13752 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13753 return false;
13754
13755 // If the variable isn't directly annotated, check to see if it's a member
13756 // of an annotated class.
13757 const CXXRecordDecl *Ctx =
13758 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13759 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13760 return false;
13761
13762 } else if (Lnk.getVisibility() != HiddenVisibility) {
13763 // Posix case
13764 return false;
13765 }
13766
13767 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13768 if (!isExternalFormalLinkage(Lnk.getLinkage()))
13769 return false;
13770
13771 return true;
13772 }
13773
13774 // Determine whether the object seems mutable for the purpose of diagnosing
13775 // possible unique object duplication, i.e. non-const-qualified, and
13776 // not an always-constant type like a function.
13777 // Not perfect: doesn't account for mutable members, for example, or
13778 // elements of container types.
13779 // For nested pointers, any individual level being non-const is sufficient.
13780 static bool looksMutable(QualType T, const ASTContext &Ctx) {
13781 T = T.getNonReferenceType();
13782 if (T->isFunctionType())
13783 return false;
13784 if (!T.isConstant(Ctx))
13785 return true;
13786 if (T->isPointerType())
13787 return looksMutable(T->getPointeeType(), Ctx);
13788 return false;
13789 }
13790
13791 void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13792 // If this object has external linkage and hidden visibility, it might be
13793 // duplicated when built into a shared library, which causes problems if it's
13794 // mutable (since the copies won't be in sync) or its initialization has side
13795 // effects (since it will run once per copy instead of once globally).
13796
13797 // Don't diagnose if we're inside a template, because it's not practical to
13798 // fix the warning in most cases.
13799 if (!VD->isTemplated() &&
13800 GloballyUniqueObjectMightBeAccidentallyDuplicated(VD)) {
13801
13802 QualType Type = VD->getType();
13803 if (looksMutable(Type, VD->getASTContext())) {
13804 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13805 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13806 }
13807
13808 // To keep false positives low, only warn if we're certain that the
13809 // initializer has side effects. Don't warn on operator new, since a mutable
13810 // pointer will trigger the previous warning, and an immutable pointer
13811 // getting duplicated just results in a little extra memory usage.
13812 const Expr *Init = VD->getAnyInitializer();
13813 if (Init &&
13814 Init->HasSideEffects(VD->getASTContext(),
13815 /*IncludePossibleEffects=*/false) &&
13816 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13817 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13818 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13819 }
13820 }
13821 }
13822
13823 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13824 llvm::scope_exit ResetDeclForInitializer([this]() {
13825 if (this->ExprEvalContexts.empty())
13826 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13827 });
13828
13829 // If there is no declaration, there was an error parsing it. Just ignore
13830 // the initializer.
13831 if (!RealDecl) {
13832 return;
13833 }
13834
13835 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13836 if (!Method->isInvalidDecl()) {
13837 // Pure-specifiers are handled in ActOnPureSpecifier.
13838 Diag(Method->getLocation(), diag::err_member_function_initialization)
13839 << Method->getDeclName() << Init->getSourceRange();
13840 Method->setInvalidDecl();
13841 }
13842 return;
13843 }
13844
13845 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13846 if (!VDecl) {
13847 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13848 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13849 RealDecl->setInvalidDecl();
13850 return;
13851 }
13852
13853 if (VDecl->isInvalidDecl()) {
13854 ExprResult Recovery =
13855 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13856 if (Expr *E = Recovery.get())
13857 VDecl->setInit(E);
13858 return;
13859 }
13860
13861 // WebAssembly tables can't be used to initialise a variable.
13862 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13863 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13864 VDecl->setInvalidDecl();
13865 return;
13866 }
13867
13868 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13869 if (VDecl->getType()->isUndeducedType()) {
13870 if (Init->containsErrors()) {
13871 // Invalidate the decl as we don't know the type for recovery-expr yet.
13872 RealDecl->setInvalidDecl();
13873 VDecl->setInit(Init);
13874 return;
13875 }
13876
13877 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
13878 assert(VDecl->isInvalidDecl() &&
13879 "decl should be invalidated when deduce fails");
13880 if (auto *RecoveryExpr =
13881 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
13882 .get())
13883 VDecl->setInit(RecoveryExpr);
13884 return;
13885 }
13886 }
13887
13888 this->CheckAttributesOnDeducedType(RealDecl);
13889
13890 // dllimport cannot be used on variable definitions.
13891 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13892 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13893 VDecl->setInvalidDecl();
13894 return;
13895 }
13896
13897 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13898 // the identifier has external or internal linkage, the declaration shall
13899 // have no initializer for the identifier.
13900 // C++14 [dcl.init]p5 is the same restriction for C++.
13901 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13902 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13903 VDecl->setInvalidDecl();
13904 return;
13905 }
13906
13907 if (!VDecl->getType()->isDependentType()) {
13908 // A definition must end up with a complete type, which means it must be
13909 // complete with the restriction that an array type might be completed by
13910 // the initializer; note that later code assumes this restriction.
13911 QualType BaseDeclType = VDecl->getType();
13912 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13913 BaseDeclType = Array->getElementType();
13914 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13915 diag::err_typecheck_decl_incomplete_type)) {
13916 RealDecl->setInvalidDecl();
13917 return;
13918 }
13919
13920 // The variable can not have an abstract class type.
13921 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13922 diag::err_abstract_type_in_decl,
13923 AbstractVariableType))
13924 VDecl->setInvalidDecl();
13925 }
13926
13927 // C++ [module.import/6]
13928 // ...
13929 // A header unit shall not contain a definition of a non-inline function or
13930 // variable whose name has external linkage.
13931 //
13932 // We choose to allow weak & selectany definitions, as they are common in
13933 // headers, and have semantics similar to inline definitions which are allowed
13934 // in header units.
13935 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13936 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13937 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13938 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13939 !VDecl->getInstantiatedFromStaticDataMember() &&
13940 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13941 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13942 VDecl->setInvalidDecl();
13943 }
13944
13945 // If adding the initializer will turn this declaration into a definition,
13946 // and we already have a definition for this variable, diagnose or otherwise
13947 // handle the situation.
13948 if (VarDecl *Def = VDecl->getDefinition())
13949 if (Def != VDecl &&
13950 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13951 !VDecl->isThisDeclarationADemotedDefinition() &&
13952 checkVarDeclRedefinition(Def, VDecl))
13953 return;
13954
13955 if (getLangOpts().CPlusPlus) {
13956 // C++ [class.static.data]p4
13957 // If a static data member is of const integral or const
13958 // enumeration type, its declaration in the class definition can
13959 // specify a constant-initializer which shall be an integral
13960 // constant expression (5.19). In that case, the member can appear
13961 // in integral constant expressions. The member shall still be
13962 // defined in a namespace scope if it is used in the program and the
13963 // namespace scope definition shall not contain an initializer.
13964 //
13965 // We already performed a redefinition check above, but for static
13966 // data members we also need to check whether there was an in-class
13967 // declaration with an initializer.
13968 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13969 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13970 << VDecl->getDeclName();
13971 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13972 diag::note_previous_initializer)
13973 << 0;
13974 return;
13975 }
13976
13977 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13978 VDecl->setInvalidDecl();
13979 return;
13980 }
13981 }
13982
13983 // If the variable has an initializer and local storage, check whether
13984 // anything jumps over the initialization.
13985 if (VDecl->hasLocalStorage())
13986 setFunctionHasBranchProtectedScope();
13987
13988 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13989 // a kernel function cannot be initialized."
13990 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13991 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13992 VDecl->setInvalidDecl();
13993 return;
13994 }
13995
13996 // The LoaderUninitialized attribute acts as a definition (of undef).
13997 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13998 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13999 VDecl->setInvalidDecl();
14000 return;
14001 }
14002
14003 if (getLangOpts().HLSL)
14004 if (!HLSL().handleInitialization(VDecl, Init))
14005 return;
14006
14007 // Get the decls type and save a reference for later, since
14008 // CheckInitializerTypes may change it.
14009 QualType DclT = VDecl->getType(), SavT = DclT;
14010
14011 // Expressions default to 'id' when we're in a debugger
14012 // and we are assigning it to a variable of Objective-C pointer type.
14013 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14014 Init->getType() == Context.UnknownAnyTy) {
14015 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
14016 if (!Result.isUsable()) {
14017 VDecl->setInvalidDecl();
14018 return;
14019 }
14020 Init = Result.get();
14021 }
14022
14023 // Perform the initialization.
14024 bool InitializedFromParenListExpr = false;
14025 bool IsParenListInit = false;
14026 if (!VDecl->isInvalidDecl()) {
14027 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
14028 InitializationKind Kind = InitializationKind::CreateForInit(
14029 VDecl->getLocation(), DirectInit, Init);
14030
14031 MultiExprArg Args = Init;
14032 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14033 Args =
14034 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14035 InitializedFromParenListExpr = true;
14036 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14037 Args = CXXDirectInit->getInitExprs();
14038 InitializedFromParenListExpr = true;
14039 }
14040
14041 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14042 /*TopLevelOfInitList=*/false,
14043 /*TreatUnavailableAsInvalid=*/false);
14044 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14045 if (!Result.isUsable()) {
14046 // If the provided initializer fails to initialize the var decl,
14047 // we attach a recovery expr for better recovery.
14048 auto RecoveryExpr =
14049 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14050 if (RecoveryExpr.get())
14051 VDecl->setInit(RecoveryExpr.get());
14052 // In general, for error recovery purposes, the initializer doesn't play
14053 // part in the valid bit of the declaration. There are a few exceptions:
14054 // 1) if the var decl has a deduced auto type, and the type cannot be
14055 // deduced by an invalid initializer;
14056 // 2) if the var decl is a decomposition decl with a non-deduced type,
14057 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14058 // Case 1) was already handled elsewhere.
14059 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14060 VDecl->setInvalidDecl();
14061 return;
14062 }
14063
14064 Init = Result.getAs<Expr>();
14065 IsParenListInit = !InitSeq.steps().empty() &&
14066 InitSeq.step_begin()->Kind ==
14067 InitializationSequence::SK_ParenthesizedListInit;
14068 QualType VDeclType = VDecl->getType();
14069 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14070 !VDeclType->isDependentType() &&
14071 Context.getAsIncompleteArrayType(VDeclType) &&
14072 Context.getAsIncompleteArrayType(Init->getType())) {
14073 // Bail out if it is not possible to deduce array size from the
14074 // initializer.
14075 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14076 << VDeclType;
14077 VDecl->setInvalidDecl();
14078 return;
14079 }
14080 }
14081
14082 // Check for self-references within variable initializers.
14083 // Variables declared within a function/method body (except for references)
14084 // are handled by a dataflow analysis.
14085 // This is undefined behavior in C++, but valid in C.
14086 if (getLangOpts().CPlusPlus)
14087 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14088 VDecl->getType()->isReferenceType())
14089 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14090
14091 // If the type changed, it means we had an incomplete type that was
14092 // completed by the initializer. For example:
14093 // int ary[] = { 1, 3, 5 };
14094 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14095 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14096 VDecl->setType(DclT);
14097
14098 if (!VDecl->isInvalidDecl()) {
14099 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14100
14101 if (VDecl->hasAttr<BlocksAttr>())
14102 ObjC().checkRetainCycles(VDecl, Init);
14103
14104 // It is safe to assign a weak reference into a strong variable.
14105 // Although this code can still have problems:
14106 // id x = self.weakProp;
14107 // id y = self.weakProp;
14108 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14109 // paths through the function. This should be revisited if
14110 // -Wrepeated-use-of-weak is made flow-sensitive.
14111 if (FunctionScopeInfo *FSI = getCurFunction())
14112 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14113 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14114 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14115 Init->getBeginLoc()))
14116 FSI->markSafeWeakUse(Init);
14117 }
14118
14119 // The initialization is usually a full-expression.
14120 //
14121 // FIXME: If this is a braced initialization of an aggregate, it is not
14122 // an expression, and each individual field initializer is a separate
14123 // full-expression. For instance, in:
14124 //
14125 // struct Temp { ~Temp(); };
14126 // struct S { S(Temp); };
14127 // struct T { S a, b; } t = { Temp(), Temp() }
14128 //
14129 // we should destroy the first Temp before constructing the second.
14130 ExprResult Result =
14131 ActOnFinishFullExpr(Init, VDecl->getLocation(),
14132 /*DiscardedValue*/ false, VDecl->isConstexpr());
14133 if (!Result.isUsable()) {
14134 VDecl->setInvalidDecl();
14135 return;
14136 }
14137 Init = Result.get();
14138
14139 // Attach the initializer to the decl.
14140 VDecl->setInit(Init);
14141
14142 if (VDecl->isLocalVarDecl()) {
14143 // Don't check the initializer if the declaration is malformed.
14144 if (VDecl->isInvalidDecl()) {
14145 // do nothing
14146
14147 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14148 // This is true even in C++ for OpenCL.
14149 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14150 CheckForConstantInitializer(Init);
14151
14152 // Otherwise, C++ does not restrict the initializer.
14153 } else if (getLangOpts().CPlusPlus) {
14154 // do nothing
14155
14156 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14157 // static storage duration shall be constant expressions or string literals.
14158 } else if (VDecl->getStorageClass() == SC_Static) {
14159 // Avoid evaluating the initializer twice for constexpr variables. It will
14160 // be evaluated later.
14161 if (!VDecl->isConstexpr())
14162 CheckForConstantInitializer(Init);
14163
14164 // C89 is stricter than C99 for aggregate initializers.
14165 // C89 6.5.7p3: All the expressions [...] in an initializer list
14166 // for an object that has aggregate or union type shall be
14167 // constant expressions.
14168 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14169 isa<InitListExpr>(Init)) {
14170 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14171 }
14172
14173 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14174 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14175 if (VDecl->hasLocalStorage())
14176 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14177 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14178 VDecl->getLexicalDeclContext()->isRecord()) {
14179 // This is an in-class initialization for a static data member, e.g.,
14180 //
14181 // struct S {
14182 // static const int value = 17;
14183 // };
14184
14185 // C++ [class.mem]p4:
14186 // A member-declarator can contain a constant-initializer only
14187 // if it declares a static member (9.4) of const integral or
14188 // const enumeration type, see 9.4.2.
14189 //
14190 // C++11 [class.static.data]p3:
14191 // If a non-volatile non-inline const static data member is of integral
14192 // or enumeration type, its declaration in the class definition can
14193 // specify a brace-or-equal-initializer in which every initializer-clause
14194 // that is an assignment-expression is a constant expression. A static
14195 // data member of literal type can be declared in the class definition
14196 // with the constexpr specifier; if so, its declaration shall specify a
14197 // brace-or-equal-initializer in which every initializer-clause that is
14198 // an assignment-expression is a constant expression.
14199
14200 // Do nothing on dependent types.
14201 if (DclT->isDependentType()) {
14202
14203 // Allow any 'static constexpr' members, whether or not they are of literal
14204 // type. We separately check that every constexpr variable is of literal
14205 // type.
14206 } else if (VDecl->isConstexpr()) {
14207
14208 // Require constness.
14209 } else if (!DclT.isConstQualified()) {
14210 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14211 << Init->getSourceRange();
14212 VDecl->setInvalidDecl();
14213
14214 // We allow integer constant expressions in all cases.
14215 } else if (DclT->isIntegralOrEnumerationType()) {
14216 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14217 // In C++11, a non-constexpr const static data member with an
14218 // in-class initializer cannot be volatile.
14219 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14220
14221 // We allow foldable floating-point constants as an extension.
14222 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14223 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14224 // it anyway and provide a fixit to add the 'constexpr'.
14225 if (getLangOpts().CPlusPlus11) {
14226 Diag(VDecl->getLocation(),
14227 diag::ext_in_class_initializer_float_type_cxx11)
14228 << DclT << Init->getSourceRange();
14229 Diag(VDecl->getBeginLoc(),
14230 diag::note_in_class_initializer_float_type_cxx11)
14231 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14232 } else {
14233 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14234 << DclT << Init->getSourceRange();
14235
14236 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14237 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14238 << Init->getSourceRange();
14239 VDecl->setInvalidDecl();
14240 }
14241 }
14242
14243 // Suggest adding 'constexpr' in C++11 for literal types.
14244 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14245 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14246 << DclT << Init->getSourceRange()
14247 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14248 VDecl->setConstexpr(true);
14249
14250 } else {
14251 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14252 << DclT << Init->getSourceRange();
14253 VDecl->setInvalidDecl();
14254 }
14255 } else if (VDecl->isFileVarDecl()) {
14256 // In C, extern is typically used to avoid tentative definitions when
14257 // declaring variables in headers, but adding an initializer makes it a
14258 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14259 // In C++, extern is often used to give implicitly static const variables
14260 // external linkage, so don't warn in that case. If selectany is present,
14261 // this might be header code intended for C and C++ inclusion, so apply the
14262 // C++ rules.
14263 if (VDecl->getStorageClass() == SC_Extern &&
14264 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14265 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14266 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14267 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
14268 Diag(VDecl->getLocation(), diag::warn_extern_init);
14269
14270 // In Microsoft C++ mode, a const variable defined in namespace scope has
14271 // external linkage by default if the variable is declared with
14272 // __declspec(dllexport).
14273 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14274 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14275 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14276 VDecl->setStorageClass(SC_Extern);
14277
14278 // C99 6.7.8p4. All file scoped initializers need to be constant.
14279 // Avoid duplicate diagnostics for constexpr variables.
14280 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14281 !VDecl->isConstexpr())
14282 CheckForConstantInitializer(Init);
14283 }
14284
14285 QualType InitType = Init->getType();
14286 if (!InitType.isNull() &&
14287 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14288 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14289 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
14290
14291 // We will represent direct-initialization similarly to copy-initialization:
14292 // int x(1); -as-> int x = 1;
14293 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14294 //
14295 // Clients that want to distinguish between the two forms, can check for
14296 // direct initializer using VarDecl::getInitStyle().
14297 // A major benefit is that clients that don't particularly care about which
14298 // exactly form was it (like the CodeGen) can handle both cases without
14299 // special case code.
14300
14301 // C++ 8.5p11:
14302 // The form of initialization (using parentheses or '=') matters
14303 // when the entity being initialized has class type.
14304 if (InitializedFromParenListExpr) {
14305 assert(DirectInit && "Call-style initializer must be direct init.");
14306 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14307 : VarDecl::CallInit);
14308 } else if (DirectInit) {
14309 // This must be list-initialization. No other way is direct-initialization.
14310 VDecl->setInitStyle(VarDecl::ListInit);
14311 }
14312
14313 if (LangOpts.OpenMP &&
14314 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14315 VDecl->isFileVarDecl())
14316 DeclsToCheckForDeferredDiags.insert(VDecl);
14317 CheckCompleteVariableDeclaration(VDecl);
14318
14319 if (LangOpts.OpenACC && !InitType.isNull())
14320 OpenACC().ActOnVariableInit(VDecl, InitType);
14321 }
14322
14323 void Sema::ActOnInitializerError(Decl *D) {
14324 // Our main concern here is re-establishing invariants like "a
14325 // variable's type is either dependent or complete".
14326 if (!D || D->isInvalidDecl()) return;
14327
14328 VarDecl *VD = dyn_cast<VarDecl>(D);
14329 if (!VD) return;
14330
14331 // Bindings are not usable if we can't make sense of the initializer.
14332 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14333 for (auto *BD : DD->bindings())
14334 BD->setInvalidDecl();
14335
14336 // Auto types are meaningless if we can't make sense of the initializer.
14337 if (VD->getType()->isUndeducedType()) {
14338 D->setInvalidDecl();
14339 return;
14340 }
14341
14342 QualType Ty = VD->getType();
14343 if (Ty->isDependentType()) return;
14344
14345 // Require a complete type.
14346 if (RequireCompleteType(VD->getLocation(),
14347 Context.getBaseElementType(Ty),
14348 diag::err_typecheck_decl_incomplete_type)) {
14349 VD->setInvalidDecl();
14350 return;
14351 }
14352
14353 // Require a non-abstract type.
14354 if (RequireNonAbstractType(VD->getLocation(), Ty,
14355 diag::err_abstract_type_in_decl,
14356 AbstractVariableType)) {
14357 VD->setInvalidDecl();
14358 return;
14359 }
14360
14361 // Don't bother complaining about constructors or destructors,
14362 // though.
14363 }
14364
14365 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14366 // If there is no declaration, there was an error parsing it. Just ignore it.
14367 if (!RealDecl)
14368 return;
14369
14370 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14371 QualType Type = Var->getType();
14372
14373 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14374 if (isa<DecompositionDecl>(RealDecl)) {
14375 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14376 Var->setInvalidDecl();
14377 return;
14378 }
14379
14380 if (Type->isUndeducedType() &&
14381 DeduceVariableDeclarationType(Var, false, nullptr))
14382 return;
14383
14384 this->CheckAttributesOnDeducedType(RealDecl);
14385
14386 // C++11 [class.static.data]p3: A static data member can be declared with
14387 // the constexpr specifier; if so, its declaration shall specify
14388 // a brace-or-equal-initializer.
14389 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14390 // the definition of a variable [...] or the declaration of a static data
14391 // member.
14392 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14393 !Var->isThisDeclarationADemotedDefinition()) {
14394 if (Var->isStaticDataMember()) {
14395 // C++1z removes the relevant rule; the in-class declaration is always
14396 // a definition there.
14397 if (!getLangOpts().CPlusPlus17 &&
14398 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14399 Diag(Var->getLocation(),
14400 diag::err_constexpr_static_mem_var_requires_init)
14401 << Var;
14402 Var->setInvalidDecl();
14403 return;
14404 }
14405 } else {
14406 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14407 Var->setInvalidDecl();
14408 return;
14409 }
14410 }
14411
14412 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14413 // be initialized.
14414 if (!Var->isInvalidDecl() &&
14415 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14416 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14417 bool HasConstExprDefaultConstructor = false;
14418 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14419 for (auto *Ctor : RD->ctors()) {
14420 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14421 Ctor->getMethodQualifiers().getAddressSpace() ==
14422 LangAS::opencl_constant) {
14423 HasConstExprDefaultConstructor = true;
14424 }
14425 }
14426 }
14427 if (!HasConstExprDefaultConstructor) {
14428 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14429 Var->setInvalidDecl();
14430 return;
14431 }
14432 }
14433
14434 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14435 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14436 Diag(Var->getLocation(), diag::err_specialization_const);
14437 Var->setInvalidDecl();
14438 return;
14439 }
14440
14441 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14442 if (Var->getStorageClass() == SC_Extern) {
14443 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14444 << Var;
14445 Var->setInvalidDecl();
14446 return;
14447 }
14448 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14449 diag::err_typecheck_decl_incomplete_type)) {
14450 Var->setInvalidDecl();
14451 return;
14452 }
14453 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14454 if (!RD->hasTrivialDefaultConstructor()) {
14455 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14456 Var->setInvalidDecl();
14457 return;
14458 }
14459 }
14460 // The declaration is uninitialized, no need for further checks.
14461 return;
14462 }
14463
14464 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14465 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14466 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14467 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14468 NonTrivialCUnionContext::DefaultInitializedObject,
14469 NTCUK_Init);
14470
14471 switch (DefKind) {
14472 case VarDecl::Definition:
14473 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14474 break;
14475
14476 // We have an out-of-line definition of a static data member
14477 // that has an in-class initializer, so we type-check this like
14478 // a declaration.
14479 //
14480 [[fallthrough]];
14481
14482 case VarDecl::DeclarationOnly:
14483 // It's only a declaration.
14484
14485 // Block scope. C99 6.7p7: If an identifier for an object is
14486 // declared with no linkage (C99 6.2.2p6), the type for the
14487 // object shall be complete.
14488 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14489 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14490 RequireCompleteType(Var->getLocation(), Type,
14491 diag::err_typecheck_decl_incomplete_type))
14492 Var->setInvalidDecl();
14493
14494 // Make sure that the type is not abstract.
14495 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14496 RequireNonAbstractType(Var->getLocation(), Type,
14497 diag::err_abstract_type_in_decl,
14498 AbstractVariableType))
14499 Var->setInvalidDecl();
14500 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14501 Var->getStorageClass() == SC_PrivateExtern) {
14502 Diag(Var->getLocation(), diag::warn_private_extern);
14503 Diag(Var->getLocation(), diag::note_private_extern);
14504 }
14505
14506 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14507 !Var->isInvalidDecl())
14508 ExternalDeclarations.push_back(Var);
14509
14510 return;
14511
14512 case VarDecl::TentativeDefinition:
14513 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14514 // object that has file scope without an initializer, and without a
14515 // storage-class specifier or with the storage-class specifier "static",
14516 // constitutes a tentative definition. Note: A tentative definition with
14517 // external linkage is valid (C99 6.2.2p5).
14518 if (!Var->isInvalidDecl()) {
14519 if (const IncompleteArrayType *ArrayT
14520 = Context.getAsIncompleteArrayType(Type)) {
14521 if (RequireCompleteSizedType(
14522 Var->getLocation(), ArrayT->getElementType(),
14523 diag::err_array_incomplete_or_sizeless_type))
14524 Var->setInvalidDecl();
14525 }
14526 if (Var->getStorageClass() == SC_Static) {
14527 // C99 6.9.2p3: If the declaration of an identifier for an object is
14528 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14529 // declared type shall not be an incomplete type.
14530 // NOTE: code such as the following
14531 // static struct s;
14532 // struct s { int a; };
14533 // is accepted by gcc. Hence here we issue a warning instead of
14534 // an error and we do not invalidate the static declaration.
14535 // NOTE: to avoid multiple warnings, only check the first declaration.
14536 if (Var->isFirstDecl())
14537 RequireCompleteType(Var->getLocation(), Type,
14538 diag::ext_typecheck_decl_incomplete_type,
14539 Type->isArrayType());
14540 }
14541 }
14542
14543 // Record the tentative definition; we're done.
14544 if (!Var->isInvalidDecl())
14545 TentativeDefinitions.push_back(Var);
14546 return;
14547 }
14548
14549 // Provide a specific diagnostic for uninitialized variable definitions
14550 // with incomplete array type, unless it is a global unbounded HLSL resource
14551 // array.
14552 if (Type->isIncompleteArrayType() &&
14553 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14554 Type->isHLSLResourceRecordArray())) {
14555 if (Var->isConstexpr())
14556 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14557 << Var;
14558 else
14559 Diag(Var->getLocation(),
14560 diag::err_typecheck_incomplete_array_needs_initializer);
14561 Var->setInvalidDecl();
14562 return;
14563 }
14564
14565 // Provide a specific diagnostic for uninitialized variable
14566 // definitions with reference type.
14567 if (Type->isReferenceType()) {
14568 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14569 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14570 return;
14571 }
14572
14573 // Do not attempt to type-check the default initializer for a
14574 // variable with dependent type.
14575 if (Type->isDependentType())
14576 return;
14577
14578 if (Var->isInvalidDecl())
14579 return;
14580
14581 if (!Var->hasAttr<AliasAttr>()) {
14582 if (RequireCompleteType(Var->getLocation(),
14583 Context.getBaseElementType(Type),
14584 diag::err_typecheck_decl_incomplete_type)) {
14585 Var->setInvalidDecl();
14586 return;
14587 }
14588 } else {
14589 return;
14590 }
14591
14592 // The variable can not have an abstract class type.
14593 if (RequireNonAbstractType(Var->getLocation(), Type,
14594 diag::err_abstract_type_in_decl,
14595 AbstractVariableType)) {
14596 Var->setInvalidDecl();
14597 return;
14598 }
14599
14600 // In C, if the definition is const-qualified and has no initializer, it
14601 // is left uninitialized unless it has static or thread storage duration.
14602 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14603 unsigned DiagID = diag::warn_default_init_const_unsafe;
14604 if (Var->getStorageDuration() == SD_Static ||
14605 Var->getStorageDuration() == SD_Thread)
14606 DiagID = diag::warn_default_init_const;
14607
14608 bool EmitCppCompat = !Diags.isIgnored(
14609 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14610 Var->getLocation());
14611
14612 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14613 }
14614
14615 // Check for jumps past the implicit initializer. C++0x
14616 // clarifies that this applies to a "variable with automatic
14617 // storage duration", not a "local variable".
14618 // C++11 [stmt.dcl]p3
14619 // A program that jumps from a point where a variable with automatic
14620 // storage duration is not in scope to a point where it is in scope is
14621 // ill-formed unless the variable has scalar type, class type with a
14622 // trivial default constructor and a trivial destructor, a cv-qualified
14623 // version of one of these types, or an array of one of the preceding
14624 // types and is declared without an initializer.
14625 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14626 if (const auto *CXXRecord =
14627 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14628 // Mark the function (if we're in one) for further checking even if the
14629 // looser rules of C++11 do not require such checks, so that we can
14630 // diagnose incompatibilities with C++98.
14631 if (!CXXRecord->isPOD())
14632 setFunctionHasBranchProtectedScope();
14633 }
14634 }
14635 // In OpenCL, we can't initialize objects in the __local address space,
14636 // even implicitly, so don't synthesize an implicit initializer.
14637 if (getLangOpts().OpenCL &&
14638 Var->getType().getAddressSpace() == LangAS::opencl_local)
14639 return;
14640
14641 // Handle HLSL uninitialized decls
14642 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14643 return;
14644
14645 // HLSL input & push-constant variables are expected to be externally
14646 // initialized, even when marked `static`.
14647 if (getLangOpts().HLSL &&
14648 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14649 return;
14650
14651 // C++03 [dcl.init]p9:
14652 // If no initializer is specified for an object, and the
14653 // object is of (possibly cv-qualified) non-POD class type (or
14654 // array thereof), the object shall be default-initialized; if
14655 // the object is of const-qualified type, the underlying class
14656 // type shall have a user-declared default
14657 // constructor. Otherwise, if no initializer is specified for
14658 // a non- static object, the object and its subobjects, if
14659 // any, have an indeterminate initial value); if the object
14660 // or any of its subobjects are of const-qualified type, the
14661 // program is ill-formed.
14662 // C++0x [dcl.init]p11:
14663 // If no initializer is specified for an object, the object is
14664 // default-initialized; [...].
14665 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14666 InitializationKind Kind
14667 = InitializationKind::CreateDefault(Var->getLocation());
14668
14669 InitializationSequence InitSeq(*this, Entity, Kind, {});
14670 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14671
14672 if (Init.get()) {
14673 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14674 // This is important for template substitution.
14675 Var->setInitStyle(VarDecl::CallInit);
14676 } else if (Init.isInvalid()) {
14677 // If default-init fails, attach a recovery-expr initializer to track
14678 // that initialization was attempted and failed.
14679 auto RecoveryExpr =
14680 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14681 if (RecoveryExpr.get())
14682 Var->setInit(RecoveryExpr.get());
14683 }
14684
14685 CheckCompleteVariableDeclaration(Var);
14686 }
14687 }
14688
14689 void Sema::ActOnCXXForRangeDecl(Decl *D) {
14690 // If there is no declaration, there was an error parsing it. Ignore it.
14691 if (!D)
14692 return;
14693
14694 VarDecl *VD = dyn_cast<VarDecl>(D);
14695 if (!VD) {
14696 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14697 D->setInvalidDecl();
14698 return;
14699 }
14700
14701 VD->setCXXForRangeDecl(true);
14702
14703 // for-range-declaration cannot be given a storage class specifier.
14704 int Error = -1;
14705 switch (VD->getStorageClass()) {
14706 case SC_None:
14707 break;
14708 case SC_Extern:
14709 Error = 0;
14710 break;
14711 case SC_Static:
14712 Error = 1;
14713 break;
14714 case SC_PrivateExtern:
14715 Error = 2;
14716 break;
14717 case SC_Auto:
14718 Error = 3;
14719 break;
14720 case SC_Register:
14721 Error = 4;
14722 break;
14723 }
14724
14725 // for-range-declaration cannot be given a storage class specifier con't.
14726 switch (VD->getTSCSpec()) {
14727 case TSCS_thread_local:
14728 Error = 6;
14729 break;
14730 case TSCS___thread:
14731 case TSCS__Thread_local:
14732 case TSCS_unspecified:
14733 break;
14734 }
14735
14736 if (Error != -1) {
14737 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14738 << VD << Error;
14739 D->setInvalidDecl();
14740 }
14741 }
14742
14743 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14744 IdentifierInfo *Ident,
14745 ParsedAttributes &Attrs) {
14746 // C++1y [stmt.iter]p1:
14747 // A range-based for statement of the form
14748 // for ( for-range-identifier : for-range-initializer ) statement
14749 // is equivalent to
14750 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14751 DeclSpec DS(Attrs.getPool().getFactory());
14752
14753 const char *PrevSpec;
14754 unsigned DiagID;
14755 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14756 getPrintingPolicy());
14757
14758 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14759 D.SetIdentifier(Ident, IdentLoc);
14760 D.takeAttributesAppending(Attrs);
14761
14762 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14763 IdentLoc);
14764 Decl *Var = ActOnDeclarator(S, D);
14765 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14766 FinalizeDeclaration(Var);
14767 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14768 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14769 : IdentLoc);
14770 }
14771
14772 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14773 if (var->isInvalidDecl()) return;
14774
14775 CUDA().MaybeAddConstantAttr(var);
14776
14777 if (getLangOpts().OpenCL) {
14778 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14779 // initialiser
14780 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14781 !var->hasInit()) {
14782 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14783 << 1 /*Init*/;
14784 var->setInvalidDecl();
14785 return;
14786 }
14787 }
14788
14789 // In Objective-C, don't allow jumps past the implicit initialization of a
14790 // local retaining variable.
14791 if (getLangOpts().ObjC &&
14792 var->hasLocalStorage()) {
14793 switch (var->getType().getObjCLifetime()) {
14794 case Qualifiers::OCL_None:
14795 case Qualifiers::OCL_ExplicitNone:
14796 case Qualifiers::OCL_Autoreleasing:
14797 break;
14798
14799 case Qualifiers::OCL_Weak:
14800 case Qualifiers::OCL_Strong:
14801 setFunctionHasBranchProtectedScope();
14802 break;
14803 }
14804 }
14805
14806 if (var->hasLocalStorage() &&
14807 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14808 setFunctionHasBranchProtectedScope();
14809
14810 // Warn about externally-visible variables being defined without a
14811 // prior declaration. We only want to do this for global
14812 // declarations, but we also specifically need to avoid doing it for
14813 // class members because the linkage of an anonymous class can
14814 // change if it's later given a typedef name.
14815 if (var->isThisDeclarationADefinition() &&
14816 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14817 var->isExternallyVisible() && var->hasLinkage() &&
14818 !var->isInline() && !var->getDescribedVarTemplate() &&
14819 var->getStorageClass() != SC_Register &&
14820 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14821 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14822 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14823 var->getLocation())) {
14824 // Find a previous declaration that's not a definition.
14825 VarDecl *prev = var->getPreviousDecl();
14826 while (prev && prev->isThisDeclarationADefinition())
14827 prev = prev->getPreviousDecl();
14828
14829 if (!prev) {
14830 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14831 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14832 << /* variable */ 0;
14833 }
14834 }
14835
14836 // Cache the result of checking for constant initialization.
14837 std::optional<bool> CacheHasConstInit;
14838 const Expr *CacheCulprit = nullptr;
14839 auto checkConstInit = [&]() mutable {
14840 const Expr *Init = var->getInit();
14841 if (Init->isInstantiationDependent())
14842 return true;
14843
14844 if (!CacheHasConstInit)
14845 CacheHasConstInit = var->getInit()->isConstantInitializer(
14846 Context, var->getType()->isReferenceType(), &CacheCulprit);
14847 return *CacheHasConstInit;
14848 };
14849
14850 if (var->getTLSKind() == VarDecl::TLS_Static) {
14851 if (var->getType().isDestructedType()) {
14852 // GNU C++98 edits for __thread, [basic.start.term]p3:
14853 // The type of an object with thread storage duration shall not
14854 // have a non-trivial destructor.
14855 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14856 if (getLangOpts().CPlusPlus11)
14857 Diag(var->getLocation(), diag::note_use_thread_local);
14858 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14859 if (!checkConstInit()) {
14860 // GNU C++98 edits for __thread, [basic.start.init]p4:
14861 // An object of thread storage duration shall not require dynamic
14862 // initialization.
14863 // FIXME: Need strict checking here.
14864 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14865 << CacheCulprit->getSourceRange();
14866 if (getLangOpts().CPlusPlus11)
14867 Diag(var->getLocation(), diag::note_use_thread_local);
14868 }
14869 }
14870 }
14871
14872
14873 if (!var->getType()->isStructureType() && var->hasInit() &&
14874 isa<InitListExpr>(var->getInit())) {
14875 const auto *ILE = cast<InitListExpr>(var->getInit());
14876 unsigned NumInits = ILE->getNumInits();
14877 if (NumInits > 2)
14878 for (unsigned I = 0; I < NumInits; ++I) {
14879 const auto *Init = ILE->getInit(I);
14880 if (!Init)
14881 break;
14882 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14883 if (!SL)
14884 break;
14885
14886 unsigned NumConcat = SL->getNumConcatenated();
14887 // Diagnose missing comma in string array initialization.
14888 // Do not warn when all the elements in the initializer are concatenated
14889 // together. Do not warn for macros too.
14890 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14891 bool OnlyOneMissingComma = true;
14892 for (unsigned J = I + 1; J < NumInits; ++J) {
14893 const auto *Init = ILE->getInit(J);
14894 if (!Init)
14895 break;
14896 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14897 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14898 OnlyOneMissingComma = false;
14899 break;
14900 }
14901 }
14902
14903 if (OnlyOneMissingComma) {
14904 SmallVector<FixItHint, 1> Hints;
14905 for (unsigned i = 0; i < NumConcat - 1; ++i)
14906 Hints.push_back(FixItHint::CreateInsertion(
14907 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14908
14909 Diag(SL->getStrTokenLoc(1),
14910 diag::warn_concatenated_literal_array_init)
14911 << Hints;
14912 Diag(SL->getBeginLoc(),
14913 diag::note_concatenated_string_literal_silence);
14914 }
14915 // In any case, stop now.
14916 break;
14917 }
14918 }
14919 }
14920
14921
14922 QualType type = var->getType();
14923
14924 if (var->hasAttr<BlocksAttr>())
14925 getCurFunction()->addByrefBlockVar(var);
14926
14927 Expr *Init = var->getInit();
14928 bool GlobalStorage = var->hasGlobalStorage();
14929 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14930 QualType baseType = Context.getBaseElementType(type);
14931 bool HasConstInit = true;
14932
14933 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14934 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14935 << var;
14936
14937 // Check whether the initializer is sufficiently constant.
14938 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14939 !type->isDependentType() && Init && !Init->isValueDependent() &&
14940 (GlobalStorage || var->isConstexpr() ||
14941 var->mightBeUsableInConstantExpressions(Context))) {
14942 // If this variable might have a constant initializer or might be usable in
14943 // constant expressions, check whether or not it actually is now. We can't
14944 // do this lazily, because the result might depend on things that change
14945 // later, such as which constexpr functions happen to be defined.
14946 SmallVector<PartialDiagnosticAt, 8> Notes;
14947 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14948 // Prior to C++11, in contexts where a constant initializer is required,
14949 // the set of valid constant initializers is described by syntactic rules
14950 // in [expr.const]p2-6.
14951 // FIXME: Stricter checking for these rules would be useful for constinit /
14952 // -Wglobal-constructors.
14953 HasConstInit = checkConstInit();
14954
14955 // Compute and cache the constant value, and remember that we have a
14956 // constant initializer.
14957 if (HasConstInit) {
14958 if (var->isStaticDataMember() && !var->isInline() &&
14959 var->getLexicalDeclContext()->isRecord() &&
14960 type->isIntegralOrEnumerationType()) {
14961 // In C++98, in-class initialization for a static data member must
14962 // be an integer constant expression.
14963 if (!Init->isIntegerConstantExpr(Context)) {
14964 Diag(Init->getExprLoc(),
14965 diag::ext_in_class_initializer_non_constant)
14966 << Init->getSourceRange();
14967 }
14968 }
14969 (void)var->checkForConstantInitialization(Notes);
14970 Notes.clear();
14971 } else if (CacheCulprit) {
14972 Notes.emplace_back(CacheCulprit->getExprLoc(),
14973 PDiag(diag::note_invalid_subexpr_in_const_expr));
14974 Notes.back().second << CacheCulprit->getSourceRange();
14975 }
14976 } else {
14977 // Evaluate the initializer to see if it's a constant initializer.
14978 HasConstInit = var->checkForConstantInitialization(Notes);
14979 }
14980
14981 if (HasConstInit) {
14982 // FIXME: Consider replacing the initializer with a ConstantExpr.
14983 } else if (var->isConstexpr()) {
14984 SourceLocation DiagLoc = var->getLocation();
14985 // If the note doesn't add any useful information other than a source
14986 // location, fold it into the primary diagnostic.
14987 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14988 diag::note_invalid_subexpr_in_const_expr) {
14989 DiagLoc = Notes[0].first;
14990 Notes.clear();
14991 }
14992 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14993 << var << Init->getSourceRange();
14994 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14995 Diag(Notes[I].first, Notes[I].second);
14996 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14997 auto *Attr = var->getAttr<ConstInitAttr>();
14998 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14999 << Init->getSourceRange();
15000 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15001 << Attr->getRange() << Attr->isConstinit();
15002 for (auto &it : Notes)
15003 Diag(it.first, it.second);
15004 } else if (var->isStaticDataMember() && !var->isInline() &&
15005 var->getLexicalDeclContext()->isRecord()) {
15006 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15007 << Init->getSourceRange();
15008 for (auto &it : Notes)
15009 Diag(it.first, it.second);
15010 var->setInvalidDecl();
15011 } else if (IsGlobal &&
15012 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15013 var->getLocation())) {
15014 // Warn about globals which don't have a constant initializer. Don't
15015 // warn about globals with a non-trivial destructor because we already
15016 // warned about them.
15017 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15018 if (!(RD && !RD->hasTrivialDestructor())) {
15019 // checkConstInit() here permits trivial default initialization even in
15020 // C++11 onwards, where such an initializer is not a constant initializer
15021 // but nonetheless doesn't require a global constructor.
15022 if (!checkConstInit())
15023 Diag(var->getLocation(), diag::warn_global_constructor)
15024 << Init->getSourceRange();
15025 }
15026 }
15027 }
15028
15029 // Apply section attributes and pragmas to global variables.
15030 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15031 !inTemplateInstantiation()) {
15032 PragmaStack<StringLiteral *> *Stack = nullptr;
15033 int SectionFlags = ASTContext::PSF_Read;
15034 bool MSVCEnv =
15035 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15036 std::optional<QualType::NonConstantStorageReason> Reason;
15037 if (HasConstInit &&
15038 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15039 Stack = &ConstSegStack;
15040 } else {
15041 SectionFlags |= ASTContext::PSF_Write;
15042 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15043 }
15044 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15045 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15046 SectionFlags |= ASTContext::PSF_Implicit;
15047 UnifySection(SA->getName(), SectionFlags, var);
15048 } else if (Stack->CurrentValue) {
15049 if (Stack != &ConstSegStack && MSVCEnv &&
15050 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15051 var->getType().isConstQualified()) {
15052 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15053 NonConstNonReferenceType) &&
15054 "This case should've already been handled elsewhere");
15055 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15056 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15057 ? QualType::NonConstantStorageReason::NonTrivialCtor
15058 : *Reason);
15059 }
15060 SectionFlags |= ASTContext::PSF_Implicit;
15061 auto SectionName = Stack->CurrentValue->getString();
15062 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15063 Stack->CurrentPragmaLocation,
15064 SectionAttr::Declspec_allocate));
15065 if (UnifySection(SectionName, SectionFlags, var))
15066 var->dropAttr<SectionAttr>();
15067 }
15068
15069 // Apply the init_seg attribute if this has an initializer. If the
15070 // initializer turns out to not be dynamic, we'll end up ignoring this
15071 // attribute.
15072 if (CurInitSeg && var->getInit())
15073 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15074 CurInitSegLoc));
15075 }
15076
15077 // All the following checks are C++ only.
15078 if (!getLangOpts().CPlusPlus) {
15079 // If this variable must be emitted, add it as an initializer for the
15080 // current module.
15081 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15082 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15083 return;
15084 }
15085
15086 DiagnoseUniqueObjectDuplication(var);
15087
15088 // Require the destructor.
15089 if (!type->isDependentType())
15090 if (auto *RD = baseType->getAsCXXRecordDecl())
15091 FinalizeVarWithDestructor(var, RD);
15092
15093 // If this variable must be emitted, add it as an initializer for the current
15094 // module.
15095 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15096 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15097
15098 // Build the bindings if this is a structured binding declaration.
15099 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15100 CheckCompleteDecompositionDeclaration(DD);
15101 }
15102
15103 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15104 assert(VD->isStaticLocal());
15105
15106 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15107
15108 // Find outermost function when VD is in lambda function.
15109 while (FD && !getDLLAttr(FD) &&
15110 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15111 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15112 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15113 }
15114
15115 if (!FD)
15116 return;
15117
15118 // Static locals inherit dll attributes from their function.
15119 if (Attr *A = getDLLAttr(FD)) {
15120 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15121 NewAttr->setInherited(true);
15122 VD->addAttr(NewAttr);
15123 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15124 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15125 NewAttr->setInherited(true);
15126 VD->addAttr(NewAttr);
15127
15128 // Export this function to enforce exporting this static variable even
15129 // if it is not used in this compilation unit.
15130 if (!FD->hasAttr<DLLExportAttr>())
15131 FD->addAttr(NewAttr);
15132
15133 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15134 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15135 NewAttr->setInherited(true);
15136 VD->addAttr(NewAttr);
15137 }
15138 }
15139
15140 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15141 assert(VD->getTLSKind());
15142
15143 // Perform TLS alignment check here after attributes attached to the variable
15144 // which may affect the alignment have been processed. Only perform the check
15145 // if the target has a maximum TLS alignment (zero means no constraints).
15146 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15147 // Protect the check so that it's not performed on dependent types and
15148 // dependent alignments (we can't determine the alignment in that case).
15149 if (!VD->hasDependentAlignment()) {
15150 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15151 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15152 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15153 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15154 << (unsigned)MaxAlignChars.getQuantity();
15155 }
15156 }
15157 }
15158 }
15159
15160 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15161 // Note that we are no longer parsing the initializer for this declaration.
15162 ParsingInitForAutoVars.erase(ThisDecl);
15163
15164 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15165 if (!VD)
15166 return;
15167
15168 // Emit any deferred warnings for the variable's initializer, even if the
15169 // variable is invalid
15170 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15171
15172 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15173 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15174 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15175 if (PragmaClangBSSSection.Valid)
15176 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15177 Context, PragmaClangBSSSection.SectionName,
15178 PragmaClangBSSSection.PragmaLocation));
15179 if (PragmaClangDataSection.Valid)
15180 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15181 Context, PragmaClangDataSection.SectionName,
15182 PragmaClangDataSection.PragmaLocation));
15183 if (PragmaClangRodataSection.Valid)
15184 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15185 Context, PragmaClangRodataSection.SectionName,
15186 PragmaClangRodataSection.PragmaLocation));
15187 if (PragmaClangRelroSection.Valid)
15188 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15189 Context, PragmaClangRelroSection.SectionName,
15190 PragmaClangRelroSection.PragmaLocation));
15191 }
15192
15193 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15194 for (auto *BD : DD->bindings()) {
15195 FinalizeDeclaration(BD);
15196 }
15197 }
15198
15199 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15200 BuiltinCountedByRefKind::Initializer);
15201
15202 checkAttributesAfterMerging(*this, *VD);
15203
15204 if (VD->isStaticLocal())
15205 CheckStaticLocalForDllExport(VD);
15206
15207 if (VD->getTLSKind())
15208 CheckThreadLocalForLargeAlignment(VD);
15209
15210 // Perform check for initializers of device-side global variables.
15211 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15212 // 7.5). We must also apply the same checks to all __shared__
15213 // variables whether they are local or not. CUDA also allows
15214 // constant initializers for __constant__ and __device__ variables.
15215 if (getLangOpts().CUDA)
15216 CUDA().checkAllowedInitializer(VD);
15217
15218 // Grab the dllimport or dllexport attribute off of the VarDecl.
15219 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15220
15221 // Imported static data members cannot be defined out-of-line.
15222 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15223 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15224 VD->isThisDeclarationADefinition()) {
15225 // We allow definitions of dllimport class template static data members
15226 // with a warning.
15227 CXXRecordDecl *Context =
15228 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
15229 bool IsClassTemplateMember =
15230 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
15231 Context->getDescribedClassTemplate();
15232
15233 Diag(VD->getLocation(),
15234 IsClassTemplateMember
15235 ? diag::warn_attribute_dllimport_static_field_definition
15236 : diag::err_attribute_dllimport_static_field_definition);
15237 Diag(IA->getLocation(), diag::note_attribute);
15238 if (!IsClassTemplateMember)
15239 VD->setInvalidDecl();
15240 }
15241 }
15242
15243 // dllimport/dllexport variables cannot be thread local, their TLS index
15244 // isn't exported with the variable.
15245 if (DLLAttr && VD->getTLSKind()) {
15246 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15247 if (F && getDLLAttr(F)) {
15248 assert(VD->isStaticLocal());
15249 // But if this is a static local in a dlimport/dllexport function, the
15250 // function will never be inlined, which means the var would never be
15251 // imported, so having it marked import/export is safe.
15252 } else {
15253 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15254 << DLLAttr;
15255 VD->setInvalidDecl();
15256 }
15257 }
15258
15259 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15260 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15261 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15262 << Attr;
15263 VD->dropAttr<UsedAttr>();
15264 }
15265 }
15266 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15267 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15268 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15269 << Attr;
15270 VD->dropAttr<RetainAttr>();
15271 }
15272 }
15273
15274 const DeclContext *DC = VD->getDeclContext();
15275 // If there's a #pragma GCC visibility in scope, and this isn't a class
15276 // member, set the visibility of this variable.
15277 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15278 AddPushedVisibilityAttribute(VD);
15279
15280 // FIXME: Warn on unused var template partial specializations.
15281 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
15282 MarkUnusedFileScopedDecl(VD);
15283
15284 // Now we have parsed the initializer and can update the table of magic
15285 // tag values.
15286 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15287 !VD->getType()->isIntegralOrEnumerationType())
15288 return;
15289
15290 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15291 const Expr *MagicValueExpr = VD->getInit();
15292 if (!MagicValueExpr) {
15293 continue;
15294 }
15295 std::optional<llvm::APSInt> MagicValueInt;
15296 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15297 Diag(I->getRange().getBegin(),
15298 diag::err_type_tag_for_datatype_not_ice)
15299 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15300 continue;
15301 }
15302 if (MagicValueInt->getActiveBits() > 64) {
15303 Diag(I->getRange().getBegin(),
15304 diag::err_type_tag_for_datatype_too_large)
15305 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15306 continue;
15307 }
15308 uint64_t MagicValue = MagicValueInt->getZExtValue();
15309 RegisterTypeTagForDatatype(I->getArgumentKind(),
15310 MagicValue,
15311 I->getMatchingCType(),
15312 I->getLayoutCompatible(),
15313 I->getMustBeNull());
15314 }
15315 }
15316
15317 static bool hasDeducedAuto(DeclaratorDecl *DD) {
15318 auto *VD = dyn_cast<VarDecl>(DD);
15319 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15320 }
15321
15322 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15323 ArrayRef<Decl *> Group) {
15324 SmallVector<Decl*, 8> Decls;
15325
15326 if (DS.isTypeSpecOwned())
15327 Decls.push_back(DS.getRepAsDecl());
15328
15329 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15330 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15331 bool DiagnosedMultipleDecomps = false;
15332 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15333 bool DiagnosedNonDeducedAuto = false;
15334
15335 for (Decl *D : Group) {
15336 if (!D)
15337 continue;
15338 // Check if the Decl has been declared in '#pragma omp declare target'
15339 // directive and has static storage duration.
15340 if (auto *VD = dyn_cast<VarDecl>(D);
15341 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15342 VD->hasGlobalStorage())
15343 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15344 // For declarators, there are some additional syntactic-ish checks we need
15345 // to perform.
15346 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15347 if (!FirstDeclaratorInGroup)
15348 FirstDeclaratorInGroup = DD;
15349 if (!FirstDecompDeclaratorInGroup)
15350 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15351 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15352 !hasDeducedAuto(DD))
15353 FirstNonDeducedAutoInGroup = DD;
15354
15355 if (FirstDeclaratorInGroup != DD) {
15356 // A decomposition declaration cannot be combined with any other
15357 // declaration in the same group.
15358 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15359 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15360 diag::err_decomp_decl_not_alone)
15361 << FirstDeclaratorInGroup->getSourceRange()
15362 << DD->getSourceRange();
15363 DiagnosedMultipleDecomps = true;
15364 }
15365
15366 // A declarator that uses 'auto' in any way other than to declare a
15367 // variable with a deduced type cannot be combined with any other
15368 // declarator in the same group.
15369 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15370 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15371 diag::err_auto_non_deduced_not_alone)
15372 << FirstNonDeducedAutoInGroup->getType()
15373 ->hasAutoForTrailingReturnType()
15374 << FirstDeclaratorInGroup->getSourceRange()
15375 << DD->getSourceRange();
15376 DiagnosedNonDeducedAuto = true;
15377 }
15378 }
15379 }
15380
15381 Decls.push_back(D);
15382 }
15383
15384 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
15385 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15386 handleTagNumbering(Tag, S);
15387 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15388 getLangOpts().CPlusPlus)
15389 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15390 }
15391 }
15392
15393 return BuildDeclaratorGroup(Decls);
15394 }
15395
15396 Sema::DeclGroupPtrTy
15397 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15398 // C++14 [dcl.spec.auto]p7: (DR1347)
15399 // If the type that replaces the placeholder type is not the same in each
15400 // deduction, the program is ill-formed.
15401 if (Group.size() > 1) {
15402 QualType Deduced;
15403 VarDecl *DeducedDecl = nullptr;
15404 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15405 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15406 if (!D || D->isInvalidDecl())
15407 break;
15408 DeducedType *DT = D->getType()->getContainedDeducedType();
15409 if (!DT || DT->getDeducedType().isNull())
15410 continue;
15411 if (Deduced.isNull()) {
15412 Deduced = DT->getDeducedType();
15413 DeducedDecl = D;
15414 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15415 auto *AT = dyn_cast<AutoType>(DT);
15416 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15417 diag::err_auto_different_deductions)
15418 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15419 << DeducedDecl->getDeclName() << DT->getDeducedType()
15420 << D->getDeclName();
15421 if (DeducedDecl->hasInit())
15422 Dia << DeducedDecl->getInit()->getSourceRange();
15423 if (D->getInit())
15424 Dia << D->getInit()->getSourceRange();
15425 D->setInvalidDecl();
15426 break;
15427 }
15428 }
15429 }
15430
15431 ActOnDocumentableDecls(Group);
15432
15433 return DeclGroupPtrTy::make(
15434 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15435 }
15436
15437 void Sema::ActOnDocumentableDecl(Decl *D) {
15438 ActOnDocumentableDecls(D);
15439 }
15440
15441 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15442 // Don't parse the comment if Doxygen diagnostics are ignored.
15443 if (Group.empty() || !Group[0])
15444 return;
15445
15446 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15447 Group[0]->getLocation()) &&
15448 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15449 Group[0]->getLocation()))
15450 return;
15451
15452 if (Group.size() >= 2) {
15453 // This is a decl group. Normally it will contain only declarations
15454 // produced from declarator list. But in case we have any definitions or
15455 // additional declaration references:
15456 // 'typedef struct S {} S;'
15457 // 'typedef struct S *S;'
15458 // 'struct S *pS;'
15459 // FinalizeDeclaratorGroup adds these as separate declarations.
15460 Decl *MaybeTagDecl = Group[0];
15461 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15462 Group = Group.slice(1);
15463 }
15464 }
15465
15466 // FIMXE: We assume every Decl in the group is in the same file.
15467 // This is false when preprocessor constructs the group from decls in
15468 // different files (e. g. macros or #include).
15469 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15470 }
15471
15472 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15473 // Check that there are no default arguments inside the type of this
15474 // parameter.
15475 if (getLangOpts().CPlusPlus)
15476 CheckExtraCXXDefaultArguments(D);
15477
15478 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15479 if (D.getCXXScopeSpec().isSet()) {
15480 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15481 << D.getCXXScopeSpec().getRange();
15482 }
15483
15484 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15485 // simple identifier except [...irrelevant cases...].
15486 switch (D.getName().getKind()) {
15487 case UnqualifiedIdKind::IK_Identifier:
15488 break;
15489
15490 case UnqualifiedIdKind::IK_OperatorFunctionId:
15491 case UnqualifiedIdKind::IK_ConversionFunctionId:
15492 case UnqualifiedIdKind::IK_LiteralOperatorId:
15493 case UnqualifiedIdKind::IK_ConstructorName:
15494 case UnqualifiedIdKind::IK_DestructorName:
15495 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15496 case UnqualifiedIdKind::IK_DeductionGuideName:
15497 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15498 << GetNameForDeclarator(D).getName();
15499 break;
15500
15501 case UnqualifiedIdKind::IK_TemplateId:
15502 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15503 // GetNameForDeclarator would not produce a useful name in this case.
15504 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15505 break;
15506 }
15507 }
15508
15509 void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15510 // This only matters in C.
15511 if (getLangOpts().CPlusPlus)
15512 return;
15513
15514 // This only matters if the declaration has a type.
15515 const auto *VD = dyn_cast<ValueDecl>(D);
15516 if (!VD)
15517 return;
15518
15519 // Get the type, this only matters for tag types.
15520 QualType QT = VD->getType();
15521 const auto *TD = QT->getAsTagDecl();
15522 if (!TD)
15523 return;
15524
15525 // Check if the tag declaration is lexically declared somewhere different
15526 // from the lexical declaration of the given object, then it will be hidden
15527 // in C++ and we should warn on it.
15528 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15529 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15530 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15531 Diag(TD->getLocation(), diag::note_declared_at);
15532 }
15533 }
15534
15535 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15536 SourceLocation ExplicitThisLoc) {
15537 if (!ExplicitThisLoc.isValid())
15538 return;
15539 assert(S.getLangOpts().CPlusPlus &&
15540 "explicit parameter in non-cplusplus mode");
15541 if (!S.getLangOpts().CPlusPlus23)
15542 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15543 << P->getSourceRange();
15544
15545 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15546 // parameter pack.
15547 if (P->isParameterPack()) {
15548 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15549 << P->getSourceRange();
15550 return;
15551 }
15552 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15553 if (LambdaScopeInfo *LSI = S.getCurLambda())
15554 LSI->ExplicitObjectParameter = P;
15555 }
15556
15557 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15558 SourceLocation ExplicitThisLoc) {
15559 const DeclSpec &DS = D.getDeclSpec();
15560
15561 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15562 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15563 // except for the special case of a single unnamed parameter of type void
15564 // with no storage class specifier, no type qualifier, and no following
15565 // ellipsis terminator.
15566 // Clang applies the C2y rules for 'register void' in all C language modes,
15567 // same as GCC, because it's questionable what that could possibly mean.
15568
15569 // C++03 [dcl.stc]p2 also permits 'auto'.
15570 StorageClass SC = SC_None;
15571 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15572 SC = SC_Register;
15573 // In C++11, the 'register' storage class specifier is deprecated.
15574 // In C++17, it is not allowed, but we tolerate it as an extension.
15575 if (getLangOpts().CPlusPlus11) {
15576 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus17
15577 ? diag::ext_register_storage_class
15578 : diag::warn_deprecated_register)
15579 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15580 } else if (!getLangOpts().CPlusPlus &&
15581 DS.getTypeSpecType() == DeclSpec::TST_void &&
15582 D.getNumTypeObjects() == 0) {
15583 Diag(DS.getStorageClassSpecLoc(),
15584 diag::err_invalid_storage_class_in_func_decl)
15585 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15586 D.getMutableDeclSpec().ClearStorageClassSpecs();
15587 }
15588 } else if (getLangOpts().CPlusPlus &&
15589 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15590 SC = SC_Auto;
15591 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15592 Diag(DS.getStorageClassSpecLoc(),
15593 diag::err_invalid_storage_class_in_func_decl);
15594 D.getMutableDeclSpec().ClearStorageClassSpecs();
15595 }
15596
15597 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15598 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15599 << DeclSpec::getSpecifierName(TSCS);
15600 if (DS.isInlineSpecified())
15601 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15602 << getLangOpts().CPlusPlus17;
15603 if (DS.hasConstexprSpecifier())
15604 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15605 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15606
15607 DiagnoseFunctionSpecifiers(DS);
15608
15609 CheckFunctionOrTemplateParamDeclarator(S, D);
15610
15611 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15612 QualType parmDeclType = TInfo->getType();
15613
15614 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15615 const IdentifierInfo *II = D.getIdentifier();
15616 if (II) {
15617 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15618 RedeclarationKind::ForVisibleRedeclaration);
15619 LookupName(R, S);
15620 if (!R.empty()) {
15621 NamedDecl *PrevDecl = *R.begin();
15622 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15623 // Maybe we will complain about the shadowed template parameter.
15624 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15625 // Just pretend that we didn't see the previous declaration.
15626 PrevDecl = nullptr;
15627 }
15628 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15629 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15630 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15631 // Recover by removing the name
15632 II = nullptr;
15633 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15634 D.setInvalidType(true);
15635 }
15636 }
15637 }
15638
15639 // Incomplete resource arrays are not allowed as function parameters in HLSL
15640 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15641 parmDeclType->isHLSLResourceRecordArray()) {
15642 Diag(D.getIdentifierLoc(),
15643 diag::err_hlsl_incomplete_resource_array_in_function_param);
15644 D.setInvalidType(true);
15645 }
15646
15647 // Temporarily put parameter variables in the translation unit, not
15648 // the enclosing context. This prevents them from accidentally
15649 // looking like class members in C++.
15650 ParmVarDecl *New =
15651 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15652 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15653
15654 if (D.isInvalidType())
15655 New->setInvalidDecl();
15656
15657 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15658
15659 assert(S->isFunctionPrototypeScope());
15660 assert(S->getFunctionPrototypeDepth() >= 1);
15661 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15662 S->getNextFunctionPrototypeIndex());
15663
15664 warnOnCTypeHiddenInCPlusPlus(New);
15665
15666 // Add the parameter declaration into this scope.
15667 S->AddDecl(New);
15668 if (II)
15669 IdResolver.AddDecl(New);
15670
15671 ProcessDeclAttributes(S, New, D);
15672
15673 if (D.getDeclSpec().isModulePrivateSpecified())
15674 Diag(New->getLocation(), diag::err_module_private_local)
15675 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15676 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15677
15678 if (New->hasAttr<BlocksAttr>()) {
15679 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15680 }
15681
15682 if (getLangOpts().OpenCL)
15683 deduceOpenCLAddressSpace(New);
15684
15685 return New;
15686 }
15687
15688 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15689 SourceLocation Loc,
15690 QualType T) {
15691 /* FIXME: setting StartLoc == Loc.
15692 Would it be worth to modify callers so as to provide proper source
15693 location for the unnamed parameters, embedding the parameter's type? */
15694 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15695 T, Context.getTrivialTypeSourceInfo(T, Loc),
15696 SC_None, nullptr);
15697 Param->setImplicit();
15698 return Param;
15699 }
15700
15701 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15702 // Don't diagnose unused-parameter errors in template instantiations; we
15703 // will already have done so in the template itself.
15704 if (inTemplateInstantiation())
15705 return;
15706
15707 for (const ParmVarDecl *Parameter : Parameters) {
15708 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15709 !Parameter->hasAttr<UnusedAttr>() &&
15710 !Parameter->getIdentifier()->isPlaceholder()) {
15711 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15712 << Parameter->getDeclName();
15713 }
15714 }
15715 }
15716
15717 void Sema::DiagnoseSizeOfParametersAndReturnValue(
15718 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15719 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15720 return;
15721
15722 // Warn if the return value is pass-by-value and larger than the specified
15723 // threshold.
15724 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15725 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15726 if (Size > LangOpts.NumLargeByValueCopy)
15727 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15728 }
15729
15730 // Warn if any parameter is pass-by-value and larger than the specified
15731 // threshold.
15732 for (const ParmVarDecl *Parameter : Parameters) {
15733 QualType T = Parameter->getType();
15734 if (T->isDependentType() || !T.isPODType(Context))
15735 continue;
15736 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15737 if (Size > LangOpts.NumLargeByValueCopy)
15738 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15739 << Parameter << Size;
15740 }
15741 }
15742
15743 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15744 SourceLocation NameLoc,
15745 const IdentifierInfo *Name, QualType T,
15746 TypeSourceInfo *TSInfo, StorageClass SC) {
15747 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15748 if (getLangOpts().ObjCAutoRefCount &&
15749 T.getObjCLifetime() == Qualifiers::OCL_None &&
15750 T->isObjCLifetimeType()) {
15751
15752 Qualifiers::ObjCLifetime lifetime;
15753
15754 // Special cases for arrays:
15755 // - if it's const, use __unsafe_unretained
15756 // - otherwise, it's an error
15757 if (T->isArrayType()) {
15758 if (!T.isConstQualified()) {
15759 if (DelayedDiagnostics.shouldDelayDiagnostics())
15760 DelayedDiagnostics.add(
15761 sema::DelayedDiagnostic::makeForbiddenType(
15762 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15763 else
15764 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15765 << TSInfo->getTypeLoc().getSourceRange();
15766 }
15767 lifetime = Qualifiers::OCL_ExplicitNone;
15768 } else {
15769 lifetime = T->getObjCARCImplicitLifetime();
15770 }
15771 T = Context.getLifetimeQualifiedType(T, lifetime);
15772 }
15773
15774 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15775 Context.getAdjustedParameterType(T),
15776 TSInfo, SC, nullptr);
15777
15778 // Make a note if we created a new pack in the scope of a lambda, so that
15779 // we know that references to that pack must also be expanded within the
15780 // lambda scope.
15781 if (New->isParameterPack())
15782 if (auto *CSI = getEnclosingLambdaOrBlock())
15783 CSI->LocalPacks.push_back(New);
15784
15785 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15786 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15787 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15788 NonTrivialCUnionContext::FunctionParam,
15789 NTCUK_Destruct | NTCUK_Copy);
15790
15791 // Parameter declarators cannot be interface types. All ObjC objects are
15792 // passed by reference.
15793 if (T->isObjCObjectType()) {
15794 SourceLocation TypeEndLoc =
15795 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15796 Diag(NameLoc,
15797 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15798 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15799 T = Context.getObjCObjectPointerType(T);
15800 New->setType(T);
15801 }
15802
15803 // __ptrauth is forbidden on parameters.
15804 if (T.getPointerAuth()) {
15805 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15806 New->setInvalidDecl();
15807 }
15808
15809 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15810 // duration shall not be qualified by an address-space qualifier."
15811 // Since all parameters have automatic store duration, they can not have
15812 // an address space.
15813 if (T.getAddressSpace() != LangAS::Default &&
15814 // OpenCL allows function arguments declared to be an array of a type
15815 // to be qualified with an address space.
15816 !(getLangOpts().OpenCL &&
15817 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15818 // WebAssembly allows reference types as parameters. Funcref in particular
15819 // lives in a different address space.
15820 !(T->isFunctionPointerType() &&
15821 T.getAddressSpace() == LangAS::wasm_funcref)) {
15822 Diag(NameLoc, diag::err_arg_with_address_space);
15823 New->setInvalidDecl();
15824 }
15825
15826 // PPC MMA non-pointer types are not allowed as function argument types.
15827 if (Context.getTargetInfo().getTriple().isPPC64() &&
15828 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15829 New->setInvalidDecl();
15830 }
15831
15832 return New;
15833 }
15834
15835 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15836 SourceLocation LocAfterDecls) {
15837 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15838
15839 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15840 // in the declaration list shall have at least one declarator, those
15841 // declarators shall only declare identifiers from the identifier list, and
15842 // every identifier in the identifier list shall be declared.
15843 //
15844 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15845 // identifiers it names shall be declared in the declaration list."
15846 //
15847 // This is why we only diagnose in C99 and later. Note, the other conditions
15848 // listed are checked elsewhere.
15849 if (!FTI.hasPrototype) {
15850 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15851 --i;
15852 if (FTI.Params[i].Param == nullptr) {
15853 if (getLangOpts().C99) {
15854 SmallString<256> Code;
15855 llvm::raw_svector_ostream(Code)
15856 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15857 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15858 << FTI.Params[i].Ident
15859 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15860 }
15861
15862 // Implicitly declare the argument as type 'int' for lack of a better
15863 // type.
15864 AttributeFactory attrs;
15865 DeclSpec DS(attrs);
15866 const char* PrevSpec; // unused
15867 unsigned DiagID; // unused
15868 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15869 DiagID, Context.getPrintingPolicy());
15870 // Use the identifier location for the type source range.
15871 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15872 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15873 Declarator ParamD(DS, ParsedAttributesView::none(),
15874 DeclaratorContext::KNRTypeList);
15875 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15876 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15877 }
15878 }
15879 }
15880 }
15881
15882 Decl *
15883 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15884 MultiTemplateParamsArg TemplateParameterLists,
15885 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15886 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15887 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15888 Scope *ParentScope = FnBodyScope->getParent();
15889
15890 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15891 // we define a non-templated function definition, we will create a declaration
15892 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15893 // The base function declaration will have the equivalent of an `omp declare
15894 // variant` annotation which specifies the mangled definition as a
15895 // specialization function under the OpenMP context defined as part of the
15896 // `omp begin declare variant`.
15897 SmallVector<FunctionDecl *, 4> Bases;
15898 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15899 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15900 ParentScope, D, TemplateParameterLists, Bases);
15901
15902 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15903 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15904 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15905
15906 if (!Bases.empty())
15907 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
15908 Bases);
15909
15910 return Dcl;
15911 }
15912
15913 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15914 Consumer.HandleInlineFunctionDefinition(D);
15915 }
15916
15917 static bool FindPossiblePrototype(const FunctionDecl *FD,
15918 const FunctionDecl *&PossiblePrototype) {
15919 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15920 Prev = Prev->getPreviousDecl()) {
15921 // Ignore any declarations that occur in function or method
15922 // scope, because they aren't visible from the header.
15923 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15924 continue;
15925
15926 PossiblePrototype = Prev;
15927 return Prev->getType()->isFunctionProtoType();
15928 }
15929 return false;
15930 }
15931
15932 static bool
15933 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15934 const FunctionDecl *&PossiblePrototype) {
15935 // Don't warn about invalid declarations.
15936 if (FD->isInvalidDecl())
15937 return false;
15938
15939 // Or declarations that aren't global.
15940 if (!FD->isGlobal())
15941 return false;
15942
15943 // Don't warn about C++ member functions.
15944 if (isa<CXXMethodDecl>(FD))
15945 return false;
15946
15947 // Don't warn about 'main'.
15948 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15949 if (IdentifierInfo *II = FD->getIdentifier())
15950 if (II->isStr("main") || II->isStr("efi_main"))
15951 return false;
15952
15953 if (FD->isMSVCRTEntryPoint())
15954 return false;
15955
15956 // Don't warn about inline functions.
15957 if (FD->isInlined())
15958 return false;
15959
15960 // Don't warn about function templates.
15961 if (FD->getDescribedFunctionTemplate())
15962 return false;
15963
15964 // Don't warn about function template specializations.
15965 if (FD->isFunctionTemplateSpecialization())
15966 return false;
15967
15968 // Don't warn for OpenCL kernels.
15969 if (FD->hasAttr<DeviceKernelAttr>())
15970 return false;
15971
15972 // Don't warn on explicitly deleted functions.
15973 if (FD->isDeleted())
15974 return false;
15975
15976 // Don't warn on implicitly local functions (such as having local-typed
15977 // parameters).
15978 if (!FD->isExternallyVisible())
15979 return false;
15980
15981 // If we were able to find a potential prototype, don't warn.
15982 if (FindPossiblePrototype(FD, PossiblePrototype))
15983 return false;
15984
15985 return true;
15986 }
15987
15988 void
15989 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15990 const FunctionDecl *EffectiveDefinition,
15991 SkipBodyInfo *SkipBody) {
15992 const FunctionDecl *Definition = EffectiveDefinition;
15993 if (!Definition &&
15994 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15995 return;
15996
15997 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15998 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15999 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16000 // A merged copy of the same function, instantiated as a member of
16001 // the same class, is OK.
16002 if (declaresSameEntity(OrigFD, OrigDef) &&
16003 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16004 cast<Decl>(FD->getLexicalDeclContext())))
16005 return;
16006 }
16007 }
16008 }
16009
16010 if (canRedefineFunction(Definition, getLangOpts()))
16011 return;
16012
16013 // Don't emit an error when this is redefinition of a typo-corrected
16014 // definition.
16015 if (TypoCorrectedFunctionDefinitions.count(Definition))
16016 return;
16017
16018 bool DefinitionVisible = false;
16019 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16020 (Definition->getFormalLinkage() == Linkage::Internal ||
16021 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16022 Definition->getNumTemplateParameterLists())) {
16023 SkipBody->ShouldSkip = true;
16024 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16025 if (!DefinitionVisible) {
16026 if (auto *TD = Definition->getDescribedFunctionTemplate())
16027 makeMergedDefinitionVisible(TD);
16028 makeMergedDefinitionVisible(const_cast<FunctionDecl *>(Definition));
16029 }
16030 return;
16031 }
16032
16033 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16034 Definition->getStorageClass() == SC_Extern)
16035 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16036 << FD << getLangOpts().CPlusPlus;
16037 else
16038 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16039
16040 Diag(Definition->getLocation(), diag::note_previous_definition);
16041 FD->setInvalidDecl();
16042 }
16043
16044 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16045 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16046
16047 LambdaScopeInfo *LSI = PushLambdaScope();
16048 LSI->CallOperator = CallOperator;
16049 LSI->Lambda = LambdaClass;
16050 LSI->ReturnType = CallOperator->getReturnType();
16051 // When this function is called in situation where the context of the call
16052 // operator is not entered, we set AfterParameterList to false, so that
16053 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16054 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16055 // where we would set the CurContext to the lambda operator before
16056 // substituting into it. In this case the flag needs to be true such that
16057 // tryCaptureVariable can correctly handle potential captures thereof.
16058 LSI->AfterParameterList = CurContext == CallOperator;
16059
16060 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16061 // used at the point of dealing with potential captures.
16062 //
16063 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16064 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16065 // associated. (Technically, we could recover that list from their
16066 // instantiation patterns, but for now, the GLTemplateParameterList seems
16067 // unnecessary in these cases.)
16068 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16069 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16070 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16071
16072 if (LCD == LCD_None)
16073 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16074 else if (LCD == LCD_ByCopy)
16075 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16076 else if (LCD == LCD_ByRef)
16077 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16078 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16079
16080 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16081 LSI->Mutable = !CallOperator->isConst();
16082 if (CallOperator->isExplicitObjectMemberFunction())
16083 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16084
16085 // Add the captures to the LSI so they can be noted as already
16086 // captured within tryCaptureVar.
16087 auto I = LambdaClass->field_begin();
16088 for (const auto &C : LambdaClass->captures()) {
16089 if (C.capturesVariable()) {
16090 ValueDecl *VD = C.getCapturedVar();
16091 if (VD->isInitCapture())
16092 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16093 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16094 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16095 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16096 /*EllipsisLoc*/C.isPackExpansion()
16097 ? C.getEllipsisLoc() : SourceLocation(),
16098 I->getType(), /*Invalid*/false);
16099
16100 } else if (C.capturesThis()) {
16101 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16102 C.getCaptureKind() == LCK_StarThis);
16103 } else {
16104 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16105 I->getType());
16106 }
16107 ++I;
16108 }
16109 return LSI;
16110 }
16111
16112 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16113 SkipBodyInfo *SkipBody,
16114 FnBodyKind BodyKind) {
16115 if (!D) {
16116 // Parsing the function declaration failed in some way. Push on a fake scope
16117 // anyway so we can try to parse the function body.
16118 PushFunctionScope();
16119 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16120 return D;
16121 }
16122
16123 FunctionDecl *FD = nullptr;
16124
16125 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16126 FD = FunTmpl->getTemplatedDecl();
16127 else
16128 FD = cast<FunctionDecl>(D);
16129
16130 // Do not push if it is a lambda because one is already pushed when building
16131 // the lambda in ActOnStartOfLambdaDefinition().
16132 if (!isLambdaCallOperator(FD))
16133 PushExpressionEvaluationContextForFunction(ExprEvalContexts.back().Context,
16134 FD);
16135
16136 // Check for defining attributes before the check for redefinition.
16137 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16138 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16139 FD->dropAttr<AliasAttr>();
16140 FD->setInvalidDecl();
16141 }
16142 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16143 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16144 FD->dropAttr<IFuncAttr>();
16145 FD->setInvalidDecl();
16146 }
16147 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16148 if (Context.getTargetInfo().getTriple().isAArch64() &&
16149 !Context.getTargetInfo().hasFeature("fmv") &&
16150 !Attr->isDefaultVersion()) {
16151 // If function multi versioning disabled skip parsing function body
16152 // defined with non-default target_version attribute
16153 if (SkipBody)
16154 SkipBody->ShouldSkip = true;
16155 return nullptr;
16156 }
16157 }
16158
16159 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16160 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16161 Ctor->isDefaultConstructor() &&
16162 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16163 // If this is an MS ABI dllexport default constructor, instantiate any
16164 // default arguments.
16165 InstantiateDefaultCtorDefaultArgs(Ctor);
16166 }
16167 }
16168
16169 // See if this is a redefinition. If 'will have body' (or similar) is already
16170 // set, then these checks were already performed when it was set.
16171 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16172 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16173 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16174
16175 // If we're skipping the body, we're done. Don't enter the scope.
16176 if (SkipBody && SkipBody->ShouldSkip)
16177 return D;
16178 }
16179
16180 // Mark this function as "will have a body eventually". This lets users to
16181 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16182 // this function.
16183 FD->setWillHaveBody();
16184
16185 // If we are instantiating a generic lambda call operator, push
16186 // a LambdaScopeInfo onto the function stack. But use the information
16187 // that's already been calculated (ActOnLambdaExpr) to prime the current
16188 // LambdaScopeInfo.
16189 // When the template operator is being specialized, the LambdaScopeInfo,
16190 // has to be properly restored so that tryCaptureVariable doesn't try
16191 // and capture any new variables. In addition when calculating potential
16192 // captures during transformation of nested lambdas, it is necessary to
16193 // have the LSI properly restored.
16194 if (isGenericLambdaCallOperatorSpecialization(FD)) {
16195 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16196 // instantiated, explicitly specialized.
16197 if (FD->getTemplateSpecializationInfo()
16198 ->isExplicitInstantiationOrSpecialization()) {
16199 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16200 FD->setInvalidDecl();
16201 PushFunctionScope();
16202 } else {
16203 assert(inTemplateInstantiation() &&
16204 "There should be an active template instantiation on the stack "
16205 "when instantiating a generic lambda!");
16206 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
16207 }
16208 } else {
16209 // Enter a new function scope
16210 PushFunctionScope();
16211 }
16212
16213 // Builtin functions cannot be defined.
16214 if (unsigned BuiltinID = FD->getBuiltinID()) {
16215 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16216 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16217 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16218 FD->setInvalidDecl();
16219 }
16220 }
16221
16222 // The return type of a function definition must be complete (C99 6.9.1p3).
16223 // C++23 [dcl.fct.def.general]/p2
16224 // The type of [...] the return for a function definition
16225 // shall not be a (possibly cv-qualified) class type that is incomplete
16226 // or abstract within the function body unless the function is deleted.
16227 QualType ResultType = FD->getReturnType();
16228 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16229 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16230 (RequireCompleteType(FD->getLocation(), ResultType,
16231 diag::err_func_def_incomplete_result) ||
16232 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
16233 diag::err_abstract_type_in_decl,
16234 AbstractReturnType)))
16235 FD->setInvalidDecl();
16236
16237 if (FnBodyScope)
16238 PushDeclContext(FnBodyScope, FD);
16239
16240 // Check the validity of our function parameters
16241 if (BodyKind != FnBodyKind::Delete)
16242 CheckParmsForFunctionDef(FD->parameters(),
16243 /*CheckParameterNames=*/true);
16244
16245 // Add non-parameter declarations already in the function to the current
16246 // scope.
16247 if (FnBodyScope) {
16248 for (Decl *NPD : FD->decls()) {
16249 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16250 if (!NonParmDecl)
16251 continue;
16252 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16253 "parameters should not be in newly created FD yet");
16254
16255 // If the decl has a name, make it accessible in the current scope.
16256 if (NonParmDecl->getDeclName())
16257 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16258
16259 // Similarly, dive into enums and fish their constants out, making them
16260 // accessible in this scope.
16261 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16262 for (auto *EI : ED->enumerators())
16263 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16264 }
16265 }
16266 }
16267
16268 // Introduce our parameters into the function scope
16269 for (auto *Param : FD->parameters()) {
16270 Param->setOwningFunction(FD);
16271
16272 // If this has an identifier, add it to the scope stack.
16273 if (Param->getIdentifier() && FnBodyScope) {
16274 CheckShadow(FnBodyScope, Param);
16275
16276 PushOnScopeChains(Param, FnBodyScope);
16277 }
16278 }
16279
16280 // C++ [module.import/6]
16281 // ...
16282 // A header unit shall not contain a definition of a non-inline function or
16283 // variable whose name has external linkage.
16284 //
16285 // Deleted and Defaulted functions are implicitly inline (but the
16286 // inline state is not set at this point, so check the BodyKind explicitly).
16287 // We choose to allow weak & selectany definitions, as they are common in
16288 // headers, and have semantics similar to inline definitions which are allowed
16289 // in header units.
16290 // FIXME: Consider an alternate location for the test where the inlined()
16291 // state is complete.
16292 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16293 !FD->isInvalidDecl() && !FD->isInlined() &&
16294 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16295 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16296 !FD->isTemplateInstantiation() &&
16297 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16298 assert(FD->isThisDeclarationADefinition());
16299 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16300 FD->setInvalidDecl();
16301 }
16302
16303 // Ensure that the function's exception specification is instantiated.
16304 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16305 ResolveExceptionSpec(D->getLocation(), FPT);
16306
16307 // dllimport cannot be applied to non-inline function definitions.
16308 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16309 !FD->isTemplateInstantiation()) {
16310 assert(!FD->hasAttr<DLLExportAttr>());
16311 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16312 FD->setInvalidDecl();
16313 return D;
16314 }
16315
16316 // Some function attributes (like OptimizeNoneAttr) need actions before
16317 // parsing body started.
16318 applyFunctionAttributesBeforeParsingBody(D);
16319
16320 // We want to attach documentation to original Decl (which might be
16321 // a function template).
16322 ActOnDocumentableDecl(D);
16323 if (getCurLexicalContext()->isObjCContainer() &&
16324 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16325 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16326 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16327
16328 maybeAddDeclWithEffects(FD);
16329
16330 return D;
16331 }
16332
16333 void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16334 if (!FD || FD->isInvalidDecl())
16335 return;
16336 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16337 FD = TD->getTemplatedDecl();
16338 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16339 FPOptionsOverride FPO;
16340 FPO.setDisallowOptimizations();
16341 CurFPFeatures.applyChanges(FPO);
16342 FpPragmaStack.CurrentValue =
16343 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16344 }
16345 }
16346
16347 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16348 ReturnStmt **Returns = Scope->Returns.data();
16349
16350 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16351 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16352 if (!NRVOCandidate->isNRVOVariable()) {
16353 Diag(Returns[I]->getRetValue()->getExprLoc(),
16354 diag::warn_not_eliding_copy_on_return);
16355 Returns[I]->setNRVOCandidate(nullptr);
16356 }
16357 }
16358 }
16359 }
16360
16361 bool Sema::canDelayFunctionBody(const Declarator &D) {
16362 // We can't delay parsing the body of a constexpr function template (yet).
16363 if (D.getDeclSpec().hasConstexprSpecifier())
16364 return false;
16365
16366 // We can't delay parsing the body of a function template with a deduced
16367 // return type (yet).
16368 if (D.getDeclSpec().hasAutoTypeSpec()) {
16369 // If the placeholder introduces a non-deduced trailing return type,
16370 // we can still delay parsing it.
16371 if (D.getNumTypeObjects()) {
16372 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16373 if (Outer.Kind == DeclaratorChunk::Function &&
16374 Outer.Fun.hasTrailingReturnType()) {
16375 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16376 return Ty.isNull() || !Ty->isUndeducedType();
16377 }
16378 }
16379 return false;
16380 }
16381
16382 return true;
16383 }
16384
16385 bool Sema::canSkipFunctionBody(Decl *D) {
16386 // We cannot skip the body of a function (or function template) which is
16387 // constexpr, since we may need to evaluate its body in order to parse the
16388 // rest of the file.
16389 // We cannot skip the body of a function with an undeduced return type,
16390 // because any callers of that function need to know the type.
16391 if (const FunctionDecl *FD = D->getAsFunction()) {
16392 if (FD->isConstexpr())
16393 return false;
16394 // We can't simply call Type::isUndeducedType here, because inside template
16395 // auto can be deduced to a dependent type, which is not considered
16396 // "undeduced".
16397 if (FD->getReturnType()->getContainedDeducedType())
16398 return false;
16399 }
16400 return Consumer.shouldSkipFunctionBody(D);
16401 }
16402
16403 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16404 if (!Decl)
16405 return nullptr;
16406 if (FunctionDecl *FD = Decl->getAsFunction())
16407 FD->setHasSkippedBody();
16408 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16409 MD->setHasSkippedBody();
16410 return Decl;
16411 }
16412
16413 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
16414 /// body.
16415 class ExitFunctionBodyRAII {
16416 public:
16417 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16418 ~ExitFunctionBodyRAII() {
16419 if (!IsLambda)
16420 S.PopExpressionEvaluationContext();
16421 }
16422
16423 private:
16424 Sema &S;
16425 bool IsLambda = false;
16426 };
16427
16428 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16429 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16430
16431 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16432 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16433 if (!Inserted)
16434 return It->second;
16435
16436 bool R = false;
16437 const BlockDecl *CurBD = BD;
16438
16439 do {
16440 R = !CurBD->doesNotEscape();
16441 if (R)
16442 break;
16443 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16444 } while (CurBD);
16445
16446 return It->second = R;
16447 };
16448
16449 // If the location where 'self' is implicitly retained is inside a escaping
16450 // block, emit a diagnostic.
16451 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16452 S.ImplicitlyRetainedSelfLocs)
16453 if (IsOrNestedInEscapingBlock(P.second))
16454 S.Diag(P.first, diag::warn_implicitly_retains_self)
16455 << FixItHint::CreateInsertion(P.first, "self->");
16456 }
16457
16458 static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16459 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16460 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16461 }
16462
16463 bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16464 return methodHasName(FD, "get_return_object");
16465 }
16466
16467 bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16468 return FD->isStatic() &&
16469 methodHasName(FD, "get_return_object_on_allocation_failure");
16470 }
16471
16472 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16473 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16474 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16475 return;
16476 // Allow some_promise_type::get_return_object().
16477 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16478 return;
16479 if (!FD->hasAttr<CoroWrapperAttr>())
16480 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16481 }
16482
16483 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16484 bool RetainFunctionScopeInfo) {
16485 FunctionScopeInfo *FSI = getCurFunction();
16486 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16487
16488 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16489 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16490
16491 SourceLocation AnalysisLoc;
16492 if (Body)
16493 AnalysisLoc = Body->getEndLoc();
16494 else if (FD)
16495 AnalysisLoc = FD->getEndLoc();
16496 sema::AnalysisBasedWarnings::Policy WP =
16497 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16498 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16499
16500 // If we skip function body, we can't tell if a function is a coroutine.
16501 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16502 if (FSI->isCoroutine())
16503 CheckCompletedCoroutineBody(FD, Body);
16504 else
16505 CheckCoroutineWrapper(FD);
16506 }
16507
16508 // Diagnose invalid SYCL kernel entry point function declarations
16509 // and build SYCLKernelCallStmts for valid ones.
16510 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16511 SYCLKernelEntryPointAttr *SKEPAttr =
16512 FD->getAttr<SYCLKernelEntryPointAttr>();
16513 if (FD->isDefaulted()) {
16514 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16515 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16516 SKEPAttr->setInvalidAttr();
16517 } else if (FD->isDeleted()) {
16518 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16519 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16520 SKEPAttr->setInvalidAttr();
16521 } else if (FSI->isCoroutine()) {
16522 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16523 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16524 SKEPAttr->setInvalidAttr();
16525 } else if (Body && isa<CXXTryStmt>(Body)) {
16526 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16527 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16528 SKEPAttr->setInvalidAttr();
16529 }
16530
16531 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16532 StmtResult SR =
16533 SYCL().BuildSYCLKernelCallStmt(FD, cast<CompoundStmt>(Body));
16534 if (SR.isInvalid())
16535 return nullptr;
16536 Body = SR.get();
16537 }
16538 }
16539
16540 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16541 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16542 if (FD->isDeletedAsWritten())
16543 Diag(SEAttr->getLocation(),
16544 diag::err_sycl_external_invalid_deleted_function)
16545 << SEAttr;
16546 }
16547
16548 {
16549 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16550 // one is already popped when finishing the lambda in BuildLambdaExpr().
16551 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16552 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16553 if (FD) {
16554 // The function body and the DefaultedOrDeletedInfo, if present, use
16555 // the same storage; don't overwrite the latter if the former is null
16556 // (the body is initialised to null anyway, so even if the latter isn't
16557 // present, this would still be a no-op).
16558 if (Body)
16559 FD->setBody(Body);
16560 FD->setWillHaveBody(false);
16561
16562 if (getLangOpts().CPlusPlus14) {
16563 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16564 FD->getReturnType()->isUndeducedType()) {
16565 // For a function with a deduced result type to return void,
16566 // the result type as written must be 'auto' or 'decltype(auto)',
16567 // possibly cv-qualified or constrained, but not ref-qualified.
16568 if (!FD->getReturnType()->getAs<AutoType>()) {
16569 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16570 << FD->getReturnType();
16571 FD->setInvalidDecl();
16572 } else {
16573 // Falling off the end of the function is the same as 'return;'.
16574 Expr *Dummy = nullptr;
16575 if (DeduceFunctionTypeFromReturnExpr(
16576 FD, dcl->getLocation(), Dummy,
16577 FD->getReturnType()->getAs<AutoType>()))
16578 FD->setInvalidDecl();
16579 }
16580 }
16581 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16582 // In C++11, we don't use 'auto' deduction rules for lambda call
16583 // operators because we don't support return type deduction.
16584 auto *LSI = getCurLambda();
16585 if (LSI->HasImplicitReturnType) {
16586 deduceClosureReturnType(*LSI);
16587
16588 // C++11 [expr.prim.lambda]p4:
16589 // [...] if there are no return statements in the compound-statement
16590 // [the deduced type is] the type void
16591 QualType RetType =
16592 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16593
16594 // Update the return type to the deduced type.
16595 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16596 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16597 Proto->getExtProtoInfo()));
16598 }
16599 }
16600
16601 // If the function implicitly returns zero (like 'main') or is naked,
16602 // don't complain about missing return statements.
16603 // Clang implicitly returns 0 in C89 mode, but that's considered an
16604 // extension. The check is necessary to ensure the expected extension
16605 // warning is emitted in C89 mode.
16606 if ((FD->hasImplicitReturnZero() &&
16607 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16608 FD->hasAttr<NakedAttr>())
16609 WP.disableCheckFallThrough();
16610
16611 // MSVC permits the use of pure specifier (=0) on function definition,
16612 // defined at class scope, warn about this non-standard construct.
16613 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16614 !FD->isOutOfLine())
16615 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16616
16617 if (!FD->isInvalidDecl()) {
16618 // Don't diagnose unused parameters of defaulted, deleted or naked
16619 // functions.
16620 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16621 !FD->hasAttr<NakedAttr>())
16622 DiagnoseUnusedParameters(FD->parameters());
16623 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
16624 FD->getReturnType(), FD);
16625
16626 // If this is a structor, we need a vtable.
16627 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16628 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16629 else if (CXXDestructorDecl *Destructor =
16630 dyn_cast<CXXDestructorDecl>(FD))
16631 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16632
16633 // Try to apply the named return value optimization. We have to check
16634 // if we can do this here because lambdas keep return statements around
16635 // to deduce an implicit return type.
16636 if (FD->getReturnType()->isRecordType() &&
16637 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16638 computeNRVO(Body, FSI);
16639 }
16640
16641 // GNU warning -Wmissing-prototypes:
16642 // Warn if a global function is defined without a previous
16643 // prototype declaration. This warning is issued even if the
16644 // definition itself provides a prototype. The aim is to detect
16645 // global functions that fail to be declared in header files.
16646 const FunctionDecl *PossiblePrototype = nullptr;
16647 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16648 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16649
16650 if (PossiblePrototype) {
16651 // We found a declaration that is not a prototype,
16652 // but that could be a zero-parameter prototype
16653 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16654 TypeLoc TL = TI->getTypeLoc();
16655 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16656 Diag(PossiblePrototype->getLocation(),
16657 diag::note_declaration_not_a_prototype)
16658 << (FD->getNumParams() != 0)
16659 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16660 FTL.getRParenLoc(), "void")
16661 : FixItHint{});
16662 }
16663 } else {
16664 // Returns true if the token beginning at this Loc is `const`.
16665 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16666 const LangOptions &LangOpts) {
16667 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16668 if (LocInfo.first.isInvalid())
16669 return false;
16670
16671 bool Invalid = false;
16672 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16673 if (Invalid)
16674 return false;
16675
16676 if (LocInfo.second > Buffer.size())
16677 return false;
16678
16679 const char *LexStart = Buffer.data() + LocInfo.second;
16680 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16681
16682 return StartTok.consume_front("const") &&
16683 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16684 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16685 };
16686
16687 auto findBeginLoc = [&]() {
16688 // If the return type has `const` qualifier, we want to insert
16689 // `static` before `const` (and not before the typename).
16690 if ((FD->getReturnType()->isAnyPointerType() &&
16691 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16692 FD->getReturnType().isConstQualified()) {
16693 // But only do this if we can determine where the `const` is.
16694
16695 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16696 getLangOpts()))
16697
16698 return FD->getBeginLoc();
16699 }
16700 return FD->getTypeSpecStartLoc();
16701 };
16702 Diag(FD->getTypeSpecStartLoc(),
16703 diag::note_static_for_internal_linkage)
16704 << /* function */ 1
16705 << (FD->getStorageClass() == SC_None
16706 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16707 : FixItHint{});
16708 }
16709 }
16710
16711 // We might not have found a prototype because we didn't wish to warn on
16712 // the lack of a missing prototype. Try again without the checks for
16713 // whether we want to warn on the missing prototype.
16714 if (!PossiblePrototype)
16715 (void)FindPossiblePrototype(FD, PossiblePrototype);
16716
16717 // If the function being defined does not have a prototype, then we may
16718 // need to diagnose it as changing behavior in C23 because we now know
16719 // whether the function accepts arguments or not. This only handles the
16720 // case where the definition has no prototype but does have parameters
16721 // and either there is no previous potential prototype, or the previous
16722 // potential prototype also has no actual prototype. This handles cases
16723 // like:
16724 // void f(); void f(a) int a; {}
16725 // void g(a) int a; {}
16726 // See MergeFunctionDecl() for other cases of the behavior change
16727 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16728 // type without a prototype.
16729 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16730 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16731 !PossiblePrototype->isImplicit()))) {
16732 // The function definition has parameters, so this will change behavior
16733 // in C23. If there is a possible prototype, it comes before the
16734 // function definition.
16735 // FIXME: The declaration may have already been diagnosed as being
16736 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16737 // there's no way to test for the "changes behavior" condition in
16738 // SemaType.cpp when forming the declaration's function type. So, we do
16739 // this awkward dance instead.
16740 //
16741 // If we have a possible prototype and it declares a function with a
16742 // prototype, we don't want to diagnose it; if we have a possible
16743 // prototype and it has no prototype, it may have already been
16744 // diagnosed in SemaType.cpp as deprecated depending on whether
16745 // -Wstrict-prototypes is enabled. If we already warned about it being
16746 // deprecated, add a note that it also changes behavior. If we didn't
16747 // warn about it being deprecated (because the diagnostic is not
16748 // enabled), warn now that it is deprecated and changes behavior.
16749
16750 // This K&R C function definition definitely changes behavior in C23,
16751 // so diagnose it.
16752 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16753 << /*definition*/ 1 << /* not supported in C23 */ 0;
16754
16755 // If we have a possible prototype for the function which is a user-
16756 // visible declaration, we already tested that it has no prototype.
16757 // This will change behavior in C23. This gets a warning rather than a
16758 // note because it's the same behavior-changing problem as with the
16759 // definition.
16760 if (PossiblePrototype)
16761 Diag(PossiblePrototype->getLocation(),
16762 diag::warn_non_prototype_changes_behavior)
16763 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16764 << /*definition*/ 1;
16765 }
16766
16767 // Warn on CPUDispatch with an actual body.
16768 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16769 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16770 if (!CmpndBody->body_empty())
16771 Diag(CmpndBody->body_front()->getBeginLoc(),
16772 diag::warn_dispatch_body_ignored);
16773
16774 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16775 const CXXMethodDecl *KeyFunction;
16776 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16777 MD->isVirtual() &&
16778 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16779 MD == KeyFunction->getCanonicalDecl()) {
16780 // Update the key-function state if necessary for this ABI.
16781 if (FD->isInlined() &&
16782 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16783 Context.setNonKeyFunction(MD);
16784
16785 // If the newly-chosen key function is already defined, then we
16786 // need to mark the vtable as used retroactively.
16787 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16788 const FunctionDecl *Definition;
16789 if (KeyFunction && KeyFunction->isDefined(Definition))
16790 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16791 } else {
16792 // We just defined they key function; mark the vtable as used.
16793 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16794 }
16795 }
16796 }
16797
16798 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16799 "Function parsing confused");
16800 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16801 assert(MD == getCurMethodDecl() && "Method parsing confused");
16802 MD->setBody(Body);
16803 if (!MD->isInvalidDecl()) {
16804 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16805 MD->getReturnType(), MD);
16806
16807 if (Body)
16808 computeNRVO(Body, FSI);
16809 }
16810 if (FSI->ObjCShouldCallSuper) {
16811 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16812 << MD->getSelector().getAsString();
16813 FSI->ObjCShouldCallSuper = false;
16814 }
16815 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16816 const ObjCMethodDecl *InitMethod = nullptr;
16817 bool isDesignated =
16818 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16819 assert(isDesignated && InitMethod);
16820 (void)isDesignated;
16821
16822 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16823 auto IFace = MD->getClassInterface();
16824 if (!IFace)
16825 return false;
16826 auto SuperD = IFace->getSuperClass();
16827 if (!SuperD)
16828 return false;
16829 return SuperD->getIdentifier() ==
16830 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16831 };
16832 // Don't issue this warning for unavailable inits or direct subclasses
16833 // of NSObject.
16834 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16835 Diag(MD->getLocation(),
16836 diag::warn_objc_designated_init_missing_super_call);
16837 Diag(InitMethod->getLocation(),
16838 diag::note_objc_designated_init_marked_here);
16839 }
16840 FSI->ObjCWarnForNoDesignatedInitChain = false;
16841 }
16842 if (FSI->ObjCWarnForNoInitDelegation) {
16843 // Don't issue this warning for unavailable inits.
16844 if (!MD->isUnavailable())
16845 Diag(MD->getLocation(),
16846 diag::warn_objc_secondary_init_missing_init_call);
16847 FSI->ObjCWarnForNoInitDelegation = false;
16848 }
16849
16850 diagnoseImplicitlyRetainedSelf(*this);
16851 } else {
16852 // Parsing the function declaration failed in some way. Pop the fake scope
16853 // we pushed on.
16854 PopFunctionScopeInfo(ActivePolicy, dcl);
16855 return nullptr;
16856 }
16857
16858 if (Body && FSI->HasPotentialAvailabilityViolations)
16859 DiagnoseUnguardedAvailabilityViolations(dcl);
16860
16861 assert(!FSI->ObjCShouldCallSuper &&
16862 "This should only be set for ObjC methods, which should have been "
16863 "handled in the block above.");
16864
16865 // Verify and clean out per-function state.
16866 if (Body && (!FD || !FD->isDefaulted())) {
16867 // C++ constructors that have function-try-blocks can't have return
16868 // statements in the handlers of that block. (C++ [except.handle]p14)
16869 // Verify this.
16870 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16871 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16872
16873 // Verify that gotos and switch cases don't jump into scopes illegally.
16874 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16875 DiagnoseInvalidJumps(Body);
16876
16877 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16878 if (!Destructor->getParent()->isDependentType())
16879 CheckDestructor(Destructor);
16880
16881 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16882 Destructor->getParent());
16883 }
16884
16885 // If any errors have occurred, clear out any temporaries that may have
16886 // been leftover. This ensures that these temporaries won't be picked up
16887 // for deletion in some later function.
16888 if (hasUncompilableErrorOccurred() ||
16889 hasAnyUnrecoverableErrorsInThisFunction() ||
16890 getDiagnostics().getSuppressAllDiagnostics()) {
16891 DiscardCleanupsInEvaluationContext();
16892 }
16893 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16894 // Since the body is valid, issue any analysis-based warnings that are
16895 // enabled.
16896 ActivePolicy = &WP;
16897 }
16898
16899 if (!IsInstantiation && FD &&
16900 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16901 !FD->isInvalidDecl() &&
16902 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16903 FD->setInvalidDecl();
16904
16905 if (FD && FD->hasAttr<NakedAttr>()) {
16906 for (const Stmt *S : Body->children()) {
16907 // Allow local register variables without initializer as they don't
16908 // require prologue.
16909 bool RegisterVariables = false;
16910 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16911 for (const auto *Decl : DS->decls()) {
16912 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16913 RegisterVariables =
16914 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16915 if (!RegisterVariables)
16916 break;
16917 }
16918 }
16919 }
16920 if (RegisterVariables)
16921 continue;
16922 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16923 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16924 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16925 FD->setInvalidDecl();
16926 break;
16927 }
16928 }
16929 }
16930
16931 assert(ExprCleanupObjects.size() ==
16932 ExprEvalContexts.back().NumCleanupObjects &&
16933 "Leftover temporaries in function");
16934 assert(!Cleanup.exprNeedsCleanups() &&
16935 "Unaccounted cleanups in function");
16936 assert(MaybeODRUseExprs.empty() &&
16937 "Leftover expressions for odr-use checking");
16938 }
16939 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16940 // the declaration context below. Otherwise, we're unable to transform
16941 // 'this' expressions when transforming immediate context functions.
16942
16943 if (FD)
16944 CheckImmediateEscalatingFunctionDefinition(FD, getCurFunction());
16945
16946 if (!IsInstantiation)
16947 PopDeclContext();
16948
16949 if (!RetainFunctionScopeInfo)
16950 PopFunctionScopeInfo(ActivePolicy, dcl);
16951 // If any errors have occurred, clear out any temporaries that may have
16952 // been leftover. This ensures that these temporaries won't be picked up for
16953 // deletion in some later function.
16954 if (hasUncompilableErrorOccurred()) {
16955 DiscardCleanupsInEvaluationContext();
16956 }
16957
16958 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16959 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16960 auto ES = getEmissionStatus(FD);
16961 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16962 ES == Sema::FunctionEmissionStatus::Unknown)
16963 DeclsToCheckForDeferredDiags.insert(FD);
16964 }
16965
16966 if (FD && !FD->isDeleted())
16967 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16968
16969 return dcl;
16970 }
16971
16972 /// When we finish delayed parsing of an attribute, we must attach it to the
16973 /// relevant Decl.
16974 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16975 ParsedAttributes &Attrs) {
16976 // Always attach attributes to the underlying decl.
16977 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16978 D = TD->getTemplatedDecl();
16979 ProcessDeclAttributeList(S, D, Attrs);
16980 ProcessAPINotes(D);
16981
16982 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16983 if (Method->isStatic())
16984 checkThisInStaticMemberFunctionAttributes(Method);
16985 }
16986
16987 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16988 IdentifierInfo &II, Scope *S) {
16989 // It is not valid to implicitly define a function in C23.
16990 assert(LangOpts.implicitFunctionsAllowed() &&
16991 "Implicit function declarations aren't allowed in this language mode");
16992
16993 // Find the scope in which the identifier is injected and the corresponding
16994 // DeclContext.
16995 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16996 // In that case, we inject the declaration into the translation unit scope
16997 // instead.
16998 Scope *BlockScope = S;
16999 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17000 BlockScope = BlockScope->getParent();
17001
17002 // Loop until we find a DeclContext that is either a function/method or the
17003 // translation unit, which are the only two valid places to implicitly define
17004 // a function. This avoids accidentally defining the function within a tag
17005 // declaration, for example.
17006 Scope *ContextScope = BlockScope;
17007 while (!ContextScope->getEntity() ||
17008 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17009 !ContextScope->getEntity()->isTranslationUnit()))
17010 ContextScope = ContextScope->getParent();
17011 ContextRAII SavedContext(*this, ContextScope->getEntity());
17012
17013 // Before we produce a declaration for an implicitly defined
17014 // function, see whether there was a locally-scoped declaration of
17015 // this name as a function or variable. If so, use that
17016 // (non-visible) declaration, and complain about it.
17017 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17018 if (ExternCPrev) {
17019 // We still need to inject the function into the enclosing block scope so
17020 // that later (non-call) uses can see it.
17021 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17022
17023 // C89 footnote 38:
17024 // If in fact it is not defined as having type "function returning int",
17025 // the behavior is undefined.
17026 if (!isa<FunctionDecl>(ExternCPrev) ||
17027 !Context.typesAreCompatible(
17028 cast<FunctionDecl>(ExternCPrev)->getType(),
17029 Context.getFunctionNoProtoType(Context.IntTy))) {
17030 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17031 << ExternCPrev << !getLangOpts().C99;
17032 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17033 return ExternCPrev;
17034 }
17035 }
17036
17037 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17038 unsigned diag_id;
17039 if (II.getName().starts_with("__builtin_"))
17040 diag_id = diag::warn_builtin_unknown;
17041 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17042 else if (getLangOpts().C99)
17043 diag_id = diag::ext_implicit_function_decl_c99;
17044 else
17045 diag_id = diag::warn_implicit_function_decl;
17046
17047 TypoCorrection Corrected;
17048 // Because typo correction is expensive, only do it if the implicit
17049 // function declaration is going to be treated as an error.
17050 //
17051 // Perform the correction before issuing the main diagnostic, as some
17052 // consumers use typo-correction callbacks to enhance the main diagnostic.
17053 if (S && !ExternCPrev &&
17054 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17055 DeclFilterCCC<FunctionDecl> CCC{};
17056 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17057 S, nullptr, CCC, CorrectTypoKind::NonError);
17058 }
17059
17060 Diag(Loc, diag_id) << &II;
17061 if (Corrected) {
17062 // If the correction is going to suggest an implicitly defined function,
17063 // skip the correction as not being a particularly good idea.
17064 bool Diagnose = true;
17065 if (const auto *D = Corrected.getCorrectionDecl())
17066 Diagnose = !D->isImplicit();
17067 if (Diagnose)
17068 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17069 /*ErrorRecovery*/ false);
17070 }
17071
17072 // If we found a prior declaration of this function, don't bother building
17073 // another one. We've already pushed that one into scope, so there's nothing
17074 // more to do.
17075 if (ExternCPrev)
17076 return ExternCPrev;
17077
17078 // Set a Declarator for the implicit definition: int foo();
17079 const char *Dummy;
17080 AttributeFactory attrFactory;
17081 DeclSpec DS(attrFactory);
17082 unsigned DiagID;
17083 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17084 Context.getPrintingPolicy());
17085 (void)Error; // Silence warning.
17086 assert(!Error && "Error setting up implicit decl!");
17087 SourceLocation NoLoc;
17088 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17089 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17090 /*IsAmbiguous=*/false,
17091 /*LParenLoc=*/NoLoc,
17092 /*Params=*/nullptr,
17093 /*NumParams=*/0,
17094 /*EllipsisLoc=*/NoLoc,
17095 /*RParenLoc=*/NoLoc,
17096 /*RefQualifierIsLvalueRef=*/true,
17097 /*RefQualifierLoc=*/NoLoc,
17098 /*MutableLoc=*/NoLoc, EST_None,
17099 /*ESpecRange=*/SourceRange(),
17100 /*Exceptions=*/nullptr,
17101 /*ExceptionRanges=*/nullptr,
17102 /*NumExceptions=*/0,
17103 /*NoexceptExpr=*/nullptr,
17104 /*ExceptionSpecTokens=*/nullptr,
17105 /*DeclsInPrototype=*/{}, Loc, Loc,
17106 D),
17107 std::move(DS.getAttributes()), SourceLocation());
17108 D.SetIdentifier(&II, Loc);
17109
17110 // Insert this function into the enclosing block scope.
17111 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17112 FD->setImplicit();
17113
17114 AddKnownFunctionAttributes(FD);
17115
17116 return FD;
17117 }
17118
17119 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17120 FunctionDecl *FD) {
17121 if (FD->isInvalidDecl())
17122 return;
17123
17124 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17125 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17126 return;
17127
17128 UnsignedOrNone AlignmentParam = std::nullopt;
17129 bool IsNothrow = false;
17130 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17131 return;
17132
17133 // C++2a [basic.stc.dynamic.allocation]p4:
17134 // An allocation function that has a non-throwing exception specification
17135 // indicates failure by returning a null pointer value. Any other allocation
17136 // function never returns a null pointer value and indicates failure only by
17137 // throwing an exception [...]
17138 //
17139 // However, -fcheck-new invalidates this possible assumption, so don't add
17140 // NonNull when that is enabled.
17141 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17142 !getLangOpts().CheckNew)
17143 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17144
17145 // C++2a [basic.stc.dynamic.allocation]p2:
17146 // An allocation function attempts to allocate the requested amount of
17147 // storage. [...] If the request succeeds, the value returned by a
17148 // replaceable allocation function is a [...] pointer value p0 different
17149 // from any previously returned value p1 [...]
17150 //
17151 // However, this particular information is being added in codegen,
17152 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17153
17154 // C++2a [basic.stc.dynamic.allocation]p2:
17155 // An allocation function attempts to allocate the requested amount of
17156 // storage. If it is successful, it returns the address of the start of a
17157 // block of storage whose length in bytes is at least as large as the
17158 // requested size.
17159 if (!FD->hasAttr<AllocSizeAttr>()) {
17160 FD->addAttr(AllocSizeAttr::CreateImplicit(
17161 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17162 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17163 }
17164
17165 // C++2a [basic.stc.dynamic.allocation]p3:
17166 // For an allocation function [...], the pointer returned on a successful
17167 // call shall represent the address of storage that is aligned as follows:
17168 // (3.1) If the allocation function takes an argument of type
17169 // std​::​align_­val_­t, the storage will have the alignment
17170 // specified by the value of this argument.
17171 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17172 FD->addAttr(AllocAlignAttr::CreateImplicit(
17173 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17174 }
17175
17176 // FIXME:
17177 // C++2a [basic.stc.dynamic.allocation]p3:
17178 // For an allocation function [...], the pointer returned on a successful
17179 // call shall represent the address of storage that is aligned as follows:
17180 // (3.2) Otherwise, if the allocation function is named operator new[],
17181 // the storage is aligned for any object that does not have
17182 // new-extended alignment ([basic.align]) and is no larger than the
17183 // requested size.
17184 // (3.3) Otherwise, the storage is aligned for any object that does not
17185 // have new-extended alignment and is of the requested size.
17186 }
17187
17188 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17189 if (FD->isInvalidDecl())
17190 return;
17191
17192 // If this is a built-in function, map its builtin attributes to
17193 // actual attributes.
17194 if (unsigned BuiltinID = FD->getBuiltinID()) {
17195 // Handle printf-formatting attributes.
17196 unsigned FormatIdx;
17197 bool HasVAListArg;
17198 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17199 if (!FD->hasAttr<FormatAttr>()) {
17200 const char *fmt = "printf";
17201 unsigned int NumParams = FD->getNumParams();
17202 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17203 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17204 fmt = "NSString";
17205 FD->addAttr(FormatAttr::CreateImplicit(Context,
17206 &Context.Idents.get(fmt),
17207 FormatIdx+1,
17208 HasVAListArg ? 0 : FormatIdx+2,
17209 FD->getLocation()));
17210 }
17211 }
17212 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17213 HasVAListArg)) {
17214 if (!FD->hasAttr<FormatAttr>())
17215 FD->addAttr(FormatAttr::CreateImplicit(Context,
17216 &Context.Idents.get("scanf"),
17217 FormatIdx+1,
17218 HasVAListArg ? 0 : FormatIdx+2,
17219 FD->getLocation()));
17220 }
17221
17222 // Handle automatically recognized callbacks.
17223 SmallVector<int, 4> Encoding;
17224 if (!FD->hasAttr<CallbackAttr>() &&
17225 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17226 FD->addAttr(CallbackAttr::CreateImplicit(
17227 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17228
17229 // Mark const if we don't care about errno and/or floating point exceptions
17230 // that are the only thing preventing the function from being const. This
17231 // allows IRgen to use LLVM intrinsics for such functions.
17232 bool NoExceptions =
17233 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17234 bool ConstWithoutErrnoAndExceptions =
17235 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17236 bool ConstWithoutExceptions =
17237 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17238 if (!FD->hasAttr<ConstAttr>() &&
17239 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17240 (!ConstWithoutErrnoAndExceptions ||
17241 (!getLangOpts().MathErrno && NoExceptions)) &&
17242 (!ConstWithoutExceptions || NoExceptions))
17243 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17244
17245 // We make "fma" on GNU or Windows const because we know it does not set
17246 // errno in those environments even though it could set errno based on the
17247 // C standard.
17248 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17249 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17250 !FD->hasAttr<ConstAttr>()) {
17251 switch (BuiltinID) {
17252 case Builtin::BI__builtin_fma:
17253 case Builtin::BI__builtin_fmaf:
17254 case Builtin::BI__builtin_fmal:
17255 case Builtin::BIfma:
17256 case Builtin::BIfmaf:
17257 case Builtin::BIfmal:
17258 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17259 break;
17260 default:
17261 break;
17262 }
17263 }
17264
17265 SmallVector<int, 4> Indxs;
17266 Builtin::Info::NonNullMode OptMode;
17267 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17268 !FD->hasAttr<NonNullAttr>()) {
17269 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17270 for (int I : Indxs) {
17271 ParmVarDecl *PVD = FD->getParamDecl(I);
17272 QualType T = PVD->getType();
17273 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17274 PVD->setType(T);
17275 }
17276 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17277 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17278 for (int I : Indxs)
17279 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17280 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17281 ParamIndxs.size()));
17282 }
17283 }
17284 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17285 !FD->hasAttr<ReturnsTwiceAttr>())
17286 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17287 FD->getLocation()));
17288 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17289 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17290 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17291 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17292 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17293 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17294 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17295 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17296 // Add the appropriate attribute, depending on the CUDA compilation mode
17297 // and which target the builtin belongs to. For example, during host
17298 // compilation, aux builtins are __device__, while the rest are __host__.
17299 if (getLangOpts().CUDAIsDevice !=
17300 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17301 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17302 else
17303 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17304 }
17305
17306 // Add known guaranteed alignment for allocation functions.
17307 switch (BuiltinID) {
17308 case Builtin::BImemalign:
17309 case Builtin::BIaligned_alloc:
17310 if (!FD->hasAttr<AllocAlignAttr>())
17311 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17312 FD->getLocation()));
17313 break;
17314 default:
17315 break;
17316 }
17317
17318 // Add allocsize attribute for allocation functions.
17319 switch (BuiltinID) {
17320 case Builtin::BIcalloc:
17321 FD->addAttr(AllocSizeAttr::CreateImplicit(
17322 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17323 break;
17324 case Builtin::BImemalign:
17325 case Builtin::BIaligned_alloc:
17326 case Builtin::BIrealloc:
17327 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17328 ParamIdx(), FD->getLocation()));
17329 break;
17330 case Builtin::BImalloc:
17331 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17332 ParamIdx(), FD->getLocation()));
17333 break;
17334 default:
17335 break;
17336 }
17337 }
17338
17339 LazyProcessLifetimeCaptureByParams(FD);
17340 inferLifetimeBoundAttribute(FD);
17341 inferLifetimeCaptureByAttribute(FD);
17342 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17343
17344 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17345 // throw, add an implicit nothrow attribute to any extern "C" function we come
17346 // across.
17347 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17348 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17349 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17350 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17351 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17352 }
17353
17354 IdentifierInfo *Name = FD->getIdentifier();
17355 if (!Name)
17356 return;
17357 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17358 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
17359 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17360 LinkageSpecLanguageIDs::C)) {
17361 // Okay: this could be a libc/libm/Objective-C function we know
17362 // about.
17363 } else
17364 return;
17365
17366 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17367 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17368 // target-specific builtins, perhaps?
17369 if (!FD->hasAttr<FormatAttr>())
17370 FD->addAttr(FormatAttr::CreateImplicit(Context,
17371 &Context.Idents.get("printf"), 2,
17372 Name->isStr("vasprintf") ? 0 : 3,
17373 FD->getLocation()));
17374 }
17375
17376 if (Name->isStr("__CFStringMakeConstantString")) {
17377 // We already have a __builtin___CFStringMakeConstantString,
17378 // but builds that use -fno-constant-cfstrings don't go through that.
17379 if (!FD->hasAttr<FormatArgAttr>())
17380 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17381 FD->getLocation()));
17382 }
17383 }
17384
17385 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17386 TypeSourceInfo *TInfo) {
17387 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17388 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17389
17390 if (!TInfo) {
17391 assert(D.isInvalidType() && "no declarator info for valid type");
17392 TInfo = Context.getTrivialTypeSourceInfo(T);
17393 }
17394
17395 // Scope manipulation handled by caller.
17396 TypedefDecl *NewTD =
17397 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
17398 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17399
17400 // Bail out immediately if we have an invalid declaration.
17401 if (D.isInvalidType()) {
17402 NewTD->setInvalidDecl();
17403 return NewTD;
17404 }
17405
17406 if (D.getDeclSpec().isModulePrivateSpecified()) {
17407 if (CurContext->isFunctionOrMethod())
17408 Diag(NewTD->getLocation(), diag::err_module_private_local)
17409 << 2 << NewTD
17410 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17411 << FixItHint::CreateRemoval(
17412 D.getDeclSpec().getModulePrivateSpecLoc());
17413 else
17414 NewTD->setModulePrivate();
17415 }
17416
17417 // C++ [dcl.typedef]p8:
17418 // If the typedef declaration defines an unnamed class (or
17419 // enum), the first typedef-name declared by the declaration
17420 // to be that class type (or enum type) is used to denote the
17421 // class type (or enum type) for linkage purposes only.
17422 // We need to check whether the type was declared in the declaration.
17423 switch (D.getDeclSpec().getTypeSpecType()) {
17424 case TST_enum:
17425 case TST_struct:
17426 case TST_interface:
17427 case TST_union:
17428 case TST_class: {
17429 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17430 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17431 break;
17432 }
17433
17434 default:
17435 break;
17436 }
17437
17438 return NewTD;
17439 }
17440
17441 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17442 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17443 QualType T = TI->getType();
17444
17445 if (T->isDependentType())
17446 return false;
17447
17448 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17449 // integral type; any cv-qualification is ignored.
17450 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17451 // non-atomic version of the type specified by the type specifiers in the
17452 // specifier qualifier list.
17453 // Because of how odd C's rule is, we'll let the user know that operations
17454 // involving the enumeration type will be non-atomic.
17455 if (T->isAtomicType())
17456 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17457
17458 Qualifiers Q = T.getQualifiers();
17459 std::optional<unsigned> QualSelect;
17460 if (Q.hasConst() && Q.hasVolatile())
17461 QualSelect = diag::CVQualList::Both;
17462 else if (Q.hasConst())
17463 QualSelect = diag::CVQualList::Const;
17464 else if (Q.hasVolatile())
17465 QualSelect = diag::CVQualList::Volatile;
17466
17467 if (QualSelect)
17468 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17469
17470 T = T.getAtomicUnqualifiedType();
17471
17472 // This doesn't use 'isIntegralType' despite the error message mentioning
17473 // integral type because isIntegralType would also allow enum types in C.
17474 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17475 if (BT->isInteger())
17476 return false;
17477
17478 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17479 << T << T->isBitIntType();
17480 }
17481
17482 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17483 QualType EnumUnderlyingTy, bool IsFixed,
17484 const EnumDecl *Prev) {
17485 if (IsScoped != Prev->isScoped()) {
17486 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17487 << Prev->isScoped();
17488 Diag(Prev->getLocation(), diag::note_previous_declaration);
17489 return true;
17490 }
17491
17492 if (IsFixed && Prev->isFixed()) {
17493 if (!EnumUnderlyingTy->isDependentType() &&
17494 !Prev->getIntegerType()->isDependentType() &&
17495 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17496 Prev->getIntegerType())) {
17497 // TODO: Highlight the underlying type of the redeclaration.
17498 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17499 << EnumUnderlyingTy << Prev->getIntegerType();
17500 Diag(Prev->getLocation(), diag::note_previous_declaration)
17501 << Prev->getIntegerTypeRange();
17502 return true;
17503 }
17504 } else if (IsFixed != Prev->isFixed()) {
17505 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17506 << Prev->isFixed();
17507 Diag(Prev->getLocation(), diag::note_previous_declaration);
17508 return true;
17509 }
17510
17511 return false;
17512 }
17513
17514 /// Get diagnostic %select index for tag kind for
17515 /// redeclaration diagnostic message.
17516 /// WARNING: Indexes apply to particular diagnostics only!
17517 ///
17518 /// \returns diagnostic %select index.
17519 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17520 switch (Tag) {
17521 case TagTypeKind::Struct:
17522 return 0;
17523 case TagTypeKind::Interface:
17524 return 1;
17525 case TagTypeKind::Class:
17526 return 2;
17527 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17528 }
17529 }
17530
17531 /// Determine if tag kind is a class-key compatible with
17532 /// class for redeclaration (class, struct, or __interface).
17533 ///
17534 /// \returns true iff the tag kind is compatible.
17535 static bool isClassCompatTagKind(TagTypeKind Tag)
17536 {
17537 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17538 Tag == TagTypeKind::Interface;
17539 }
17540
17541 NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17542 if (isa<TypedefDecl>(PrevDecl))
17543 return NonTagKind::Typedef;
17544 else if (isa<TypeAliasDecl>(PrevDecl))
17545 return NonTagKind::TypeAlias;
17546 else if (isa<ClassTemplateDecl>(PrevDecl))
17547 return NonTagKind::Template;
17548 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17549 return NonTagKind::TypeAliasTemplate;
17550 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17551 return NonTagKind::TemplateTemplateArgument;
17552 switch (TTK) {
17553 case TagTypeKind::Struct:
17554 case TagTypeKind::Interface:
17555 case TagTypeKind::Class:
17556 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17557 : NonTagKind::NonStruct;
17558 case TagTypeKind::Union:
17559 return NonTagKind::NonUnion;
17560 case TagTypeKind::Enum:
17561 return NonTagKind::NonEnum;
17562 }
17563 llvm_unreachable("invalid TTK");
17564 }
17565
17566 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17567 TagTypeKind NewTag, bool isDefinition,
17568 SourceLocation NewTagLoc,
17569 const IdentifierInfo *Name) {
17570 // C++ [dcl.type.elab]p3:
17571 // The class-key or enum keyword present in the
17572 // elaborated-type-specifier shall agree in kind with the
17573 // declaration to which the name in the elaborated-type-specifier
17574 // refers. This rule also applies to the form of
17575 // elaborated-type-specifier that declares a class-name or
17576 // friend class since it can be construed as referring to the
17577 // definition of the class. Thus, in any
17578 // elaborated-type-specifier, the enum keyword shall be used to
17579 // refer to an enumeration (7.2), the union class-key shall be
17580 // used to refer to a union (clause 9), and either the class or
17581 // struct class-key shall be used to refer to a class (clause 9)
17582 // declared using the class or struct class-key.
17583 TagTypeKind OldTag = Previous->getTagKind();
17584 if (OldTag != NewTag &&
17585 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
17586 return false;
17587
17588 // Tags are compatible, but we might still want to warn on mismatched tags.
17589 // Non-class tags can't be mismatched at this point.
17590 if (!isClassCompatTagKind(NewTag))
17591 return true;
17592
17593 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17594 // by our warning analysis. We don't want to warn about mismatches with (eg)
17595 // declarations in system headers that are designed to be specialized, but if
17596 // a user asks us to warn, we should warn if their code contains mismatched
17597 // declarations.
17598 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17599 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17600 Loc);
17601 };
17602 if (IsIgnoredLoc(NewTagLoc))
17603 return true;
17604
17605 auto IsIgnored = [&](const TagDecl *Tag) {
17606 return IsIgnoredLoc(Tag->getLocation());
17607 };
17608 while (IsIgnored(Previous)) {
17609 Previous = Previous->getPreviousDecl();
17610 if (!Previous)
17611 return true;
17612 OldTag = Previous->getTagKind();
17613 }
17614
17615 bool isTemplate = false;
17616 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17617 isTemplate = Record->getDescribedClassTemplate();
17618
17619 if (inTemplateInstantiation()) {
17620 if (OldTag != NewTag) {
17621 // In a template instantiation, do not offer fix-its for tag mismatches
17622 // since they usually mess up the template instead of fixing the problem.
17623 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17624 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17625 << getRedeclDiagFromTagKind(OldTag);
17626 // FIXME: Note previous location?
17627 }
17628 return true;
17629 }
17630
17631 if (isDefinition) {
17632 // On definitions, check all previous tags and issue a fix-it for each
17633 // one that doesn't match the current tag.
17634 if (Previous->getDefinition()) {
17635 // Don't suggest fix-its for redefinitions.
17636 return true;
17637 }
17638
17639 bool previousMismatch = false;
17640 for (const TagDecl *I : Previous->redecls()) {
17641 if (I->getTagKind() != NewTag) {
17642 // Ignore previous declarations for which the warning was disabled.
17643 if (IsIgnored(I))
17644 continue;
17645
17646 if (!previousMismatch) {
17647 previousMismatch = true;
17648 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17649 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17650 << getRedeclDiagFromTagKind(I->getTagKind());
17651 }
17652 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17653 << getRedeclDiagFromTagKind(NewTag)
17654 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17655 TypeWithKeyword::getTagTypeKindName(NewTag));
17656 }
17657 }
17658 return true;
17659 }
17660
17661 // Identify the prevailing tag kind: this is the kind of the definition (if
17662 // there is a non-ignored definition), or otherwise the kind of the prior
17663 // (non-ignored) declaration.
17664 const TagDecl *PrevDef = Previous->getDefinition();
17665 if (PrevDef && IsIgnored(PrevDef))
17666 PrevDef = nullptr;
17667 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17668 if (Redecl->getTagKind() != NewTag) {
17669 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17670 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17671 << getRedeclDiagFromTagKind(OldTag);
17672 Diag(Redecl->getLocation(), diag::note_previous_use);
17673
17674 // If there is a previous definition, suggest a fix-it.
17675 if (PrevDef) {
17676 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17677 << getRedeclDiagFromTagKind(Redecl->getTagKind())
17678 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
17679 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
17680 }
17681 }
17682
17683 return true;
17684 }
17685
17686 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17687 /// from an outer enclosing namespace or file scope inside a friend declaration.
17688 /// This should provide the commented out code in the following snippet:
17689 /// namespace N {
17690 /// struct X;
17691 /// namespace M {
17692 /// struct Y { friend struct /*N::*/ X; };
17693 /// }
17694 /// }
17695 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17696 SourceLocation NameLoc) {
17697 // While the decl is in a namespace, do repeated lookup of that name and see
17698 // if we get the same namespace back. If we do not, continue until
17699 // translation unit scope, at which point we have a fully qualified NNS.
17700 SmallVector<IdentifierInfo *, 4> Namespaces;
17701 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17702 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17703 // This tag should be declared in a namespace, which can only be enclosed by
17704 // other namespaces. Bail if there's an anonymous namespace in the chain.
17705 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17706 if (!Namespace || Namespace->isAnonymousNamespace())
17707 return FixItHint();
17708 IdentifierInfo *II = Namespace->getIdentifier();
17709 Namespaces.push_back(II);
17710 NamedDecl *Lookup = SemaRef.LookupSingleName(
17711 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17712 if (Lookup == Namespace)
17713 break;
17714 }
17715
17716 // Once we have all the namespaces, reverse them to go outermost first, and
17717 // build an NNS.
17718 SmallString<64> Insertion;
17719 llvm::raw_svector_ostream OS(Insertion);
17720 if (DC->isTranslationUnit())
17721 OS << "::";
17722 std::reverse(Namespaces.begin(), Namespaces.end());
17723 for (auto *II : Namespaces)
17724 OS << II->getName() << "::";
17725 return FixItHint::CreateInsertion(NameLoc, Insertion);
17726 }
17727
17728 /// Determine whether a tag originally declared in context \p OldDC can
17729 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17730 /// found a declaration in \p OldDC as a previous decl, perhaps through a
17731 /// using-declaration).
17732 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17733 DeclContext *NewDC) {
17734 OldDC = OldDC->getRedeclContext();
17735 NewDC = NewDC->getRedeclContext();
17736
17737 if (OldDC->Equals(NewDC))
17738 return true;
17739
17740 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17741 // encloses the other).
17742 if (S.getLangOpts().MSVCCompat &&
17743 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17744 return true;
17745
17746 return false;
17747 }
17748
17749 DeclResult
17750 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17751 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17752 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17753 SourceLocation ModulePrivateLoc,
17754 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17755 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17756 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17757 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17758 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17759 // If this is not a definition, it must have a name.
17760 IdentifierInfo *OrigName = Name;
17761 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17762 "Nameless record must be a definition!");
17763 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17764
17765 OwnedDecl = false;
17766 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17767 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17768
17769 // FIXME: Check member specializations more carefully.
17770 bool isMemberSpecialization = false;
17771 bool IsInjectedClassName = false;
17772 bool Invalid = false;
17773
17774 // We only need to do this matching if we have template parameters
17775 // or a scope specifier, which also conveniently avoids this work
17776 // for non-C++ cases.
17777 if (TemplateParameterLists.size() > 0 ||
17778 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17779 TemplateParameterList *TemplateParams =
17780 MatchTemplateParametersToScopeSpecifier(
17781 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17782 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17783
17784 // C++23 [dcl.type.elab] p2:
17785 // If an elaborated-type-specifier is the sole constituent of a
17786 // declaration, the declaration is ill-formed unless it is an explicit
17787 // specialization, an explicit instantiation or it has one of the
17788 // following forms: [...]
17789 // C++23 [dcl.enum] p1:
17790 // If the enum-head-name of an opaque-enum-declaration contains a
17791 // nested-name-specifier, the declaration shall be an explicit
17792 // specialization.
17793 //
17794 // FIXME: Class template partial specializations can be forward declared
17795 // per CWG2213, but the resolution failed to allow qualified forward
17796 // declarations. This is almost certainly unintentional, so we allow them.
17797 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17798 !isMemberSpecialization)
17799 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17800 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17801
17802 if (TemplateParams) {
17803 if (Kind == TagTypeKind::Enum) {
17804 Diag(KWLoc, diag::err_enum_template);
17805 return true;
17806 }
17807
17808 if (TemplateParams->size() > 0) {
17809 // This is a declaration or definition of a class template (which may
17810 // be a member of another template).
17811
17812 if (Invalid)
17813 return true;
17814
17815 OwnedDecl = false;
17816 DeclResult Result = CheckClassTemplate(
17817 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17818 AS, ModulePrivateLoc,
17819 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17820 TemplateParameterLists.data(), SkipBody);
17821 return Result.get();
17822 } else {
17823 // The "template<>" header is extraneous.
17824 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17825 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17826 isMemberSpecialization = true;
17827 }
17828 }
17829
17830 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17831 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17832 return true;
17833 }
17834
17835 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17836 // C++23 [dcl.type.elab]p4:
17837 // If an elaborated-type-specifier appears with the friend specifier as
17838 // an entire member-declaration, the member-declaration shall have one
17839 // of the following forms:
17840 // friend class-key nested-name-specifier(opt) identifier ;
17841 // friend class-key simple-template-id ;
17842 // friend class-key nested-name-specifier template(opt)
17843 // simple-template-id ;
17844 //
17845 // Since enum is not a class-key, so declarations like "friend enum E;"
17846 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17847 // invalid, most implementations accept so we issue a pedantic warning.
17848 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17849 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17850 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17851 Diag(KWLoc, diag::note_enum_friend)
17852 << (ScopedEnum + ScopedEnumUsesClassTag);
17853 }
17854
17855 // Figure out the underlying type if this a enum declaration. We need to do
17856 // this early, because it's needed to detect if this is an incompatible
17857 // redeclaration.
17858 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17859 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17860
17861 if (Kind == TagTypeKind::Enum) {
17862 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17863 // No underlying type explicitly specified, or we failed to parse the
17864 // type, default to int.
17865 EnumUnderlying = Context.IntTy.getTypePtr();
17866 } else if (UnderlyingType.get()) {
17867 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17868 // integral type; any cv-qualification is ignored.
17869 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17870 // unqualified, non-atomic version of the type specified by the type
17871 // specifiers in the specifier qualifier list.
17872 TypeSourceInfo *TI = nullptr;
17873 GetTypeFromParser(UnderlyingType.get(), &TI);
17874 EnumUnderlying = TI;
17875
17876 if (CheckEnumUnderlyingType(TI))
17877 // Recover by falling back to int.
17878 EnumUnderlying = Context.IntTy.getTypePtr();
17879
17880 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17881 UPPC_FixedUnderlyingType))
17882 EnumUnderlying = Context.IntTy.getTypePtr();
17883
17884 // If the underlying type is atomic, we need to adjust the type before
17885 // continuing. This only happens in the case we stored a TypeSourceInfo
17886 // into EnumUnderlying because the other cases are error recovery up to
17887 // this point. But because it's not possible to gin up a TypeSourceInfo
17888 // for a non-atomic type from an atomic one, we'll store into the Type
17889 // field instead. FIXME: it would be nice to have an easy way to get a
17890 // derived TypeSourceInfo which strips qualifiers including the weird
17891 // ones like _Atomic where it forms a different type.
17892 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17893 TI && TI->getType()->isAtomicType())
17894 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17895
17896 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17897 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17898 // of 'int'. However, if this is an unfixed forward declaration, don't set
17899 // the underlying type unless the user enables -fms-compatibility. This
17900 // makes unfixed forward declared enums incomplete and is more conforming.
17901 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17902 EnumUnderlying = Context.IntTy.getTypePtr();
17903 }
17904 }
17905
17906 DeclContext *SearchDC = CurContext;
17907 DeclContext *DC = CurContext;
17908 bool isStdBadAlloc = false;
17909 bool isStdAlignValT = false;
17910
17911 RedeclarationKind Redecl = forRedeclarationInCurContext();
17912 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17913 Redecl = RedeclarationKind::NotForRedeclaration;
17914
17915 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17916 /// implemented asks for structural equivalence checking, the returned decl
17917 /// here is passed back to the parser, allowing the tag body to be parsed.
17918 auto createTagFromNewDecl = [&]() -> TagDecl * {
17919 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17920 // If there is an identifier, use the location of the identifier as the
17921 // location of the decl, otherwise use the location of the struct/union
17922 // keyword.
17923 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17924 TagDecl *New = nullptr;
17925
17926 if (Kind == TagTypeKind::Enum) {
17927 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17928 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17929 // If this is an undefined enum, bail.
17930 if (TUK != TagUseKind::Definition && !Invalid)
17931 return nullptr;
17932 if (EnumUnderlying) {
17933 EnumDecl *ED = cast<EnumDecl>(New);
17934 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17935 ED->setIntegerTypeSourceInfo(TI);
17936 else
17937 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17938 QualType EnumTy = ED->getIntegerType();
17939 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17940 ? Context.getPromotedIntegerType(EnumTy)
17941 : EnumTy);
17942 }
17943 } else { // struct/union
17944 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17945 nullptr);
17946 }
17947
17948 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17949 // Add alignment attributes if necessary; these attributes are checked
17950 // when the ASTContext lays out the structure.
17951 //
17952 // It is important for implementing the correct semantics that this
17953 // happen here (in ActOnTag). The #pragma pack stack is
17954 // maintained as a result of parser callbacks which can occur at
17955 // many points during the parsing of a struct declaration (because
17956 // the #pragma tokens are effectively skipped over during the
17957 // parsing of the struct).
17958 if (TUK == TagUseKind::Definition &&
17959 (!SkipBody || !SkipBody->ShouldSkip)) {
17960 if (LangOpts.HLSL)
17961 RD->addAttr(PackedAttr::CreateImplicit(Context));
17962 AddAlignmentAttributesForRecord(RD);
17963 AddMsStructLayoutForRecord(RD);
17964 }
17965 }
17966 New->setLexicalDeclContext(CurContext);
17967 return New;
17968 };
17969
17970 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17971 if (Name && SS.isNotEmpty()) {
17972 // We have a nested-name tag ('struct foo::bar').
17973
17974 // Check for invalid 'foo::'.
17975 if (SS.isInvalid()) {
17976 Name = nullptr;
17977 goto CreateNewDecl;
17978 }
17979
17980 // If this is a friend or a reference to a class in a dependent
17981 // context, don't try to make a decl for it.
17982 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17983 DC = computeDeclContext(SS, false);
17984 if (!DC) {
17985 IsDependent = true;
17986 return true;
17987 }
17988 } else {
17989 DC = computeDeclContext(SS, true);
17990 if (!DC) {
17991 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17992 << SS.getRange();
17993 return true;
17994 }
17995 }
17996
17997 if (RequireCompleteDeclContext(SS, DC))
17998 return true;
17999
18000 SearchDC = DC;
18001 // Look-up name inside 'foo::'.
18002 LookupQualifiedName(Previous, DC);
18003
18004 if (Previous.isAmbiguous())
18005 return true;
18006
18007 if (Previous.empty()) {
18008 // Name lookup did not find anything. However, if the
18009 // nested-name-specifier refers to the current instantiation,
18010 // and that current instantiation has any dependent base
18011 // classes, we might find something at instantiation time: treat
18012 // this as a dependent elaborated-type-specifier.
18013 // But this only makes any sense for reference-like lookups.
18014 if (Previous.wasNotFoundInCurrentInstantiation() &&
18015 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18016 IsDependent = true;
18017 return true;
18018 }
18019
18020 // A tag 'foo::bar' must already exist.
18021 Diag(NameLoc, diag::err_not_tag_in_scope)
18022 << Kind << Name << DC << SS.getRange();
18023 Name = nullptr;
18024 Invalid = true;
18025 goto CreateNewDecl;
18026 }
18027 } else if (Name) {
18028 // C++14 [class.mem]p14:
18029 // If T is the name of a class, then each of the following shall have a
18030 // name different from T:
18031 // -- every member of class T that is itself a type
18032 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18033 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18034 return true;
18035
18036 // If this is a named struct, check to see if there was a previous forward
18037 // declaration or definition.
18038 // FIXME: We're looking into outer scopes here, even when we
18039 // shouldn't be. Doing so can result in ambiguities that we
18040 // shouldn't be diagnosing.
18041 LookupName(Previous, S);
18042
18043 // When declaring or defining a tag, ignore ambiguities introduced
18044 // by types using'ed into this scope.
18045 if (Previous.isAmbiguous() &&
18046 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18047 LookupResult::Filter F = Previous.makeFilter();
18048 while (F.hasNext()) {
18049 NamedDecl *ND = F.next();
18050 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18051 SearchDC->getRedeclContext()))
18052 F.erase();
18053 }
18054 F.done();
18055 }
18056
18057 // C++11 [namespace.memdef]p3:
18058 // If the name in a friend declaration is neither qualified nor
18059 // a template-id and the declaration is a function or an
18060 // elaborated-type-specifier, the lookup to determine whether
18061 // the entity has been previously declared shall not consider
18062 // any scopes outside the innermost enclosing namespace.
18063 //
18064 // MSVC doesn't implement the above rule for types, so a friend tag
18065 // declaration may be a redeclaration of a type declared in an enclosing
18066 // scope. They do implement this rule for friend functions.
18067 //
18068 // Does it matter that this should be by scope instead of by
18069 // semantic context?
18070 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18071 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18072 LookupResult::Filter F = Previous.makeFilter();
18073 bool FriendSawTagOutsideEnclosingNamespace = false;
18074 while (F.hasNext()) {
18075 NamedDecl *ND = F.next();
18076 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18077 if (DC->isFileContext() &&
18078 !EnclosingNS->Encloses(ND->getDeclContext())) {
18079 if (getLangOpts().MSVCCompat)
18080 FriendSawTagOutsideEnclosingNamespace = true;
18081 else
18082 F.erase();
18083 }
18084 }
18085 F.done();
18086
18087 // Diagnose this MSVC extension in the easy case where lookup would have
18088 // unambiguously found something outside the enclosing namespace.
18089 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18090 NamedDecl *ND = Previous.getFoundDecl();
18091 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18092 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18093 }
18094 }
18095
18096 // Note: there used to be some attempt at recovery here.
18097 if (Previous.isAmbiguous())
18098 return true;
18099
18100 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18101 // FIXME: This makes sure that we ignore the contexts associated
18102 // with C structs, unions, and enums when looking for a matching
18103 // tag declaration or definition. See the similar lookup tweak
18104 // in Sema::LookupName; is there a better way to deal with this?
18105 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
18106 SearchDC = SearchDC->getParent();
18107 } else if (getLangOpts().CPlusPlus) {
18108 // Inside ObjCContainer want to keep it as a lexical decl context but go
18109 // past it (most often to TranslationUnit) to find the semantic decl
18110 // context.
18111 while (isa<ObjCContainerDecl>(SearchDC))
18112 SearchDC = SearchDC->getParent();
18113 }
18114 } else if (getLangOpts().CPlusPlus) {
18115 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18116 // TagDecl the same way as we skip it for named TagDecl.
18117 while (isa<ObjCContainerDecl>(SearchDC))
18118 SearchDC = SearchDC->getParent();
18119 }
18120
18121 if (Previous.isSingleResult() &&
18122 Previous.getFoundDecl()->isTemplateParameter()) {
18123 // Maybe we will complain about the shadowed template parameter.
18124 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18125 // Just pretend that we didn't see the previous declaration.
18126 Previous.clear();
18127 }
18128
18129 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18130 DC->Equals(getStdNamespace())) {
18131 if (Name->isStr("bad_alloc")) {
18132 // This is a declaration of or a reference to "std::bad_alloc".
18133 isStdBadAlloc = true;
18134
18135 // If std::bad_alloc has been implicitly declared (but made invisible to
18136 // name lookup), fill in this implicit declaration as the previous
18137 // declaration, so that the declarations get chained appropriately.
18138 if (Previous.empty() && StdBadAlloc)
18139 Previous.addDecl(getStdBadAlloc());
18140 } else if (Name->isStr("align_val_t")) {
18141 isStdAlignValT = true;
18142 if (Previous.empty() && StdAlignValT)
18143 Previous.addDecl(getStdAlignValT());
18144 }
18145 }
18146
18147 // If we didn't find a previous declaration, and this is a reference
18148 // (or friend reference), move to the correct scope. In C++, we
18149 // also need to do a redeclaration lookup there, just in case
18150 // there's a shadow friend decl.
18151 if (Name && Previous.empty() &&
18152 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18153 IsTemplateParamOrArg)) {
18154 if (Invalid) goto CreateNewDecl;
18155 assert(SS.isEmpty());
18156
18157 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18158 // C++ [basic.scope.pdecl]p5:
18159 // -- for an elaborated-type-specifier of the form
18160 //
18161 // class-key identifier
18162 //
18163 // if the elaborated-type-specifier is used in the
18164 // decl-specifier-seq or parameter-declaration-clause of a
18165 // function defined in namespace scope, the identifier is
18166 // declared as a class-name in the namespace that contains
18167 // the declaration; otherwise, except as a friend
18168 // declaration, the identifier is declared in the smallest
18169 // non-class, non-function-prototype scope that contains the
18170 // declaration.
18171 //
18172 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18173 // C structs and unions.
18174 //
18175 // It is an error in C++ to declare (rather than define) an enum
18176 // type, including via an elaborated type specifier. We'll
18177 // diagnose that later; for now, declare the enum in the same
18178 // scope as we would have picked for any other tag type.
18179 //
18180 // GNU C also supports this behavior as part of its incomplete
18181 // enum types extension, while GNU C++ does not.
18182 //
18183 // Find the context where we'll be declaring the tag.
18184 // FIXME: We would like to maintain the current DeclContext as the
18185 // lexical context,
18186 SearchDC = getTagInjectionContext(SearchDC);
18187
18188 // Find the scope where we'll be declaring the tag.
18189 S = getTagInjectionScope(S, getLangOpts());
18190 } else {
18191 assert(TUK == TagUseKind::Friend);
18192 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18193
18194 // C++ [namespace.memdef]p3:
18195 // If a friend declaration in a non-local class first declares a
18196 // class or function, the friend class or function is a member of
18197 // the innermost enclosing namespace.
18198 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18199 : SearchDC->getEnclosingNamespaceContext();
18200 }
18201
18202 // In C++, we need to do a redeclaration lookup to properly
18203 // diagnose some problems.
18204 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18205 // hidden declaration so that we don't get ambiguity errors when using a
18206 // type declared by an elaborated-type-specifier. In C that is not correct
18207 // and we should instead merge compatible types found by lookup.
18208 if (getLangOpts().CPlusPlus) {
18209 // FIXME: This can perform qualified lookups into function contexts,
18210 // which are meaningless.
18211 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18212 LookupQualifiedName(Previous, SearchDC);
18213 } else {
18214 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18215 LookupName(Previous, S);
18216 }
18217 }
18218
18219 // If we have a known previous declaration to use, then use it.
18220 if (Previous.empty() && SkipBody && SkipBody->Previous)
18221 Previous.addDecl(SkipBody->Previous);
18222
18223 if (!Previous.empty()) {
18224 NamedDecl *PrevDecl = Previous.getFoundDecl();
18225 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18226
18227 // It's okay to have a tag decl in the same scope as a typedef
18228 // which hides a tag decl in the same scope. Finding this
18229 // with a redeclaration lookup can only actually happen in C++.
18230 //
18231 // This is also okay for elaborated-type-specifiers, which is
18232 // technically forbidden by the current standard but which is
18233 // okay according to the likely resolution of an open issue;
18234 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18235 if (getLangOpts().CPlusPlus) {
18236 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18237 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18238 if (Tag->getDeclName() == Name &&
18239 Tag->getDeclContext()->getRedeclContext()
18240 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18241 PrevDecl = Tag;
18242 Previous.clear();
18243 Previous.addDecl(Tag);
18244 Previous.resolveKind();
18245 }
18246 }
18247 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18248 TUK == TagUseKind::Reference && RD &&
18249 RD->isInjectedClassName()) {
18250 // If lookup found the injected class name, the previous declaration is
18251 // the class being injected into.
18252 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18253 Previous.clear();
18254 Previous.addDecl(PrevDecl);
18255 Previous.resolveKind();
18256 IsInjectedClassName = true;
18257 }
18258 }
18259
18260 // If this is a redeclaration of a using shadow declaration, it must
18261 // declare a tag in the same context. In MSVC mode, we allow a
18262 // redefinition if either context is within the other.
18263 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18264 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18265 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18266 TUK != TagUseKind::Friend &&
18267 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18268 !(OldTag && isAcceptableTagRedeclContext(
18269 *this, OldTag->getDeclContext(), SearchDC))) {
18270 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18271 Diag(Shadow->getTargetDecl()->getLocation(),
18272 diag::note_using_decl_target);
18273 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18274 << 0;
18275 // Recover by ignoring the old declaration.
18276 Previous.clear();
18277 goto CreateNewDecl;
18278 }
18279 }
18280
18281 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18282 // If this is a use of a previous tag, or if the tag is already declared
18283 // in the same scope (so that the definition/declaration completes or
18284 // rementions the tag), reuse the decl.
18285 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18286 isDeclInScope(DirectPrevDecl, SearchDC, S,
18287 SS.isNotEmpty() || isMemberSpecialization)) {
18288 // Make sure that this wasn't declared as an enum and now used as a
18289 // struct or something similar.
18290 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18291 TUK == TagUseKind::Definition, KWLoc,
18292 Name)) {
18293 bool SafeToContinue =
18294 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18295 Kind != TagTypeKind::Enum);
18296 if (SafeToContinue)
18297 Diag(KWLoc, diag::err_use_with_wrong_tag)
18298 << Name
18299 << FixItHint::CreateReplacement(SourceRange(KWLoc),
18300 PrevTagDecl->getKindName());
18301 else
18302 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18303 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18304
18305 if (SafeToContinue)
18306 Kind = PrevTagDecl->getTagKind();
18307 else {
18308 // Recover by making this an anonymous redefinition.
18309 Name = nullptr;
18310 Previous.clear();
18311 Invalid = true;
18312 }
18313 }
18314
18315 if (Kind == TagTypeKind::Enum &&
18316 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18317 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18318 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18319 return PrevTagDecl;
18320
18321 QualType EnumUnderlyingTy;
18322 if (TypeSourceInfo *TI =
18323 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18324 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18325 else if (const Type *T =
18326 dyn_cast_if_present<const Type *>(EnumUnderlying))
18327 EnumUnderlyingTy = QualType(T, 0);
18328
18329 // All conflicts with previous declarations are recovered by
18330 // returning the previous declaration, unless this is a definition,
18331 // in which case we want the caller to bail out.
18332 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18333 ScopedEnum, EnumUnderlyingTy,
18334 IsFixed, PrevEnum))
18335 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18336 }
18337
18338 // C++11 [class.mem]p1:
18339 // A member shall not be declared twice in the member-specification,
18340 // except that a nested class or member class template can be declared
18341 // and then later defined.
18342 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18343 S->isDeclScope(PrevDecl)) {
18344 Diag(NameLoc, diag::ext_member_redeclared);
18345 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18346 }
18347
18348 if (!Invalid) {
18349 // If this is a use, just return the declaration we found, unless
18350 // we have attributes.
18351 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18352 if (!Attrs.empty()) {
18353 // FIXME: Diagnose these attributes. For now, we create a new
18354 // declaration to hold them.
18355 } else if (TUK == TagUseKind::Reference &&
18356 (PrevTagDecl->getFriendObjectKind() ==
18357 Decl::FOK_Undeclared ||
18358 PrevDecl->getOwningModule() != getCurrentModule()) &&
18359 SS.isEmpty()) {
18360 // This declaration is a reference to an existing entity, but
18361 // has different visibility from that entity: it either makes
18362 // a friend visible or it makes a type visible in a new module.
18363 // In either case, create a new declaration. We only do this if
18364 // the declaration would have meant the same thing if no prior
18365 // declaration were found, that is, if it was found in the same
18366 // scope where we would have injected a declaration.
18367 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18368 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18369 return PrevTagDecl;
18370 // This is in the injected scope, create a new declaration in
18371 // that scope.
18372 S = getTagInjectionScope(S, getLangOpts());
18373 } else {
18374 return PrevTagDecl;
18375 }
18376 }
18377
18378 // Diagnose attempts to redefine a tag.
18379 if (TUK == TagUseKind::Definition) {
18380 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18381 // If the type is currently being defined, complain
18382 // about a nested redefinition.
18383 if (Def->isBeingDefined()) {
18384 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18385 Diag(PrevTagDecl->getLocation(),
18386 diag::note_previous_definition);
18387 Name = nullptr;
18388 Previous.clear();
18389 Invalid = true;
18390 } else {
18391 // If we're defining a specialization and the previous
18392 // definition is from an implicit instantiation, don't emit an
18393 // error here; we'll catch this in the general case below.
18394 bool IsExplicitSpecializationAfterInstantiation = false;
18395 if (isMemberSpecialization) {
18396 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18397 IsExplicitSpecializationAfterInstantiation =
18398 RD->getTemplateSpecializationKind() !=
18399 TSK_ExplicitSpecialization;
18400 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18401 IsExplicitSpecializationAfterInstantiation =
18402 ED->getTemplateSpecializationKind() !=
18403 TSK_ExplicitSpecialization;
18404 }
18405
18406 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18407 // do not keep more that one definition around (merge them).
18408 // However, ensure the decl passes the structural compatibility
18409 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18410 NamedDecl *Hidden = nullptr;
18411 bool HiddenDefVisible = false;
18412 if (SkipBody &&
18413 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18414 getLangOpts().C23)) {
18415 // There is a definition of this tag, but it is not visible.
18416 // We explicitly make use of C++'s one definition rule here,
18417 // and assume that this definition is identical to the hidden
18418 // one we already have. Make the existing definition visible
18419 // and use it in place of this one.
18420 if (!getLangOpts().CPlusPlus) {
18421 // Postpone making the old definition visible until after we
18422 // complete parsing the new one and do the structural
18423 // comparison.
18424 SkipBody->CheckSameAsPrevious = true;
18425 SkipBody->New = createTagFromNewDecl();
18426 SkipBody->Previous = Def;
18427
18428 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18429 return Def;
18430 }
18431
18432 SkipBody->ShouldSkip = true;
18433 SkipBody->Previous = Def;
18434 if (!HiddenDefVisible && Hidden)
18435 makeMergedDefinitionVisible(Hidden);
18436 // Carry on and handle it like a normal definition. We'll
18437 // skip starting the definition later.
18438
18439 } else if (!IsExplicitSpecializationAfterInstantiation) {
18440 // A redeclaration in function prototype scope in C isn't
18441 // visible elsewhere, so merely issue a warning.
18442 if (!getLangOpts().CPlusPlus &&
18443 S->containedInPrototypeScope())
18444 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18445 << Name;
18446 else
18447 Diag(NameLoc, diag::err_redefinition) << Name;
18448 notePreviousDefinition(Def,
18449 NameLoc.isValid() ? NameLoc : KWLoc);
18450 // If this is a redefinition, recover by making this
18451 // struct be anonymous, which will make any later
18452 // references get the previous definition.
18453 Name = nullptr;
18454 Previous.clear();
18455 Invalid = true;
18456 }
18457 }
18458 }
18459
18460 // Okay, this is definition of a previously declared or referenced
18461 // tag. We're going to create a new Decl for it.
18462 }
18463
18464 // Okay, we're going to make a redeclaration. If this is some kind
18465 // of reference, make sure we build the redeclaration in the same DC
18466 // as the original, and ignore the current access specifier.
18467 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18468 SearchDC = PrevTagDecl->getDeclContext();
18469 AS = AS_none;
18470 }
18471 }
18472 // If we get here we have (another) forward declaration or we
18473 // have a definition. Just create a new decl.
18474
18475 } else {
18476 // If we get here, this is a definition of a new tag type in a nested
18477 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18478 // new decl/type. We set PrevDecl to NULL so that the entities
18479 // have distinct types.
18480 Previous.clear();
18481 }
18482 // If we get here, we're going to create a new Decl. If PrevDecl
18483 // is non-NULL, it's a definition of the tag declared by
18484 // PrevDecl. If it's NULL, we have a new definition.
18485
18486 // Otherwise, PrevDecl is not a tag, but was found with tag
18487 // lookup. This is only actually possible in C++, where a few
18488 // things like templates still live in the tag namespace.
18489 } else {
18490 // Use a better diagnostic if an elaborated-type-specifier
18491 // found the wrong kind of type on the first
18492 // (non-redeclaration) lookup.
18493 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18494 !Previous.isForRedeclaration()) {
18495 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18496 Diag(NameLoc, diag::err_tag_reference_non_tag)
18497 << PrevDecl << NTK << Kind;
18498 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18499 Invalid = true;
18500
18501 // Otherwise, only diagnose if the declaration is in scope.
18502 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18503 SS.isNotEmpty() || isMemberSpecialization)) {
18504 // do nothing
18505
18506 // Diagnose implicit declarations introduced by elaborated types.
18507 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18508 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18509 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18510 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18511 Invalid = true;
18512
18513 // Otherwise it's a declaration. Call out a particularly common
18514 // case here.
18515 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18516 unsigned Kind = 0;
18517 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18518 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18519 << Name << Kind << TND->getUnderlyingType();
18520 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18521 Invalid = true;
18522
18523 // Otherwise, diagnose.
18524 } else {
18525 // The tag name clashes with something else in the target scope,
18526 // issue an error and recover by making this tag be anonymous.
18527 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18528 notePreviousDefinition(PrevDecl, NameLoc);
18529 Name = nullptr;
18530 Invalid = true;
18531 }
18532
18533 // The existing declaration isn't relevant to us; we're in a
18534 // new scope, so clear out the previous declaration.
18535 Previous.clear();
18536 }
18537 }
18538
18539 CreateNewDecl:
18540
18541 TagDecl *PrevDecl = nullptr;
18542 if (Previous.isSingleResult())
18543 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18544
18545 // If there is an identifier, use the location of the identifier as the
18546 // location of the decl, otherwise use the location of the struct/union
18547 // keyword.
18548 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18549
18550 // Otherwise, create a new declaration. If there is a previous
18551 // declaration of the same entity, the two will be linked via
18552 // PrevDecl.
18553 TagDecl *New;
18554
18555 if (Kind == TagTypeKind::Enum) {
18556 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18557 // enum X { A, B, C } D; D should chain to X.
18558 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18559 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18560 ScopedEnumUsesClassTag, IsFixed);
18561
18562 EnumDecl *ED = cast<EnumDecl>(New);
18563 ED->setEnumKeyRange(SourceRange(
18564 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18565
18566 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18567 StdAlignValT = cast<EnumDecl>(New);
18568
18569 // If this is an undefined enum, warn.
18570 if (TUK != TagUseKind::Definition && !Invalid) {
18571 TagDecl *Def;
18572 if (IsFixed && ED->isFixed()) {
18573 // C++0x: 7.2p2: opaque-enum-declaration.
18574 // Conflicts are diagnosed above. Do nothing.
18575 } else if (PrevDecl &&
18576 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18577 Diag(Loc, diag::ext_forward_ref_enum_def)
18578 << New;
18579 Diag(Def->getLocation(), diag::note_previous_definition);
18580 } else {
18581 unsigned DiagID = diag::ext_forward_ref_enum;
18582 if (getLangOpts().MSVCCompat)
18583 DiagID = diag::ext_ms_forward_ref_enum;
18584 else if (getLangOpts().CPlusPlus)
18585 DiagID = diag::err_forward_ref_enum;
18586 Diag(Loc, DiagID);
18587 }
18588 }
18589
18590 if (EnumUnderlying) {
18591 EnumDecl *ED = cast<EnumDecl>(New);
18592 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18593 ED->setIntegerTypeSourceInfo(TI);
18594 else
18595 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18596 QualType EnumTy = ED->getIntegerType();
18597 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18598 ? Context.getPromotedIntegerType(EnumTy)
18599 : EnumTy);
18600 assert(ED->isComplete() && "enum with type should be complete");
18601 }
18602 } else {
18603 // struct/union/class
18604
18605 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18606 // struct X { int A; } D; D should chain to X.
18607 if (getLangOpts().CPlusPlus) {
18608 // FIXME: Look for a way to use RecordDecl for simple structs.
18609 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18610 cast_or_null<CXXRecordDecl>(PrevDecl));
18611
18612 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18613 StdBadAlloc = cast<CXXRecordDecl>(New);
18614 } else
18615 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18616 cast_or_null<RecordDecl>(PrevDecl));
18617 }
18618
18619 // Only C23 and later allow defining new types in 'offsetof()'.
18620 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18621 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18622 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18623 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18624
18625 // C++11 [dcl.type]p3:
18626 // A type-specifier-seq shall not define a class or enumeration [...].
18627 if (!Invalid && getLangOpts().CPlusPlus &&
18628 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18629 TUK == TagUseKind::Definition) {
18630 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18631 << Context.getCanonicalTagType(New);
18632 Invalid = true;
18633 }
18634
18635 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18636 DC->getDeclKind() == Decl::Enum) {
18637 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18638 << Context.getCanonicalTagType(New);
18639 Invalid = true;
18640 }
18641
18642 // Maybe add qualifier info.
18643 if (SS.isNotEmpty()) {
18644 if (SS.isSet()) {
18645 // If this is either a declaration or a definition, check the
18646 // nested-name-specifier against the current context.
18647 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18648 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18649 /*TemplateId=*/nullptr,
18650 isMemberSpecialization))
18651 Invalid = true;
18652
18653 New->setQualifierInfo(SS.getWithLocInContext(Context));
18654 if (TemplateParameterLists.size() > 0) {
18655 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18656 }
18657 }
18658 else
18659 Invalid = true;
18660 }
18661
18662 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18663 // Add alignment attributes if necessary; these attributes are checked when
18664 // the ASTContext lays out the structure.
18665 //
18666 // It is important for implementing the correct semantics that this
18667 // happen here (in ActOnTag). The #pragma pack stack is
18668 // maintained as a result of parser callbacks which can occur at
18669 // many points during the parsing of a struct declaration (because
18670 // the #pragma tokens are effectively skipped over during the
18671 // parsing of the struct).
18672 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18673 if (LangOpts.HLSL)
18674 RD->addAttr(PackedAttr::CreateImplicit(Context));
18675 AddAlignmentAttributesForRecord(RD);
18676 AddMsStructLayoutForRecord(RD);
18677 }
18678 }
18679
18680 if (ModulePrivateLoc.isValid()) {
18681 if (isMemberSpecialization)
18682 Diag(New->getLocation(), diag::err_module_private_specialization)
18683 << 2
18684 << FixItHint::CreateRemoval(ModulePrivateLoc);
18685 // __module_private__ does not apply to local classes. However, we only
18686 // diagnose this as an error when the declaration specifiers are
18687 // freestanding. Here, we just ignore the __module_private__.
18688 else if (!SearchDC->isFunctionOrMethod())
18689 New->setModulePrivate();
18690 }
18691
18692 // If this is a specialization of a member class (of a class template),
18693 // check the specialization.
18694 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18695 Invalid = true;
18696
18697 // If we're declaring or defining a tag in function prototype scope in C,
18698 // note that this type can only be used within the function and add it to
18699 // the list of decls to inject into the function definition scope. However,
18700 // in C23 and later, while the type is only visible within the function, the
18701 // function can be called with a compatible type defined in the same TU, so
18702 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18703 if ((Name || Kind == TagTypeKind::Enum) &&
18704 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18705 if (getLangOpts().CPlusPlus) {
18706 // C++ [dcl.fct]p6:
18707 // Types shall not be defined in return or parameter types.
18708 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18709 Diag(Loc, diag::err_type_defined_in_param_type)
18710 << Name;
18711 Invalid = true;
18712 }
18713 if (TUK == TagUseKind::Declaration)
18714 Invalid = true;
18715 } else if (!PrevDecl) {
18716 // In C23 mode, if the declaration is complete, we do not want to
18717 // diagnose.
18718 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18719 Diag(Loc, diag::warn_decl_in_param_list)
18720 << Context.getCanonicalTagType(New);
18721 }
18722 }
18723
18724 if (Invalid)
18725 New->setInvalidDecl();
18726
18727 // Set the lexical context. If the tag has a C++ scope specifier, the
18728 // lexical context will be different from the semantic context.
18729 New->setLexicalDeclContext(CurContext);
18730
18731 // Mark this as a friend decl if applicable.
18732 // In Microsoft mode, a friend declaration also acts as a forward
18733 // declaration so we always pass true to setObjectOfFriendDecl to make
18734 // the tag name visible.
18735 if (TUK == TagUseKind::Friend)
18736 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18737
18738 // Set the access specifier.
18739 if (!Invalid && SearchDC->isRecord())
18740 SetMemberAccessSpecifier(New, PrevDecl, AS);
18741
18742 if (PrevDecl)
18743 CheckRedeclarationInModule(New, PrevDecl);
18744
18745 if (TUK == TagUseKind::Definition) {
18746 if (!SkipBody || !SkipBody->ShouldSkip) {
18747 New->startDefinition();
18748 } else {
18749 New->setCompleteDefinition();
18750 New->demoteThisDefinitionToDeclaration();
18751 }
18752 }
18753
18754 ProcessDeclAttributeList(S, New, Attrs);
18755 AddPragmaAttributes(S, New);
18756
18757 // If this has an identifier, add it to the scope stack.
18758 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18759 // We might be replacing an existing declaration in the lookup tables;
18760 // if so, borrow its access specifier.
18761 if (PrevDecl)
18762 New->setAccess(PrevDecl->getAccess());
18763
18764 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18765 DC->makeDeclVisibleInContext(New);
18766 if (Name) // can be null along some error paths
18767 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18768 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18769 } else if (Name) {
18770 S = getNonFieldDeclScope(S);
18771 PushOnScopeChains(New, S, true);
18772 } else {
18773 CurContext->addDecl(New);
18774 }
18775
18776 // If this is the C FILE type, notify the AST context.
18777 if (IdentifierInfo *II = New->getIdentifier())
18778 if (!New->isInvalidDecl() &&
18779 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18780 II->isStr("FILE"))
18781 Context.setFILEDecl(New);
18782
18783 if (PrevDecl)
18784 mergeDeclAttributes(New, PrevDecl);
18785
18786 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18787 inferGslOwnerPointerAttribute(CXXRD);
18788 inferNullableClassAttribute(CXXRD);
18789 }
18790
18791 // If there's a #pragma GCC visibility in scope, set the visibility of this
18792 // record.
18793 AddPushedVisibilityAttribute(New);
18794
18795 // If this is not a definition, process API notes for it now.
18796 if (TUK != TagUseKind::Definition)
18797 ProcessAPINotes(New);
18798
18799 if (isMemberSpecialization && !New->isInvalidDecl())
18800 CompleteMemberSpecialization(New, Previous);
18801
18802 OwnedDecl = true;
18803 // In C++, don't return an invalid declaration. We can't recover well from
18804 // the cases where we make the type anonymous.
18805 if (Invalid && getLangOpts().CPlusPlus) {
18806 if (New->isBeingDefined())
18807 if (auto RD = dyn_cast<RecordDecl>(New))
18808 RD->completeDefinition();
18809 return true;
18810 } else if (SkipBody && SkipBody->ShouldSkip) {
18811 return SkipBody->Previous;
18812 } else {
18813 return New;
18814 }
18815 }
18816
18817 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18818 AdjustDeclIfTemplate(TagD);
18819 TagDecl *Tag = cast<TagDecl>(TagD);
18820
18821 // Enter the tag context.
18822 PushDeclContext(S, Tag);
18823
18824 ActOnDocumentableDecl(TagD);
18825
18826 // If there's a #pragma GCC visibility in scope, set the visibility of this
18827 // record.
18828 AddPushedVisibilityAttribute(Tag);
18829 }
18830
18831 bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18832 SkipBodyInfo &SkipBody) {
18833 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18834 return false;
18835
18836 // Make the previous decl visible.
18837 makeMergedDefinitionVisible(SkipBody.Previous);
18838 CleanupMergedEnum(S, SkipBody.New);
18839 return true;
18840 }
18841
18842 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18843 SourceLocation FinalLoc,
18844 bool IsFinalSpelledSealed,
18845 bool IsAbstract,
18846 SourceLocation LBraceLoc) {
18847 AdjustDeclIfTemplate(TagD);
18848 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18849
18850 FieldCollector->StartClass();
18851
18852 if (!Record->getIdentifier())
18853 return;
18854
18855 if (IsAbstract)
18856 Record->markAbstract();
18857
18858 if (FinalLoc.isValid()) {
18859 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18860 IsFinalSpelledSealed
18861 ? FinalAttr::Keyword_sealed
18862 : FinalAttr::Keyword_final));
18863 }
18864
18865 // C++ [class]p2:
18866 // [...] The class-name is also inserted into the scope of the
18867 // class itself; this is known as the injected-class-name. For
18868 // purposes of access checking, the injected-class-name is treated
18869 // as if it were a public member name.
18870 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18871 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18872 Record->getLocation(), Record->getIdentifier());
18873 InjectedClassName->setImplicit();
18874 InjectedClassName->setAccess(AS_public);
18875 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18876 InjectedClassName->setDescribedClassTemplate(Template);
18877
18878 PushOnScopeChains(InjectedClassName, S);
18879 assert(InjectedClassName->isInjectedClassName() &&
18880 "Broken injected-class-name");
18881 }
18882
18883 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18884 SourceRange BraceRange) {
18885 AdjustDeclIfTemplate(TagD);
18886 TagDecl *Tag = cast<TagDecl>(TagD);
18887 Tag->setBraceRange(BraceRange);
18888
18889 // Make sure we "complete" the definition even it is invalid.
18890 if (Tag->isBeingDefined()) {
18891 assert(Tag->isInvalidDecl() && "We should already have completed it");
18892 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18893 RD->completeDefinition();
18894 }
18895
18896 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18897 FieldCollector->FinishClass();
18898 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18899 auto *Def = RD->getDefinition();
18900 assert(Def && "The record is expected to have a completed definition");
18901 unsigned NumInitMethods = 0;
18902 for (auto *Method : Def->methods()) {
18903 if (!Method->getIdentifier())
18904 continue;
18905 if (Method->getName() == "__init")
18906 NumInitMethods++;
18907 }
18908 if (NumInitMethods > 1 || !Def->hasInitMethod())
18909 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18910 }
18911
18912 // If we're defining a dynamic class in a module interface unit, we always
18913 // need to produce the vtable for it, even if the vtable is not used in the
18914 // current TU.
18915 //
18916 // The case where the current class is not dynamic is handled in
18917 // MarkVTableUsed.
18918 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18919 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18920 }
18921
18922 // Exit this scope of this tag's definition.
18923 PopDeclContext();
18924
18925 if (getCurLexicalContext()->isObjCContainer() &&
18926 Tag->getDeclContext()->isFileContext())
18927 Tag->setTopLevelDeclInObjCContainer();
18928
18929 // Notify the consumer that we've defined a tag.
18930 if (!Tag->isInvalidDecl())
18931 Consumer.HandleTagDeclDefinition(Tag);
18932
18933 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18934 // from XLs and instead matches the XL #pragma pack(1) behavior.
18935 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18936 AlignPackStack.hasValue()) {
18937 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18938 // Only diagnose #pragma align(packed).
18939 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18940 return;
18941 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18942 if (!RD)
18943 return;
18944 // Only warn if there is at least 1 bitfield member.
18945 if (llvm::any_of(RD->fields(),
18946 [](const FieldDecl *FD) { return FD->isBitField(); }))
18947 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18948 }
18949 }
18950
18951 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18952 AdjustDeclIfTemplate(TagD);
18953 TagDecl *Tag = cast<TagDecl>(TagD);
18954 Tag->setInvalidDecl();
18955
18956 // Make sure we "complete" the definition even it is invalid.
18957 if (Tag->isBeingDefined()) {
18958 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18959 RD->completeDefinition();
18960 }
18961
18962 // We're undoing ActOnTagStartDefinition here, not
18963 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18964 // the FieldCollector.
18965
18966 PopDeclContext();
18967 }
18968
18969 // Note that FieldName may be null for anonymous bitfields.
18970 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18971 const IdentifierInfo *FieldName,
18972 QualType FieldTy, bool IsMsStruct,
18973 Expr *BitWidth) {
18974 assert(BitWidth);
18975 if (BitWidth->containsErrors())
18976 return ExprError();
18977
18978 // C99 6.7.2.1p4 - verify the field type.
18979 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18980 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18981 // Handle incomplete and sizeless types with a specific error.
18982 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18983 diag::err_field_incomplete_or_sizeless))
18984 return ExprError();
18985 if (FieldName)
18986 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18987 << FieldName << FieldTy << BitWidth->getSourceRange();
18988 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18989 << FieldTy << BitWidth->getSourceRange();
18990 } else if (DiagnoseUnexpandedParameterPack(BitWidth, UPPC_BitFieldWidth))
18991 return ExprError();
18992
18993 // If the bit-width is type- or value-dependent, don't try to check
18994 // it now.
18995 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18996 return BitWidth;
18997
18998 llvm::APSInt Value;
18999 ExprResult ICE =
19000 VerifyIntegerConstantExpression(BitWidth, &Value, AllowFoldKind::Allow);
19001 if (ICE.isInvalid())
19002 return ICE;
19003 BitWidth = ICE.get();
19004
19005 // Zero-width bitfield is ok for anonymous field.
19006 if (Value == 0 && FieldName)
19007 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19008 << FieldName << BitWidth->getSourceRange();
19009
19010 if (Value.isSigned() && Value.isNegative()) {
19011 if (FieldName)
19012 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19013 << FieldName << toString(Value, 10);
19014 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19015 << toString(Value, 10);
19016 }
19017
19018 // The size of the bit-field must not exceed our maximum permitted object
19019 // size.
19020 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19021 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19022 << !FieldName << FieldName << toString(Value, 10);
19023 }
19024
19025 if (!FieldTy->isDependentType()) {
19026 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19027 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19028 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19029
19030 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19031 // ABI.
19032 bool CStdConstraintViolation =
19033 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19034 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19035 if (CStdConstraintViolation || MSBitfieldViolation) {
19036 unsigned DiagWidth =
19037 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19038 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19039 << (bool)FieldName << FieldName << toString(Value, 10)
19040 << !CStdConstraintViolation << DiagWidth;
19041 }
19042
19043 // Warn on types where the user might conceivably expect to get all
19044 // specified bits as value bits: that's all integral types other than
19045 // 'bool'.
19046 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19047 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19048 << FieldName << Value << (unsigned)TypeWidth;
19049 }
19050 }
19051
19052 if (isa<ConstantExpr>(BitWidth))
19053 return BitWidth;
19054 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19055 }
19056
19057 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19058 Declarator &D, Expr *BitfieldWidth) {
19059 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19060 D, BitfieldWidth,
19061 /*InitStyle=*/ICIS_NoInit, AS_public);
19062 return Res;
19063 }
19064
19065 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19066 SourceLocation DeclStart,
19067 Declarator &D, Expr *BitWidth,
19068 InClassInitStyle InitStyle,
19069 AccessSpecifier AS) {
19070 if (D.isDecompositionDeclarator()) {
19071 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19072 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19073 << Decomp.getSourceRange();
19074 return nullptr;
19075 }
19076
19077 const IdentifierInfo *II = D.getIdentifier();
19078 SourceLocation Loc = DeclStart;
19079 if (II) Loc = D.getIdentifierLoc();
19080
19081 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19082 QualType T = TInfo->getType();
19083 if (getLangOpts().CPlusPlus) {
19084 CheckExtraCXXDefaultArguments(D);
19085
19086 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19087 UPPC_DataMemberType)) {
19088 D.setInvalidType();
19089 T = Context.IntTy;
19090 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19091 }
19092 }
19093
19094 DiagnoseFunctionSpecifiers(D.getDeclSpec());
19095
19096 if (D.getDeclSpec().isInlineSpecified())
19097 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19098 << getLangOpts().CPlusPlus17;
19099 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19100 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19101 diag::err_invalid_thread)
19102 << DeclSpec::getSpecifierName(TSCS);
19103
19104 // Check to see if this name was declared as a member previously
19105 NamedDecl *PrevDecl = nullptr;
19106 LookupResult Previous(*this, II, Loc, LookupMemberName,
19107 RedeclarationKind::ForVisibleRedeclaration);
19108 LookupName(Previous, S);
19109 switch (Previous.getResultKind()) {
19110 case LookupResultKind::Found:
19111 case LookupResultKind::FoundUnresolvedValue:
19112 PrevDecl = Previous.getAsSingle<NamedDecl>();
19113 break;
19114
19115 case LookupResultKind::FoundOverloaded:
19116 PrevDecl = Previous.getRepresentativeDecl();
19117 break;
19118
19119 case LookupResultKind::NotFound:
19120 case LookupResultKind::NotFoundInCurrentInstantiation:
19121 case LookupResultKind::Ambiguous:
19122 break;
19123 }
19124 Previous.suppressDiagnostics();
19125
19126 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19127 // Maybe we will complain about the shadowed template parameter.
19128 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19129 // Just pretend that we didn't see the previous declaration.
19130 PrevDecl = nullptr;
19131 }
19132
19133 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19134 PrevDecl = nullptr;
19135
19136 bool Mutable
19137 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19138 SourceLocation TSSL = D.getBeginLoc();
19139 FieldDecl *NewFD
19140 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19141 TSSL, AS, PrevDecl, &D);
19142
19143 if (NewFD->isInvalidDecl())
19144 Record->setInvalidDecl();
19145
19146 if (D.getDeclSpec().isModulePrivateSpecified())
19147 NewFD->setModulePrivate();
19148
19149 if (NewFD->isInvalidDecl() && PrevDecl) {
19150 // Don't introduce NewFD into scope; there's already something
19151 // with the same name in the same scope.
19152 } else if (II) {
19153 PushOnScopeChains(NewFD, S);
19154 } else
19155 Record->addDecl(NewFD);
19156
19157 return NewFD;
19158 }
19159
19160 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19161 TypeSourceInfo *TInfo,
19162 RecordDecl *Record, SourceLocation Loc,
19163 bool Mutable, Expr *BitWidth,
19164 InClassInitStyle InitStyle,
19165 SourceLocation TSSL,
19166 AccessSpecifier AS, NamedDecl *PrevDecl,
19167 Declarator *D) {
19168 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19169 bool InvalidDecl = false;
19170 if (D) InvalidDecl = D->isInvalidType();
19171
19172 // If we receive a broken type, recover by assuming 'int' and
19173 // marking this declaration as invalid.
19174 if (T.isNull() || T->containsErrors()) {
19175 InvalidDecl = true;
19176 T = Context.IntTy;
19177 }
19178
19179 QualType EltTy = Context.getBaseElementType(T);
19180 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19181 bool isIncomplete =
19182 LangOpts.HLSL // HLSL allows sizeless builtin types
19183 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19184 : RequireCompleteSizedType(Loc, EltTy,
19185 diag::err_field_incomplete_or_sizeless);
19186 if (isIncomplete) {
19187 // Fields of incomplete type force their record to be invalid.
19188 Record->setInvalidDecl();
19189 InvalidDecl = true;
19190 } else {
19191 NamedDecl *Def;
19192 EltTy->isIncompleteType(&Def);
19193 if (Def && Def->isInvalidDecl()) {
19194 Record->setInvalidDecl();
19195 InvalidDecl = true;
19196 }
19197 }
19198 }
19199
19200 // TR 18037 does not allow fields to be declared with address space
19201 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19202 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19203 Diag(Loc, diag::err_field_with_address_space);
19204 Record->setInvalidDecl();
19205 InvalidDecl = true;
19206 }
19207
19208 if (LangOpts.OpenCL) {
19209 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19210 // used as structure or union field: image, sampler, event or block types.
19211 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19212 T->isBlockPointerType()) {
19213 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19214 Record->setInvalidDecl();
19215 InvalidDecl = true;
19216 }
19217 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19218 // is enabled.
19219 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19220 "__cl_clang_bitfields", LangOpts)) {
19221 Diag(Loc, diag::err_opencl_bitfields);
19222 InvalidDecl = true;
19223 }
19224 }
19225
19226 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19227 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19228 T.hasQualifiers()) {
19229 InvalidDecl = true;
19230 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19231 }
19232
19233 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19234 // than a variably modified type.
19235 if (!InvalidDecl && T->isVariablyModifiedType()) {
19236 if (!tryToFixVariablyModifiedVarType(
19237 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19238 InvalidDecl = true;
19239 }
19240
19241 // Fields can not have abstract class types
19242 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19243 diag::err_abstract_type_in_decl,
19244 AbstractFieldType))
19245 InvalidDecl = true;
19246
19247 if (InvalidDecl)
19248 BitWidth = nullptr;
19249 // If this is declared as a bit-field, check the bit-field.
19250 if (BitWidth) {
19251 BitWidth =
19252 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19253 if (!BitWidth) {
19254 InvalidDecl = true;
19255 BitWidth = nullptr;
19256 }
19257 }
19258
19259 // Check that 'mutable' is consistent with the type of the declaration.
19260 if (!InvalidDecl && Mutable) {
19261 unsigned DiagID = 0;
19262 if (T->isReferenceType())
19263 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19264 : diag::err_mutable_reference;
19265 else if (T.isConstQualified())
19266 DiagID = diag::err_mutable_const;
19267
19268 if (DiagID) {
19269 SourceLocation ErrLoc = Loc;
19270 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19271 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19272 Diag(ErrLoc, DiagID);
19273 if (DiagID != diag::ext_mutable_reference) {
19274 Mutable = false;
19275 InvalidDecl = true;
19276 }
19277 }
19278 }
19279
19280 // C++11 [class.union]p8 (DR1460):
19281 // At most one variant member of a union may have a
19282 // brace-or-equal-initializer.
19283 if (InitStyle != ICIS_NoInit)
19284 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
19285
19286 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19287 BitWidth, Mutable, InitStyle);
19288 if (InvalidDecl)
19289 NewFD->setInvalidDecl();
19290
19291 if (!InvalidDecl)
19292 warnOnCTypeHiddenInCPlusPlus(NewFD);
19293
19294 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19295 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19296 Diag(Loc, diag::err_duplicate_member) << II;
19297 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19298 NewFD->setInvalidDecl();
19299 }
19300
19301 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19302 if (Record->isUnion()) {
19303 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19304 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19305
19306 // C++ [class.union]p1: An object of a class with a non-trivial
19307 // constructor, a non-trivial copy constructor, a non-trivial
19308 // destructor, or a non-trivial copy assignment operator
19309 // cannot be a member of a union, nor can an array of such
19310 // objects.
19311 if (CheckNontrivialField(NewFD))
19312 NewFD->setInvalidDecl();
19313 }
19314
19315 // C++ [class.union]p1: If a union contains a member of reference type,
19316 // the program is ill-formed, except when compiling with MSVC extensions
19317 // enabled.
19318 if (EltTy->isReferenceType()) {
19319 const bool HaveMSExt =
19320 getLangOpts().MicrosoftExt &&
19321 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
19322
19323 Diag(NewFD->getLocation(),
19324 HaveMSExt ? diag::ext_union_member_of_reference_type
19325 : diag::err_union_member_of_reference_type)
19326 << NewFD->getDeclName() << EltTy;
19327 if (!HaveMSExt)
19328 NewFD->setInvalidDecl();
19329 }
19330 }
19331 }
19332
19333 // FIXME: We need to pass in the attributes given an AST
19334 // representation, not a parser representation.
19335 if (D) {
19336 // FIXME: The current scope is almost... but not entirely... correct here.
19337 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19338
19339 if (NewFD->hasAttrs())
19340 CheckAlignasUnderalignment(NewFD);
19341 }
19342
19343 // In auto-retain/release, infer strong retension for fields of
19344 // retainable type.
19345 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19346 NewFD->setInvalidDecl();
19347
19348 if (T.isObjCGCWeak())
19349 Diag(Loc, diag::warn_attribute_weak_on_field);
19350
19351 // PPC MMA non-pointer types are not allowed as field types.
19352 if (Context.getTargetInfo().getTriple().isPPC64() &&
19353 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19354 NewFD->setInvalidDecl();
19355
19356 NewFD->setAccess(AS);
19357 return NewFD;
19358 }
19359
19360 bool Sema::CheckNontrivialField(FieldDecl *FD) {
19361 assert(FD);
19362 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19363
19364 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19365 return false;
19366
19367 QualType EltTy = Context.getBaseElementType(FD->getType());
19368 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19369 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19370 // We check for copy constructors before constructors
19371 // because otherwise we'll never get complaints about
19372 // copy constructors.
19373
19374 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19375 // We're required to check for any non-trivial constructors. Since the
19376 // implicit default constructor is suppressed if there are any
19377 // user-declared constructors, we just need to check that there is a
19378 // trivial default constructor and a trivial copy constructor. (We don't
19379 // worry about move constructors here, since this is a C++98 check.)
19380 if (RDecl->hasNonTrivialCopyConstructor())
19381 member = CXXSpecialMemberKind::CopyConstructor;
19382 else if (!RDecl->hasTrivialDefaultConstructor())
19383 member = CXXSpecialMemberKind::DefaultConstructor;
19384 else if (RDecl->hasNonTrivialCopyAssignment())
19385 member = CXXSpecialMemberKind::CopyAssignment;
19386 else if (RDecl->hasNonTrivialDestructor())
19387 member = CXXSpecialMemberKind::Destructor;
19388
19389 if (member != CXXSpecialMemberKind::Invalid) {
19390 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19391 RDecl->hasObjectMember()) {
19392 // Objective-C++ ARC: it is an error to have a non-trivial field of
19393 // a union. However, system headers in Objective-C programs
19394 // occasionally have Objective-C lifetime objects within unions,
19395 // and rather than cause the program to fail, we make those
19396 // members unavailable.
19397 SourceLocation Loc = FD->getLocation();
19398 if (getSourceManager().isInSystemHeader(Loc)) {
19399 if (!FD->hasAttr<UnavailableAttr>())
19400 FD->addAttr(UnavailableAttr::CreateImplicit(
19401 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19402 return false;
19403 }
19404 }
19405
19406 Diag(FD->getLocation(),
19407 getLangOpts().CPlusPlus11
19408 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19409 : diag::err_illegal_union_or_anon_struct_member)
19410 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19411 DiagnoseNontrivial(RDecl, member);
19412 return !getLangOpts().CPlusPlus11;
19413 }
19414 }
19415
19416 return false;
19417 }
19418
19419 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19420 SmallVectorImpl<Decl *> &AllIvarDecls) {
19421 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19422 return;
19423
19424 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19425 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19426
19427 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19428 return;
19429 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19430 if (!ID) {
19431 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19432 if (!CD->IsClassExtension())
19433 return;
19434 }
19435 // No need to add this to end of @implementation.
19436 else
19437 return;
19438 }
19439 // All conditions are met. Add a new bitfield to the tail end of ivars.
19440 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19441 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19442 Expr *BitWidth =
19443 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19444
19445 Ivar = ObjCIvarDecl::Create(
19446 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19447 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19448 ObjCIvarDecl::Private, BitWidth, true);
19449 AllIvarDecls.push_back(Ivar);
19450 }
19451
19452 /// [class.dtor]p4:
19453 /// At the end of the definition of a class, overload resolution is
19454 /// performed among the prospective destructors declared in that class with
19455 /// an empty argument list to select the destructor for the class, also
19456 /// known as the selected destructor.
19457 ///
19458 /// We do the overload resolution here, then mark the selected constructor in the AST.
19459 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19460 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19461 if (!Record->hasUserDeclaredDestructor()) {
19462 return;
19463 }
19464
19465 SourceLocation Loc = Record->getLocation();
19466 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19467
19468 for (auto *Decl : Record->decls()) {
19469 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19470 if (DD->isInvalidDecl())
19471 continue;
19472 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19473 OCS);
19474 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19475 }
19476 }
19477
19478 if (OCS.empty()) {
19479 return;
19480 }
19481 OverloadCandidateSet::iterator Best;
19482 unsigned Msg = 0;
19483 OverloadCandidateDisplayKind DisplayKind;
19484
19485 switch (OCS.BestViableFunction(S, Loc, Best)) {
19486 case OR_Success:
19487 case OR_Deleted:
19488 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19489 break;
19490
19491 case OR_Ambiguous:
19492 Msg = diag::err_ambiguous_destructor;
19493 DisplayKind = OCD_AmbiguousCandidates;
19494 break;
19495
19496 case OR_No_Viable_Function:
19497 Msg = diag::err_no_viable_destructor;
19498 DisplayKind = OCD_AllCandidates;
19499 break;
19500 }
19501
19502 if (Msg) {
19503 // OpenCL have got their own thing going with destructors. It's slightly broken,
19504 // but we allow it.
19505 if (!S.LangOpts.OpenCL) {
19506 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19507 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19508 Record->setInvalidDecl();
19509 }
19510 // It's a bit hacky: At this point we've raised an error but we want the
19511 // rest of the compiler to continue somehow working. However almost
19512 // everything we'll try to do with the class will depend on there being a
19513 // destructor. So let's pretend the first one is selected and hope for the
19514 // best.
19515 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19516 }
19517 }
19518
19519 /// [class.mem.special]p5
19520 /// Two special member functions are of the same kind if:
19521 /// - they are both default constructors,
19522 /// - they are both copy or move constructors with the same first parameter
19523 /// type, or
19524 /// - they are both copy or move assignment operators with the same first
19525 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19526 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19527 CXXMethodDecl *M1,
19528 CXXMethodDecl *M2,
19529 CXXSpecialMemberKind CSM) {
19530 // We don't want to compare templates to non-templates: See
19531 // https://github.com/llvm/llvm-project/issues/59206
19532 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19533 return bool(M1->getDescribedFunctionTemplate()) ==
19534 bool(M2->getDescribedFunctionTemplate());
19535 // FIXME: better resolve CWG
19536 // https://cplusplus.github.io/CWG/issues/2787.html
19537 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19538 M2->getNonObjectParameter(0)->getType()))
19539 return false;
19540 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19541 M2->getFunctionObjectParameterReferenceType()))
19542 return false;
19543
19544 return true;
19545 }
19546
19547 /// [class.mem.special]p6:
19548 /// An eligible special member function is a special member function for which:
19549 /// - the function is not deleted,
19550 /// - the associated constraints, if any, are satisfied, and
19551 /// - no special member function of the same kind whose associated constraints
19552 /// [CWG2595], if any, are satisfied is more constrained.
19553 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19554 ArrayRef<CXXMethodDecl *> Methods,
19555 CXXSpecialMemberKind CSM) {
19556 SmallVector<bool, 4> SatisfactionStatus;
19557
19558 for (CXXMethodDecl *Method : Methods) {
19559 if (!Method->getTrailingRequiresClause())
19560 SatisfactionStatus.push_back(true);
19561 else {
19562 ConstraintSatisfaction Satisfaction;
19563 if (S.CheckFunctionConstraints(Method, Satisfaction))
19564 SatisfactionStatus.push_back(false);
19565 else
19566 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19567 }
19568 }
19569
19570 for (size_t i = 0; i < Methods.size(); i++) {
19571 if (!SatisfactionStatus[i])
19572 continue;
19573 CXXMethodDecl *Method = Methods[i];
19574 CXXMethodDecl *OrigMethod = Method;
19575 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19576 OrigMethod = cast<CXXMethodDecl>(MF);
19577
19578 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19579 bool AnotherMethodIsMoreConstrained = false;
19580 for (size_t j = 0; j < Methods.size(); j++) {
19581 if (i == j || !SatisfactionStatus[j])
19582 continue;
19583 CXXMethodDecl *OtherMethod = Methods[j];
19584 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19585 OtherMethod = cast<CXXMethodDecl>(MF);
19586
19587 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19588 CSM))
19589 continue;
19590
19591 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19592 if (!Other)
19593 continue;
19594 if (!Orig) {
19595 AnotherMethodIsMoreConstrained = true;
19596 break;
19597 }
19598 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19599 AnotherMethodIsMoreConstrained)) {
19600 // There was an error with the constraints comparison. Exit the loop
19601 // and don't consider this function eligible.
19602 AnotherMethodIsMoreConstrained = true;
19603 }
19604 if (AnotherMethodIsMoreConstrained)
19605 break;
19606 }
19607 // FIXME: Do not consider deleted methods as eligible after implementing
19608 // DR1734 and DR1496.
19609 if (!AnotherMethodIsMoreConstrained) {
19610 Method->setIneligibleOrNotSelected(false);
19611 Record->addedEligibleSpecialMemberFunction(Method,
19612 1 << llvm::to_underlying(CSM));
19613 }
19614 }
19615 }
19616
19617 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19618 CXXRecordDecl *Record) {
19619 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19620 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19621 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19622 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19623 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19624
19625 for (auto *Decl : Record->decls()) {
19626 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19627 if (!MD) {
19628 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19629 if (FTD)
19630 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19631 }
19632 if (!MD)
19633 continue;
19634 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19635 if (CD->isInvalidDecl())
19636 continue;
19637 if (CD->isDefaultConstructor())
19638 DefaultConstructors.push_back(MD);
19639 else if (CD->isCopyConstructor())
19640 CopyConstructors.push_back(MD);
19641 else if (CD->isMoveConstructor())
19642 MoveConstructors.push_back(MD);
19643 } else if (MD->isCopyAssignmentOperator()) {
19644 CopyAssignmentOperators.push_back(MD);
19645 } else if (MD->isMoveAssignmentOperator()) {
19646 MoveAssignmentOperators.push_back(MD);
19647 }
19648 }
19649
19650 SetEligibleMethods(S, Record, DefaultConstructors,
19651 CXXSpecialMemberKind::DefaultConstructor);
19652 SetEligibleMethods(S, Record, CopyConstructors,
19653 CXXSpecialMemberKind::CopyConstructor);
19654 SetEligibleMethods(S, Record, MoveConstructors,
19655 CXXSpecialMemberKind::MoveConstructor);
19656 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19657 CXXSpecialMemberKind::CopyAssignment);
19658 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19659 CXXSpecialMemberKind::MoveAssignment);
19660 }
19661
19662 bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19663 // Check to see if a FieldDecl is a pointer to a function.
19664 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19665 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19666 if (!FD) {
19667 // Check whether this is a forward declaration that was inserted by
19668 // Clang. This happens when a non-forward declared / defined type is
19669 // used, e.g.:
19670 //
19671 // struct foo {
19672 // struct bar *(*f)();
19673 // struct bar *(*g)();
19674 // };
19675 //
19676 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19677 // incomplete definition.
19678 if (const auto *TD = dyn_cast<TagDecl>(D))
19679 return !TD->isCompleteDefinition();
19680 return false;
19681 }
19682 QualType FieldType = FD->getType().getDesugaredType(Context);
19683 if (isa<PointerType>(FieldType)) {
19684 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19685 return PointeeType.getDesugaredType(Context)->isFunctionType();
19686 }
19687 // If a member is a struct entirely of function pointers, that counts too.
19688 if (const auto *Record = FieldType->getAsRecordDecl();
19689 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19690 return true;
19691 return false;
19692 };
19693
19694 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19695 }
19696
19697 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19698 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19699 SourceLocation RBrac,
19700 const ParsedAttributesView &Attrs) {
19701 assert(EnclosingDecl && "missing record or interface decl");
19702
19703 // If this is an Objective-C @implementation or category and we have
19704 // new fields here we should reset the layout of the interface since
19705 // it will now change.
19706 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19707 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19708 switch (DC->getKind()) {
19709 default: break;
19710 case Decl::ObjCCategory:
19711 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19712 break;
19713 case Decl::ObjCImplementation:
19714 Context.
19715 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19716 break;
19717 }
19718 }
19719
19720 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19721 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19722
19723 // Start counting up the number of named members; make sure to include
19724 // members of anonymous structs and unions in the total.
19725 unsigned NumNamedMembers = 0;
19726 if (Record) {
19727 for (const auto *I : Record->decls()) {
19728 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19729 if (IFD->getDeclName())
19730 ++NumNamedMembers;
19731 }
19732 }
19733
19734 // Verify that all the fields are okay.
19735 SmallVector<FieldDecl*, 32> RecFields;
19736 const FieldDecl *PreviousField = nullptr;
19737 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19738 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19739 FieldDecl *FD = cast<FieldDecl>(*i);
19740
19741 // Get the type for the field.
19742 const Type *FDTy = FD->getType().getTypePtr();
19743
19744 if (!FD->isAnonymousStructOrUnion()) {
19745 // Remember all fields written by the user.
19746 RecFields.push_back(FD);
19747 }
19748
19749 // If the field is already invalid for some reason, don't emit more
19750 // diagnostics about it.
19751 if (FD->isInvalidDecl()) {
19752 EnclosingDecl->setInvalidDecl();
19753 continue;
19754 }
19755
19756 // C99 6.7.2.1p2:
19757 // A structure or union shall not contain a member with
19758 // incomplete or function type (hence, a structure shall not
19759 // contain an instance of itself, but may contain a pointer to
19760 // an instance of itself), except that the last member of a
19761 // structure with more than one named member may have incomplete
19762 // array type; such a structure (and any union containing,
19763 // possibly recursively, a member that is such a structure)
19764 // shall not be a member of a structure or an element of an
19765 // array.
19766 bool IsLastField = (i + 1 == Fields.end());
19767 if (FDTy->isFunctionType()) {
19768 // Field declared as a function.
19769 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19770 << FD->getDeclName();
19771 FD->setInvalidDecl();
19772 EnclosingDecl->setInvalidDecl();
19773 continue;
19774 } else if (FDTy->isIncompleteArrayType() &&
19775 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19776 if (Record) {
19777 // Flexible array member.
19778 // Microsoft and g++ is more permissive regarding flexible array.
19779 // It will accept flexible array in union and also
19780 // as the sole element of a struct/class.
19781 unsigned DiagID = 0;
19782 if (!Record->isUnion() && !IsLastField) {
19783 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19784 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19785 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19786 FD->setInvalidDecl();
19787 EnclosingDecl->setInvalidDecl();
19788 continue;
19789 } else if (Record->isUnion())
19790 DiagID = getLangOpts().MicrosoftExt
19791 ? diag::ext_flexible_array_union_ms
19792 : diag::ext_flexible_array_union_gnu;
19793 else if (NumNamedMembers < 1)
19794 DiagID = getLangOpts().MicrosoftExt
19795 ? diag::ext_flexible_array_empty_aggregate_ms
19796 : diag::ext_flexible_array_empty_aggregate_gnu;
19797
19798 if (DiagID)
19799 Diag(FD->getLocation(), DiagID)
19800 << FD->getDeclName() << Record->getTagKind();
19801 // While the layout of types that contain virtual bases is not specified
19802 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19803 // virtual bases after the derived members. This would make a flexible
19804 // array member declared at the end of an object not adjacent to the end
19805 // of the type.
19806 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19807 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19808 << FD->getDeclName() << Record->getTagKind();
19809 if (!getLangOpts().C99)
19810 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19811 << FD->getDeclName() << Record->getTagKind();
19812
19813 // If the element type has a non-trivial destructor, we would not
19814 // implicitly destroy the elements, so disallow it for now.
19815 //
19816 // FIXME: GCC allows this. We should probably either implicitly delete
19817 // the destructor of the containing class, or just allow this.
19818 QualType BaseElem = Context.getBaseElementType(FD->getType());
19819 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19820 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19821 << FD->getDeclName() << FD->getType();
19822 FD->setInvalidDecl();
19823 EnclosingDecl->setInvalidDecl();
19824 continue;
19825 }
19826 // Okay, we have a legal flexible array member at the end of the struct.
19827 Record->setHasFlexibleArrayMember(true);
19828 } else {
19829 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19830 // unless they are followed by another ivar. That check is done
19831 // elsewhere, after synthesized ivars are known.
19832 }
19833 } else if (!FDTy->isDependentType() &&
19834 (LangOpts.HLSL // HLSL allows sizeless builtin types
19835 ? RequireCompleteType(FD->getLocation(), FD->getType(),
19836 diag::err_incomplete_type)
19837 : RequireCompleteSizedType(
19838 FD->getLocation(), FD->getType(),
19839 diag::err_field_incomplete_or_sizeless))) {
19840 // Incomplete type
19841 FD->setInvalidDecl();
19842 EnclosingDecl->setInvalidDecl();
19843 continue;
19844 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19845 if (Record && RD->hasFlexibleArrayMember()) {
19846 // A type which contains a flexible array member is considered to be a
19847 // flexible array member.
19848 Record->setHasFlexibleArrayMember(true);
19849 if (!Record->isUnion()) {
19850 // If this is a struct/class and this is not the last element, reject
19851 // it. Note that GCC supports variable sized arrays in the middle of
19852 // structures.
19853 if (!IsLastField)
19854 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19855 << FD->getDeclName() << FD->getType();
19856 else {
19857 // We support flexible arrays at the end of structs in
19858 // other structs as an extension.
19859 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19860 << FD->getDeclName();
19861 }
19862 }
19863 }
19864 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19865 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19866 diag::err_abstract_type_in_decl,
19867 AbstractIvarType)) {
19868 // Ivars can not have abstract class types
19869 FD->setInvalidDecl();
19870 }
19871 if (Record && RD->hasObjectMember())
19872 Record->setHasObjectMember(true);
19873 if (Record && RD->hasVolatileMember())
19874 Record->setHasVolatileMember(true);
19875 } else if (FDTy->isObjCObjectType()) {
19876 /// A field cannot be an Objective-c object
19877 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19878 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19879 QualType T = Context.getObjCObjectPointerType(FD->getType());
19880 FD->setType(T);
19881 } else if (Record && Record->isUnion() &&
19882 FD->getType().hasNonTrivialObjCLifetime() &&
19883 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19884 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19885 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19886 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19887 // For backward compatibility, fields of C unions declared in system
19888 // headers that have non-trivial ObjC ownership qualifications are marked
19889 // as unavailable unless the qualifier is explicit and __strong. This can
19890 // break ABI compatibility between programs compiled with ARC and MRR, but
19891 // is a better option than rejecting programs using those unions under
19892 // ARC.
19893 FD->addAttr(UnavailableAttr::CreateImplicit(
19894 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19895 FD->getLocation()));
19896 } else if (getLangOpts().ObjC &&
19897 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19898 !Record->hasObjectMember()) {
19899 if (FD->getType()->isObjCObjectPointerType() ||
19900 FD->getType().isObjCGCStrong())
19901 Record->setHasObjectMember(true);
19902 else if (Context.getAsArrayType(FD->getType())) {
19903 QualType BaseType = Context.getBaseElementType(FD->getType());
19904 if (const auto *RD = BaseType->getAsRecordDecl();
19905 RD && RD->hasObjectMember())
19906 Record->setHasObjectMember(true);
19907 else if (BaseType->isObjCObjectPointerType() ||
19908 BaseType.isObjCGCStrong())
19909 Record->setHasObjectMember(true);
19910 }
19911 }
19912
19913 if (Record && !getLangOpts().CPlusPlus &&
19914 !shouldIgnoreForRecordTriviality(FD)) {
19915 QualType FT = FD->getType();
19916 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19917 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19918 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19919 Record->isUnion())
19920 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19921 }
19922 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19923 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19924 Record->setNonTrivialToPrimitiveCopy(true);
19925 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19926 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19927 }
19928 if (FD->hasAttr<ExplicitInitAttr>())
19929 Record->setHasUninitializedExplicitInitFields(true);
19930 if (FT.isDestructedType()) {
19931 Record->setNonTrivialToPrimitiveDestroy(true);
19932 Record->setParamDestroyedInCallee(true);
19933 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19934 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19935 }
19936
19937 if (const auto *RD = FT->getAsRecordDecl()) {
19938 if (RD->getArgPassingRestrictions() ==
19939 RecordArgPassingKind::CanNeverPassInRegs)
19940 Record->setArgPassingRestrictions(
19941 RecordArgPassingKind::CanNeverPassInRegs);
19942 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19943 Record->setArgPassingRestrictions(
19944 RecordArgPassingKind::CanNeverPassInRegs);
19945 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19946 Q && Q.isAddressDiscriminated()) {
19947 Record->setArgPassingRestrictions(
19948 RecordArgPassingKind::CanNeverPassInRegs);
19949 Record->setNonTrivialToPrimitiveCopy(true);
19950 }
19951 }
19952
19953 if (Record && FD->getType().isVolatileQualified())
19954 Record->setHasVolatileMember(true);
19955 bool ReportMSBitfieldStoragePacking =
19956 Record && PreviousField &&
19957 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19958 Record->getLocation());
19959 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19960 return FD->isBitField() && !FD->getType()->isDependentType();
19961 };
19962
19963 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19964 IsNonDependentBitField(PreviousField)) {
19965 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19966 CharUnits PreviousFieldStorageSize =
19967 Context.getTypeSizeInChars(PreviousField->getType());
19968 if (FDStorageSize != PreviousFieldStorageSize) {
19969 Diag(FD->getLocation(),
19970 diag::warn_ms_bitfield_mismatched_storage_packing)
19971 << FD << FD->getType() << FDStorageSize.getQuantity()
19972 << PreviousFieldStorageSize.getQuantity();
19973 Diag(PreviousField->getLocation(),
19974 diag::note_ms_bitfield_mismatched_storage_size_previous)
19975 << PreviousField << PreviousField->getType();
19976 }
19977 }
19978 // Keep track of the number of named members.
19979 if (FD->getIdentifier())
19980 ++NumNamedMembers;
19981 }
19982
19983 // Okay, we successfully defined 'Record'.
19984 if (Record) {
19985 bool Completed = false;
19986 if (S) {
19987 Scope *Parent = S->getParent();
19988 if (Parent && Parent->isTypeAliasScope() &&
19989 Parent->isTemplateParamScope())
19990 Record->setInvalidDecl();
19991 }
19992
19993 if (CXXRecord) {
19994 if (!CXXRecord->isInvalidDecl()) {
19995 // Set access bits correctly on the directly-declared conversions.
19996 for (CXXRecordDecl::conversion_iterator
19997 I = CXXRecord->conversion_begin(),
19998 E = CXXRecord->conversion_end(); I != E; ++I)
19999 I.setAccess((*I)->getAccess());
20000 }
20001
20002 // Add any implicitly-declared members to this class.
20003 AddImplicitlyDeclaredMembersToClass(CXXRecord);
20004
20005 if (!CXXRecord->isDependentType()) {
20006 if (!CXXRecord->isInvalidDecl()) {
20007 // If we have virtual base classes, we may end up finding multiple
20008 // final overriders for a given virtual function. Check for this
20009 // problem now.
20010 if (CXXRecord->getNumVBases()) {
20011 CXXFinalOverriderMap FinalOverriders;
20012 CXXRecord->getFinalOverriders(FinalOverriders);
20013
20014 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20015 MEnd = FinalOverriders.end();
20016 M != MEnd; ++M) {
20017 for (OverridingMethods::iterator SO = M->second.begin(),
20018 SOEnd = M->second.end();
20019 SO != SOEnd; ++SO) {
20020 assert(SO->second.size() > 0 &&
20021 "Virtual function without overriding functions?");
20022 if (SO->second.size() == 1)
20023 continue;
20024
20025 // C++ [class.virtual]p2:
20026 // In a derived class, if a virtual member function of a base
20027 // class subobject has more than one final overrider the
20028 // program is ill-formed.
20029 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20030 << (const NamedDecl *)M->first << Record;
20031 Diag(M->first->getLocation(),
20032 diag::note_overridden_virtual_function);
20033 for (OverridingMethods::overriding_iterator
20034 OM = SO->second.begin(),
20035 OMEnd = SO->second.end();
20036 OM != OMEnd; ++OM)
20037 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20038 << (const NamedDecl *)M->first << OM->Method->getParent();
20039
20040 Record->setInvalidDecl();
20041 }
20042 }
20043 CXXRecord->completeDefinition(&FinalOverriders);
20044 Completed = true;
20045 }
20046 }
20047 ComputeSelectedDestructor(*this, CXXRecord);
20048 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
20049 }
20050 }
20051
20052 if (!Completed)
20053 Record->completeDefinition();
20054
20055 // Handle attributes before checking the layout.
20056 ProcessDeclAttributeList(S, Record, Attrs);
20057
20058 // Maybe randomize the record's decls. We automatically randomize a record
20059 // of function pointers, unless it has the "no_randomize_layout" attribute.
20060 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20061 !Record->isRandomized() && !Record->isUnion() &&
20062 (Record->hasAttr<RandomizeLayoutAttr>() ||
20063 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20064 EntirelyFunctionPointers(Record)))) {
20065 SmallVector<Decl *, 32> NewDeclOrdering;
20066 if (randstruct::randomizeStructureLayout(Context, Record,
20067 NewDeclOrdering))
20068 Record->reorderDecls(NewDeclOrdering);
20069 }
20070
20071 // We may have deferred checking for a deleted destructor. Check now.
20072 if (CXXRecord) {
20073 auto *Dtor = CXXRecord->getDestructor();
20074 if (Dtor && Dtor->isImplicit() &&
20075 ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {
20076 CXXRecord->setImplicitDestructorIsDeleted();
20077 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20078 }
20079 }
20080
20081 if (Record->hasAttrs()) {
20082 CheckAlignasUnderalignment(Record);
20083
20084 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20085 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
20086 IA->getRange(), IA->getBestCase(),
20087 IA->getInheritanceModel());
20088 }
20089
20090 // Check if the structure/union declaration is a type that can have zero
20091 // size in C. For C this is a language extension, for C++ it may cause
20092 // compatibility problems.
20093 bool CheckForZeroSize;
20094 if (!getLangOpts().CPlusPlus) {
20095 CheckForZeroSize = true;
20096 } else {
20097 // For C++ filter out types that cannot be referenced in C code.
20098 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
20099 CheckForZeroSize =
20100 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20101 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20102 CXXRecord->isCLike();
20103 }
20104 if (CheckForZeroSize) {
20105 bool ZeroSize = true;
20106 bool IsEmpty = true;
20107 unsigned NonBitFields = 0;
20108 for (RecordDecl::field_iterator I = Record->field_begin(),
20109 E = Record->field_end();
20110 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20111 IsEmpty = false;
20112 if (I->isUnnamedBitField()) {
20113 if (!I->isZeroLengthBitField())
20114 ZeroSize = false;
20115 } else {
20116 ++NonBitFields;
20117 QualType FieldType = I->getType();
20118 if (FieldType->isIncompleteType() ||
20119 !Context.getTypeSizeInChars(FieldType).isZero())
20120 ZeroSize = false;
20121 }
20122 }
20123
20124 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20125 // allowed in C++, but warn if its declaration is inside
20126 // extern "C" block.
20127 if (ZeroSize) {
20128 Diag(RecLoc, getLangOpts().CPlusPlus ?
20129 diag::warn_zero_size_struct_union_in_extern_c :
20130 diag::warn_zero_size_struct_union_compat)
20131 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20132 }
20133
20134 // Structs without named members are extension in C (C99 6.7.2.1p7),
20135 // but are accepted by GCC. In C2y, this became implementation-defined
20136 // (C2y 6.7.3.2p10).
20137 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20138 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20139 : diag::ext_no_named_members_in_struct_union)
20140 << Record->isUnion();
20141 }
20142 }
20143 } else {
20144 ObjCIvarDecl **ClsFields =
20145 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20146 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20147 ID->setEndOfDefinitionLoc(RBrac);
20148 // Add ivar's to class's DeclContext.
20149 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20150 ClsFields[i]->setLexicalDeclContext(ID);
20151 ID->addDecl(ClsFields[i]);
20152 }
20153 // Must enforce the rule that ivars in the base classes may not be
20154 // duplicates.
20155 if (ID->getSuperClass())
20156 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20157 } else if (ObjCImplementationDecl *IMPDecl =
20158 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20159 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20160 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20161 // Ivar declared in @implementation never belongs to the implementation.
20162 // Only it is in implementation's lexical context.
20163 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20164 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20165 RBrac);
20166 IMPDecl->setIvarLBraceLoc(LBrac);
20167 IMPDecl->setIvarRBraceLoc(RBrac);
20168 } else if (ObjCCategoryDecl *CDecl =
20169 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20170 // case of ivars in class extension; all other cases have been
20171 // reported as errors elsewhere.
20172 // FIXME. Class extension does not have a LocEnd field.
20173 // CDecl->setLocEnd(RBrac);
20174 // Add ivar's to class extension's DeclContext.
20175 // Diagnose redeclaration of private ivars.
20176 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20177 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20178 if (IDecl) {
20179 if (const ObjCIvarDecl *ClsIvar =
20180 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20181 Diag(ClsFields[i]->getLocation(),
20182 diag::err_duplicate_ivar_declaration);
20183 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20184 continue;
20185 }
20186 for (const auto *Ext : IDecl->known_extensions()) {
20187 if (const ObjCIvarDecl *ClsExtIvar
20188 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20189 Diag(ClsFields[i]->getLocation(),
20190 diag::err_duplicate_ivar_declaration);
20191 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20192 continue;
20193 }
20194 }
20195 }
20196 ClsFields[i]->setLexicalDeclContext(CDecl);
20197 CDecl->addDecl(ClsFields[i]);
20198 }
20199 CDecl->setIvarLBraceLoc(LBrac);
20200 CDecl->setIvarRBraceLoc(RBrac);
20201 }
20202 }
20203 if (Record && !isa<ClassTemplateSpecializationDecl>(Record))
20204 ProcessAPINotes(Record);
20205 }
20206
20207 // Given an integral type, return the next larger integral type
20208 // (or a NULL type of no such type exists).
20209 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20210 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20211 // enum checking below.
20212 assert((T->isIntegralType(Context) ||
20213 T->isEnumeralType()) && "Integral type required!");
20214 const unsigned NumTypes = 4;
20215 QualType SignedIntegralTypes[NumTypes] = {
20216 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20217 };
20218 QualType UnsignedIntegralTypes[NumTypes] = {
20219 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20220 Context.UnsignedLongLongTy
20221 };
20222
20223 unsigned BitWidth = Context.getTypeSize(T);
20224 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20225 : UnsignedIntegralTypes;
20226 for (unsigned I = 0; I != NumTypes; ++I)
20227 if (Context.getTypeSize(Types[I]) > BitWidth)
20228 return Types[I];
20229
20230 return QualType();
20231 }
20232
20233 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20234 EnumConstantDecl *LastEnumConst,
20235 SourceLocation IdLoc,
20236 IdentifierInfo *Id,
20237 Expr *Val) {
20238 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20239 llvm::APSInt EnumVal(IntWidth);
20240 QualType EltTy;
20241
20242 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
20243 Val = nullptr;
20244
20245 if (Val)
20246 Val = DefaultLvalueConversion(Val).get();
20247
20248 if (Val) {
20249 if (Enum->isDependentType() || Val->isTypeDependent() ||
20250 Val->containsErrors())
20251 EltTy = Context.DependentTy;
20252 else {
20253 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20254 // underlying type, but do allow it in all other contexts.
20255 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20256 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20257 // constant-expression in the enumerator-definition shall be a converted
20258 // constant expression of the underlying type.
20259 EltTy = Enum->getIntegerType();
20260 ExprResult Converted = CheckConvertedConstantExpression(
20261 Val, EltTy, EnumVal, CCEKind::Enumerator);
20262 if (Converted.isInvalid())
20263 Val = nullptr;
20264 else
20265 Val = Converted.get();
20266 } else if (!Val->isValueDependent() &&
20267 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20268 AllowFoldKind::Allow)
20269 .get())) {
20270 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20271 } else {
20272 if (Enum->isComplete()) {
20273 EltTy = Enum->getIntegerType();
20274
20275 // In Obj-C and Microsoft mode, require the enumeration value to be
20276 // representable in the underlying type of the enumeration. In C++11,
20277 // we perform a non-narrowing conversion as part of converted constant
20278 // expression checking.
20279 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20280 if (Context.getTargetInfo()
20281 .getTriple()
20282 .isWindowsMSVCEnvironment()) {
20283 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20284 } else {
20285 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20286 }
20287 }
20288
20289 // Cast to the underlying type.
20290 Val = ImpCastExprToType(Val, EltTy,
20291 EltTy->isBooleanType() ? CK_IntegralToBoolean
20292 : CK_IntegralCast)
20293 .get();
20294 } else if (getLangOpts().CPlusPlus) {
20295 // C++11 [dcl.enum]p5:
20296 // If the underlying type is not fixed, the type of each enumerator
20297 // is the type of its initializing value:
20298 // - If an initializer is specified for an enumerator, the
20299 // initializing value has the same type as the expression.
20300 EltTy = Val->getType();
20301 } else {
20302 // C99 6.7.2.2p2:
20303 // The expression that defines the value of an enumeration constant
20304 // shall be an integer constant expression that has a value
20305 // representable as an int.
20306
20307 // Complain if the value is not representable in an int.
20308 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20309 Diag(IdLoc, getLangOpts().C23
20310 ? diag::warn_c17_compat_enum_value_not_int
20311 : diag::ext_c23_enum_value_not_int)
20312 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20313 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20314 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20315 // Force the type of the expression to 'int'.
20316 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20317 }
20318 EltTy = Val->getType();
20319 }
20320 }
20321 }
20322 }
20323
20324 if (!Val) {
20325 if (Enum->isDependentType())
20326 EltTy = Context.DependentTy;
20327 else if (!LastEnumConst) {
20328 // C++0x [dcl.enum]p5:
20329 // If the underlying type is not fixed, the type of each enumerator
20330 // is the type of its initializing value:
20331 // - If no initializer is specified for the first enumerator, the
20332 // initializing value has an unspecified integral type.
20333 //
20334 // GCC uses 'int' for its unspecified integral type, as does
20335 // C99 6.7.2.2p3.
20336 if (Enum->isFixed()) {
20337 EltTy = Enum->getIntegerType();
20338 }
20339 else {
20340 EltTy = Context.IntTy;
20341 }
20342 } else {
20343 // Assign the last value + 1.
20344 EnumVal = LastEnumConst->getInitVal();
20345 ++EnumVal;
20346 EltTy = LastEnumConst->getType();
20347
20348 // Check for overflow on increment.
20349 if (EnumVal < LastEnumConst->getInitVal()) {
20350 // C++0x [dcl.enum]p5:
20351 // If the underlying type is not fixed, the type of each enumerator
20352 // is the type of its initializing value:
20353 //
20354 // - Otherwise the type of the initializing value is the same as
20355 // the type of the initializing value of the preceding enumerator
20356 // unless the incremented value is not representable in that type,
20357 // in which case the type is an unspecified integral type
20358 // sufficient to contain the incremented value. If no such type
20359 // exists, the program is ill-formed.
20360 QualType T = getNextLargerIntegralType(Context, EltTy);
20361 if (T.isNull() || Enum->isFixed()) {
20362 // There is no integral type larger enough to represent this
20363 // value. Complain, then allow the value to wrap around.
20364 EnumVal = LastEnumConst->getInitVal();
20365 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20366 ++EnumVal;
20367 if (Enum->isFixed())
20368 // When the underlying type is fixed, this is ill-formed.
20369 Diag(IdLoc, diag::err_enumerator_wrapped)
20370 << toString(EnumVal, 10)
20371 << EltTy;
20372 else
20373 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20374 << toString(EnumVal, 10);
20375 } else {
20376 EltTy = T;
20377 }
20378
20379 // Retrieve the last enumerator's value, extent that type to the
20380 // type that is supposed to be large enough to represent the incremented
20381 // value, then increment.
20382 EnumVal = LastEnumConst->getInitVal();
20383 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20384 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20385 ++EnumVal;
20386
20387 // If we're not in C++, diagnose the overflow of enumerator values,
20388 // which in C99 means that the enumerator value is not representable in
20389 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20390 // are representable in some larger integral type and we allow it in
20391 // older language modes as an extension.
20392 // Exclude fixed enumerators since they are diagnosed with an error for
20393 // this case.
20394 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20395 Diag(IdLoc, getLangOpts().C23
20396 ? diag::warn_c17_compat_enum_value_not_int
20397 : diag::ext_c23_enum_value_not_int)
20398 << 1 << toString(EnumVal, 10) << 1;
20399 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20400 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20401 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20402 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20403 : diag::ext_c23_enum_value_not_int)
20404 << 1 << toString(EnumVal, 10) << 1;
20405 }
20406 }
20407 }
20408
20409 if (!EltTy->isDependentType()) {
20410 // Make the enumerator value match the signedness and size of the
20411 // enumerator's type.
20412 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20413 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20414 }
20415
20416 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20417 Val, EnumVal);
20418 }
20419
20420 SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20421 SourceLocation IILoc) {
20422 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20423 !getLangOpts().CPlusPlus)
20424 return SkipBodyInfo();
20425
20426 // We have an anonymous enum definition. Look up the first enumerator to
20427 // determine if we should merge the definition with an existing one and
20428 // skip the body.
20429 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20430 forRedeclarationInCurContext());
20431 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20432 if (!PrevECD)
20433 return SkipBodyInfo();
20434
20435 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20436 NamedDecl *Hidden;
20437 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20438 SkipBodyInfo Skip;
20439 Skip.Previous = Hidden;
20440 return Skip;
20441 }
20442
20443 return SkipBodyInfo();
20444 }
20445
20446 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20447 SourceLocation IdLoc, IdentifierInfo *Id,
20448 const ParsedAttributesView &Attrs,
20449 SourceLocation EqualLoc, Expr *Val,
20450 SkipBodyInfo *SkipBody) {
20451 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20452 EnumConstantDecl *LastEnumConst =
20453 cast_or_null<EnumConstantDecl>(lastEnumConst);
20454
20455 // The scope passed in may not be a decl scope. Zip up the scope tree until
20456 // we find one that is.
20457 S = getNonFieldDeclScope(S);
20458
20459 // Verify that there isn't already something declared with this name in this
20460 // scope.
20461 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20462 RedeclarationKind::ForVisibleRedeclaration);
20463 LookupName(R, S);
20464 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20465
20466 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20467 // Maybe we will complain about the shadowed template parameter.
20468 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20469 // Just pretend that we didn't see the previous declaration.
20470 PrevDecl = nullptr;
20471 }
20472
20473 // C++ [class.mem]p15:
20474 // If T is the name of a class, then each of the following shall have a name
20475 // different from T:
20476 // - every enumerator of every member of class T that is an unscoped
20477 // enumerated type
20478 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20479 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
20480 DeclarationNameInfo(Id, IdLoc)))
20481 return nullptr;
20482
20483 EnumConstantDecl *New =
20484 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20485 if (!New)
20486 return nullptr;
20487
20488 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20489 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20490 // Check for other kinds of shadowing not already handled.
20491 CheckShadow(New, PrevDecl, R);
20492 }
20493
20494 // When in C++, we may get a TagDecl with the same name; in this case the
20495 // enum constant will 'hide' the tag.
20496 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20497 "Received TagDecl when not in C++!");
20498 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20499 if (isa<EnumConstantDecl>(PrevDecl))
20500 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20501 else
20502 Diag(IdLoc, diag::err_redefinition) << Id;
20503 notePreviousDefinition(PrevDecl, IdLoc);
20504 return nullptr;
20505 }
20506 }
20507
20508 // Process attributes.
20509 ProcessDeclAttributeList(S, New, Attrs);
20510 AddPragmaAttributes(S, New);
20511 ProcessAPINotes(New);
20512
20513 // Register this decl in the current scope stack.
20514 New->setAccess(TheEnumDecl->getAccess());
20515 PushOnScopeChains(New, S);
20516
20517 ActOnDocumentableDecl(New);
20518
20519 return New;
20520 }
20521
20522 // Returns true when the enum initial expression does not trigger the
20523 // duplicate enum warning. A few common cases are exempted as follows:
20524 // Element2 = Element1
20525 // Element2 = Element1 + 1
20526 // Element2 = Element1 - 1
20527 // Where Element2 and Element1 are from the same enum.
20528 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20529 Expr *InitExpr = ECD->getInitExpr();
20530 if (!InitExpr)
20531 return true;
20532 InitExpr = InitExpr->IgnoreImpCasts();
20533
20534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20535 if (!BO->isAdditiveOp())
20536 return true;
20537 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20538 if (!IL)
20539 return true;
20540 if (IL->getValue() != 1)
20541 return true;
20542
20543 InitExpr = BO->getLHS();
20544 }
20545
20546 // This checks if the elements are from the same enum.
20547 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20548 if (!DRE)
20549 return true;
20550
20551 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20552 if (!EnumConstant)
20553 return true;
20554
20555 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
20556 Enum)
20557 return true;
20558
20559 return false;
20560 }
20561
20562 // Emits a warning when an element is implicitly set a value that
20563 // a previous element has already been set to.
20564 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20565 EnumDecl *Enum, QualType EnumType) {
20566 // Avoid anonymous enums
20567 if (!Enum->getIdentifier())
20568 return;
20569
20570 // Only check for small enums.
20571 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20572 return;
20573
20574 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20575 return;
20576
20577 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20578 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20579
20580 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20581
20582 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20583 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20584
20585 // Use int64_t as a key to avoid needing special handling for map keys.
20586 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20587 llvm::APSInt Val = D->getInitVal();
20588 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20589 };
20590
20591 DuplicatesVector DupVector;
20592 ValueToVectorMap EnumMap;
20593
20594 // Populate the EnumMap with all values represented by enum constants without
20595 // an initializer.
20596 for (auto *Element : Elements) {
20597 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20598
20599 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20600 // this constant. Skip this enum since it may be ill-formed.
20601 if (!ECD) {
20602 return;
20603 }
20604
20605 // Constants with initializers are handled in the next loop.
20606 if (ECD->getInitExpr())
20607 continue;
20608
20609 // Duplicate values are handled in the next loop.
20610 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20611 }
20612
20613 if (EnumMap.size() == 0)
20614 return;
20615
20616 // Create vectors for any values that has duplicates.
20617 for (auto *Element : Elements) {
20618 // The last loop returned if any constant was null.
20619 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
20620 if (!ValidDuplicateEnum(ECD, Enum))
20621 continue;
20622
20623 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20624 if (Iter == EnumMap.end())
20625 continue;
20626
20627 DeclOrVector& Entry = Iter->second;
20628 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20629 // Ensure constants are different.
20630 if (D == ECD)
20631 continue;
20632
20633 // Create new vector and push values onto it.
20634 auto Vec = std::make_unique<ECDVector>();
20635 Vec->push_back(D);
20636 Vec->push_back(ECD);
20637
20638 // Update entry to point to the duplicates vector.
20639 Entry = Vec.get();
20640
20641 // Store the vector somewhere we can consult later for quick emission of
20642 // diagnostics.
20643 DupVector.emplace_back(std::move(Vec));
20644 continue;
20645 }
20646
20647 ECDVector *Vec = cast<ECDVector *>(Entry);
20648 // Make sure constants are not added more than once.
20649 if (*Vec->begin() == ECD)
20650 continue;
20651
20652 Vec->push_back(ECD);
20653 }
20654
20655 // Emit diagnostics.
20656 for (const auto &Vec : DupVector) {
20657 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20658
20659 // Emit warning for one enum constant.
20660 auto *FirstECD = Vec->front();
20661 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20662 << FirstECD << toString(FirstECD->getInitVal(), 10)
20663 << FirstECD->getSourceRange();
20664
20665 // Emit one note for each of the remaining enum constants with
20666 // the same value.
20667 for (auto *ECD : llvm::drop_begin(*Vec))
20668 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20669 << ECD << toString(ECD->getInitVal(), 10)
20670 << ECD->getSourceRange();
20671 }
20672 }
20673
20674 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20675 bool AllowMask) const {
20676 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20677 assert(ED->isCompleteDefinition() && "expected enum definition");
20678
20679 auto R = FlagBitsCache.try_emplace(ED);
20680 llvm::APInt &FlagBits = R.first->second;
20681
20682 if (R.second) {
20683 for (auto *E : ED->enumerators()) {
20684 const auto &EVal = E->getInitVal();
20685 // Only single-bit enumerators introduce new flag values.
20686 if (EVal.isPowerOf2())
20687 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20688 }
20689 }
20690
20691 // A value is in a flag enum if either its bits are a subset of the enum's
20692 // flag bits (the first condition) or we are allowing masks and the same is
20693 // true of its complement (the second condition). When masks are allowed, we
20694 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20695 //
20696 // While it's true that any value could be used as a mask, the assumption is
20697 // that a mask will have all of the insignificant bits set. Anything else is
20698 // likely a logic error.
20699 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20700 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20701 }
20702
20703 // Emits a warning when a suspicious comparison operator is used along side
20704 // binary operators in enum initializers.
20705 static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20706 const EnumDecl *Enum) {
20707 bool HasBitwiseOp = false;
20708 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20709
20710 // Iterate over all the enum values, gather suspisious comparison ops and
20711 // whether any enum initialisers contain a binary operator.
20712 for (const auto *ECD : Enum->enumerators()) {
20713 const Expr *InitExpr = ECD->getInitExpr();
20714 if (!InitExpr)
20715 continue;
20716
20717 const Expr *E = InitExpr->IgnoreParenImpCasts();
20718
20719 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20720 BinaryOperatorKind Op = BinOp->getOpcode();
20721
20722 // Check for bitwise ops (<<, >>, &, |)
20723 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20724 HasBitwiseOp = true;
20725 } else if (Op == BO_LT || Op == BO_GT) {
20726 // Check for the typo pattern (Comparison < or >)
20727 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20728 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20729 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20730 if (IntLiteral->getValue() == 1)
20731 SuspiciousCompares.push_back(BinOp);
20732 }
20733 }
20734 }
20735 }
20736
20737 // If we found a bitwise op and some sus compares, iterate over the compares
20738 // and warn.
20739 if (HasBitwiseOp) {
20740 for (const auto *BinOp : SuspiciousCompares) {
20741 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20742 ? BinaryOperator::getOpcodeStr(BO_Shl)
20743 : BinaryOperator::getOpcodeStr(BO_Shr);
20744 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20745
20746 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20747 << BinOp->getOpcodeStr() << SuggestedOp;
20748
20749 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20750 << SuggestedOp
20751 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20752 }
20753 }
20754 }
20755
20756 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20757 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20758 const ParsedAttributesView &Attrs) {
20759 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20760 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20761
20762 ProcessDeclAttributeList(S, Enum, Attrs);
20763 ProcessAPINotes(Enum);
20764
20765 if (Enum->isDependentType()) {
20766 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20767 EnumConstantDecl *ECD =
20768 cast_or_null<EnumConstantDecl>(Elements[i]);
20769 if (!ECD) continue;
20770
20771 ECD->setType(EnumType);
20772 }
20773
20774 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20775 return;
20776 }
20777
20778 // Verify that all the values are okay, compute the size of the values, and
20779 // reverse the list.
20780 unsigned NumNegativeBits = 0;
20781 unsigned NumPositiveBits = 0;
20782 bool MembersRepresentableByInt =
20783 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20784
20785 // Figure out the type that should be used for this enum.
20786 QualType BestType;
20787 unsigned BestWidth;
20788
20789 // C++0x N3000 [conv.prom]p3:
20790 // An rvalue of an unscoped enumeration type whose underlying
20791 // type is not fixed can be converted to an rvalue of the first
20792 // of the following types that can represent all the values of
20793 // the enumeration: int, unsigned int, long int, unsigned long
20794 // int, long long int, or unsigned long long int.
20795 // C99 6.4.4.3p2:
20796 // An identifier declared as an enumeration constant has type int.
20797 // The C99 rule is modified by C23.
20798 QualType BestPromotionType;
20799
20800 bool Packed = Enum->hasAttr<PackedAttr>();
20801 // -fshort-enums is the equivalent to specifying the packed attribute on all
20802 // enum definitions.
20803 if (LangOpts.ShortEnums)
20804 Packed = true;
20805
20806 // If the enum already has a type because it is fixed or dictated by the
20807 // target, promote that type instead of analyzing the enumerators.
20808 if (Enum->isComplete()) {
20809 BestType = Enum->getIntegerType();
20810 if (Context.isPromotableIntegerType(BestType))
20811 BestPromotionType = Context.getPromotedIntegerType(BestType);
20812 else
20813 BestPromotionType = BestType;
20814
20815 BestWidth = Context.getIntWidth(BestType);
20816 } else {
20817 bool EnumTooLarge = Context.computeBestEnumTypes(
20818 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20819 BestWidth = Context.getIntWidth(BestType);
20820 if (EnumTooLarge)
20821 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20822 }
20823
20824 // Loop over all of the enumerator constants, changing their types to match
20825 // the type of the enum if needed.
20826 for (auto *D : Elements) {
20827 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20828 if (!ECD) continue; // Already issued a diagnostic.
20829
20830 // C99 says the enumerators have int type, but we allow, as an
20831 // extension, the enumerators to be larger than int size. If each
20832 // enumerator value fits in an int, type it as an int, otherwise type it the
20833 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20834 // that X has type 'int', not 'unsigned'.
20835
20836 // Determine whether the value fits into an int.
20837 llvm::APSInt InitVal = ECD->getInitVal();
20838
20839 // If it fits into an integer type, force it. Otherwise force it to match
20840 // the enum decl type.
20841 QualType NewTy;
20842 unsigned NewWidth;
20843 bool NewSign;
20844 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20845 MembersRepresentableByInt) {
20846 // C23 6.7.3.3.3p15:
20847 // The enumeration member type for an enumerated type without fixed
20848 // underlying type upon completion is:
20849 // - int if all the values of the enumeration are representable as an
20850 // int; or,
20851 // - the enumerated type
20852 NewTy = Context.IntTy;
20853 NewWidth = Context.getTargetInfo().getIntWidth();
20854 NewSign = true;
20855 } else if (ECD->getType() == BestType) {
20856 // Already the right type!
20857 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
20858 // C++ [dcl.enum]p4: Following the closing brace of an
20859 // enum-specifier, each enumerator has the type of its
20860 // enumeration.
20861 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20862 // with fixed underlying type is the enumerated type.
20863 ECD->setType(EnumType);
20864 continue;
20865 } else {
20866 NewTy = BestType;
20867 NewWidth = BestWidth;
20868 NewSign = BestType->isSignedIntegerOrEnumerationType();
20869 }
20870
20871 // Adjust the APSInt value.
20872 InitVal = InitVal.extOrTrunc(NewWidth);
20873 InitVal.setIsSigned(NewSign);
20874 ECD->setInitVal(Context, InitVal);
20875
20876 // Adjust the Expr initializer and type.
20877 if (ECD->getInitExpr() &&
20878 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20879 ECD->setInitExpr(ImplicitCastExpr::Create(
20880 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20881 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20882 if (getLangOpts().CPlusPlus ||
20883 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
20884 // C++ [dcl.enum]p4: Following the closing brace of an
20885 // enum-specifier, each enumerator has the type of its
20886 // enumeration.
20887 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20888 // with fixed underlying type is the enumerated type.
20889 ECD->setType(EnumType);
20890 else
20891 ECD->setType(NewTy);
20892 }
20893
20894 Enum->completeDefinition(BestType, BestPromotionType,
20895 NumPositiveBits, NumNegativeBits);
20896
20897 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20898 CheckForComparisonInEnumInitializer(*this, Enum);
20899
20900 if (Enum->isClosedFlag()) {
20901 for (Decl *D : Elements) {
20902 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20903 if (!ECD) continue; // Already issued a diagnostic.
20904
20905 llvm::APSInt InitVal = ECD->getInitVal();
20906 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20907 !IsValueInFlagEnum(Enum, InitVal, true))
20908 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20909 << ECD << Enum;
20910 }
20911 }
20912
20913 // Now that the enum type is defined, ensure it's not been underaligned.
20914 if (Enum->hasAttrs())
20915 CheckAlignasUnderalignment(Enum);
20916 }
20917
20918 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
20919 SourceLocation EndLoc) {
20920
20921 FileScopeAsmDecl *New =
20922 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20923 CurContext->addDecl(New);
20924 return New;
20925 }
20926
20927 TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20928 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20929 CurContext->addDecl(New);
20930 PushDeclContext(S, New);
20931 PushFunctionScope();
20932 PushCompoundScope(false);
20933 return New;
20934 }
20935
20936 void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20937 if (Statement)
20938 D->setStmt(Statement);
20939 PopCompoundScope();
20940 PopFunctionScopeInfo();
20941 PopDeclContext();
20942 }
20943
20944 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20945 IdentifierInfo* AliasName,
20946 SourceLocation PragmaLoc,
20947 SourceLocation NameLoc,
20948 SourceLocation AliasNameLoc) {
20949 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20950 LookupOrdinaryName);
20951 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20952 AttributeCommonInfo::Form::Pragma());
20953 AsmLabelAttr *Attr =
20954 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20955
20956 // If a declaration that:
20957 // 1) declares a function or a variable
20958 // 2) has external linkage
20959 // already exists, add a label attribute to it.
20960 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20961 if (isDeclExternC(PrevDecl))
20962 PrevDecl->addAttr(Attr);
20963 else
20964 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20965 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20966 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20967 } else
20968 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20969 }
20970
20971 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20972 SourceLocation PragmaLoc,
20973 SourceLocation NameLoc) {
20974 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20975
20976 if (PrevDecl) {
20977 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20978 } else {
20979 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20980 }
20981 }
20982
20983 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20984 IdentifierInfo* AliasName,
20985 SourceLocation PragmaLoc,
20986 SourceLocation NameLoc,
20987 SourceLocation AliasNameLoc) {
20988 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20989 LookupOrdinaryName);
20990 WeakInfo W = WeakInfo(Name, NameLoc);
20991
20992 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20993 if (!PrevDecl->hasAttr<AliasAttr>())
20994 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20995 DeclApplyPragmaWeak(TUScope, ND, W);
20996 } else {
20997 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20998 }
20999 }
21000
21001 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21002 bool Final) {
21003 assert(FD && "Expected non-null FunctionDecl");
21004
21005 // SYCL functions can be template, so we check if they have appropriate
21006 // attribute prior to checking if it is a template.
21007 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
21008 return FunctionEmissionStatus::Emitted;
21009
21010 // Templates are emitted when they're instantiated.
21011 if (FD->isDependentContext())
21012 return FunctionEmissionStatus::TemplateDiscarded;
21013
21014 // Check whether this function is an externally visible definition.
21015 auto IsEmittedForExternalSymbol = [this, FD]() {
21016 // We have to check the GVA linkage of the function's *definition* -- if we
21017 // only have a declaration, we don't know whether or not the function will
21018 // be emitted, because (say) the definition could include "inline".
21019 const FunctionDecl *Def = FD->getDefinition();
21020
21021 // We can't compute linkage when we skip function bodies.
21022 return Def && !Def->hasSkippedBody() &&
21023 !isDiscardableGVALinkage(
21024 getASTContext().GetGVALinkageForFunction(Def));
21025 };
21026
21027 if (LangOpts.OpenMPIsTargetDevice) {
21028 // In OpenMP device mode we will not emit host only functions, or functions
21029 // we don't need due to their linkage.
21030 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21031 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21032 // DevTy may be changed later by
21033 // #pragma omp declare target to(*) device_type(*).
21034 // Therefore DevTy having no value does not imply host. The emission status
21035 // will be checked again at the end of compilation unit with Final = true.
21036 if (DevTy)
21037 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21038 return FunctionEmissionStatus::OMPDiscarded;
21039 // If we have an explicit value for the device type, or we are in a target
21040 // declare context, we need to emit all extern and used symbols.
21041 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21042 if (IsEmittedForExternalSymbol())
21043 return FunctionEmissionStatus::Emitted;
21044 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21045 // we'll omit it.
21046 if (Final)
21047 return FunctionEmissionStatus::OMPDiscarded;
21048 } else if (LangOpts.OpenMP > 45) {
21049 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21050 // function. In 5.0, no_host was introduced which might cause a function to
21051 // be omitted.
21052 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21053 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21054 if (DevTy)
21055 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21056 return FunctionEmissionStatus::OMPDiscarded;
21057 }
21058
21059 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21060 return FunctionEmissionStatus::Emitted;
21061
21062 if (LangOpts.CUDA) {
21063 // When compiling for device, host functions are never emitted. Similarly,
21064 // when compiling for host, device and global functions are never emitted.
21065 // (Technically, we do emit a host-side stub for global functions, but this
21066 // doesn't count for our purposes here.)
21067 CUDAFunctionTarget T = CUDA().IdentifyTarget(FD);
21068 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21069 return FunctionEmissionStatus::CUDADiscarded;
21070 if (!LangOpts.CUDAIsDevice &&
21071 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21072 return FunctionEmissionStatus::CUDADiscarded;
21073
21074 if (IsEmittedForExternalSymbol())
21075 return FunctionEmissionStatus::Emitted;
21076
21077 // If FD is a virtual destructor of an explicit instantiation
21078 // of a template class, return Emitted.
21079 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
21080 if (Destructor->isVirtual()) {
21081 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21082 Destructor->getParent())) {
21083 TemplateSpecializationKind TSK =
21084 Spec->getTemplateSpecializationKind();
21085 if (TSK == TSK_ExplicitInstantiationDeclaration ||
21086 TSK == TSK_ExplicitInstantiationDefinition)
21087 return FunctionEmissionStatus::Emitted;
21088 }
21089 }
21090 }
21091 }
21092
21093 // Otherwise, the function is known-emitted if it's in our set of
21094 // known-emitted functions.
21095 return FunctionEmissionStatus::Unknown;
21096 }
21097
21098 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21099 // Host-side references to a __global__ function refer to the stub, so the
21100 // function itself is never emitted and therefore should not be marked.
21101 // If we have host fn calls kernel fn calls host+device, the HD function
21102 // does not get instantiated on the host. We model this by omitting at the
21103 // call to the kernel from the callgraph. This ensures that, when compiling
21104 // for host, only HD functions actually called from the host get marked as
21105 // known-emitted.
21106 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21107 CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global;
21108 }
21109
21110 bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21111 bool &Visible) {
21112 Visible = hasVisibleDefinition(D, Suggested);
21113 // The redefinition of D in the **current** TU is allowed if D is invisible or
21114 // D is defined in the global module of other module units. We didn't check if
21115 // it is in global module as, we'll check the redefinition in named module
21116 // later with better diagnostic message.
21117 return D->isInAnotherModuleUnit() || !Visible;
21118 }