clang 24.0.0git
SemaDecl.cpp
Go to the documentation of this file.
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"
16#include "clang/AST/ASTLambda.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"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
50#include "clang/Sema/SemaARM.h"
51#include "clang/Sema/SemaCUDA.h"
52#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaObjC.h"
57#include "clang/Sema/SemaPPC.h"
60#include "clang/Sema/SemaSYCL.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
85 }
86
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(*this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
156 Diag(NameLoc,
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(TD, NameLoc);
165 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(*SS, false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(*SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
318 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
319 SS->getScopeRep(), &II);
321 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
328 (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
333 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
335 SourceLocation(), QualifierLoc, II, NameLoc);
336 return ParsedType::make(T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(*SS, LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
396 bool MemberOfUnknownSpecialization;
398 TemplateName.setIdentifier(NewII, NameLoc);
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 PDiag(diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
433 SS->getScopeRep(), &II);
434 TypeLocBuilder TLB;
438 TL.setNameLoc(NameLoc);
440 }
441 [[fallthrough]];
444 Result.suppressDiagnostics();
445 return nullptr;
446
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
463 RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 IsImplicitTypename ? DiagCtorKind::Implicit
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
508 SS ? SS->getScopeRep() : std::nullopt,
509 FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
518 SS ? SS->getScopeRep() : std::nullopt, Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(T);
522 auto TL = TLB.push<TagTypeLoc>(T);
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
528 TN && !isa<ObjCTypeParamDecl>(TN)) {
529 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
530 SS ? SS->getScopeRep() : std::nullopt, TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
538 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
539 SS ? SS->getScopeRep() : std::nullopt,
540 UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(T);
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
583 (void)DiagnoseUseOfDecl(UD, NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
595 Template);
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
656 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
687}
688
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
702 return DeclSpec::TST_union;
704 return DeclSpec::TST_class;
706 return DeclSpec::TST_enum;
707 }
708 }
709
711}
712
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
719 return true;
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T, Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Corrected,
757 PDiag(IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Corrected,
765 PDiag(IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
769 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Corrected,
773 PDiag(IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
788 SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
792 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(II, IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, nullptr, true, TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(IILoc, IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(*SS, false))
822 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
828 } else if (isDependentScopeSpecifier(*SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
835
836 Diag(SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(*I))
857 return true;
858 }
859
860 return false;
861}
862
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
873 FixItTagName = "class ";
874 break;
875
877 FixItTagName = "enum ";
878 break;
879
881 FixItTagName = "struct ";
882 break;
883
885 FixItTagName = "__interface ";
886 break;
887
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
905 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(*Name, S, &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
952 if (Ivar.isInvalid())
954 if (Ivar.isUsable())
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1002 Context.getAssumedTemplateName(NameInfo.getName());
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1020 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1045 << Name << computeDeclContext(SS, false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1070 if (R.isInvalid())
1072 if (R.isUsable())
1073 return NameClassification::NonType(Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1083
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1100 }
1101
1105 break;
1106
1108 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1109 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1134 (IsFilteredTemplateName ||
1136 Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Result.begin(),
1159 Result.end());
1160 } else if (!Result.empty()) {
1162 *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(*Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1199 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1200 USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1205 Type);
1206 if (isa<TagType>(T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1228 DiagnoseUseOfDecl(Type, NameLoc);
1229 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(Class, NameLoc);
1243
1244 if (NextToken.is(tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Class);
1252 return ParsedType::make(T);
1253 }
1254
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1277 if ((NextToken.is(tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(Type, NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1293 return NameClassification::NonType(Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1298 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1299 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1310}
1311
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(*I, I.getAccess());
1354 Result.resolveKind();
1356 nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1383
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1416
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1449 }
1450}
1451
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1509 ArrayRef<ParmVarDecl *> Params) {
1510 for (ParmVarDecl *Param : Params)
1511 if (Param->getIdentifier()) {
1512 S->AddDecl(Param);
1513 IdResolver.AddDecl(Param);
1514 }
1515}
1516
1518 ArrayRef<ParmVarDecl *> Params) {
1519 // Remove in reverse so each name is the most recent one when it is removed.
1520 for (ParmVarDecl *Param : llvm::reverse(Params))
1521 if (Param->getIdentifier()) {
1522 IdResolver.RemoveDecl(Param);
1523 S->RemoveDecl(Param);
1524 }
1525}
1526
1528 // We assume that the caller has already called
1529 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1530 FunctionDecl *FD = D->getAsFunction();
1531 if (!FD)
1532 return;
1533
1534 // Same implementation as PushDeclContext, but enters the context
1535 // from the lexical parent, rather than the top-level class.
1536 assert(CurContext == FD->getLexicalParent() &&
1537 "The next DeclContext should be lexically contained in the current one.");
1538 CurContext = FD;
1540
1542}
1543
1545 // Same implementation as PopDeclContext, but returns to the lexical parent,
1546 // rather than the top-level class.
1547 assert(CurContext && "DeclContext imbalance!");
1548 CurContext = CurContext->getLexicalParent();
1549 assert(CurContext && "Popped translation unit!");
1550}
1551
1552/// Determine whether overloading is allowed for a new function
1553/// declaration considering prior declarations of the same name.
1554///
1555/// This routine determines whether overloading is possible, not
1556/// whether a new declaration actually overloads a previous one.
1557/// It will return true in C++ (where overloads are always permitted)
1558/// or, as a C extension, when either the new declaration or a
1559/// previous one is declared with the 'overloadable' attribute.
1561 ASTContext &Context,
1562 const FunctionDecl *New) {
1563 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1564 return true;
1565
1566 // Multiversion function declarations are not overloads in the
1567 // usual sense of that term, but lookup will report that an
1568 // overload set was found if more than one multiversion function
1569 // declaration is present for the same name. It is therefore
1570 // inadequate to assume that some prior declaration(s) had
1571 // the overloadable attribute; checking is required. Since one
1572 // declaration is permitted to omit the attribute, it is necessary
1573 // to check at least two; hence the 'any_of' check below. Note that
1574 // the overloadable attribute is implicitly added to declarations
1575 // that were required to have it but did not.
1576 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1577 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1578 return ND->hasAttr<OverloadableAttr>();
1579 });
1580 } else if (Previous.getResultKind() == LookupResultKind::Found)
1581 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1582
1583 return false;
1584}
1585
1586void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1587 // Move up the scope chain until we find the nearest enclosing
1588 // non-transparent context. The declaration will be introduced into this
1589 // scope.
1590 while (S->getEntity() && S->getEntity()->isTransparentContext())
1591 S = S->getParent();
1592
1593 // Add scoped declarations into their context, so that they can be
1594 // found later. Declarations without a context won't be inserted
1595 // into any context.
1596 if (AddToContext)
1597 CurContext->addDecl(D);
1598
1599 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1600 // are function-local declarations.
1601 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1602 if (!S->getFnParent())
1603 return;
1604
1605 // Even inside a function, an out-of-line definition of a type that is
1606 // nested inside a local class must not be pushed into the enclosing
1607 // function scope. For example:
1608 //
1609 // class A { public: class B; };
1610 // class A::B {}; // out-of-line definition inside the function
1611 // B b; // must fail - only A::B is valid
1612 // Wrapper{B{}} // must also fail
1613 //
1614 // Per C++ scoping rules only the qualified form A::B is accessible.
1615 // Without this guard, PushOnScopeChains would add B to the function's
1616 // local scope, making it findable via unqualified lookup, which is
1617 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1618 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1619 // of a local class being defined out-of-line.
1621 return;
1622 }
1623
1624 // Template instantiations should also not be pushed into scope.
1625 if (isa<FunctionDecl>(D) &&
1626 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1627 return;
1628
1629 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1630 S->AddDecl(D);
1631 return;
1632 }
1633 // If this replaces anything in the current scope,
1635 IEnd = IdResolver.end();
1636 for (; I != IEnd; ++I) {
1637 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1638 S->RemoveDecl(*I);
1639 IdResolver.RemoveDecl(*I);
1640
1641 // Should only need to replace one decl.
1642 break;
1643 }
1644 }
1645
1646 S->AddDecl(D);
1647
1648 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1649 // Implicitly-generated labels may end up getting generated in an order that
1650 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1651 // the label at the appropriate place in the identifier chain.
1652 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1653 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1654 if (IDC == CurContext) {
1655 if (!S->isDeclScope(*I))
1656 continue;
1657 } else if (IDC->Encloses(CurContext))
1658 break;
1659 }
1660
1661 IdResolver.InsertDeclAfter(I, D);
1662 } else {
1663 IdResolver.AddDecl(D);
1664 }
1666}
1667
1669 bool AllowInlineNamespace) const {
1670 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1671}
1672
1674 bool AllowInlineNamespace) const {
1675 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1676 return true;
1677
1678 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D))
1679 return isDeclInScope(Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1680
1681 return false;
1682}
1683
1685 DeclContext *TargetDC = DC->getPrimaryContext();
1686 do {
1687 if (DeclContext *ScopeDC = S->getEntity())
1688 if (ScopeDC->getPrimaryContext() == TargetDC)
1689 return S;
1690 } while ((S = S->getParent()));
1691
1692 return nullptr;
1693}
1694
1696 DeclContext*,
1697 ASTContext&);
1698
1700 bool ConsiderLinkage,
1701 bool AllowInlineNamespace) {
1702 LookupResult::Filter F = R.makeFilter();
1703 while (F.hasNext()) {
1704 NamedDecl *D = F.next();
1705
1706 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1707 continue;
1708
1709 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1710 continue;
1711
1712 F.erase();
1713 }
1714
1715 F.done();
1716}
1717
1719 if (auto *VD = dyn_cast<VarDecl>(D))
1720 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1721 if (auto *FD = dyn_cast<FunctionDecl>(D))
1722 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1723 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1724 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1725
1726 return false;
1727}
1728
1730 // [module.interface]p7:
1731 // A declaration is attached to a module as follows:
1732 // - If the declaration is a non-dependent friend declaration that nominates a
1733 // function with a declarator-id that is a qualified-id or template-id or that
1734 // nominates a class other than with an elaborated-type-specifier with neither
1735 // a nested-name-specifier nor a simple-template-id, it is attached to the
1736 // module to which the friend is attached ([basic.link]).
1737 if (New->getFriendObjectKind() &&
1738 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1739 New->setLocalOwningModule(Old->getOwningModule());
1741 return false;
1742 }
1743
1744 // Although we have questions for the module ownership of implicit
1745 // instantiations, it should be sure that we shouldn't diagnose the
1746 // redeclaration of incorrect module ownership for different implicit
1747 // instantiations in different modules. We will diagnose the redeclaration of
1748 // incorrect module ownership for the template itself.
1750 return false;
1751
1752 Module *NewM = New->getOwningModule();
1753 Module *OldM = Old->getOwningModule();
1754
1755 if (NewM && NewM->isPrivateModule())
1756 NewM = NewM->Parent;
1757 if (OldM && OldM->isPrivateModule())
1758 OldM = OldM->Parent;
1759
1760 if (NewM == OldM)
1761 return false;
1762
1763 if (NewM && OldM) {
1764 // A module implementation unit has visibility of the decls in its
1765 // implicitly imported interface.
1766 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1767 return false;
1768
1769 // Partitions are part of the module, but a partition could import another
1770 // module, so verify that the PMIs agree.
1771 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1772 getASTContext().isInSameModule(NewM, OldM))
1773 return false;
1774 }
1775
1776 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1777 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1778 if (NewIsModuleInterface || OldIsModuleInterface) {
1779 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1780 // if a declaration of D [...] appears in the purview of a module, all
1781 // other such declarations shall appear in the purview of the same module
1782 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1783 << New
1784 << NewIsModuleInterface
1785 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1786 << OldIsModuleInterface
1787 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1788 Diag(Old->getLocation(), diag::note_previous_declaration);
1789 New->setInvalidDecl();
1790 return true;
1791 }
1792
1793 return false;
1794}
1795
1797 // [module.interface]p1:
1798 // An export-declaration shall inhabit a namespace scope.
1799 //
1800 // So it is meaningless to talk about redeclaration which is not at namespace
1801 // scope.
1802 if (!New->getLexicalDeclContext()
1803 ->getNonTransparentContext()
1804 ->isFileContext() ||
1805 !Old->getLexicalDeclContext()
1807 ->isFileContext())
1808 return false;
1809
1810 bool IsNewExported = New->isInExportDeclContext();
1811 bool IsOldExported = Old->isInExportDeclContext();
1812
1813 // It should be irrevelant if both of them are not exported.
1814 if (!IsNewExported && !IsOldExported)
1815 return false;
1816
1817 if (IsOldExported)
1818 return false;
1819
1820 // If the Old declaration are not attached to named modules
1821 // and the New declaration are attached to global module.
1822 // It should be fine to allow the export since it doesn't change
1823 // the linkage of declarations. See
1824 // https://github.com/llvm/llvm-project/issues/98583 for details.
1825 if (!Old->isInNamedModule() && New->getOwningModule() &&
1826 New->getOwningModule()->isImplicitGlobalModule())
1827 return false;
1828
1829 assert(IsNewExported);
1830
1831 auto Lk = Old->getFormalLinkage();
1832 int S = 0;
1833 if (Lk == Linkage::Internal)
1834 S = 1;
1835 else if (Lk == Linkage::Module)
1836 S = 2;
1837 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1838 Diag(Old->getLocation(), diag::note_previous_declaration);
1839 return true;
1840}
1841
1844 return true;
1845
1847 return true;
1848
1849 return false;
1850}
1851
1853 const NamedDecl *Old) const {
1854 assert(getASTContext().isSameEntity(New, Old) &&
1855 "New and Old are not the same definition, we should diagnostic it "
1856 "immediately instead of checking it.");
1857 assert(const_cast<Sema *>(this)->isReachable(New) &&
1858 const_cast<Sema *>(this)->isReachable(Old) &&
1859 "We shouldn't see unreachable definitions here.");
1860
1861 Module *NewM = New->getOwningModule();
1862 Module *OldM = Old->getOwningModule();
1863
1864 // We only checks for named modules here. The header like modules is skipped.
1865 // FIXME: This is not right if we import the header like modules in the module
1866 // purview.
1867 //
1868 // For example, assuming "header.h" provides definition for `D`.
1869 // ```C++
1870 // //--- M.cppm
1871 // export module M;
1872 // import "header.h"; // or #include "header.h" but import it by clang modules
1873 // actually.
1874 //
1875 // //--- Use.cpp
1876 // import M;
1877 // import "header.h"; // or uses clang modules.
1878 // ```
1879 //
1880 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1881 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1882 // reject it. But the current implementation couldn't detect the case since we
1883 // don't record the information about the importee modules.
1884 //
1885 // But this might not be painful in practice. Since the design of C++20 Named
1886 // Modules suggests us to use headers in global module fragment instead of
1887 // module purview.
1888 if (NewM && NewM->isHeaderLikeModule())
1889 NewM = nullptr;
1890 if (OldM && OldM->isHeaderLikeModule())
1891 OldM = nullptr;
1892
1893 if (!NewM && !OldM)
1894 return true;
1895
1896 // [basic.def.odr]p14.3
1897 // Each such definition shall not be attached to a named module
1898 // ([module.unit]).
1899 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1900 return true;
1901
1902 // Then New and Old lives in the same TU if their share one same module unit.
1903 if (NewM)
1904 NewM = NewM->getTopLevelModule();
1905 if (OldM)
1906 OldM = OldM->getTopLevelModule();
1907 return OldM == NewM;
1908}
1909
1911 if (D->getDeclContext()->isFileContext())
1912 return false;
1913
1914 return isa<UsingShadowDecl>(D) ||
1917}
1918
1919/// Removes using shadow declarations not at class scope from the lookup
1920/// results.
1922 LookupResult::Filter F = R.makeFilter();
1923 while (F.hasNext())
1925 F.erase();
1926
1927 F.done();
1928}
1929
1930/// Check for this common pattern:
1931/// @code
1932/// class S {
1933/// S(const S&); // DO NOT IMPLEMENT
1934/// void operator=(const S&); // DO NOT IMPLEMENT
1935/// };
1936/// @endcode
1938 // FIXME: Should check for private access too but access is set after we get
1939 // the decl here.
1941 return false;
1942
1943 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1944 return CD->isCopyConstructor();
1945 return D->isCopyAssignmentOperator();
1946}
1947
1948bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1949 const DeclContext *DC = D->getDeclContext();
1950 while (!DC->isTranslationUnit()) {
1951 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1952 if (!RD->hasNameForLinkage())
1953 return true;
1954 }
1955 DC = DC->getParent();
1956 }
1957
1958 return !D->isExternallyVisible();
1959}
1960
1962 assert(D);
1963
1964 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1965 return false;
1966
1967 // Ignore all entities declared within templates, and out-of-line definitions
1968 // of members of class templates.
1969 if (D->getDeclContext()->isDependentContext() ||
1971 return false;
1972
1973 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1974 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1975 return false;
1976 // A non-out-of-line declaration of a member specialization was implicitly
1977 // instantiated; it's the out-of-line declaration that we're interested in.
1978 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1979 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1980 return false;
1981
1982 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1983 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1984 return false;
1985 } else {
1986 // 'static inline' functions are defined in headers; don't warn.
1987 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1988 return false;
1989 }
1990
1991 if (FD->doesThisDeclarationHaveABody() &&
1992 Context.DeclMustBeEmitted(FD))
1993 return false;
1994 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1995 // Constants and utility variables are defined in headers with internal
1996 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1997 // like "inline".)
1998 if (!isMainFileLoc(VD->getLocation()))
1999 return false;
2000
2001 if (Context.DeclMustBeEmitted(VD))
2002 return false;
2003
2004 if (VD->isStaticDataMember() &&
2005 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2006 return false;
2007 if (VD->isStaticDataMember() &&
2008 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2009 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
2010 return false;
2011
2012 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
2013 return false;
2014 } else {
2015 return false;
2016 }
2017
2018 // Only warn for unused decls internal to the translation unit.
2019 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2020 // for inline functions defined in the main source file, for instance.
2021 return mightHaveNonExternalLinkage(D);
2022}
2023
2025 if (!D)
2026 return;
2027
2028 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2029 const FunctionDecl *First = FD->getFirstDecl();
2031 return; // First should already be in the vector.
2032 }
2033
2034 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2035 const VarDecl *First = VD->getFirstDecl();
2037 return; // First should already be in the vector.
2038 }
2039
2041 UnusedFileScopedDecls.push_back(D);
2042}
2043
2044static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2045 const NamedDecl *D) {
2046 if (D->isInvalidDecl())
2047 return false;
2048
2049 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2050 // For a decomposition declaration, warn if none of the bindings are
2051 // referenced, instead of if the variable itself is referenced (which
2052 // it is, by the bindings' expressions).
2053 bool IsAllIgnored = true;
2054 for (const auto *BD : DD->bindings()) {
2055 if (BD->isReferenced())
2056 return false;
2057 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2058 BD->hasAttr<UnusedAttr>());
2059 }
2060 if (IsAllIgnored)
2061 return false;
2062 } else if (!D->getDeclName()) {
2063 return false;
2064 } else if (D->isReferenced() || D->isUsed()) {
2065 return false;
2066 }
2067
2068 if (D->isPlaceholderVar(LangOpts))
2069 return false;
2070
2071 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2072 D->hasAttr<CleanupAttr>())
2073 return false;
2074
2075 if (isa<LabelDecl>(D))
2076 return true;
2077
2078 // Except for labels, we only care about unused decls that are local to
2079 // functions.
2080 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2081 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2082 // For dependent types, the diagnostic is deferred.
2083 WithinFunction =
2084 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2085 if (!WithinFunction)
2086 return false;
2087
2088 if (isa<TypedefNameDecl>(D))
2089 return true;
2090
2091 // White-list anything that isn't a local variable.
2093 return false;
2094
2095 // Types of valid local variables should be complete, so this should succeed.
2096 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2097
2098 const Expr *Init = VD->getInit();
2099 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2100 Init = Cleanups->getSubExpr();
2101
2102 const auto *Ty = VD->getType().getTypePtr();
2103
2104 // Only look at the outermost level of typedef.
2105 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2106 // Allow anything marked with __attribute__((unused)).
2107 if (TT->getDecl()->hasAttr<UnusedAttr>())
2108 return false;
2109 }
2110
2111 // Warn for reference variables whose initializtion performs lifetime
2112 // extension.
2113 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2114 MTE && MTE->getExtendingDecl()) {
2115 Ty = VD->getType().getNonReferenceType().getTypePtr();
2116 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2117 }
2118
2119 // If we failed to complete the type for some reason, or if the type is
2120 // dependent, don't diagnose the variable.
2121 if (Ty->isIncompleteType() || Ty->isDependentType())
2122 return false;
2123
2124 // Look at the element type to ensure that the warning behaviour is
2125 // consistent for both scalars and arrays.
2126 Ty = Ty->getBaseElementTypeUnsafe();
2127
2128 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2129 if (Tag->hasAttr<UnusedAttr>())
2130 return false;
2131
2132 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2133 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2134 return false;
2135
2136 if (Init) {
2137 const auto *Construct =
2138 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2139 if (Construct && !Construct->isElidable()) {
2140 const CXXConstructorDecl *CD = Construct->getConstructor();
2141 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2142 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2143 return false;
2144 }
2145
2146 // Suppress the warning if we don't know how this is constructed, and
2147 // it could possibly be non-trivial constructor.
2148 if (Init->isTypeDependent()) {
2149 for (const CXXConstructorDecl *Ctor : RD->ctors())
2150 if (!Ctor->isTrivial())
2151 return false;
2152 }
2153
2154 // Suppress the warning if the constructor is unresolved because
2155 // its arguments are dependent.
2157 return false;
2158 }
2159 }
2160 }
2161
2162 // TODO: __attribute__((unused)) templates?
2163 }
2164
2165 return true;
2166}
2167
2169 FixItHint &Hint) {
2170 if (isa<LabelDecl>(D)) {
2172 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2173 /*SkipTrailingWhitespaceAndNewline=*/false);
2174 if (AfterColon.isInvalid())
2175 return;
2177 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2178 }
2179}
2180
2183 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2184}
2185
2187 DiagReceiverTy DiagReceiver) {
2188 if (D->isDependentType())
2189 return;
2190
2191 for (auto *TmpD : D->decls()) {
2192 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2193 DiagnoseUnusedDecl(T, DiagReceiver);
2194 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2195 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2196 }
2197}
2198
2201 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2202}
2203
2206 return;
2207
2208 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2209 // typedefs can be referenced later on, so the diagnostics are emitted
2210 // at end-of-translation-unit.
2212 return;
2213 }
2214
2215 FixItHint Hint;
2217
2218 unsigned DiagID;
2219 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2220 DiagID = diag::warn_unused_exception_param;
2221 else if (isa<LabelDecl>(D))
2222 DiagID = diag::warn_unused_label;
2223 else
2224 DiagID = diag::warn_unused_variable;
2225
2226 SourceLocation DiagLoc = D->getLocation();
2227 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2228}
2229
2231 DiagReceiverTy DiagReceiver) {
2232 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2233 // it's not really unused.
2234 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2235 return;
2236
2237 // In C++, `_` variables behave as if they were maybe_unused
2238 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2239 return;
2240
2241 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2242
2243 if (Ty->isReferenceType() || Ty->isDependentType())
2244 return;
2245
2246 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2247 if (Tag->hasAttr<UnusedAttr>())
2248 return;
2249 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2250 // mimic gcc's behavior.
2251 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2252 RD && !RD->hasAttr<WarnUnusedAttr>())
2253 return;
2254 }
2255
2256 // Don't warn on volatile file-scope variables. They are visible beyond their
2257 // declaring function and writes to them could be observable side effects.
2258 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2259 return;
2260
2261 // Don't warn about __block Objective-C pointer variables, as they might
2262 // be assigned in the block but not used elsewhere for the purpose of lifetime
2263 // extension.
2264 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2265 return;
2266
2267 // Don't warn about Objective-C pointer variables with precise lifetime
2268 // semantics; they can be used to ensure ARC releases the object at a known
2269 // time, which may mean assignment but no other references.
2270 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2271 return;
2272
2273 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2274 if (iter == RefsMinusAssignments.end())
2275 return;
2276
2277 assert(iter->getSecond() >= 0 &&
2278 "Found a negative number of references to a VarDecl");
2279 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2280 // Assume the given VarDecl is "used" if its ref count stored in
2281 // `RefMinusAssignments` is positive, with one exception.
2282 //
2283 // For a C++ variable whose decl (with initializer) entirely consist the
2284 // condition expression of a if/while/for construct,
2285 // Clang creates a DeclRefExpr for the condition expression rather than a
2286 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2287 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2288 // used in the body of the if/while/for construct.
2289 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2290 if (!UnusedCXXCondDecl)
2291 return;
2292 }
2293
2294 unsigned DiagID;
2295 if (isa<ParmVarDecl>(VD))
2296 DiagID = diag::warn_unused_but_set_parameter;
2297 else if (VD->isFileVarDecl())
2298 DiagID = diag::warn_unused_but_set_global;
2299 else
2300 DiagID = diag::warn_unused_but_set_variable;
2301 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2302}
2303
2305 Sema::DiagReceiverTy DiagReceiver) {
2306 // Verify that we have no forward references left. If so, there was a goto
2307 // or address of a label taken, but no definition of it. Label fwd
2308 // definitions are indicated with a null substmt which is also not a resolved
2309 // MS inline assembly label name.
2310 bool Diagnose = false;
2311 if (L->isMSAsmLabel())
2312 Diagnose = !L->isResolvedMSAsmLabel();
2313 else
2314 Diagnose = L->getStmt() == nullptr;
2315 if (Diagnose)
2316 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2317 << L);
2318}
2319
2321 S->applyNRVO();
2322
2323 if (S->decl_empty()) return;
2325 "Scope shouldn't contain decls!");
2326
2327 /// We visit the decls in non-deterministic order, but we want diagnostics
2328 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2329 /// and sort the diagnostics before emitting them, after we visited all decls.
2330 struct LocAndDiag {
2331 SourceLocation Loc;
2332 std::optional<SourceLocation> PreviousDeclLoc;
2334 };
2336 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2337 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2338 };
2339 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2340 SourceLocation PreviousDeclLoc,
2341 PartialDiagnostic PD) {
2342 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2343 };
2344
2345 for (auto *TmpD : S->decls()) {
2346 assert(TmpD && "This decl didn't get pushed??");
2347
2348 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2349 NamedDecl *D = cast<NamedDecl>(TmpD);
2350
2351 // Diagnose unused variables in this scope.
2353 DiagnoseUnusedDecl(D, addDiag);
2354 if (const auto *RD = dyn_cast<RecordDecl>(D))
2355 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2356 // Wait until end of TU to diagnose internal linkage file vars.
2357 if (auto *VD = dyn_cast<VarDecl>(D);
2358 VD && !VD->isInternalLinkageFileVar()) {
2359 DiagnoseUnusedButSetDecl(VD, addDiag);
2360 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2361 }
2362 }
2363
2364 if (!D->getDeclName()) continue;
2365
2366 // If this was a forward reference to a label, verify it was defined.
2367 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2368 CheckPoppedLabel(LD, *this, addDiag);
2369
2370 // Partial translation units that are created in incremental processing must
2371 // not clean up the IdResolver because PTUs should take into account the
2372 // declarations that came from previous PTUs.
2373 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2375 IdResolver.RemoveDecl(D);
2376
2377 // Warn on it if we are shadowing a declaration.
2378 auto ShadowI = ShadowingDecls.find(D);
2379 if (ShadowI != ShadowingDecls.end()) {
2380 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2381 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2382 PDiag(diag::warn_ctor_parm_shadows_field)
2383 << D << FD << FD->getParent());
2384 }
2385 ShadowingDecls.erase(ShadowI);
2386 }
2387 }
2388
2389 llvm::sort(DeclDiags,
2390 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2391 // The particular order for diagnostics is not important, as long
2392 // as the order is deterministic. Using the raw location is going
2393 // to generally be in source order unless there are macro
2394 // expansions involved.
2395 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2396 });
2397 for (const LocAndDiag &D : DeclDiags) {
2398 Diag(D.Loc, D.PD);
2399 if (D.PreviousDeclLoc)
2400 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2401 }
2402}
2403
2405 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2406 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2407 (S->isClassScope() && !getLangOpts().CPlusPlus))
2408 S = S->getParent();
2409 return S;
2410}
2411
2412static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2414 switch (Error) {
2416 return "";
2418 return BuiltinInfo.getHeaderName(ID);
2420 return "stdio.h";
2422 return "setjmp.h";
2424 return "ucontext.h";
2425 }
2426 llvm_unreachable("unhandled error kind");
2427}
2428
2430 unsigned ID, SourceLocation Loc) {
2431 DeclContext *Parent = Context.getTranslationUnitDecl();
2432
2433 if (getLangOpts().CPlusPlus) {
2435 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2436 CLinkageDecl->setImplicit();
2437 Parent->addDecl(CLinkageDecl);
2438 Parent = CLinkageDecl;
2439 }
2440
2442 if (Context.BuiltinInfo.isImmediate(ID)) {
2443 assert(getLangOpts().CPlusPlus20 &&
2444 "consteval builtins should only be available in C++20 mode");
2445 ConstexprKind = ConstexprSpecKind::Consteval;
2446 }
2447
2449 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2450 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2451 Type->isFunctionProtoType(), ConstexprKind);
2452 New->setImplicit();
2453 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2454
2455 // Create Decl objects for each parameter, adding them to the
2456 // FunctionDecl.
2457 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2459 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2461 Context, New, SourceLocation(), SourceLocation(), nullptr,
2462 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2463 parm->setScopeInfo(0, i);
2464 Params.push_back(parm);
2465 }
2466 New->setParams(Params);
2467 }
2468
2470 return New;
2471}
2472
2474 Scope *S, bool ForRedeclaration,
2475 SourceLocation Loc) {
2477
2479 QualType R = Context.GetBuiltinType(ID, Error);
2480 if (Error) {
2481 if (!ForRedeclaration)
2482 return nullptr;
2483
2484 // If we have a builtin without an associated type we should not emit a
2485 // warning when we were not able to find a type for it.
2487 Context.BuiltinInfo.allowTypeMismatch(ID))
2488 return nullptr;
2489
2490 // If we could not find a type for setjmp it is because the jmp_buf type was
2491 // not defined prior to the setjmp declaration.
2493 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2494 << Context.BuiltinInfo.getName(ID);
2495 return nullptr;
2496 }
2497
2498 // Generally, we emit a warning that the declaration requires the
2499 // appropriate header.
2500 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2501 << getHeaderName(Context.BuiltinInfo, ID, Error)
2502 << Context.BuiltinInfo.getName(ID);
2503 return nullptr;
2504 }
2505
2506 if (!ForRedeclaration &&
2507 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2508 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2509 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2510 : diag::ext_implicit_lib_function_decl)
2511 << Context.BuiltinInfo.getName(ID) << R;
2512 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2513 Diag(Loc, diag::note_include_header_or_declare)
2514 << Header << Context.BuiltinInfo.getName(ID);
2515 }
2516
2517 if (R.isNull())
2518 return nullptr;
2519
2520 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2522
2523 // TUScope is the translation-unit scope to insert this function into.
2524 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2525 // relate Scopes to DeclContexts, and probably eliminate CurContext
2526 // entirely, but we're not there yet.
2527 DeclContext *SavedContext = CurContext;
2528 CurContext = New->getDeclContext();
2530 CurContext = SavedContext;
2531 return New;
2532}
2533
2534/// Typedef declarations don't have linkage, but they still denote the same
2535/// entity if their types are the same.
2536/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2537/// isSameEntity.
2538static void
2541 // This is only interesting when modules are enabled.
2542 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2543 return;
2544
2545 // Empty sets are uninteresting.
2546 if (Previous.empty())
2547 return;
2548
2549 LookupResult::Filter Filter = Previous.makeFilter();
2550 while (Filter.hasNext()) {
2551 NamedDecl *Old = Filter.next();
2552
2553 // Non-hidden declarations are never ignored.
2554 if (S.isVisible(Old))
2555 continue;
2556
2557 // Declarations of the same entity are not ignored, even if they have
2558 // different linkages.
2559 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2560 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2561 Decl->getUnderlyingType()))
2562 continue;
2563
2564 // If both declarations give a tag declaration a typedef name for linkage
2565 // purposes, then they declare the same entity.
2566 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2567 Decl->getAnonDeclWithTypedefName())
2568 continue;
2569 }
2570
2571 Filter.erase();
2572 }
2573
2574 Filter.done();
2575}
2576
2578 QualType OldType;
2579 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2580 OldType = OldTypedef->getUnderlyingType();
2581 else
2582 OldType = Context.getTypeDeclType(Old);
2583 QualType NewType = New->getUnderlyingType();
2584
2585 if (NewType->isVariablyModifiedType()) {
2586 // Must not redefine a typedef with a variably-modified type.
2587 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2588 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2589 << Kind << NewType;
2590 if (Old->getLocation().isValid())
2591 notePreviousDefinition(Old, New->getLocation());
2592 New->setInvalidDecl();
2593 return true;
2594 }
2595
2596 if (OldType != NewType &&
2597 !OldType->isDependentType() &&
2598 !NewType->isDependentType() &&
2599 !Context.hasSameType(OldType, NewType)) {
2600 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2601 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2602 << Kind << NewType << OldType;
2603 if (Old->getLocation().isValid())
2604 notePreviousDefinition(Old, New->getLocation());
2605 New->setInvalidDecl();
2606 return true;
2607 }
2608 return false;
2609}
2610
2612 LookupResult &OldDecls) {
2613 // If the new decl is known invalid already, don't bother doing any
2614 // merging checks.
2615 if (New->isInvalidDecl()) return;
2616
2617 // Allow multiple definitions for ObjC built-in typedefs.
2618 // FIXME: Verify the underlying types are equivalent!
2619 if (getLangOpts().ObjC) {
2620 const IdentifierInfo *TypeID = New->getIdentifier();
2621 switch (TypeID->getLength()) {
2622 default: break;
2623 case 2:
2624 {
2625 if (!TypeID->isStr("id"))
2626 break;
2627 QualType T = New->getUnderlyingType();
2628 if (!T->isPointerType())
2629 break;
2630 if (!T->isVoidPointerType()) {
2631 QualType PT = T->castAs<PointerType>()->getPointeeType();
2632 if (!PT->isStructureType())
2633 break;
2634 }
2635 Context.setObjCIdRedefinitionType(T);
2636 // Install the built-in type for 'id', ignoring the current definition.
2637 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2638 Context.getObjCIdType());
2639 return;
2640 }
2641 case 5:
2642 if (!TypeID->isStr("Class"))
2643 break;
2644 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2645 // Install the built-in type for 'Class', ignoring the current definition.
2646 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2647 Context.getObjCClassType());
2648 return;
2649 case 3:
2650 if (!TypeID->isStr("SEL"))
2651 break;
2652 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2653 // Install the built-in type for 'SEL', ignoring the current definition.
2654 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2655 Context.getObjCSelType());
2656 return;
2657 }
2658 // Fall through - the typedef name was not a builtin type.
2659 }
2660
2661 // Verify the old decl was also a type.
2662 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2663 if (!Old) {
2664 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2665 << New->getDeclName();
2666
2667 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2668 if (OldD->getLocation().isValid())
2669 notePreviousDefinition(OldD, New->getLocation());
2670
2671 return New->setInvalidDecl();
2672 }
2673
2674 // If the old declaration is invalid, just give up here.
2675 if (Old->isInvalidDecl())
2676 return New->setInvalidDecl();
2677
2678 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2679 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2680 auto *NewTag = New->getAnonDeclWithTypedefName();
2681 NamedDecl *Hidden = nullptr;
2682 if (OldTag && NewTag &&
2683 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2684 !hasVisibleDefinition(OldTag, &Hidden)) {
2685 // There is a definition of this tag, but it is not visible. Use it
2686 // instead of our tag.
2687 if (OldTD->isModed())
2688 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2689 OldTD->getUnderlyingType());
2690 else
2691 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2692
2693 // An anonymous enum is recognized as a redeclaration only when its
2694 // typedef name gets merged, at which point the new enum and its
2695 // enumerators already have a distinct canonical type. Link the enum
2696 // declarations, but also retype the new enumerators because
2697 // setPreviousDecl() does not update QualTypes built before the merge;
2698 // otherwise the merged typedef and its enumerators disagree on the type
2699 // (GH213299).
2700 //
2701 // FIXME: The global module restriction only limits the impact of this
2702 // change; relax it if the issue shows up in other contexts.
2703 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2704 if (auto *NewEnum = dyn_cast<EnumDecl>(NewTag)) {
2705 if (auto *OldEnum = dyn_cast<EnumDecl>(OldTag)) {
2706 NewEnum->setPreviousDecl(OldEnum);
2707 QualType EnumType = Context.getCanonicalTagType(OldEnum);
2708 for (auto *ECD : NewEnum->enumerators())
2709 ECD->setType(EnumType);
2710 }
2711 }
2712 }
2713
2714 // Make the old tag definition visible.
2716
2718 }
2719 }
2720
2721 // If the typedef types are not identical, reject them in all languages and
2722 // with any extensions enabled.
2723 if (isIncompatibleTypedef(Old, New))
2724 return;
2725
2726 // The types match. Link up the redeclaration chain and merge attributes if
2727 // the old declaration was a typedef.
2728 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2729 New->setPreviousDecl(Typedef);
2731 }
2732
2733 if (getLangOpts().MicrosoftExt)
2734 return;
2735
2736 if (getLangOpts().CPlusPlus) {
2737 // C++ [dcl.typedef]p2:
2738 // In a given non-class scope, a typedef specifier can be used to
2739 // redefine the name of any type declared in that scope to refer
2740 // to the type to which it already refers.
2742 return;
2743
2744 // C++0x [dcl.typedef]p4:
2745 // In a given class scope, a typedef specifier can be used to redefine
2746 // any class-name declared in that scope that is not also a typedef-name
2747 // to refer to the type to which it already refers.
2748 //
2749 // This wording came in via DR424, which was a correction to the
2750 // wording in DR56, which accidentally banned code like:
2751 //
2752 // struct S {
2753 // typedef struct A { } A;
2754 // };
2755 //
2756 // in the C++03 standard. We implement the C++0x semantics, which
2757 // allow the above but disallow
2758 //
2759 // struct S {
2760 // typedef int I;
2761 // typedef int I;
2762 // };
2763 //
2764 // since that was the intent of DR56.
2765 if (!isa<TypedefNameDecl>(Old))
2766 return;
2767
2768 Diag(New->getLocation(), diag::err_redefinition)
2769 << New->getDeclName();
2770 notePreviousDefinition(Old, New->getLocation());
2771 return New->setInvalidDecl();
2772 }
2773
2774 // Modules always permit redefinition of typedefs, as does C11.
2775 if (getLangOpts().Modules || getLangOpts().C11)
2776 return;
2777
2778 // If we have a redefinition of a typedef in C, emit a warning. This warning
2779 // is normally mapped to an error, but can be controlled with
2780 // -Wtypedef-redefinition. If either the original or the redefinition is
2781 // in a system header, don't emit this for compatibility with GCC.
2782 if (getDiagnostics().getSuppressSystemWarnings() &&
2783 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2784 (Old->isImplicit() ||
2785 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2786 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2787 return;
2788
2789 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2790 << New->getDeclName();
2791 notePreviousDefinition(Old, New->getLocation());
2792}
2793
2795 // If this was an unscoped enumeration, yank all of its enumerators
2796 // out of the scope.
2797 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2798 Scope *EnumScope = getNonFieldDeclScope(S);
2799 for (auto *ECD : ED->enumerators()) {
2800 assert(EnumScope->isDeclScope(ECD));
2801 EnumScope->RemoveDecl(ECD);
2802 IdResolver.RemoveDecl(ECD);
2803 }
2804 }
2805}
2806
2807/// DeclhasAttr - returns true if decl Declaration already has the target
2808/// attribute.
2809static bool DeclHasAttr(const Decl *D, const Attr *A) {
2810 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2811 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2812 for (const auto *i : D->attrs())
2813 if (i->getKind() == A->getKind()) {
2814 if (Ann) {
2815 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2816 return true;
2817 continue;
2818 }
2819 // FIXME: Don't hardcode this check
2820 if (OA && isa<OwnershipAttr>(i))
2821 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2822 return true;
2823 }
2824
2825 return false;
2826}
2827
2829 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2830 return VD->isThisDeclarationADefinition();
2831 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2832 return TD->isCompleteDefinition() || TD->isBeingDefined();
2833 return true;
2834}
2835
2836/// Merge alignment attributes from \p Old to \p New, taking into account the
2837/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2838///
2839/// \return \c true if any attributes were added to \p New.
2840static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2841 // Look for alignas attributes on Old, and pick out whichever attribute
2842 // specifies the strictest alignment requirement.
2843 AlignedAttr *OldAlignasAttr = nullptr;
2844 AlignedAttr *OldStrictestAlignAttr = nullptr;
2845 unsigned OldAlign = 0;
2846 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2847 // FIXME: We have no way of representing inherited dependent alignments
2848 // in a case like:
2849 // template<int A, int B> struct alignas(A) X;
2850 // template<int A, int B> struct alignas(B) X {};
2851 // For now, we just ignore any alignas attributes which are not on the
2852 // definition in such a case.
2853 if (I->isAlignmentDependent())
2854 return false;
2855
2856 if (I->isAlignas())
2857 OldAlignasAttr = I;
2858
2859 unsigned Align = I->getAlignment(S.Context);
2860 if (Align > OldAlign) {
2861 OldAlign = Align;
2862 OldStrictestAlignAttr = I;
2863 }
2864 }
2865
2866 // Look for alignas attributes on New.
2867 AlignedAttr *NewAlignasAttr = nullptr;
2868 unsigned NewAlign = 0;
2869 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2870 if (I->isAlignmentDependent())
2871 return false;
2872
2873 if (I->isAlignas())
2874 NewAlignasAttr = I;
2875
2876 unsigned Align = I->getAlignment(S.Context);
2877 if (Align > NewAlign)
2878 NewAlign = Align;
2879 }
2880
2881 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2882 // Both declarations have 'alignas' attributes. We require them to match.
2883 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2884 // fall short. (If two declarations both have alignas, they must both match
2885 // every definition, and so must match each other if there is a definition.)
2886
2887 // If either declaration only contains 'alignas(0)' specifiers, then it
2888 // specifies the natural alignment for the type.
2889 if (OldAlign == 0 || NewAlign == 0) {
2890 QualType Ty;
2891 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2892 Ty = VD->getType();
2893 else
2895
2896 if (OldAlign == 0)
2897 OldAlign = S.Context.getTypeAlign(Ty);
2898 if (NewAlign == 0)
2899 NewAlign = S.Context.getTypeAlign(Ty);
2900 }
2901
2902 if (OldAlign != NewAlign) {
2903 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2906 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2907 }
2908 }
2909
2910 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2911 // C++11 [dcl.align]p6:
2912 // if any declaration of an entity has an alignment-specifier,
2913 // every defining declaration of that entity shall specify an
2914 // equivalent alignment.
2915 // C11 6.7.5/7:
2916 // If the definition of an object does not have an alignment
2917 // specifier, any other declaration of that object shall also
2918 // have no alignment specifier.
2919 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2920 << OldAlignasAttr;
2921 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2922 << OldAlignasAttr;
2923 }
2924
2925 bool AnyAdded = false;
2926
2927 // Ensure we have an attribute representing the strictest alignment.
2928 if (OldAlign > NewAlign) {
2929 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2930 Clone->setInherited(true);
2931 New->addAttr(Clone);
2932 AnyAdded = true;
2933 }
2934
2935 // Ensure we have an alignas attribute if the old declaration had one.
2936 if (OldAlignasAttr && !NewAlignasAttr &&
2937 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2938 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2939 Clone->setInherited(true);
2940 New->addAttr(Clone);
2941 AnyAdded = true;
2942 }
2943
2944 return AnyAdded;
2945}
2946
2947#define WANT_DECL_MERGE_LOGIC
2948#include "clang/Sema/AttrParsedAttrImpl.inc"
2949#undef WANT_DECL_MERGE_LOGIC
2950
2952 const InheritableAttr *Attr,
2954 // Diagnose any mutual exclusions between the attribute that we want to add
2955 // and attributes that already exist on the declaration.
2956 if (!DiagnoseMutualExclusions(S, D, Attr))
2957 return false;
2958
2959 // This function copies an attribute Attr from a previous declaration to the
2960 // new declaration D if the new declaration doesn't itself have that attribute
2961 // yet or if that attribute allows duplicates.
2962 // If you're adding a new attribute that requires logic different from
2963 // "use explicit attribute on decl if present, else use attribute from
2964 // previous decl", for example if the attribute needs to be consistent
2965 // between redeclarations, you need to call a custom merge function here.
2966 InheritableAttr *NewAttr = nullptr;
2967 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2968 const IdentifierInfo *InferredPlatformII = nullptr;
2969 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2970 InferredPlatformII = Inf->getPlatform();
2972 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2973 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2974 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2975 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2976 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2977 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2978 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2979 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2980 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2981 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2982 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2983 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2984 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2985 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2986 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2987 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2988 FA->getFirstArg());
2989 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2990 NewAttr = S.mergeFormatMatchesAttr(
2991 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2992 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2993 NewAttr = S.mergeModularFormatAttr(
2994 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2995 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2996 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2997 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2998 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2999 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
3000 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
3001 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
3002 IA->getInheritanceModel());
3003 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
3004 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
3005 &S.Context.Idents.get(AA->getSpelling()));
3006 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
3009 // CUDA target attributes are part of function signature for
3010 // overloading purposes and must not be merged.
3011 return false;
3012 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
3013 NewAttr = S.mergeMinSizeAttr(D, *MA);
3014 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
3015 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
3016 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Attr))
3017 NewAttr = S.Swift().mergeAttrAttr(D, *SAA);
3018 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
3019 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
3020 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
3021 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
3022 else if (isa<AlignedAttr>(Attr))
3023 // AlignedAttrs are handled separately, because we need to handle all
3024 // such attributes on a declaration at the same time.
3025 NewAttr = nullptr;
3030 NewAttr = nullptr;
3031 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
3032 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
3033 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
3034 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
3035 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
3036 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
3037 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Attr))
3038 NewAttr = S.Wasm().mergeExportNameAttr(D, *ENA);
3039 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
3040 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
3041 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
3042 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
3043 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
3044 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
3045 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
3046 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
3047 NT->getZ());
3048 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
3049 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
3050 WS->getPreferred(),
3051 WS->getSpelledArgsCount());
3052 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
3053 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
3054 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3055 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3056 else if (isa<SuppressAttr>(Attr))
3057 // Do nothing. Each redeclaration should be suppressed separately.
3058 NewAttr = nullptr;
3059 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
3060 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
3061 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3062 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3063 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
3064 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
3065
3066 if (NewAttr) {
3067 NewAttr->setInherited(true);
3068 D->addAttr(NewAttr);
3069 if (isa<MSInheritanceAttr>(NewAttr))
3071 return true;
3072 }
3073
3074 return false;
3075}
3076
3077static const NamedDecl *getDefinition(const Decl *D) {
3078 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3079 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3080 return Def;
3081 return nullptr;
3082 }
3083 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3084 const VarDecl *Def = VD->getDefinition();
3085 if (Def)
3086 return Def;
3087 return VD->getActingDefinition();
3088 }
3089 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3090 const FunctionDecl *Def = nullptr;
3091 if (FD->isDefined(Def, true))
3092 return Def;
3093 }
3094 return nullptr;
3095}
3096
3097static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3098 for (const auto *Attribute : D->attrs())
3099 if (Attribute->getKind() == Kind)
3100 return true;
3101 return false;
3102}
3103
3104/// checkNewAttributesAfterDef - If we already have a definition, check that
3105/// there are no new attributes in this declaration.
3106static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3107 if (!New->hasAttrs())
3108 return;
3109
3110 const NamedDecl *Def = getDefinition(Old);
3111 if (!Def || Def == New)
3112 return;
3113
3114 AttrVec &NewAttributes = New->getAttrs();
3115 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3116 Attr *NewAttribute = NewAttributes[I];
3117
3118 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3120 SkipBodyInfo SkipBody;
3121 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3122
3123 // If we're skipping this definition, drop the "alias" attribute.
3124 if (SkipBody.ShouldSkip) {
3125 NewAttributes.erase(NewAttributes.begin() + I);
3126 --E;
3127 continue;
3128 }
3129 } else {
3130 VarDecl *VD = cast<VarDecl>(New);
3131 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3133 ? diag::err_alias_after_tentative
3134 : diag::err_redefinition;
3135 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3136 if (Diag == diag::err_redefinition)
3137 S.notePreviousDefinition(Def, VD->getLocation());
3138 else
3139 S.Diag(Def->getLocation(), diag::note_previous_definition);
3140 VD->setInvalidDecl();
3141 }
3142 ++I;
3143 continue;
3144 }
3145
3146 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3147 // Tentative definitions are only interesting for the alias check above.
3148 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3149 ++I;
3150 continue;
3151 }
3152 }
3153
3154 if (hasAttribute(Def, NewAttribute->getKind())) {
3155 ++I;
3156 continue; // regular attr merging will take care of validating this.
3157 }
3158
3159 if (NewAttribute->getLocation().isInvalid()) {
3160 // An attribute with no source location was not written by the user. API
3161 // notes, in particular, are matched against whichever declaration the
3162 // compiler reaches, which can be a redeclaration that follows the
3163 // definition, possibly in a different module. There is nothing for the
3164 // user to correct, and erasing the attribute would silently change what
3165 // the annotated API means.
3166 ++I;
3167 continue;
3168 }
3169
3170 if (isa<C11NoReturnAttr>(NewAttribute)) {
3171 // C's _Noreturn is allowed to be added to a function after it is defined.
3172 ++I;
3173 continue;
3174 } else if (isa<UuidAttr>(NewAttribute)) {
3175 // msvc will allow a subsequent definition to add an uuid to a class
3176 ++I;
3177 continue;
3179 NewAttribute) &&
3180 NewAttribute->isStandardAttributeSyntax()) {
3181 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3182 // deprecated attribute can later be re-declared with the attribute and
3183 // vice-versa.
3184 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3185 // maybe_unused attribute can later be redeclared with the attribute and
3186 // vice versa.
3187 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3188 // nodiscard attribute can later be redeclared with the attribute and
3189 // vice-versa.
3190 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3191 ++I;
3192 continue;
3193 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3194 if (AA->isAlignas()) {
3195 // C++11 [dcl.align]p6:
3196 // if any declaration of an entity has an alignment-specifier,
3197 // every defining declaration of that entity shall specify an
3198 // equivalent alignment.
3199 // C11 6.7.5/7:
3200 // If the definition of an object does not have an alignment
3201 // specifier, any other declaration of that object shall also
3202 // have no alignment specifier.
3203 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3204 << AA;
3205 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3206 << AA;
3207 NewAttributes.erase(NewAttributes.begin() + I);
3208 --E;
3209 continue;
3210 }
3211 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3212 // If there is a C definition followed by a redeclaration with this
3213 // attribute then there are two different definitions. In C++, prefer the
3214 // standard diagnostics.
3215 if (!S.getLangOpts().CPlusPlus) {
3216 S.Diag(NewAttribute->getLocation(),
3217 diag::err_loader_uninitialized_redeclaration);
3218 S.Diag(Def->getLocation(), diag::note_previous_definition);
3219 NewAttributes.erase(NewAttributes.begin() + I);
3220 --E;
3221 continue;
3222 }
3223 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3224 cast<VarDecl>(New)->isInline() &&
3225 !cast<VarDecl>(New)->isInlineSpecified()) {
3226 // Don't warn about applying selectany to implicitly inline variables.
3227 // Older compilers and language modes would require the use of selectany
3228 // to make such variables inline, and it would have no effect if we
3229 // honored it.
3230 ++I;
3231 continue;
3232 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3233 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3234 // declarations after definitions.
3235 ++I;
3236 continue;
3237 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3238 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3239 // error since the definition will have already been created without
3240 // the semantic effects of the attribute having been applied.
3241 S.Diag(NewAttribute->getLocation(),
3242 diag::err_sycl_entry_point_after_definition)
3243 << NewAttribute;
3244 S.Diag(Def->getLocation(), diag::note_previous_definition);
3245 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3246 ++I;
3247 continue;
3248 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3249 // SYCLExternalAttr may be added after a definition.
3250 ++I;
3251 continue;
3252 }
3253
3254 S.Diag(NewAttribute->getLocation(),
3255 diag::warn_attribute_precede_definition);
3256 S.Diag(Def->getLocation(), diag::note_previous_definition);
3257 NewAttributes.erase(NewAttributes.begin() + I);
3258 --E;
3259 }
3260}
3261
3262static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3263 const ConstInitAttr *CIAttr,
3264 bool AttrBeforeInit) {
3265 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3266
3267 // Figure out a good way to write this specifier on the old declaration.
3268 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3269 // enough of the attribute list spelling information to extract that without
3270 // heroics.
3271 std::string SuitableSpelling;
3272 if (S.getLangOpts().CPlusPlus20)
3273 SuitableSpelling = std::string(
3274 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3275 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3276 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3277 InsertLoc, {tok::l_square, tok::l_square,
3278 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3279 S.PP.getIdentifierInfo("require_constant_initialization"),
3280 tok::r_square, tok::r_square}));
3281 if (SuitableSpelling.empty())
3282 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3283 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3284 S.PP.getIdentifierInfo("require_constant_initialization"),
3285 tok::r_paren, tok::r_paren}));
3286 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3287 SuitableSpelling = "constinit";
3288 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3289 SuitableSpelling = "[[clang::require_constant_initialization]]";
3290 if (SuitableSpelling.empty())
3291 SuitableSpelling = "__attribute__((require_constant_initialization))";
3292 SuitableSpelling += " ";
3293
3294 if (AttrBeforeInit) {
3295 // extern constinit int a;
3296 // int a = 0; // error (missing 'constinit'), accepted as extension
3297 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3298 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3299 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3300 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3301 } else {
3302 // int a = 0;
3303 // constinit extern int a; // error (missing 'constinit')
3304 S.Diag(CIAttr->getLocation(),
3305 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3306 : diag::warn_require_const_init_added_too_late)
3307 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3308 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3309 << CIAttr->isConstinit()
3310 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3311 }
3312}
3313
3316 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3317 UsedAttr *NewAttr = OldAttr->clone(Context);
3318 NewAttr->setInherited(true);
3319 New->addAttr(NewAttr);
3320 }
3321 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3322 RetainAttr *NewAttr = OldAttr->clone(Context);
3323 NewAttr->setInherited(true);
3324 New->addAttr(NewAttr);
3325 }
3326
3327 if (!Old->hasAttrs() && !New->hasAttrs())
3328 return;
3329
3330 // [dcl.constinit]p1:
3331 // If the [constinit] specifier is applied to any declaration of a
3332 // variable, it shall be applied to the initializing declaration.
3333 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3334 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3335 if (bool(OldConstInit) != bool(NewConstInit)) {
3336 const auto *OldVD = cast<VarDecl>(Old);
3337 auto *NewVD = cast<VarDecl>(New);
3338
3339 // Find the initializing declaration. Note that we might not have linked
3340 // the new declaration into the redeclaration chain yet.
3341 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3342 if (!InitDecl &&
3343 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3344 InitDecl = NewVD;
3345
3346 if (InitDecl == NewVD) {
3347 // This is the initializing declaration. If it would inherit 'constinit',
3348 // that's ill-formed. (Note that we do not apply this to the attribute
3349 // form).
3350 if (OldConstInit && OldConstInit->isConstinit())
3351 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3352 /*AttrBeforeInit=*/true);
3353 } else if (NewConstInit) {
3354 // This is the first time we've been told that this declaration should
3355 // have a constant initializer. If we already saw the initializing
3356 // declaration, this is too late.
3357 if (InitDecl && InitDecl != NewVD) {
3358 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3359 /*AttrBeforeInit=*/false);
3360 NewVD->dropAttr<ConstInitAttr>();
3361 }
3362 }
3363 }
3364
3365 // Attributes declared post-definition are currently ignored.
3366 checkNewAttributesAfterDef(*this, New, Old);
3367
3368 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3369 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3370 if (!OldA->isEquivalent(NewA)) {
3371 // This redeclaration changes __asm__ label.
3372 Diag(New->getLocation(), diag::err_different_asm_label);
3373 Diag(OldA->getLocation(), diag::note_previous_declaration);
3374 }
3375 } else if (Old->isUsed()) {
3376 // This redeclaration adds an __asm__ label to a declaration that has
3377 // already been ODR-used.
3378 Diag(New->getLocation(), diag::err_late_asm_label_name)
3379 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3380 }
3381 }
3382
3383 // Re-declaration cannot add abi_tag's.
3384 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3385 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3386 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3387 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3388 Diag(NewAbiTagAttr->getLocation(),
3389 diag::err_new_abi_tag_on_redeclaration)
3390 << NewTag;
3391 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3392 }
3393 }
3394 } else {
3395 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3396 Diag(Old->getLocation(), diag::note_previous_declaration);
3397 }
3398 }
3399
3400 // This redeclaration adds a section attribute.
3401 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3402 if (auto *VD = dyn_cast<VarDecl>(New)) {
3403 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3404 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3405 Diag(Old->getLocation(), diag::note_previous_declaration);
3406 }
3407 }
3408 }
3409
3410 // Redeclaration adds code-seg attribute.
3411 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3412 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3413 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3414 Diag(New->getLocation(), diag::warn_mismatched_section)
3415 << 0 /*codeseg*/;
3416 Diag(Old->getLocation(), diag::note_previous_declaration);
3417 }
3418
3419 if (!Old->hasAttrs())
3420 return;
3421
3422 bool foundAny = New->hasAttrs();
3423
3424 // Ensure that any moving of objects within the allocated map is done before
3425 // we process them.
3426 if (!foundAny) New->setAttrs(AttrVec());
3427
3428 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3429 // Ignore deprecated/unavailable/availability attributes if requested.
3431 if (isa<DeprecatedAttr>(I) ||
3434 switch (AMK) {
3436 continue;
3437
3442 LocalAMK = AMK;
3443 break;
3444 }
3445 }
3446
3447 // Already handled.
3448 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3449 continue;
3450
3451 // Don't propagate inferred noreturn or conflicting inline attributes to
3452 // explicit specializations.
3454 isa<NoInlineAttr>(I)) {
3455 if (auto *FD = dyn_cast<FunctionDecl>(New);
3456 FD &&
3457 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3458 continue;
3459 }
3460
3461 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3462 foundAny = true;
3463 }
3464
3465 if (mergeAlignedAttrs(*this, New, Old))
3466 foundAny = true;
3467
3468 if (!foundAny) New->dropAttrs();
3469}
3470
3472 for (const Attr *A : D->attrs())
3473 checkAttrIsTypeDependent(D, A);
3474}
3475
3476// Returns the number of added attributes.
3477template <class T>
3478static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3479 Sema &S) {
3480 unsigned found = 0;
3481 for (const auto *I : From->specific_attrs<T>()) {
3482 if (!DeclHasAttr(To, I)) {
3483 T *newAttr = cast<T>(I->clone(S.Context));
3484 newAttr->setInherited(true);
3485 To->addAttr(newAttr);
3486 ++found;
3487 }
3488 }
3489 return found;
3490}
3491
3492template <class F>
3493static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3494 F &&propagator) {
3495 if (!From->hasAttrs()) {
3496 return;
3497 }
3498
3499 bool foundAny = To->hasAttrs();
3500
3501 // Ensure that any moving of objects within the allocated map is
3502 // done before we process them.
3503 if (!foundAny)
3504 To->setAttrs(AttrVec());
3505
3506 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3507
3508 if (!foundAny)
3509 To->dropAttrs();
3510}
3511
3512/// mergeParamDeclAttributes - Copy attributes from the old parameter
3513/// to the new one.
3515 const ParmVarDecl *oldDecl, Sema &S) {
3517 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3518 unsigned found = 0;
3519 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3520 // Propagate the lifetimebound attribute from parameters to the
3521 // most recent declaration. Note that this doesn't include the implicit
3522 // 'this' parameter, as the attribute is applied to the function type in
3523 // that case.
3524 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3525 return found;
3526 });
3527}
3528
3530 const ASTContext &Ctx) {
3531
3532 auto NoSizeInfo = [&Ctx](QualType Ty) {
3533 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3534 return true;
3535 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3536 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3537 return false;
3538 };
3539
3540 // `type[]` is equivalent to `type *` and `type[*]`.
3541 if (NoSizeInfo(Old) && NoSizeInfo(New))
3542 return true;
3543
3544 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3545 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3546 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3547 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3548 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3549 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3550 return false;
3551 return true;
3552 }
3553
3554 // Only compare size, ignore Size modifiers and CVR.
3555 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3556 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3558 }
3559
3560 // Don't try to compare dependent sized array
3561 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3562 return true;
3563 }
3564
3565 return Old == New;
3566}
3567
3568static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3569 const ParmVarDecl *OldParam,
3570 Sema &S) {
3571 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3572 if (auto Newnullability = NewParam->getType()->getNullability()) {
3573 if (*Oldnullability != *Newnullability) {
3574 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3576 *Newnullability,
3578 != 0))
3580 *Oldnullability,
3582 != 0));
3583 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3584 }
3585 } else {
3586 QualType NewT = NewParam->getType();
3587 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3588 NewParam->setType(NewT);
3589 }
3590 }
3591 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3592 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3593 if (OldParamDT && NewParamDT &&
3594 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3595 QualType OldParamOT = OldParamDT->getOriginalType();
3596 QualType NewParamOT = NewParamDT->getOriginalType();
3597 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3598 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3599 << NewParam << NewParamOT;
3600 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3601 << OldParamOT;
3602 }
3603 }
3604}
3605
3606namespace {
3607
3608/// Used in MergeFunctionDecl to keep track of function parameters in
3609/// C.
3610struct GNUCompatibleParamWarning {
3611 ParmVarDecl *OldParm;
3612 ParmVarDecl *NewParm;
3613 QualType PromotedType;
3614};
3615
3616} // end anonymous namespace
3617
3618// Determine whether the previous declaration was a definition, implicit
3619// declaration, or a declaration.
3620template <typename T>
3621static std::pair<diag::kind, SourceLocation>
3623 diag::kind PrevDiag;
3624 SourceLocation OldLocation = Old->getLocation();
3625 if (Old->isThisDeclarationADefinition())
3626 PrevDiag = diag::note_previous_definition;
3627 else if (Old->isImplicit()) {
3628 PrevDiag = diag::note_previous_implicit_declaration;
3629 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3630 if (FD->getBuiltinID())
3631 PrevDiag = diag::note_previous_builtin_declaration;
3632 }
3633 if (OldLocation.isInvalid())
3634 OldLocation = New->getLocation();
3635 } else
3636 PrevDiag = diag::note_previous_declaration;
3637 return std::make_pair(PrevDiag, OldLocation);
3638}
3639
3640/// canRedefineFunction - checks if a function can be redefined. Currently,
3641/// only extern inline functions can be redefined, and even then only in
3642/// GNU89 mode.
3643static bool canRedefineFunction(const FunctionDecl *FD,
3644 const LangOptions& LangOpts) {
3645 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3646 !LangOpts.CPlusPlus &&
3647 FD->isInlineSpecified() &&
3648 FD->getStorageClass() == SC_Extern);
3649}
3650
3651const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3652 const AttributedType *AT = T->getAs<AttributedType>();
3653 while (AT && !AT->isCallingConv())
3654 AT = AT->getModifiedType()->getAs<AttributedType>();
3655 return AT;
3656}
3657
3658template <typename T>
3659static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3660 const DeclContext *DC = Old->getDeclContext();
3661 if (DC->isRecord())
3662 return false;
3663
3664 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3665 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3666 return true;
3667 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3668 return true;
3669 return false;
3670}
3671
3672template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3673static bool isExternC(VarTemplateDecl *) { return false; }
3674static bool isExternC(FunctionTemplateDecl *) { return false; }
3675
3676/// Check whether a redeclaration of an entity introduced by a
3677/// using-declaration is valid, given that we know it's not an overload
3678/// (nor a hidden tag declaration).
3679template<typename ExpectedDecl>
3681 ExpectedDecl *New) {
3682 // C++11 [basic.scope.declarative]p4:
3683 // Given a set of declarations in a single declarative region, each of
3684 // which specifies the same unqualified name,
3685 // -- they shall all refer to the same entity, or all refer to functions
3686 // and function templates; or
3687 // -- exactly one declaration shall declare a class name or enumeration
3688 // name that is not a typedef name and the other declarations shall all
3689 // refer to the same variable or enumerator, or all refer to functions
3690 // and function templates; in this case the class name or enumeration
3691 // name is hidden (3.3.10).
3692
3693 // C++11 [namespace.udecl]p14:
3694 // If a function declaration in namespace scope or block scope has the
3695 // same name and the same parameter-type-list as a function introduced
3696 // by a using-declaration, and the declarations do not declare the same
3697 // function, the program is ill-formed.
3698
3699 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3700 if (Old &&
3701 !Old->getDeclContext()->getRedeclContext()->Equals(
3702 New->getDeclContext()->getRedeclContext()) &&
3703 !(isExternC(Old) && isExternC(New)))
3704 Old = nullptr;
3705
3706 if (!Old) {
3707 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3708 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3709 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3710 return true;
3711 }
3712 return false;
3713}
3714
3716 const FunctionDecl *B) {
3717 assert(A->getNumParams() == B->getNumParams());
3718
3719 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3720 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3721 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3722 if (AttrA == AttrB)
3723 return true;
3724 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3725 AttrA->isDynamic() == AttrB->isDynamic();
3726 };
3727
3728 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3729}
3730
3731/// If necessary, adjust the semantic declaration context for a qualified
3732/// declaration to name the correct inline namespace within the qualifier.
3734 DeclaratorDecl *OldD) {
3735 // The only case where we need to update the DeclContext is when
3736 // redeclaration lookup for a qualified name finds a declaration
3737 // in an inline namespace within the context named by the qualifier:
3738 //
3739 // inline namespace N { int f(); }
3740 // int ::f(); // Sema DC needs adjusting from :: to N::.
3741 //
3742 // For unqualified declarations, the semantic context *can* change
3743 // along the redeclaration chain (for local extern declarations,
3744 // extern "C" declarations, and friend declarations in particular).
3745 if (!NewD->getQualifier())
3746 return;
3747
3748 // NewD is probably already in the right context.
3749 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3750 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3751 if (NamedDC->Equals(SemaDC))
3752 return;
3753
3754 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3755 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3756 "unexpected context for redeclaration");
3757
3758 auto *LexDC = NewD->getLexicalDeclContext();
3759 auto FixSemaDC = [=](NamedDecl *D) {
3760 if (!D)
3761 return;
3762 D->setDeclContext(SemaDC);
3763 D->setLexicalDeclContext(LexDC);
3764 };
3765
3766 FixSemaDC(NewD);
3767 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3768 FixSemaDC(FD->getDescribedFunctionTemplate());
3769 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3770 FixSemaDC(VD->getDescribedVarTemplate());
3771}
3772
3774 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3775 // Verify the old decl was also a function.
3776 FunctionDecl *Old = OldD->getAsFunction();
3777 if (!Old) {
3778 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3779 // We don't need to check the using friend pattern from other module unit
3780 // since we should have diagnosed such cases in its unit already.
3781 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3782 Diag(New->getLocation(), diag::err_using_decl_friend);
3783 Diag(Shadow->getTargetDecl()->getLocation(),
3784 diag::note_using_decl_target);
3785 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3786 << 0;
3787 return true;
3788 }
3789
3790 // Check whether the two declarations might declare the same function or
3791 // function template.
3792 if (FunctionTemplateDecl *NewTemplate =
3793 New->getDescribedFunctionTemplate()) {
3795 NewTemplate))
3796 return true;
3797 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3798 ->getAsFunction();
3799 } else {
3800 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3801 return true;
3802 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3803 }
3804 } else {
3805 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3806 << New->getDeclName();
3807 notePreviousDefinition(OldD, New->getLocation());
3808 return true;
3809 }
3810 }
3811
3812 // If the old declaration was found in an inline namespace and the new
3813 // declaration was qualified, update the DeclContext to match.
3815
3816 // If the old declaration is invalid, just give up here.
3817 if (Old->isInvalidDecl())
3818 return true;
3819
3820 // Disallow redeclaration of some builtins.
3821 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3822 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3823 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3824 << Old << Old->getType();
3825 return true;
3826 }
3827
3828 diag::kind PrevDiag;
3829 SourceLocation OldLocation;
3830 std::tie(PrevDiag, OldLocation) =
3832
3833 // Don't complain about this if we're in GNU89 mode and the old function
3834 // is an extern inline function.
3835 // Don't complain about specializations. They are not supposed to have
3836 // storage classes.
3837 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3838 New->getStorageClass() == SC_Static &&
3839 Old->hasExternalFormalLinkage() &&
3840 !New->getTemplateSpecializationInfo() &&
3842 if (getLangOpts().MicrosoftExt) {
3843 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3844 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3845 } else {
3846 Diag(New->getLocation(), diag::err_static_non_static)
3847 << New << /*MixedLinkageUB=*/false;
3848 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3849 return true;
3850 }
3851 }
3852
3853 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3854 if (!Old->hasAttr<InternalLinkageAttr>()) {
3855 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3856 << ILA;
3857 Diag(Old->getLocation(), diag::note_previous_declaration);
3858 New->dropAttr<InternalLinkageAttr>();
3859 }
3860
3861 if (auto *EA = New->getAttr<ErrorAttr>()) {
3862 if (!Old->hasAttr<ErrorAttr>()) {
3863 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3864 Diag(Old->getLocation(), diag::note_previous_declaration);
3865 New->dropAttr<ErrorAttr>();
3866 }
3867 }
3868
3870 return true;
3871
3872 if (!getLangOpts().CPlusPlus) {
3873 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3874 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3875 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3876 << New << OldOvl;
3877
3878 // Try our best to find a decl that actually has the overloadable
3879 // attribute for the note. In most cases (e.g. programs with only one
3880 // broken declaration/definition), this won't matter.
3881 //
3882 // FIXME: We could do this if we juggled some extra state in
3883 // OverloadableAttr, rather than just removing it.
3884 const Decl *DiagOld = Old;
3885 if (OldOvl) {
3886 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3887 const auto *A = D->getAttr<OverloadableAttr>();
3888 return A && !A->isImplicit();
3889 });
3890 // If we've implicitly added *all* of the overloadable attrs to this
3891 // chain, emitting a "previous redecl" note is pointless.
3892 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3893 }
3894
3895 if (DiagOld)
3896 Diag(DiagOld->getLocation(),
3897 diag::note_attribute_overloadable_prev_overload)
3898 << OldOvl;
3899
3900 if (OldOvl)
3901 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3902 else
3903 New->dropAttr<OverloadableAttr>();
3904 }
3905 }
3906
3907 // It is not permitted to redeclare an SME function with different SME
3908 // attributes.
3909 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3910 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3911 << New->getType() << Old->getType();
3912 Diag(OldLocation, diag::note_previous_declaration);
3913 return true;
3914 }
3915
3916 // If a function is first declared with a calling convention, but is later
3917 // declared or defined without one, all following decls assume the calling
3918 // convention of the first.
3919 //
3920 // It's OK if a function is first declared without a calling convention,
3921 // but is later declared or defined with the default calling convention.
3922 //
3923 // To test if either decl has an explicit calling convention, we look for
3924 // AttributedType sugar nodes on the type as written. If they are missing or
3925 // were canonicalized away, we assume the calling convention was implicit.
3926 //
3927 // Note also that we DO NOT return at this point, because we still have
3928 // other tests to run.
3929 QualType OldQType = Context.getCanonicalType(Old->getType());
3930 QualType NewQType = Context.getCanonicalType(New->getType());
3931 const FunctionType *OldType = cast<FunctionType>(OldQType);
3932 const FunctionType *NewType = cast<FunctionType>(NewQType);
3933 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3934 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3935 bool RequiresAdjustment = false;
3936
3937 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3939 const FunctionType *FT =
3940 First->getType().getCanonicalType()->castAs<FunctionType>();
3942 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3943 if (!NewCCExplicit) {
3944 // Inherit the CC from the previous declaration if it was specified
3945 // there but not here.
3946 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3947 RequiresAdjustment = true;
3948 } else if (Old->getBuiltinID()) {
3949 // Builtin attribute isn't propagated to the new one yet at this point,
3950 // so we check if the old one is a builtin.
3951
3952 // Calling Conventions on a Builtin aren't really useful and setting a
3953 // default calling convention and cdecl'ing some builtin redeclarations is
3954 // common, so warn and ignore the calling convention on the redeclaration.
3955 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3956 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3958 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3959 RequiresAdjustment = true;
3960 } else {
3961 // Calling conventions aren't compatible, so complain.
3962 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3963 Diag(New->getLocation(), diag::err_cconv_change)
3964 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3965 << !FirstCCExplicit
3966 << (!FirstCCExplicit ? "" :
3968
3969 // Put the note on the first decl, since it is the one that matters.
3970 Diag(First->getLocation(), diag::note_previous_declaration);
3971 return true;
3972 }
3973 }
3974
3975 // FIXME: diagnose the other way around?
3976 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3977 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3978 RequiresAdjustment = true;
3979 }
3980
3981 // If the declaration is marked with cfi_unchecked_callee but the definition
3982 // isn't, the definition is also cfi_unchecked_callee.
3983 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3984 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3985 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3986 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3987
3988 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3989 EPI2.CFIUncheckedCallee = true;
3990 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3991 FPT2->getParamTypes(), EPI2);
3992 NewType = cast<FunctionType>(NewQType);
3993 New->setType(NewQType);
3994 }
3995 }
3996 }
3997
3998 // Merge regparm attribute.
3999 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
4000 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
4001 if (NewTypeInfo.getHasRegParm()) {
4002 Diag(New->getLocation(), diag::err_regparm_mismatch)
4003 << NewType->getRegParmType()
4004 << OldType->getRegParmType();
4005 Diag(OldLocation, diag::note_previous_declaration);
4006 return true;
4007 }
4008
4009 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
4010 RequiresAdjustment = true;
4011 }
4012
4013 // Merge ns_returns_retained attribute.
4014 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4015 if (NewTypeInfo.getProducesResult()) {
4016 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
4017 << "'ns_returns_retained'";
4018 Diag(OldLocation, diag::note_previous_declaration);
4019 return true;
4020 }
4021
4022 NewTypeInfo = NewTypeInfo.withProducesResult(true);
4023 RequiresAdjustment = true;
4024 }
4025
4026 if (OldTypeInfo.getNoCallerSavedRegs() !=
4027 NewTypeInfo.getNoCallerSavedRegs()) {
4028 if (NewTypeInfo.getNoCallerSavedRegs()) {
4029 AnyX86NoCallerSavedRegistersAttr *Attr =
4030 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4031 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
4032 Diag(OldLocation, diag::note_previous_declaration);
4033 return true;
4034 }
4035
4036 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
4037 RequiresAdjustment = true;
4038 }
4039
4040 if (RequiresAdjustment) {
4041 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4042 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
4043 New->setType(QualType(AdjustedType, 0));
4044 NewQType = Context.getCanonicalType(New->getType());
4045 }
4046
4047 // If this redeclaration makes the function inline, we may need to add it to
4048 // UndefinedButUsed.
4049 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4050 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
4051 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4052 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4053 SourceLocation()));
4054
4055 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4056 // about it.
4057 if (New->hasAttr<GNUInlineAttr>() &&
4058 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4059 UndefinedButUsed.erase(Old->getCanonicalDecl());
4060 }
4061
4062 // If pass_object_size params don't match up perfectly, this isn't a valid
4063 // redeclaration.
4064 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4066 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4067 << New->getDeclName();
4068 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4069 return true;
4070 }
4071
4072 QualType OldQTypeForComparison = OldQType;
4073 if (Context.hasAnyFunctionEffects()) {
4074 const auto OldFX = Old->getFunctionEffects();
4075 const auto NewFX = New->getFunctionEffects();
4076 if (OldFX != NewFX) {
4077 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4078 for (const auto &Diff : Diffs) {
4079 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4080 Diag(New->getLocation(),
4081 diag::warn_mismatched_func_effect_redeclaration)
4082 << Diff.effectName();
4083 Diag(Old->getLocation(), diag::note_previous_declaration);
4084 }
4085 }
4086 // Following a warning, we could skip merging effects from the previous
4087 // declaration, but that would trigger an additional "conflicting types"
4088 // error.
4089 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4091 FunctionEffectSet MergedFX =
4092 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4093 if (!MergeErrs.empty())
4094 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4095 Old->getLocation());
4096
4097 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4098 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4099 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4100 NewFPT->getParamTypes(), EPI);
4101
4102 New->setType(ModQT);
4103 NewQType = New->getType();
4104
4105 // Revise OldQTForComparison to include the merged effects,
4106 // so as not to fail due to differences later.
4107 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4108 EPI = OldFPT->getExtProtoInfo();
4109 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4110 OldQTypeForComparison = Context.getFunctionType(
4111 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4112 }
4113 if (OldFX.empty()) {
4114 // A redeclaration may add the attribute to a previously seen function
4115 // body which needs to be verified.
4116 maybeAddDeclWithEffects(Old, MergedFX);
4117 }
4118 }
4119 }
4120 }
4121
4122 if (getLangOpts().CPlusPlus) {
4123 OldQType = Context.getCanonicalType(Old->getType());
4124 NewQType = Context.getCanonicalType(New->getType());
4125
4126 // Go back to the type source info to compare the declared return types,
4127 // per C++1y [dcl.type.auto]p13:
4128 // Redeclarations or specializations of a function or function template
4129 // with a declared return type that uses a placeholder type shall also
4130 // use that placeholder, not a deduced type.
4131 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4132 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4133 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4134 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4135 OldDeclaredReturnType)) {
4136 QualType ResQT;
4137 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4138 OldDeclaredReturnType->isObjCObjectPointerType())
4139 // FIXME: This does the wrong thing for a deduced return type.
4140 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4141 if (ResQT.isNull()) {
4142 if (New->isCXXClassMember() && New->isOutOfLine())
4143 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4144 << New << New->getReturnTypeSourceRange();
4145 else if (Old->isExternC() && New->isExternC() &&
4146 !Old->hasAttr<OverloadableAttr>() &&
4147 !New->hasAttr<OverloadableAttr>())
4148 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4149 else
4150 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4151 << New->getReturnTypeSourceRange();
4152 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4153 << Old->getReturnTypeSourceRange();
4154 return true;
4155 }
4156 else
4157 NewQType = ResQT;
4158 }
4159
4160 QualType OldReturnType = OldType->getReturnType();
4161 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4162 if (OldReturnType != NewReturnType) {
4163 // If this function has a deduced return type and has already been
4164 // defined, copy the deduced value from the old declaration.
4165 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4166 if (OldAT && OldAT->isDeduced()) {
4167 QualType DT = OldAT->getDeducedType();
4168 if (DT.isNull()) {
4169 New->setType(SubstAutoTypeDependent(New->getType()));
4170 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4171 } else {
4172 New->setType(SubstAutoType(New->getType(), DT));
4173 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4174 }
4175 }
4176 }
4177
4178 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4179 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4180 if (OldMethod && NewMethod) {
4181 // Preserve triviality.
4182 NewMethod->setTrivial(OldMethod->isTrivial());
4183
4184 // MSVC allows explicit template specialization at class scope:
4185 // 2 CXXMethodDecls referring to the same function will be injected.
4186 // We don't want a redeclaration error.
4187 bool IsClassScopeExplicitSpecialization =
4188 OldMethod->isFunctionTemplateSpecialization() &&
4190 bool isFriend = NewMethod->getFriendObjectKind();
4191
4192 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4193 !IsClassScopeExplicitSpecialization) {
4194 // -- Member function declarations with the same name and the
4195 // same parameter types cannot be overloaded if any of them
4196 // is a static member function declaration.
4197 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4198 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4199 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4200 return true;
4201 }
4202
4203 // C++ [class.mem]p1:
4204 // [...] A member shall not be declared twice in the
4205 // member-specification, except that a nested class or member
4206 // class template can be declared and then later defined.
4207 if (!inTemplateInstantiation()) {
4208 unsigned NewDiag;
4209 if (isa<CXXConstructorDecl>(OldMethod))
4210 NewDiag = diag::err_constructor_redeclared;
4211 else if (isa<CXXDestructorDecl>(NewMethod))
4212 NewDiag = diag::err_destructor_redeclared;
4213 else if (isa<CXXConversionDecl>(NewMethod))
4214 NewDiag = diag::err_conv_function_redeclared;
4215 else
4216 NewDiag = diag::err_member_redeclared;
4217
4218 Diag(New->getLocation(), NewDiag);
4219 } else {
4220 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4221 << New << New->getType();
4222 }
4223 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4224 return true;
4225
4226 // Complain if this is an explicit declaration of a special
4227 // member that was initially declared implicitly.
4228 //
4229 // As an exception, it's okay to befriend such methods in order
4230 // to permit the implicit constructor/destructor/operator calls.
4231 } else if (OldMethod->isImplicit()) {
4232 if (isFriend) {
4233 NewMethod->setImplicit();
4234 } else {
4235 Diag(NewMethod->getLocation(),
4236 diag::err_definition_of_implicitly_declared_member)
4237 << New << OldMethod->getSpecialMemberKind();
4238 return true;
4239 }
4240 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4241 Diag(NewMethod->getLocation(),
4242 diag::err_definition_of_explicitly_defaulted_member)
4243 << OldMethod->getSpecialMemberKind();
4244 return true;
4245 }
4246 }
4247
4248 // C++1z [over.load]p2
4249 // Certain function declarations cannot be overloaded:
4250 // -- Function declarations that differ only in the return type,
4251 // the exception specification, or both cannot be overloaded.
4252
4253 // Check the exception specifications match. This may recompute the type of
4254 // both Old and New if it resolved exception specifications, so grab the
4255 // types again after this. Because this updates the type, we do this before
4256 // any of the other checks below, which may update the "de facto" NewQType
4257 // but do not necessarily update the type of New.
4259 return true;
4260
4261 // C++11 [dcl.attr.noreturn]p1:
4262 // The first declaration of a function shall specify the noreturn
4263 // attribute if any declaration of that function specifies the noreturn
4264 // attribute.
4265 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4266 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4267 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4268 << NRA;
4269 Diag(Old->getLocation(), diag::note_previous_declaration);
4270 }
4271
4272 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4273 // When a function is declared with SYCL_EXTERNAL, that macro must be
4274 // used on the first declaration of that function in the translation unit.
4275 // Redeclarations of the function in the same translation unit may
4276 // optionally use SYCL_EXTERNAL, but this is not required.
4277 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4278 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4279 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4280 << SEA;
4281 Diag(Old->getLocation(), diag::note_previous_declaration);
4282 }
4283
4284 // (C++98 8.3.5p3):
4285 // All declarations for a function shall agree exactly in both the
4286 // return type and the parameter-type-list.
4287 // We also want to respect all the extended bits except noreturn.
4288
4289 // noreturn should now match unless the old type info didn't have it.
4290 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4291 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4292 const FunctionType *OldTypeForComparison
4293 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4294 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4295 assert(OldQTypeForComparison.isCanonical());
4296 }
4297
4299 // As a special case, retain the language linkage from previous
4300 // declarations of a friend function as an extension.
4301 //
4302 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4303 // and is useful because there's otherwise no way to specify language
4304 // linkage within class scope.
4305 //
4306 // Check cautiously as the friend object kind isn't yet complete.
4307 if (New->getFriendObjectKind() != Decl::FOK_None) {
4308 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4309 Diag(OldLocation, PrevDiag);
4310 } else {
4311 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4312 Diag(OldLocation, PrevDiag);
4313 return true;
4314 }
4315 }
4316
4317 // HLSL check parameters for matching ABI specifications.
4318 if (getLangOpts().HLSL) {
4319 if (HLSL().CheckCompatibleParameterABI(New, Old))
4320 return true;
4321
4322 // If no errors are generated when checking parameter ABIs we can check if
4323 // the two declarations have the same type ignoring the ABIs and if so,
4324 // the declarations can be merged. This case for merging is only valid in
4325 // HLSL because there are no valid cases of merging mismatched parameter
4326 // ABIs except the HLSL implicit in and explicit in.
4327 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4328 NewQType))
4329 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4330 // Fall through for conflicting redeclarations and redefinitions.
4331 }
4332
4333 // If the function types are compatible, merge the declarations. Ignore the
4334 // exception specifier because it was already checked above in
4335 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4336 // about incompatible types under -fms-compatibility.
4337 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4338 NewQType))
4339 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4340
4341 // If the types are imprecise (due to dependent constructs in friends or
4342 // local extern declarations), it's OK if they differ. We'll check again
4343 // during instantiation.
4344 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4345 return false;
4346
4347 // Fall through for conflicting redeclarations and redefinitions.
4348 }
4349
4350 // C: Function types need to be compatible, not identical. This handles
4351 // duplicate function decls like "void f(int); void f(enum X);" properly.
4352 if (!getLangOpts().CPlusPlus) {
4353 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4354 // type is specified by a function definition that contains a (possibly
4355 // empty) identifier list, both shall agree in the number of parameters
4356 // and the type of each parameter shall be compatible with the type that
4357 // results from the application of default argument promotions to the
4358 // type of the corresponding identifier. ...
4359 // This cannot be handled by ASTContext::typesAreCompatible() because that
4360 // doesn't know whether the function type is for a definition or not when
4361 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4362 // we need to cover here is that the number of arguments agree as the
4363 // default argument promotion rules were already checked by
4364 // ASTContext::typesAreCompatible().
4365 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4366 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4367 if (Old->hasInheritedPrototype())
4368 Old = Old->getCanonicalDecl();
4369 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4370 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4371 return true;
4372 }
4373
4374 // If we are merging two functions where only one of them has a prototype,
4375 // we may have enough information to decide to issue a diagnostic that the
4376 // function without a prototype will change behavior in C23. This handles
4377 // cases like:
4378 // void i(); void i(int j);
4379 // void i(int j); void i();
4380 // void i(); void i(int j) {}
4381 // See ActOnFinishFunctionBody() for other cases of the behavior change
4382 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4383 // type without a prototype.
4384 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4385 !New->isImplicit() && !Old->isImplicit()) {
4386 const FunctionDecl *WithProto, *WithoutProto;
4387 if (New->hasWrittenPrototype()) {
4388 WithProto = New;
4389 WithoutProto = Old;
4390 } else {
4391 WithProto = Old;
4392 WithoutProto = New;
4393 }
4394
4395 if (WithProto->getNumParams() != 0) {
4396 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4397 // The one without the prototype will be changing behavior in C23, so
4398 // warn about that one so long as it's a user-visible declaration.
4399 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4400 if (WithoutProto == New)
4401 IsWithoutProtoADef = NewDeclIsDefn;
4402 else
4403 IsWithProtoADef = NewDeclIsDefn;
4404 Diag(WithoutProto->getLocation(),
4405 diag::warn_non_prototype_changes_behavior)
4406 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4407 << (WithoutProto == Old) << IsWithProtoADef;
4408
4409 // The reason the one without the prototype will be changing behavior
4410 // is because of the one with the prototype, so note that so long as
4411 // it's a user-visible declaration. There is one exception to this:
4412 // when the new declaration is a definition without a prototype, the
4413 // old declaration with a prototype is not the cause of the issue,
4414 // and that does not need to be noted because the one with a
4415 // prototype will not change behavior in C23.
4416 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4417 !IsWithoutProtoADef)
4418 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4419 }
4420 }
4421 }
4422
4423 if (Context.typesAreCompatible(OldQType, NewQType)) {
4424 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4425 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4426 const FunctionProtoType *OldProto = nullptr;
4427 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4428 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4429 // The old declaration provided a function prototype, but the
4430 // new declaration does not. Merge in the prototype.
4431 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4432 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4433 OldProto->getParamTypes(),
4434 OldProto->getExtProtoInfo());
4435 New->setType(NewQType);
4436 New->setHasInheritedPrototype();
4437
4438 // Synthesize parameters with the same types.
4440 for (const auto &ParamType : OldProto->param_types()) {
4442 Context, New, SourceLocation(), SourceLocation(), nullptr,
4443 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4444 Param->setScopeInfo(0, Params.size());
4445 Param->setImplicit();
4446 Params.push_back(Param);
4447 }
4448
4449 New->setParams(Params);
4450 }
4451
4452 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4453 }
4454 }
4455
4456 // Check if the function types are compatible when pointer size address
4457 // spaces are ignored.
4458 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4459 return false;
4460
4461 // GNU C permits a K&R definition to follow a prototype declaration
4462 // if the declared types of the parameters in the K&R definition
4463 // match the types in the prototype declaration, even when the
4464 // promoted types of the parameters from the K&R definition differ
4465 // from the types in the prototype. GCC then keeps the types from
4466 // the prototype.
4467 //
4468 // If a variadic prototype is followed by a non-variadic K&R definition,
4469 // the K&R definition becomes variadic. This is sort of an edge case, but
4470 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4471 // C99 6.9.1p8.
4472 if (!getLangOpts().CPlusPlus &&
4473 Old->hasPrototype() && !New->hasPrototype() &&
4474 New->getType()->getAs<FunctionProtoType>() &&
4475 Old->getNumParams() == New->getNumParams()) {
4478 const FunctionProtoType *OldProto
4479 = Old->getType()->getAs<FunctionProtoType>();
4480 const FunctionProtoType *NewProto
4481 = New->getType()->getAs<FunctionProtoType>();
4482
4483 // Determine whether this is the GNU C extension.
4484 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4485 NewProto->getReturnType());
4486 bool LooseCompatible = !MergedReturn.isNull();
4487 for (unsigned Idx = 0, End = Old->getNumParams();
4488 LooseCompatible && Idx != End; ++Idx) {
4489 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4490 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4491 if (Context.typesAreCompatible(OldParm->getType(),
4492 NewProto->getParamType(Idx))) {
4493 ArgTypes.push_back(NewParm->getType());
4494 } else if (Context.typesAreCompatible(OldParm->getType(),
4495 NewParm->getType(),
4496 /*CompareUnqualified=*/true)) {
4497 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4498 NewProto->getParamType(Idx) };
4499 Warnings.push_back(Warn);
4500 ArgTypes.push_back(NewParm->getType());
4501 } else
4502 LooseCompatible = false;
4503 }
4504
4505 if (LooseCompatible) {
4506 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4507 Diag(Warnings[Warn].NewParm->getLocation(),
4508 diag::ext_param_promoted_not_compatible_with_prototype)
4509 << Warnings[Warn].PromotedType
4510 << Warnings[Warn].OldParm->getType();
4511 if (Warnings[Warn].OldParm->getLocation().isValid())
4512 Diag(Warnings[Warn].OldParm->getLocation(),
4513 diag::note_previous_declaration);
4514 }
4515
4516 if (MergeTypeWithOld)
4517 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4518 OldProto->getExtProtoInfo()));
4519 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4520 }
4521
4522 // Fall through to diagnose conflicting types.
4523 }
4524
4525 // A function that has already been declared has been redeclared or
4526 // defined with a different type; show an appropriate diagnostic.
4527
4528 // If the previous declaration was an implicitly-generated builtin
4529 // declaration, then at the very least we should use a specialized note.
4530 unsigned BuiltinID;
4531 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4532 // If it's actually a library-defined builtin function like 'malloc'
4533 // or 'printf', just warn about the incompatible redeclaration.
4534 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4535 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4536 Diag(OldLocation, diag::note_previous_builtin_declaration)
4537 << Old << Old->getType();
4538 return false;
4539 }
4540
4541 PrevDiag = diag::note_previous_builtin_declaration;
4542 }
4543
4544 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4545 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4546 return true;
4547}
4548
4550 Scope *S, bool MergeTypeWithOld) {
4551 // Merge the attributes
4553
4554 // Merge "pure" flag.
4555 if (Old->isPureVirtual())
4556 New->setIsPureVirtual();
4557
4558 // Merge "used" flag.
4559 if (Old->getMostRecentDecl()->isUsed(false))
4560 New->setIsUsed();
4561
4562 // Merge attributes from the parameters. These can mismatch with K&R
4563 // declarations.
4564 if (New->getNumParams() == Old->getNumParams())
4565 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4566 ParmVarDecl *NewParam = New->getParamDecl(i);
4567 ParmVarDecl *OldParam = Old->getParamDecl(i);
4568 mergeParamDeclAttributes(NewParam, OldParam, *this);
4569 mergeParamDeclTypes(NewParam, OldParam, *this);
4570 }
4571
4572 if (getLangOpts().CPlusPlus)
4573 return MergeCXXFunctionDecl(New, Old, S);
4574
4575 // Merge the function types so the we get the composite types for the return
4576 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4577 // was visible.
4578 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4579 if (!Merged.isNull() && MergeTypeWithOld)
4580 New->setType(Merged);
4581
4582 return false;
4583}
4584
4586 ObjCMethodDecl *oldMethod) {
4587 // Merge the attributes, including deprecated/unavailable
4588 AvailabilityMergeKind MergeKind =
4590 ? (oldMethod->isOptional()
4593 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4596
4597 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4598
4599 // Merge attributes from the parameters.
4601 oe = oldMethod->param_end();
4603 ni = newMethod->param_begin(), ne = newMethod->param_end();
4604 ni != ne && oi != oe; ++ni, ++oi)
4605 mergeParamDeclAttributes(*ni, *oi, *this);
4606
4607 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4608}
4609
4611 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4612
4613 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4614 ? diag::err_redefinition_different_type
4615 : diag::err_redeclaration_different_type)
4616 << New->getDeclName() << New->getType() << Old->getType();
4617
4618 diag::kind PrevDiag;
4619 SourceLocation OldLocation;
4620 std::tie(PrevDiag, OldLocation)
4622 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4623 New->setInvalidDecl();
4624}
4625
4627 bool MergeTypeWithOld) {
4628 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4629 return;
4630
4631 QualType MergedT;
4632 if (getLangOpts().CPlusPlus) {
4633 if (New->getType()->isUndeducedType()) {
4634 // We don't know what the new type is until the initializer is attached.
4635 return;
4636 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4637 // These could still be something that needs exception specs checked.
4638 return MergeVarDeclExceptionSpecs(New, Old);
4639 }
4640 // C++ [basic.link]p10:
4641 // [...] the types specified by all declarations referring to a given
4642 // object or function shall be identical, except that declarations for an
4643 // array object can specify array types that differ by the presence or
4644 // absence of a major array bound (8.3.4).
4645 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4646 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4647 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4648
4649 // We are merging a variable declaration New into Old. If it has an array
4650 // bound, and that bound differs from Old's bound, we should diagnose the
4651 // mismatch.
4652 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4653 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4654 PrevVD = PrevVD->getPreviousDecl()) {
4655 QualType PrevVDTy = PrevVD->getType();
4656 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4657 continue;
4658
4659 if (!Context.hasSameType(New->getType(), PrevVDTy))
4660 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4661 }
4662 }
4663
4664 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4665 if (Context.hasSameType(OldArray->getElementType(),
4666 NewArray->getElementType()))
4667 MergedT = New->getType();
4668 }
4669 // FIXME: Check visibility. New is hidden but has a complete type. If New
4670 // has no array bound, it should not inherit one from Old, if Old is not
4671 // visible.
4672 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4673 if (Context.hasSameType(OldArray->getElementType(),
4674 NewArray->getElementType()))
4675 MergedT = Old->getType();
4676 }
4677 }
4678 else if (New->getType()->isObjCObjectPointerType() &&
4679 Old->getType()->isObjCObjectPointerType()) {
4680 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4681 Old->getType());
4682 }
4683 } else {
4684 // C 6.2.7p2:
4685 // All declarations that refer to the same object or function shall have
4686 // compatible type.
4687 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4688 }
4689 if (MergedT.isNull()) {
4690 // It's OK if we couldn't merge types if either type is dependent, for a
4691 // block-scope variable. In other cases (static data members of class
4692 // templates, variable templates, ...), we require the types to be
4693 // equivalent.
4694 // FIXME: The C++ standard doesn't say anything about this.
4695 if ((New->getType()->isDependentType() ||
4696 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4697 // If the old type was dependent, we can't merge with it, so the new type
4698 // becomes dependent for now. We'll reproduce the original type when we
4699 // instantiate the TypeSourceInfo for the variable.
4700 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4701 New->setType(Context.DependentTy);
4702 return;
4703 }
4704 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4705 }
4706
4707 // Don't actually update the type on the new declaration if the old
4708 // declaration was an extern declaration in a different scope.
4709 if (MergeTypeWithOld)
4710 New->setType(MergedT);
4711}
4712
4713static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4715 // C11 6.2.7p4:
4716 // For an identifier with internal or external linkage declared
4717 // in a scope in which a prior declaration of that identifier is
4718 // visible, if the prior declaration specifies internal or
4719 // external linkage, the type of the identifier at the later
4720 // declaration becomes the composite type.
4721 //
4722 // If the variable isn't visible, we do not merge with its type.
4723 if (Previous.isShadowed())
4724 return false;
4725
4726 if (S.getLangOpts().CPlusPlus) {
4727 // C++11 [dcl.array]p3:
4728 // If there is a preceding declaration of the entity in the same
4729 // scope in which the bound was specified, an omitted array bound
4730 // is taken to be the same as in that earlier declaration.
4731 return NewVD->isPreviousDeclInSameBlockScope() ||
4732 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4734 } else {
4735 // If the old declaration was function-local, don't merge with its
4736 // type unless we're in the same function.
4737 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4738 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4739 }
4740}
4741
4743 // If the new decl is already invalid, don't do any other checking.
4744 if (New->isInvalidDecl())
4745 return;
4746
4747 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4748 return;
4749
4750 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4751
4752 // Verify the old decl was also a variable or variable template.
4753 VarDecl *Old = nullptr;
4754 VarTemplateDecl *OldTemplate = nullptr;
4755 if (Previous.isSingleResult()) {
4756 if (NewTemplate) {
4757 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4758 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4759
4760 if (auto *Shadow =
4761 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4762 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4763 return New->setInvalidDecl();
4764 } else {
4765 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4766
4767 if (auto *Shadow =
4768 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4769 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4770 return New->setInvalidDecl();
4771 }
4772 }
4773 if (!Old) {
4774 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4775 << New->getDeclName();
4776 notePreviousDefinition(Previous.getRepresentativeDecl(),
4777 New->getLocation());
4778 return New->setInvalidDecl();
4779 }
4780
4781 // If the old declaration was found in an inline namespace and the new
4782 // declaration was qualified, update the DeclContext to match.
4784
4785 // Ensure the template parameters are compatible.
4786 if (NewTemplate &&
4788 OldTemplate->getTemplateParameters(),
4789 /*Complain=*/true, TPL_TemplateMatch))
4790 return New->setInvalidDecl();
4791
4792 // C++ [class.mem]p1:
4793 // A member shall not be declared twice in the member-specification [...]
4794 //
4795 // Here, we need only consider static data members.
4796 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4797 Diag(New->getLocation(), diag::err_duplicate_member)
4798 << New->getIdentifier();
4799 Diag(Old->getLocation(), diag::note_previous_declaration);
4800 New->setInvalidDecl();
4801 }
4802
4803 if (NewTemplate && OldTemplate)
4804 mergeDeclAttributes(NewTemplate, OldTemplate);
4805
4807
4808 // Warn if an already-defined variable is made a weak_import in a subsequent
4809 // declaration
4810 if (New->hasAttr<WeakImportAttr>())
4811 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4812 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4813 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4814 Diag(D->getLocation(), diag::note_previous_definition);
4815 // Remove weak_import attribute on new declaration.
4816 New->dropAttr<WeakImportAttr>();
4817 break;
4818 }
4819 }
4820
4821 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4822 if (!Old->hasAttr<InternalLinkageAttr>()) {
4823 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4824 << ILA;
4825 Diag(Old->getLocation(), diag::note_previous_declaration);
4826 New->dropAttr<InternalLinkageAttr>();
4827 }
4828
4829 // Merge the types.
4830 VarDecl *MostRecent = Old->getMostRecentDecl();
4831 if (MostRecent != Old) {
4832 MergeVarDeclTypes(New, MostRecent,
4833 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4834 if (New->isInvalidDecl())
4835 return;
4836 }
4837
4839 if (New->isInvalidDecl())
4840 return;
4841
4842 diag::kind PrevDiag;
4843 SourceLocation OldLocation;
4844 std::tie(PrevDiag, OldLocation) =
4846
4847 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4848 if (New->getStorageClass() == SC_Static &&
4849 !New->isStaticDataMember() &&
4850 Old->hasExternalFormalLinkage()) {
4851 if (getLangOpts().MicrosoftExt) {
4852 Diag(New->getLocation(), diag::ext_static_non_static)
4853 << New->getDeclName();
4854 Diag(OldLocation, PrevDiag);
4855 } else {
4856 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4857 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4858 // the older C language modes.
4859 Diag(New->getLocation(), diag::err_static_non_static)
4860 << New->getDeclName()
4861 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4862 Diag(OldLocation, PrevDiag);
4863 return New->setInvalidDecl();
4864 }
4865 }
4866
4867 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4868 // external linkage within a translation unit. Before C2y this was UB
4869 // (C11 6.2.2p7).
4870 //
4871 // In C, a local shadow prevents a block-scope extern from inheriting the
4872 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4873 // external linkage, creating the conflict.
4874 //
4875 // In C++, block-scope extern declarations target the enclosing namespace
4876 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4877 // the extern always inherits internal linkage. No conflict arises.
4878 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4879 New->hasExternalStorage() && Previous.isShadowed() &&
4881 Diag(New->getLocation(), diag::err_internal_extern_mismatch)
4882 << New->getDeclName() << getLangOpts().C2y;
4883 Diag(OldLocation, diag::note_previous_declaration);
4884 return New->setInvalidDecl();
4885 }
4886
4887 // C99 6.2.2p4:
4888 // For an identifier declared with the storage-class specifier
4889 // extern in a scope in which a prior declaration of that
4890 // identifier is visible,23) if the prior declaration specifies
4891 // internal or external linkage, the linkage of the identifier at
4892 // the later declaration is the same as the linkage specified at
4893 // the prior declaration. If no prior declaration is visible, or
4894 // if the prior declaration specifies no linkage, then the
4895 // identifier has external linkage.
4896 if (New->hasExternalStorage() && Old->hasLinkage())
4897 /* Okay */;
4898 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4899 !New->isStaticDataMember() &&
4901 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4902 Diag(OldLocation, PrevDiag);
4903 return New->setInvalidDecl();
4904 }
4905
4906 // Check if extern is followed by non-extern and vice-versa.
4907 if (New->hasExternalStorage() &&
4908 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4909 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4910 Diag(OldLocation, PrevDiag);
4911 return New->setInvalidDecl();
4912 }
4913 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4914 !New->hasExternalStorage()) {
4915 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4916 Diag(OldLocation, PrevDiag);
4917 return New->setInvalidDecl();
4918 }
4919
4921 return;
4922
4923 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4924
4925 // FIXME: The test for external storage here seems wrong? We still
4926 // need to check for mismatches.
4927 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4928 // Don't complain about out-of-line definitions of static members.
4929 !(Old->getLexicalDeclContext()->isRecord() &&
4930 !New->getLexicalDeclContext()->isRecord())) {
4931 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4932 Diag(OldLocation, PrevDiag);
4933 return New->setInvalidDecl();
4934 }
4935
4936 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4937 if (VarDecl *Def = Old->getDefinition()) {
4938 // C++1z [dcl.fcn.spec]p4:
4939 // If the definition of a variable appears in a translation unit before
4940 // its first declaration as inline, the program is ill-formed.
4941 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4942 Diag(Def->getLocation(), diag::note_previous_definition);
4943 }
4944 }
4945
4946 // If this redeclaration makes the variable inline, we may need to add it to
4947 // UndefinedButUsed.
4948 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4949 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4950 !Old->isInAnotherModuleUnit())
4951 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4952 SourceLocation()));
4953
4954 if (New->getTLSKind() != Old->getTLSKind()) {
4955 if (!Old->getTLSKind()) {
4956 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4957 Diag(OldLocation, PrevDiag);
4958 } else if (!New->getTLSKind()) {
4959 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4960 Diag(OldLocation, PrevDiag);
4961 } else {
4962 // Do not allow redeclaration to change the variable between requiring
4963 // static and dynamic initialization.
4964 // FIXME: GCC allows this, but uses the TLS keyword on the first
4965 // declaration to determine the kind. Do we need to be compatible here?
4966 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4967 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4968 Diag(OldLocation, PrevDiag);
4969 }
4970 }
4971
4972 // C++ doesn't have tentative definitions, so go right ahead and check here.
4973 if (getLangOpts().CPlusPlus) {
4974 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4975 Old->getCanonicalDecl()->isConstexpr()) {
4976 // This definition won't be a definition any more once it's been merged.
4977 Diag(New->getLocation(),
4978 diag::warn_deprecated_redundant_constexpr_static_def);
4979 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4980 VarDecl *Def = Old->getDefinition();
4981 if (Def && checkVarDeclRedefinition(Def, New))
4982 return;
4983 if (Old->isInvalidDecl())
4984 New->setInvalidDecl();
4985 }
4986 } else {
4987 // C++ may not have a tentative definition rule, but it has a different
4988 // rule about what constitutes a definition in the first place. See
4989 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4990 // contains the extern specifier and doesn't have an initializer, it's fine
4991 // in C++.
4992 if (New->getTLSKind() != VarDecl::TLS_None &&
4993 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4994 VarDecl *Def = Old->getDefinition();
4995 if (Def && checkVarDeclRedefinition(Def, New)) {
4996 return;
4997 }
4998 } else if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4999 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
5000 << New;
5001 Diag(Old->getLocation(), diag::note_previous_declaration);
5002 }
5003 }
5004
5006 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
5007 Diag(OldLocation, PrevDiag);
5008 New->setInvalidDecl();
5009 return;
5010 }
5011
5012 // Merge "used" flag.
5013 if (Old->getMostRecentDecl()->isUsed(false))
5014 New->setIsUsed();
5015
5016 // Keep a chain of previous declarations.
5017 New->setPreviousDecl(Old);
5018 if (NewTemplate)
5019 NewTemplate->setPreviousDecl(OldTemplate);
5020
5021 // Inherit access appropriately.
5022 New->setAccess(Old->getAccess());
5023 if (NewTemplate)
5024 NewTemplate->setAccess(New->getAccess());
5025
5026 if (Old->isInline())
5027 New->setImplicitlyInline();
5028}
5029
5032 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
5033 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
5034 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
5035 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
5036 auto &HSI = PP.getHeaderSearchInfo();
5037 StringRef HdrFilename =
5038 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
5039
5040 auto noteFromModuleOrInclude = [&](Module *Mod,
5041 SourceLocation IncLoc) -> bool {
5042 // Redefinition errors with modules are common with non modular mapped
5043 // headers, example: a non-modular header H in module A that also gets
5044 // included directly in a TU. Pointing twice to the same header/definition
5045 // is confusing, try to get better diagnostics when modules is on.
5046 if (IncLoc.isValid()) {
5047 if (Mod) {
5048 Diag(IncLoc, diag::note_redefinition_modules_same_file)
5049 << HdrFilename.str() << Mod->getFullModuleName();
5050 if (!Mod->DefinitionLoc.isInvalid())
5051 Diag(Mod->DefinitionLoc, diag::note_defined_here)
5052 << Mod->getFullModuleName();
5053 } else {
5054 Diag(IncLoc, diag::note_redefinition_include_same_file)
5055 << HdrFilename.str();
5056 }
5057 return true;
5058 }
5059
5060 return false;
5061 };
5062
5063 // Is it the same file and same offset? Provide more information on why
5064 // this leads to a redefinition error.
5065 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5066 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
5067 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
5068 bool EmittedDiag =
5069 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5070 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5071
5072 // If the header has no guards, emit a note suggesting one.
5073 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
5074 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
5075
5076 if (EmittedDiag)
5077 return;
5078 }
5079
5080 // Redefinition coming from different files or couldn't do better above.
5081 if (Old->getLocation().isValid())
5082 Diag(Old->getLocation(), diag::note_previous_definition);
5083}
5084
5086 if ((!hasVisibleDefinition(Old) ||
5087 isFromSameSingleIncludeHeader(Old, New->getLocation())) &&
5088 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5090 New->getDescribedVarTemplate() ||
5091 !New->getTemplateParameterLists().empty() ||
5092 New->getDeclContext()->isDependentContext() ||
5093 New->hasAttr<SelectAnyAttr>())) {
5094 // The previous definition is hidden, and multiple definitions are
5095 // permitted (in separate TUs). Demote this to a declaration.
5096 New->demoteThisDefinitionToDeclaration();
5097
5098 // Make the canonical definition visible.
5099 if (auto *OldTD = Old->getDescribedVarTemplate())
5102 return false;
5103 } else {
5104 Diag(New->getLocation(), diag::err_redefinition) << New;
5105 notePreviousDefinition(Old, New->getLocation());
5106 New->setInvalidDecl();
5107 return true;
5108 }
5109}
5110
5112 DeclSpec &DS,
5113 const ParsedAttributesView &DeclAttrs,
5114 RecordDecl *&AnonRecord) {
5116 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5117}
5118
5119// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5120// disambiguate entities defined in different scopes.
5121// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5122// compatibility.
5123// We will pick our mangling number depending on which version of MSVC is being
5124// targeted.
5125static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5129}
5130
5131void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5132 if (!Context.getLangOpts().CPlusPlus)
5133 return;
5134
5135 if (isa<CXXRecordDecl>(Tag->getParent())) {
5136 // If this tag is the direct child of a class, number it if
5137 // it is anonymous.
5138 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5139 return;
5141 Context.getManglingNumberContext(Tag->getParent());
5142 Context.setManglingNumber(
5143 Tag, MCtx.getManglingNumber(
5144 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5145 return;
5146 }
5147
5148 // If this tag isn't a direct child of a class, number it if it is local.
5150 Decl *ManglingContextDecl;
5151 std::tie(MCtx, ManglingContextDecl) =
5152 getCurrentMangleNumberContext(Tag->getDeclContext());
5153 if (MCtx) {
5154 Context.setManglingNumber(
5155 Tag, MCtx->getManglingNumber(
5156 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5157 }
5158}
5159
5160namespace {
5161struct NonCLikeKind {
5162 enum {
5163 None,
5164 BaseClass,
5165 DefaultMemberInit,
5166 Lambda,
5167 Friend,
5168 OtherMember,
5169 Invalid,
5170 } Kind = None;
5171 SourceRange Range;
5172
5173 explicit operator bool() { return Kind != None; }
5174};
5175}
5176
5177/// Determine whether a class is C-like, according to the rules of C++
5178/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5179static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5180 if (RD->isInvalidDecl())
5181 return {NonCLikeKind::Invalid, {}};
5182
5183 // C++ [dcl.typedef]p9: [P1766R1]
5184 // An unnamed class with a typedef name for linkage purposes shall not
5185 //
5186 // -- have any base classes
5187 if (RD->getNumBases())
5188 return {NonCLikeKind::BaseClass,
5190 RD->bases_end()[-1].getEndLoc())};
5191 bool Invalid = false;
5192 for (Decl *D : RD->decls()) {
5193 // Don't complain about things we already diagnosed.
5194 if (D->isInvalidDecl()) {
5195 Invalid = true;
5196 continue;
5197 }
5198
5199 // -- have any [...] default member initializers
5200 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5201 if (FD->hasInClassInitializer()) {
5202 auto *Init = FD->getInClassInitializer();
5203 return {NonCLikeKind::DefaultMemberInit,
5204 Init ? Init->getSourceRange() : D->getSourceRange()};
5205 }
5206 continue;
5207 }
5208
5209 // FIXME: We don't allow friend declarations. This violates the wording of
5210 // P1766, but not the intent.
5211 if (isa<FriendDecl>(D))
5212 return {NonCLikeKind::Friend, D->getSourceRange()};
5213
5214 // -- declare any members other than non-static data members, member
5215 // enumerations, or member classes,
5217 isa<EnumDecl>(D))
5218 continue;
5219 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5220 if (!MemberRD) {
5221 if (D->isImplicit())
5222 continue;
5223 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5224 }
5225
5226 // -- contain a lambda-expression,
5227 if (MemberRD->isLambda())
5228 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5229
5230 // and all member classes shall also satisfy these requirements
5231 // (recursively).
5232 if (MemberRD->isThisDeclarationADefinition()) {
5233 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5234 return Kind;
5235 }
5236 }
5237
5238 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5239}
5240
5242 TypedefNameDecl *NewTD) {
5243 if (TagFromDeclSpec->isInvalidDecl())
5244 return;
5245
5246 // Do nothing if the tag already has a name for linkage purposes.
5247 if (TagFromDeclSpec->hasNameForLinkage())
5248 return;
5249
5250 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5251 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5252
5253 // The type must match the tag exactly; no qualifiers allowed.
5254 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5255 Context.getCanonicalTagType(TagFromDeclSpec))) {
5256 if (getLangOpts().CPlusPlus)
5257 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5258 return;
5259 }
5260
5261 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5262 // An unnamed class with a typedef name for linkage purposes shall [be
5263 // C-like].
5264 //
5265 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5266 // shouldn't happen, but there are constructs that the language rule doesn't
5267 // disallow for which we can't reasonably avoid computing linkage early.
5268 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5269 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5270 : NonCLikeKind();
5271 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5272 if (NonCLike || ChangesLinkage) {
5273 if (NonCLike.Kind == NonCLikeKind::Invalid)
5274 return;
5275
5276 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5277 if (ChangesLinkage) {
5278 // If the linkage changes, we can't accept this as an extension.
5279 if (NonCLike.Kind == NonCLikeKind::None)
5280 DiagID = diag::err_typedef_changes_linkage;
5281 else
5282 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5283 }
5284
5285 SourceLocation FixitLoc =
5286 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5287 llvm::SmallString<40> TextToInsert;
5288 TextToInsert += ' ';
5289 TextToInsert += NewTD->getIdentifier()->getName();
5290
5291 Diag(FixitLoc, DiagID)
5292 << isa<TypeAliasDecl>(NewTD)
5293 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5294 if (NonCLike.Kind != NonCLikeKind::None) {
5295 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5296 << NonCLike.Kind - 1 << NonCLike.Range;
5297 }
5298 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5299 << NewTD << isa<TypeAliasDecl>(NewTD);
5300
5301 if (ChangesLinkage)
5302 return;
5303 }
5304
5305 // Otherwise, set this as the anon-decl typedef for the tag.
5306 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5307
5308 // Now that we have a name for the tag, process API notes again.
5309 ProcessAPINotes(TagFromDeclSpec);
5310}
5311
5312static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5314 switch (T) {
5316 return 0;
5318 return 1;
5320 return 2;
5322 return 3;
5323 case DeclSpec::TST_enum:
5324 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5325 if (ED->isScopedUsingClassTag())
5326 return 5;
5327 if (ED->isScoped())
5328 return 6;
5329 }
5330 return 4;
5331 default:
5332 llvm_unreachable("unexpected type specifier");
5333 }
5334}
5335
5337 DeclSpec &DS,
5338 const ParsedAttributesView &DeclAttrs,
5339 MultiTemplateParamsArg TemplateParams,
5340 bool IsExplicitInstantiation,
5341 RecordDecl *&AnonRecord,
5342 SourceLocation EllipsisLoc) {
5343 Decl *TagD = nullptr;
5344 TagDecl *Tag = nullptr;
5350 TagD = DS.getRepAsDecl();
5351
5352 if (!TagD) // We probably had an error
5353 return nullptr;
5354
5355 // Note that the above type specs guarantee that the
5356 // type rep is a Decl, whereas in many of the others
5357 // it's a Type.
5358 if (isa<TagDecl>(TagD))
5359 Tag = cast<TagDecl>(TagD);
5360 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5361 Tag = CTD->getTemplatedDecl();
5362 }
5363
5364 if (Tag) {
5365 handleTagNumbering(Tag, S);
5366 Tag->setFreeStanding();
5367 if (Tag->isInvalidDecl())
5368 return Tag;
5369 }
5370
5371 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5372 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5373 // or incomplete types shall not be restrict-qualified."
5374 if (TypeQuals & DeclSpec::TQ_restrict)
5376 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5377 << DS.getSourceRange();
5378 }
5379
5380 if (DS.isInlineSpecified())
5381 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5382 << getLangOpts().CPlusPlus17;
5383
5384 if (DS.hasConstexprSpecifier()) {
5385 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5386 // and definitions of functions and variables.
5387 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5388 // the declaration of a function or function template
5389 if (Tag)
5390 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5392 << static_cast<int>(DS.getConstexprSpecifier());
5393 else if (getLangOpts().C23)
5394 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5395 else
5396 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5397 << static_cast<int>(DS.getConstexprSpecifier());
5398 // Don't emit warnings after this error.
5399 return TagD;
5400 }
5401
5403
5404 if (DS.isFriendSpecified()) {
5405 // If we're dealing with a decl but not a TagDecl, assume that
5406 // whatever routines created it handled the friendship aspect.
5407 if (TagD && !Tag)
5408 return nullptr;
5409 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5410 }
5411
5412 assert(EllipsisLoc.isInvalid() &&
5413 "Friend ellipsis but not friend-specified?");
5414
5415 // Track whether this decl-specifier declares anything.
5416 bool DeclaresAnything = true;
5417
5418 // Handle anonymous struct definitions.
5419 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5420 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5422 if (getLangOpts().CPlusPlus ||
5423 Record->getDeclContext()->isRecord()) {
5424 // If CurContext is a DeclContext that can contain statements,
5425 // RecursiveASTVisitor won't visit the decls that
5426 // BuildAnonymousStructOrUnion() will put into CurContext.
5427 // Also store them here so that they can be part of the
5428 // DeclStmt that gets created in this case.
5429 // FIXME: Also return the IndirectFieldDecls created by
5430 // BuildAnonymousStructOr union, for the same reason?
5431 if (CurContext->isFunctionOrMethod())
5432 AnonRecord = Record;
5433 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5434 Context.getPrintingPolicy());
5435 }
5436
5437 DeclaresAnything = false;
5438 }
5439 }
5440
5441 // C11 6.7.2.1p2:
5442 // A struct-declaration that does not declare an anonymous structure or
5443 // anonymous union shall contain a struct-declarator-list.
5444 //
5445 // This rule also existed in C89 and C99; the grammar for struct-declaration
5446 // did not permit a struct-declaration without a struct-declarator-list.
5447 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5449 // Check for Microsoft C extension: anonymous struct/union member.
5450 // Handle 2 kinds of anonymous struct/union:
5451 // struct STRUCT;
5452 // union UNION;
5453 // and
5454 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5455 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5456 if ((Tag && Tag->getDeclName()) ||
5458 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5459 : DS.getRepAsType().get()->getAsRecordDecl();
5460 if (Record && getLangOpts().MSAnonymousStructs) {
5461 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5462 << Record->isUnion() << DS.getSourceRange();
5464 }
5465
5466 DeclaresAnything = false;
5467 }
5468 }
5469
5470 // Skip all the checks below if we have a type error.
5472 (TagD && TagD->isInvalidDecl()))
5473 return TagD;
5474
5475 if (getLangOpts().CPlusPlus &&
5477 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5478 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5479 !Enum->isInvalidDecl())
5480 DeclaresAnything = false;
5481
5482 if (!DS.isMissingDeclaratorOk()) {
5483 // Customize diagnostic for a typedef missing a name.
5485 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5486 << DS.getSourceRange();
5487 else
5488 DeclaresAnything = false;
5489 }
5490
5491 if (DS.isModulePrivateSpecified() &&
5492 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5493 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5494 << Tag->getTagKind()
5496
5498
5499 // C 6.7/2:
5500 // A declaration [...] shall declare at least a declarator [...], a tag,
5501 // or the members of an enumeration.
5502 // C++ [dcl.dcl]p3:
5503 // [If there are no declarators], and except for the declaration of an
5504 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5505 // names into the program, or shall redeclare a name introduced by a
5506 // previous declaration.
5507 if (!DeclaresAnything) {
5508 // In C, we allow this as a (popular) extension / bug. Don't bother
5509 // producing further diagnostics for redundant qualifiers after this.
5510 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5511 ? diag::err_no_declarators
5512 : diag::ext_no_declarators)
5513 << DS.getSourceRange();
5514 return TagD;
5515 }
5516
5517 // C++ [dcl.stc]p1:
5518 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5519 // init-declarator-list of the declaration shall not be empty.
5520 // C++ [dcl.fct.spec]p1:
5521 // If a cv-qualifier appears in a decl-specifier-seq, the
5522 // init-declarator-list of the declaration shall not be empty.
5523 //
5524 // Spurious qualifiers here appear to be valid in C.
5525 unsigned DiagID = diag::warn_standalone_specifier;
5526 if (getLangOpts().CPlusPlus)
5527 DiagID = diag::ext_standalone_specifier;
5528
5529 // Note that a linkage-specification sets a storage class, but
5530 // 'extern "C" struct foo;' is actually valid and not theoretically
5531 // useless.
5532 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5533 if (SCS == DeclSpec::SCS_mutable)
5534 // Since mutable is not a viable storage class specifier in C, there is
5535 // no reason to treat it as an extension. Instead, diagnose as an error.
5536 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5537 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5538 Diag(DS.getStorageClassSpecLoc(), DiagID)
5540 }
5541
5545 if (DS.getTypeQualifiers()) {
5547 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5549 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5550 // Restrict is covered above.
5552 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5554 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5555 }
5556
5557 // Warn about ignored type attributes, for example:
5558 // __attribute__((aligned)) struct A;
5559 // Attributes should be placed after tag to apply to type declaration.
5560 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5561 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5562 if (TypeSpecType == DeclSpec::TST_class ||
5563 TypeSpecType == DeclSpec::TST_struct ||
5564 TypeSpecType == DeclSpec::TST_interface ||
5565 TypeSpecType == DeclSpec::TST_union ||
5566 TypeSpecType == DeclSpec::TST_enum) {
5567
5568 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5569 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5570 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5571 DiagnosticId = diag::warn_attribute_ignored;
5572 else if (AL.isRegularKeywordAttribute())
5573 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5574 else
5575 DiagnosticId = diag::warn_declspec_attribute_ignored;
5576 Diag(AL.getLoc(), DiagnosticId)
5577 << AL << GetDiagnosticTypeSpecifierID(DS);
5578 };
5579
5580 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5581 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5582 }
5583 }
5584
5585 return TagD;
5586}
5587
5588/// We are trying to inject an anonymous member into the given scope;
5589/// check if there's an existing declaration that can't be overloaded.
5590///
5591/// \return true if this is a forbidden redeclaration
5592static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5593 DeclContext *Owner,
5594 DeclarationName Name,
5595 SourceLocation NameLoc, bool IsUnion,
5596 StorageClass SC) {
5597 LookupResult R(SemaRef, Name, NameLoc,
5601 if (!SemaRef.LookupName(R, S)) return false;
5602
5603 // Pick a representative declaration.
5604 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5605 assert(PrevDecl && "Expected a non-null Decl");
5606
5607 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5608 return false;
5609
5610 if (SC == StorageClass::SC_None &&
5611 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5612 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5613 if (!Owner->isRecord())
5614 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5615 return false;
5616 }
5617
5618 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5619 << IsUnion << Name;
5620 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5621
5622 return true;
5623}
5624
5626 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5628}
5629
5631 if (!getLangOpts().CPlusPlus)
5632 return;
5633
5634 // This function can be parsed before we have validated the
5635 // structure as an anonymous struct
5636 if (Record->isAnonymousStructOrUnion())
5637 return;
5638
5639 const NamedDecl *First = 0;
5640 for (const Decl *D : Record->decls()) {
5641 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5642 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5643 continue;
5644 if (!First)
5645 First = ND;
5646 else
5648 }
5649}
5650
5651/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5652/// anonymous struct or union AnonRecord into the owning context Owner
5653/// and scope S. This routine will be invoked just after we realize
5654/// that an unnamed union or struct is actually an anonymous union or
5655/// struct, e.g.,
5656///
5657/// @code
5658/// union {
5659/// int i;
5660/// float f;
5661/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5662/// // f into the surrounding scope.x
5663/// @endcode
5664///
5665/// This routine is recursive, injecting the names of nested anonymous
5666/// structs/unions into the owning context and scope as well.
5667static bool
5669 RecordDecl *AnonRecord, AccessSpecifier AS,
5670 StorageClass SC,
5671 SmallVectorImpl<NamedDecl *> &Chaining) {
5672 bool Invalid = false;
5673
5674 // Look every FieldDecl and IndirectFieldDecl with a name.
5675 for (auto *D : AnonRecord->decls()) {
5676 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5677 cast<NamedDecl>(D)->getDeclName()) {
5678 ValueDecl *VD = cast<ValueDecl>(D);
5679 // C++ [class.union]p2:
5680 // The names of the members of an anonymous union shall be
5681 // distinct from the names of any other entity in the
5682 // scope in which the anonymous union is declared.
5683
5684 bool FieldInvalid = CheckAnonMemberRedeclaration(
5685 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5686 AnonRecord->isUnion(), SC);
5687 if (FieldInvalid)
5688 Invalid = true;
5689
5690 // Inject the IndirectFieldDecl even if invalid, because later
5691 // diagnostics may depend on it being present, see findDefaultInitializer.
5692
5693 // C++ [class.union]p2:
5694 // For the purpose of name lookup, after the anonymous union
5695 // definition, the members of the anonymous union are
5696 // considered to have been defined in the scope in which the
5697 // anonymous union is declared.
5698 unsigned OldChainingSize = Chaining.size();
5699 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5700 Chaining.append(IF->chain_begin(), IF->chain_end());
5701 else
5702 Chaining.push_back(VD);
5703
5704 assert(Chaining.size() >= 2);
5705 NamedDecl **NamedChain =
5706 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5707 for (unsigned i = 0; i < Chaining.size(); i++)
5708 NamedChain[i] = Chaining[i];
5709
5711 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5712 VD->getType(), {NamedChain, Chaining.size()});
5713
5714 for (const auto *Attr : VD->attrs())
5715 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5716
5717 IndirectField->setAccess(AS);
5718 IndirectField->setImplicit();
5719 IndirectField->setInvalidDecl(FieldInvalid);
5720 SemaRef.PushOnScopeChains(IndirectField, S);
5721
5722 // That includes picking up the appropriate access specifier.
5723 if (AS != AS_none)
5724 IndirectField->setAccess(AS);
5725
5726 Chaining.resize(OldChainingSize);
5727 }
5728 }
5729
5730 return Invalid;
5731}
5732
5733/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5734/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5735/// illegal input values are mapped to SC_None.
5736static StorageClass
5738 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5739 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5740 "Parser allowed 'typedef' as storage class VarDecl.");
5741 switch (StorageClassSpec) {
5744 if (DS.isExternInLinkageSpec())
5745 return SC_None;
5746 return SC_Extern;
5747 case DeclSpec::SCS_static: return SC_Static;
5748 case DeclSpec::SCS_auto: return SC_Auto;
5751 // Illegal SCSs map to None: error reporting is up to the caller.
5752 case DeclSpec::SCS_mutable: // Fall through.
5753 case DeclSpec::SCS_typedef: return SC_None;
5754 }
5755 llvm_unreachable("unknown storage class specifier");
5756}
5757
5759 assert(Record->hasInClassInitializer());
5760
5761 for (const auto *I : Record->decls()) {
5762 const auto *FD = dyn_cast<FieldDecl>(I);
5763 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5764 FD = IFD->getAnonField();
5765 if (FD && FD->hasInClassInitializer())
5766 return FD->getLocation();
5767 }
5768
5769 llvm_unreachable("couldn't find in-class initializer");
5770}
5771
5773 SourceLocation DefaultInitLoc) {
5774 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5775 return;
5776
5777 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5778 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5779}
5780
5782 CXXRecordDecl *AnonUnion) {
5783 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5784 return;
5785
5787}
5788
5790 AccessSpecifier AS,
5792 const PrintingPolicy &Policy) {
5793 DeclContext *Owner = Record->getDeclContext();
5794
5795 // Diagnose whether this anonymous struct/union is an extension.
5796 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5797 Diag(Record->getLocation(), diag::ext_anonymous_union);
5798 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5799 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5800 else if (!Record->isUnion() && !getLangOpts().C11)
5801 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5802
5803 // C and C++ require different kinds of checks for anonymous
5804 // structs/unions.
5805 bool Invalid = false;
5806 if (getLangOpts().CPlusPlus) {
5807 const char *PrevSpec = nullptr;
5808 if (Record->isUnion()) {
5809 // C++ [class.union]p6:
5810 // C++17 [class.union.anon]p2:
5811 // Anonymous unions declared in a named namespace or in the
5812 // global namespace shall be declared static.
5813 unsigned DiagID;
5814 DeclContext *OwnerScope = Owner->getRedeclContext();
5816 (OwnerScope->isTranslationUnit() ||
5817 (OwnerScope->isNamespace() &&
5818 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5819 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5820 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5821
5822 // Recover by adding 'static'.
5824 PrevSpec, DiagID, Policy);
5825 }
5826 // C++ [class.union]p6:
5827 // A storage class is not allowed in a declaration of an
5828 // anonymous union in a class scope.
5830 isa<RecordDecl>(Owner)) {
5832 diag::err_anonymous_union_with_storage_spec)
5834
5835 // Recover by removing the storage specifier.
5838 PrevSpec, DiagID, Context.getPrintingPolicy());
5839 }
5840 }
5841
5842 // Ignore const/volatile/restrict qualifiers.
5843 if (DS.getTypeQualifiers()) {
5845 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5846 << Record->isUnion() << "const"
5850 diag::ext_anonymous_struct_union_qualified)
5851 << Record->isUnion() << "volatile"
5855 diag::ext_anonymous_struct_union_qualified)
5856 << Record->isUnion() << "restrict"
5860 diag::ext_anonymous_struct_union_qualified)
5861 << Record->isUnion() << "_Atomic"
5865 diag::ext_anonymous_struct_union_qualified)
5866 << Record->isUnion() << "__unaligned"
5868
5870 }
5871
5872 // C++ [class.union]p2:
5873 // The member-specification of an anonymous union shall only
5874 // define non-static data members. [Note: nested types and
5875 // functions cannot be declared within an anonymous union. ]
5876 for (auto *Mem : Record->decls()) {
5877 // Ignore invalid declarations; we already diagnosed them.
5878 if (Mem->isInvalidDecl())
5879 continue;
5880
5881 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5882 // C++ [class.union]p3:
5883 // An anonymous union shall not have private or protected
5884 // members (clause 11).
5885 assert(FD->getAccess() != AS_none);
5886 if (FD->getAccess() != AS_public) {
5887 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5888 << Record->isUnion() << (FD->getAccess() == AS_protected);
5889 Invalid = true;
5890 }
5891
5892 // C++ [class.union]p1
5893 // An object of a class with a non-trivial constructor, a non-trivial
5894 // copy constructor, a non-trivial destructor, or a non-trivial copy
5895 // assignment operator cannot be a member of a union, nor can an
5896 // array of such objects.
5897 if (CheckNontrivialField(FD))
5898 Invalid = true;
5899 } else if (Mem->isImplicit()) {
5900 // Any implicit members are fine.
5901 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5902 // This is a type that showed up in an
5903 // elaborated-type-specifier inside the anonymous struct or
5904 // union, but which actually declares a type outside of the
5905 // anonymous struct or union. It's okay.
5906 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5907 if (!MemRecord->isAnonymousStructOrUnion() &&
5908 MemRecord->getDeclName()) {
5909 // Visual C++ allows type definition in anonymous struct or union.
5910 if (getLangOpts().MicrosoftExt)
5911 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5912 << Record->isUnion();
5913 else {
5914 // This is a nested type declaration.
5915 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5916 << Record->isUnion();
5917 Invalid = true;
5918 }
5919 } else {
5920 // This is an anonymous type definition within another anonymous type.
5921 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5922 // not part of standard C++.
5923 Diag(MemRecord->getLocation(),
5924 diag::ext_anonymous_record_with_anonymous_type)
5925 << Record->isUnion();
5926 }
5927 } else if (isa<AccessSpecDecl>(Mem)) {
5928 // Any access specifier is fine.
5929 } else if (isa<StaticAssertDecl>(Mem)) {
5930 // In C++1z, static_assert declarations are also fine.
5931 } else {
5932 // We have something that isn't a non-static data
5933 // member. Complain about it.
5934 unsigned DK = diag::err_anonymous_record_bad_member;
5935 if (isa<TypeDecl>(Mem))
5936 DK = diag::err_anonymous_record_with_type;
5937 else if (isa<FunctionDecl>(Mem))
5938 DK = diag::err_anonymous_record_with_function;
5939 else if (isa<VarDecl>(Mem))
5940 DK = diag::err_anonymous_record_with_static;
5941
5942 // Visual C++ allows type definition in anonymous struct or union.
5943 if (getLangOpts().MicrosoftExt &&
5944 DK == diag::err_anonymous_record_with_type)
5945 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5946 << Record->isUnion();
5947 else {
5948 Diag(Mem->getLocation(), DK) << Record->isUnion();
5949 Invalid = true;
5950 }
5951 }
5952 }
5953
5954 // C++11 [class.union]p8 (DR1460):
5955 // At most one variant member of a union may have a
5956 // brace-or-equal-initializer.
5957 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5958 Owner->isRecord())
5961 }
5962
5963 if (!Record->isUnion() && !Owner->isRecord()) {
5964 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5965 << getLangOpts().CPlusPlus;
5966 Invalid = true;
5967 }
5968
5969 // C++ [dcl.dcl]p3:
5970 // [If there are no declarators], and except for the declaration of an
5971 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5972 // names into the program
5973 // C++ [class.mem]p2:
5974 // each such member-declaration shall either declare at least one member
5975 // name of the class or declare at least one unnamed bit-field
5976 //
5977 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5978 if (getLangOpts().CPlusPlus && Record->field_empty())
5979 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5980
5981 // Mock up a declarator.
5985 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5986
5987 // Create a declaration for this anonymous struct/union.
5988 NamedDecl *Anon = nullptr;
5989 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5990 Anon = FieldDecl::Create(
5991 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5992 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5993 /*BitWidth=*/nullptr, /*Mutable=*/false,
5994 /*InitStyle=*/ICIS_NoInit);
5995 Anon->setAccess(AS);
5996 ProcessDeclAttributes(S, Anon, Dc);
5997
5998 if (getLangOpts().CPlusPlus)
5999 FieldCollector->Add(cast<FieldDecl>(Anon));
6000 } else {
6001 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
6002 if (SCSpec == DeclSpec::SCS_mutable) {
6003 // mutable can only appear on non-static class members, so it's always
6004 // an error here
6005 Diag(Record->getLocation(), diag::err_mutable_nonmember);
6006 Invalid = true;
6007 SC = SC_None;
6008 }
6009
6010 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
6011 Record->getLocation(), /*IdentifierInfo=*/nullptr,
6012 Context.getCanonicalTagType(Record), TInfo, SC);
6013 if (Invalid)
6014 Anon->setInvalidDecl();
6015
6016 ProcessDeclAttributes(S, Anon, Dc);
6017
6018 // Default-initialize the implicit variable. This initialization will be
6019 // trivial in almost all cases, except if a union member has an in-class
6020 // initializer:
6021 // union { int n = 0; };
6023 }
6024 Anon->setImplicit();
6025
6026 // Mark this as an anonymous struct/union type.
6027 Record->setAnonymousStructOrUnion(true);
6028
6029 // Add the anonymous struct/union object to the current
6030 // context. We'll be referencing this object when we refer to one of
6031 // its members.
6032 Owner->addDecl(Anon);
6033
6034 // Inject the members of the anonymous struct/union into the owning
6035 // context and into the identifier resolver chain for name lookup
6036 // purposes.
6038 Chain.push_back(Anon);
6039
6040 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
6041 Chain))
6042 Invalid = true;
6043
6044 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
6045 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6047 Decl *ManglingContextDecl;
6048 std::tie(MCtx, ManglingContextDecl) =
6049 getCurrentMangleNumberContext(NewVD->getDeclContext());
6050 if (MCtx) {
6051 Context.setManglingNumber(
6052 NewVD, MCtx->getManglingNumber(
6053 NewVD, getMSManglingNumber(getLangOpts(), S)));
6054 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6055 }
6056 }
6057 }
6058
6059 if (Invalid)
6060 Anon->setInvalidDecl();
6061
6062 return Anon;
6063}
6064
6066 RecordDecl *Record) {
6067 assert(Record && "expected a record!");
6068
6069 // Mock up a declarator.
6072 assert(TInfo && "couldn't build declarator info for anonymous struct");
6073
6074 auto *ParentDecl = cast<RecordDecl>(CurContext);
6075 CanQualType RecTy = Context.getCanonicalTagType(Record);
6076
6077 // Create a declaration for this anonymous struct.
6078 NamedDecl *Anon =
6079 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
6080 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6081 /*BitWidth=*/nullptr, /*Mutable=*/false,
6082 /*InitStyle=*/ICIS_NoInit);
6083 Anon->setImplicit();
6084
6085 // Add the anonymous struct object to the current context.
6086 CurContext->addDecl(Anon);
6087
6088 // Inject the members of the anonymous struct into the current
6089 // context and into the identifier resolver chain for name lookup
6090 // purposes.
6092 Chain.push_back(Anon);
6093
6094 RecordDecl *RecordDef = Record->getDefinition();
6095 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6096 diag::err_field_incomplete_or_sizeless) ||
6098 *this, S, CurContext, RecordDef, AS_none,
6100 Anon->setInvalidDecl();
6101 ParentDecl->setInvalidDecl();
6102 }
6103
6104 return Anon;
6105}
6106
6110
6113 DeclarationNameInfo NameInfo;
6114 NameInfo.setLoc(Name.StartLocation);
6115
6116 switch (Name.getKind()) {
6117
6120 NameInfo.setName(Name.Identifier);
6121 return NameInfo;
6122
6124 // C++ [temp.deduct.guide]p3:
6125 // The simple-template-id shall name a class template specialization.
6126 // The template-name shall be the same identifier as the template-name
6127 // of the simple-template-id.
6128 // These together intend to imply that the template-name shall name a
6129 // class template.
6130 // FIXME: template<typename T> struct X {};
6131 // template<typename T> using Y = X<T>;
6132 // Y(int) -> Y<int>;
6133 // satisfies these rules but does not name a class template.
6134 TemplateName TN = Name.TemplateName.get().get();
6135 auto *Template = TN.getAsTemplateDecl();
6137 Diag(Name.StartLocation,
6138 diag::err_deduction_guide_name_not_class_template)
6139 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6140 if (Template)
6142 return DeclarationNameInfo();
6143 }
6144
6145 NameInfo.setName(
6146 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6147 return NameInfo;
6148 }
6149
6151 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6155 return NameInfo;
6156
6158 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6159 Name.Identifier));
6161 return NameInfo;
6162
6164 TypeSourceInfo *TInfo;
6166 if (Ty.isNull())
6167 return DeclarationNameInfo();
6168 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6169 Context.getCanonicalType(Ty)));
6170 NameInfo.setNamedTypeInfo(TInfo);
6171 return NameInfo;
6172 }
6173
6175 TypeSourceInfo *TInfo;
6176 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6177 if (Ty.isNull())
6178 return DeclarationNameInfo();
6179 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6180 Context.getCanonicalType(Ty)));
6181 NameInfo.setNamedTypeInfo(TInfo);
6182 return NameInfo;
6183 }
6184
6186 // In well-formed code, we can only have a constructor
6187 // template-id that refers to the current context, so go there
6188 // to find the actual type being constructed.
6189 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6190 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6191 return DeclarationNameInfo();
6192
6193 // Determine the type of the class being constructed.
6194 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6195
6196 // FIXME: Check two things: that the template-id names the same type as
6197 // CurClassType, and that the template-id does not occur when the name
6198 // was qualified.
6199
6200 NameInfo.setName(
6201 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6202 // FIXME: should we retrieve TypeSourceInfo?
6203 NameInfo.setNamedTypeInfo(nullptr);
6204 return NameInfo;
6205 }
6206
6208 TypeSourceInfo *TInfo;
6209 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6210 if (Ty.isNull())
6211 return DeclarationNameInfo();
6212 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6213 Context.getCanonicalType(Ty)));
6214 NameInfo.setNamedTypeInfo(TInfo);
6215 return NameInfo;
6216 }
6217
6219 TemplateName TName = Name.TemplateId->Template.get();
6220 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6221 return Context.getNameForTemplate(TName, TNameLoc);
6222 }
6223
6224 } // switch (Name.getKind())
6225
6226 llvm_unreachable("Unknown name kind");
6227}
6228
6230 do {
6231 if (Ty->isPointerOrReferenceType())
6232 Ty = Ty->getPointeeType();
6233 else if (Ty->isArrayType())
6235 else
6236 return Ty.withoutLocalFastQualifiers();
6237 } while (true);
6238}
6239
6240/// hasSimilarParameters - Determine whether the C++ functions Declaration
6241/// and Definition have "nearly" matching parameters. This heuristic is
6242/// used to improve diagnostics in the case where an out-of-line function
6243/// definition doesn't match any declaration within the class or namespace.
6244/// Also sets Params to the list of indices to the parameters that differ
6245/// between the declaration and the definition. If hasSimilarParameters
6246/// returns true and Params is empty, then all of the parameters match.
6250 SmallVectorImpl<unsigned> &Params) {
6251 Params.clear();
6252 if (Declaration->param_size() != Definition->param_size())
6253 return false;
6254 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6255 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6256 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6257
6258 // The parameter types are identical
6259 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6260 continue;
6261
6262 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6263 QualType DefParamBaseTy = getCoreType(DefParamTy);
6264 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6265 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6266
6267 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6268 (DeclTyName && DeclTyName == DefTyName))
6269 Params.push_back(Idx);
6270 else // The two parameters aren't even close
6271 return false;
6272 }
6273
6274 return true;
6275}
6276
6277/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6278/// declarator needs to be rebuilt in the current instantiation.
6279/// Any bits of declarator which appear before the name are valid for
6280/// consideration here. That's specifically the type in the decl spec
6281/// and the base type in any member-pointer chunks.
6283 DeclarationName Name) {
6284 // The types we specifically need to rebuild are:
6285 // - typenames, typeofs, and decltypes
6286 // - types which will become injected class names
6287 // Of course, we also need to rebuild any type referencing such a
6288 // type. It's safest to just say "dependent", but we call out a
6289 // few cases here.
6290
6291 DeclSpec &DS = D.getMutableDeclSpec();
6292 switch (DS.getTypeSpecType()) {
6296#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6297#include "clang/Basic/BuiltinTraits.inc"
6298 case DeclSpec::TST_atomic: {
6299 // Grab the type from the parser.
6300 TypeSourceInfo *TSI = nullptr;
6301 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6302 if (T.isNull() || !T->isInstantiationDependentType()) break;
6303
6304 // Make sure there's a type source info. This isn't really much
6305 // of a waste; most dependent types should have type source info
6306 // attached already.
6307 if (!TSI)
6309
6310 // Rebuild the type in the current instantiation.
6312 if (!TSI) return true;
6313
6314 // Store the new type back in the decl spec.
6315 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6316 DS.UpdateTypeRep(LocType);
6317 break;
6318 }
6319
6323 Expr *E = DS.getRepAsExpr();
6325 if (Result.isInvalid()) return true;
6326 DS.UpdateExprRep(Result.get());
6327 break;
6328 }
6329
6330 default:
6331 // Nothing to do for these decl specs.
6332 break;
6333 }
6334
6335 // It doesn't matter what order we do this in.
6336 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6337 DeclaratorChunk &Chunk = D.getTypeObject(I);
6338
6339 // The only type information in the declarator which can come
6340 // before the declaration name is the base type of a member
6341 // pointer.
6343 continue;
6344
6345 // Rebuild the scope specifier in-place.
6346 CXXScopeSpec &SS = Chunk.Mem.Scope();
6348 return true;
6349 }
6350
6351 return false;
6352}
6353
6354/// Returns true if the declaration is declared in a system header or from a
6355/// system macro.
6356static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6357 return SM.isInSystemHeader(D->getLocation()) ||
6359}
6360
6362 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6363 // of system decl.
6364 if (D->getPreviousDecl() || D->isImplicit())
6365 return;
6368 !isFromSystemHeader(Context.getSourceManager(), D)) {
6369 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6370 << D << static_cast<int>(Status);
6371 }
6372}
6373
6376
6377 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6378 // declaration only if the `bind_to_declaration` extension is set.
6380 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6381 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6382 llvm::omp::TraitProperty::
6383 implementation_extension_bind_to_declaration))
6385 S, D, MultiTemplateParamsArg(), Bases);
6386
6388
6389 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6390 Dcl && Dcl->getDeclContext()->isFileContext())
6392
6393 if (!Bases.empty())
6395 Bases);
6396
6397 return Dcl;
6398}
6399
6401 DeclarationNameInfo NameInfo) {
6402 DeclarationName Name = NameInfo.getName();
6403
6404 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6405 while (Record && Record->isAnonymousStructOrUnion())
6406 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6407 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6408 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6409 return true;
6410 }
6411
6412 return false;
6413}
6414
6416 DeclarationName Name,
6417 SourceLocation Loc,
6418 TemplateIdAnnotation *TemplateId,
6419 bool IsMemberSpecialization) {
6420 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6421 "without nested-name-specifier");
6422 DeclContext *Cur = CurContext;
6423 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6424 Cur = Cur->getParent();
6425
6426 // If the user provided a superfluous scope specifier that refers back to the
6427 // class in which the entity is already declared, diagnose and ignore it.
6428 //
6429 // class X {
6430 // void X::f();
6431 // };
6432 //
6433 // Note, it was once ill-formed to give redundant qualification in all
6434 // contexts, but that rule was removed by DR482.
6435 if (Cur->Equals(DC)) {
6436 if (Cur->isRecord()) {
6437 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6438 : diag::err_member_extra_qualification)
6439 << Name << FixItHint::CreateRemoval(SS.getRange());
6440 SS.clear();
6441 } else {
6442 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6443 }
6444 return false;
6445 }
6446
6447 // Check whether the qualifying scope encloses the scope of the original
6448 // declaration. For a template-id, we perform the checks in
6449 // CheckTemplateSpecializationScope.
6450 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6452 if (Cur->isRecord())
6453 Diag(Loc, diag::err_member_qualification)
6454 << Name << SS.getRange();
6455 else if (isa<TranslationUnitDecl>(DC))
6456 Diag(Loc, diag::err_invalid_declarator_global_scope)
6457 << Name << SS.getRange();
6458 else if (isa<FunctionDecl>(Cur))
6459 Diag(Loc, diag::err_invalid_declarator_in_function)
6460 << Name << SS.getRange();
6461 else if (isa<BlockDecl>(Cur))
6462 Diag(Loc, diag::err_invalid_declarator_in_block)
6463 << Name << SS.getRange();
6464 else if (isa<ExportDecl>(Cur)) {
6465 if (!isa<NamespaceDecl>(DC))
6466 Diag(Loc, diag::err_export_non_namespace_scope_name)
6467 << Name << SS.getRange();
6468 else
6469 // The cases that DC is not NamespaceDecl should be handled in
6470 // CheckRedeclarationExported.
6471 return false;
6472 } else
6473 Diag(Loc, diag::err_invalid_declarator_scope)
6474 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6475
6476 return true;
6477 }
6478
6479 if (Cur->isRecord()) {
6480 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6481 // An explicit specialization may be declared in any scope in which the
6482 // corresponding primary template may be defined.
6483 if (IsMemberSpecialization)
6484 return false;
6485
6486 // Cannot qualify members within a class.
6487 Diag(Loc, diag::err_member_qualification)
6488 << Name << SS.getRange();
6489 SS.clear();
6490
6491 // C++ constructors and destructors with incorrect scopes can break
6492 // our AST invariants by having the wrong underlying types. If
6493 // that's the case, then drop this declaration entirely.
6496 !Context.hasSameType(
6497 Name.getCXXNameType(),
6498 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6499 return true;
6500
6501 return false;
6502 }
6503
6504 // C++23 [temp.names]p5:
6505 // The keyword template shall not appear immediately after a declarative
6506 // nested-name-specifier.
6507 //
6508 // First check the template-id (if any), and then check each component of the
6509 // nested-name-specifier in reverse order.
6510 //
6511 // FIXME: nested-name-specifiers in friend declarations are declarative,
6512 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6513 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6514 Diag(Loc, diag::ext_template_after_declarative_nns)
6516
6518 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6519 TL = std::exchange(NextTL, TypeLoc())) {
6520 SourceLocation TemplateKeywordLoc;
6521 switch (TL.getTypeLocClass()) {
6522 case TypeLoc::TemplateSpecialization: {
6523 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6524 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6525 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6526 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6527 << TST.getLocalSourceRange();
6528 break;
6529 }
6530 case TypeLoc::Decltype:
6531 case TypeLoc::PackIndexing: {
6532 const Type *T = TL.getTypePtr();
6533 // C++23 [expr.prim.id.qual]p2:
6534 // [...] A declarative nested-name-specifier shall not have a
6535 // computed-type-specifier.
6536 //
6537 // CWG2858 changed this from 'decltype-specifier' to
6538 // 'computed-type-specifier'.
6539 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6540 << T->isDecltypeType() << TL.getSourceRange();
6541 break;
6542 }
6543 case TypeLoc::DependentName:
6544 NextTL =
6545 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6546 break;
6547 default:
6548 break;
6549 }
6550 if (TemplateKeywordLoc.isValid())
6551 Diag(Loc, diag::ext_template_after_declarative_nns)
6552 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6553 }
6554
6555 return false;
6556}
6557
6559 MultiTemplateParamsArg TemplateParamLists) {
6560 // TODO: consider using NameInfo for diagnostic.
6562 DeclarationName Name = NameInfo.getName();
6563
6564 // All of these full declarators require an identifier. If it doesn't have
6565 // one, the ParsedFreeStandingDeclSpec action should be used.
6566 if (D.isDecompositionDeclarator()) {
6567 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6568 } else if (!Name) {
6569 if (!D.isInvalidType()) // Reject this if we think it is valid.
6570 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6572 return nullptr;
6574 return nullptr;
6575
6576 DeclContext *DC = CurContext;
6577 if (D.getCXXScopeSpec().isInvalid())
6578 D.setInvalidType();
6579 else if (D.getCXXScopeSpec().isSet()) {
6582 return nullptr;
6583
6584 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6585 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6586 if (!DC || isa<EnumDecl>(DC)) {
6587 // If we could not compute the declaration context, it's because the
6588 // declaration context is dependent but does not refer to a class,
6589 // class template, or class template partial specialization. Complain
6590 // and return early, to avoid the coming semantic disaster.
6592 diag::err_template_qualified_declarator_no_match)
6594 << D.getCXXScopeSpec().getRange();
6595 return nullptr;
6596 }
6597 bool IsDependentContext = DC->isDependentContext();
6598
6599 if (!IsDependentContext &&
6601 return nullptr;
6602
6603 // If a class is incomplete, do not parse entities inside it.
6606 diag::err_member_def_undefined_record)
6607 << Name << DC << D.getCXXScopeSpec().getRange();
6608 return nullptr;
6609 }
6610 if (!D.getDeclSpec().isFriendSpecified()) {
6611 TemplateIdAnnotation *TemplateId =
6613 ? D.getName().TemplateId
6614 : nullptr;
6616 D.getIdentifierLoc(), TemplateId,
6617 /*IsMemberSpecialization=*/false)) {
6618 if (DC->isRecord())
6619 return nullptr;
6620
6621 D.setInvalidType();
6622 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6623 D.setInvalidType();
6624 }
6625 }
6626
6627 // Check whether we need to rebuild the type of the given
6628 // declaration in the current instantiation.
6629 if (EnteringContext && IsDependentContext &&
6630 TemplateParamLists.size() != 0) {
6631 ContextRAII SavedContext(*this, DC);
6632 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6633 D.setInvalidType();
6634 }
6635 }
6636
6638 QualType R = TInfo->getType();
6639
6642 D.setInvalidType();
6643
6644 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6646
6647 // See if this is a redefinition of a variable in the same scope.
6648 if (!D.getCXXScopeSpec().isSet()) {
6649 bool IsLinkageLookup = false;
6650 bool CreateBuiltins = false;
6651
6652 // If the declaration we're planning to build will be a function
6653 // or object with linkage, then look for another declaration with
6654 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6655 //
6656 // If the declaration we're planning to build will be declared with
6657 // external linkage in the translation unit, create any builtin with
6658 // the same name.
6660 /* Do nothing*/;
6661 else if (CurContext->isFunctionOrMethod() &&
6663 R->isFunctionType())) {
6664 IsLinkageLookup = true;
6665 CreateBuiltins =
6666 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6667 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6669 CreateBuiltins = true;
6670
6671 if (IsLinkageLookup) {
6673 Previous.setRedeclarationKind(
6675 }
6676
6677 LookupName(Previous, S, CreateBuiltins);
6678 } else { // Something like "int foo::x;"
6680
6681 // C++ [dcl.meaning]p1:
6682 // When the declarator-id is qualified, the declaration shall refer to a
6683 // previously declared member of the class or namespace to which the
6684 // qualifier refers (or, in the case of a namespace, of an element of the
6685 // inline namespace set of that namespace (7.3.1)) or to a specialization
6686 // thereof; [...]
6687 //
6688 // Note that we already checked the context above, and that we do not have
6689 // enough information to make sure that Previous contains the declaration
6690 // we want to match. For example, given:
6691 //
6692 // class X {
6693 // void f();
6694 // void f(float);
6695 // };
6696 //
6697 // void X::f(int) { } // ill-formed
6698 //
6699 // In this case, Previous will point to the overload set
6700 // containing the two f's declared in X, but neither of them
6701 // matches.
6702
6704 }
6705
6706 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6707 TPD && TPD->isTemplateParameter()) {
6708 // Older versions of clang allowed the names of function/variable templates
6709 // to shadow the names of their template parameters. For the compatibility
6710 // purposes we detect such cases and issue a default-to-error warning that
6711 // can be disabled with -Wno-strict-primary-template-shadow.
6712 if (!D.isInvalidType()) {
6713 bool AllowForCompatibility = false;
6714 if (Scope *DeclParent = S->getDeclParent();
6715 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6716 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6717 TemplateParamParent->isDeclScope(TPD);
6718 }
6720 AllowForCompatibility);
6721 }
6722
6723 // Just pretend that we didn't see the previous declaration.
6724 Previous.clear();
6725 }
6726
6727 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6728 // Forget that the previous declaration is the injected-class-name.
6729 Previous.clear();
6730
6731 // In C++, the previous declaration we find might be a tag type
6732 // (class or enum). In this case, the new declaration will hide the
6733 // tag type. Note that this applies to functions, function templates, and
6734 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6735 if (Previous.isSingleTagDecl() &&
6737 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6738 Previous.clear();
6739
6740 // Check that there are no default arguments other than in the parameters
6741 // of a function declaration (C++ only).
6742 if (getLangOpts().CPlusPlus)
6744
6745 /// Get the innermost enclosing declaration scope.
6746 S = S->getDeclParent();
6747
6748 NamedDecl *New;
6749
6750 bool AddToScope = true;
6752 if (TemplateParamLists.size()) {
6753 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6754 return nullptr;
6755 }
6756
6757 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6758 } else if (R->isFunctionType()) {
6759 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6760 TemplateParamLists,
6761 AddToScope);
6762 } else {
6763 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6764 AddToScope);
6765 }
6766
6767 if (!New)
6768 return nullptr;
6769
6771
6772 // If this has an identifier and is not a function template specialization,
6773 // add it to the scope stack.
6774 if (New->getDeclName() && AddToScope)
6776
6777 if (OpenMP().isInOpenMPDeclareTargetContext())
6779
6780 return New;
6781}
6782
6783/// Helper method to turn variable array types into constant array
6784/// types in certain situations which would otherwise be errors (for
6785/// GCC compatibility).
6787 ASTContext &Context,
6788 bool &SizeIsNegative,
6789 llvm::APSInt &Oversized) {
6790 // This method tries to turn a variable array into a constant
6791 // array even when the size isn't an ICE. This is necessary
6792 // for compatibility with code that depends on gcc's buggy
6793 // constant expression folding, like struct {char x[(int)(char*)2];}
6794 SizeIsNegative = false;
6795 Oversized = 0;
6796
6797 if (T->isDependentType())
6798 return QualType();
6799
6801 const Type *Ty = Qs.strip(T);
6802
6803 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6804 QualType Pointee = PTy->getPointeeType();
6805 QualType FixedType =
6806 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6807 Oversized);
6808 if (FixedType.isNull()) return FixedType;
6809 FixedType = Context.getPointerType(FixedType);
6810 return Qs.apply(Context, FixedType);
6811 }
6812 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6813 QualType Inner = PTy->getInnerType();
6814 QualType FixedType =
6815 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6816 Oversized);
6817 if (FixedType.isNull()) return FixedType;
6818 FixedType = Context.getParenType(FixedType);
6819 return Qs.apply(Context, FixedType);
6820 }
6821
6822 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6823 if (!VLATy)
6824 return QualType();
6825
6826 QualType ElemTy = VLATy->getElementType();
6827 if (ElemTy->isVariablyModifiedType()) {
6828 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6829 SizeIsNegative, Oversized);
6830 if (ElemTy.isNull())
6831 return QualType();
6832 }
6833
6835 if (!VLATy->getSizeExpr() ||
6836 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6837 return QualType();
6838
6839 llvm::APSInt Res = Result.Val.getInt();
6840
6841 // Check whether the array size is negative.
6842 if (Res.isSigned() && Res.isNegative()) {
6843 SizeIsNegative = true;
6844 return QualType();
6845 }
6846
6847 // Check whether the array is too large to be addressed.
6848 unsigned ActiveSizeBits =
6849 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6850 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6851 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6852 : Res.getActiveBits();
6853 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6854 Oversized = std::move(Res);
6855 return QualType();
6856 }
6857
6858 QualType FoldedArrayType = Context.getConstantArrayType(
6859 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6860 return Qs.apply(Context, FoldedArrayType);
6861}
6862
6863static void
6865 SrcTL = SrcTL.getUnqualifiedLoc();
6866 DstTL = DstTL.getUnqualifiedLoc();
6867 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6868 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6869 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6870 DstPTL.getPointeeLoc());
6871 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6872 return;
6873 }
6874 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6875 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6876 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6877 DstPTL.getInnerLoc());
6878 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6879 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6880 return;
6881 }
6882 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6883 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6884 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6885 TypeLoc DstElemTL = DstATL.getElementLoc();
6886 if (VariableArrayTypeLoc SrcElemATL =
6887 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6888 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6889 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6890 } else {
6891 DstElemTL.initializeFullCopy(SrcElemTL);
6892 }
6893 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6894 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6895 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6896}
6897
6898/// Helper method to turn variable array types into constant array
6899/// types in certain situations which would otherwise be errors (for
6900/// GCC compatibility).
6901static TypeSourceInfo*
6903 ASTContext &Context,
6904 bool &SizeIsNegative,
6905 llvm::APSInt &Oversized) {
6906 QualType FixedTy
6907 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6908 SizeIsNegative, Oversized);
6909 if (FixedTy.isNull())
6910 return nullptr;
6911 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6913 FixedTInfo->getTypeLoc());
6914 return FixedTInfo;
6915}
6916
6919 unsigned FailedFoldDiagID) {
6920 bool SizeIsNegative;
6921 llvm::APSInt Oversized;
6923 TInfo, Context, SizeIsNegative, Oversized);
6924 if (FixedTInfo) {
6925 Diag(Loc, diag::ext_vla_folded_to_constant);
6926 TInfo = FixedTInfo;
6927 T = FixedTInfo->getType();
6928 return true;
6929 }
6930
6931 if (SizeIsNegative)
6932 Diag(Loc, diag::err_typecheck_negative_array_size);
6933 else if (Oversized.getBoolValue())
6934 Diag(Loc, diag::err_array_too_large) << toString(
6935 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6936 /*UpperCase=*/false, /*InsertSeparators=*/true);
6937 else if (FailedFoldDiagID)
6938 Diag(Loc, FailedFoldDiagID);
6939 return false;
6940}
6941
6942void
6944 if (!getLangOpts().CPlusPlus &&
6946 // Don't need to track declarations in the TU in C.
6947 return;
6948
6949 // Note that we have a locally-scoped external with this name.
6950 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6951}
6952
6954 // FIXME: We can have multiple results via __attribute__((overloadable)).
6955 auto Result = Context.getExternCContextDecl()->lookup(Name);
6956 return Result.empty() ? nullptr : *Result.begin();
6957}
6958
6960 // FIXME: We should probably indicate the identifier in question to avoid
6961 // confusion for constructs like "virtual int a(), b;"
6962 if (DS.isVirtualSpecified())
6964 diag::err_virtual_non_function);
6965
6966 if (DS.hasExplicitSpecifier())
6968 diag::err_explicit_non_function);
6969
6970 if (DS.isNoreturnSpecified())
6972 diag::err_noreturn_non_function);
6973}
6974
6975NamedDecl*
6978 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6979 if (D.getCXXScopeSpec().isSet()) {
6980 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6981 << D.getCXXScopeSpec().getRange();
6982 D.setInvalidType();
6983 // Pretend we didn't see the scope specifier.
6984 DC = CurContext;
6985 Previous.clear();
6986 }
6987
6989
6992 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6993 ? diag::warn_ms_inline_non_function
6994 : diag::err_inline_non_function)
6995 << getLangOpts().CPlusPlus17;
6997 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6998 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6999
7003 diag::err_deduction_guide_invalid_specifier)
7004 << "typedef";
7005 else
7006 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
7007 << D.getName().getSourceRange();
7008 return nullptr;
7009 }
7010
7011 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
7012 if (!NewTD) return nullptr;
7013
7014 // Handle attributes prior to checking for duplicates in MergeVarDecl
7015 ProcessDeclAttributes(S, NewTD, D);
7016
7018
7019 bool Redeclaration = D.isRedeclaration();
7022 return ND;
7023}
7024
7025void
7027 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7028 // then it shall have block scope.
7029 // Note that variably modified types must be fixed before merging the decl so
7030 // that redeclarations will match.
7031 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7032 QualType T = TInfo->getType();
7033 if (T->isVariablyModifiedType()) {
7035
7036 if (S->getFnParent() == nullptr) {
7037 bool SizeIsNegative;
7038 llvm::APSInt Oversized;
7039 TypeSourceInfo *FixedTInfo =
7041 SizeIsNegative,
7042 Oversized);
7043 if (FixedTInfo) {
7044 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
7045 NewTD->setTypeSourceInfo(FixedTInfo);
7046 } else {
7047 if (SizeIsNegative)
7048 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
7049 else if (T->isVariableArrayType())
7050 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
7051 else if (Oversized.getBoolValue())
7052 Diag(NewTD->getLocation(), diag::err_array_too_large)
7053 << toString(Oversized, 10);
7054 else
7055 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
7056 NewTD->setInvalidDecl();
7057 }
7058 }
7059 }
7060}
7061
7062NamedDecl*
7065
7066 // Find the shadowed declaration before filtering for scope.
7067 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
7068
7069 // Merge the decl with the existing one if appropriate. If the decl is
7070 // in an outer scope, it isn't the same thing.
7071 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
7072 /*AllowInlineNamespace*/false);
7074 if (!Previous.empty()) {
7075 Redeclaration = true;
7076 MergeTypedefNameDecl(S, NewTD, Previous);
7077 } else {
7079 }
7080
7081 if (ShadowedDecl && !Redeclaration)
7082 CheckShadow(NewTD, ShadowedDecl, Previous);
7083
7084 // If this is the C FILE type, notify the AST context.
7085 if (IdentifierInfo *II = NewTD->getIdentifier())
7086 if (!NewTD->isInvalidDecl() &&
7088 switch (II->getNotableIdentifierID()) {
7089 case tok::NotableIdentifierKind::FILE:
7090 Context.setFILEDecl(NewTD);
7091 break;
7092 case tok::NotableIdentifierKind::jmp_buf:
7093 Context.setjmp_bufDecl(NewTD);
7094 break;
7095 case tok::NotableIdentifierKind::sigjmp_buf:
7096 Context.setsigjmp_bufDecl(NewTD);
7097 break;
7098 case tok::NotableIdentifierKind::ucontext_t:
7099 Context.setucontext_tDecl(NewTD);
7100 break;
7101 case tok::NotableIdentifierKind::float_t:
7102 case tok::NotableIdentifierKind::double_t:
7103 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7104 break;
7105 default:
7106 break;
7107 }
7108 }
7109
7110 return NewTD;
7111}
7112
7113/// Determines whether the given declaration is an out-of-scope
7114/// previous declaration.
7115///
7116/// This routine should be invoked when name lookup has found a
7117/// previous declaration (PrevDecl) that is not in the scope where a
7118/// new declaration by the same name is being introduced. If the new
7119/// declaration occurs in a local scope, previous declarations with
7120/// linkage may still be considered previous declarations (C99
7121/// 6.2.2p4-5, C++ [basic.link]p6).
7122///
7123/// \param PrevDecl the previous declaration found by name
7124/// lookup
7125///
7126/// \param DC the context in which the new declaration is being
7127/// declared.
7128///
7129/// \returns true if PrevDecl is an out-of-scope previous declaration
7130/// for a new delcaration with the same name.
7131static bool
7133 ASTContext &Context) {
7134 if (!PrevDecl)
7135 return false;
7136
7137 if (!PrevDecl->hasLinkage())
7138 return false;
7139
7140 if (Context.getLangOpts().CPlusPlus) {
7141 // C++ [basic.link]p6:
7142 // If there is a visible declaration of an entity with linkage
7143 // having the same name and type, ignoring entities declared
7144 // outside the innermost enclosing namespace scope, the block
7145 // scope declaration declares that same entity and receives the
7146 // linkage of the previous declaration.
7147 DeclContext *OuterContext = DC->getRedeclContext();
7148 if (!OuterContext->isFunctionOrMethod())
7149 // This rule only applies to block-scope declarations.
7150 return false;
7151
7152 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7153 if (PrevOuterContext->isRecord())
7154 // We found a member function: ignore it.
7155 return false;
7156
7157 // Find the innermost enclosing namespace for the new and
7158 // previous declarations.
7159 OuterContext = OuterContext->getEnclosingNamespaceContext();
7160 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7161
7162 // The previous declaration is in a different namespace, so it
7163 // isn't the same function.
7164 if (!OuterContext->Equals(PrevOuterContext))
7165 return false;
7166 }
7167
7168 return true;
7169}
7170
7172 CXXScopeSpec &SS = D.getCXXScopeSpec();
7173 if (!SS.isSet()) return;
7175}
7176
7179 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7180 // __opencl_c_program_scope_global_variables feature, the address space
7181 // for a variable at program scope or a static or extern variable inside
7182 // a function are inferred to be __global.
7183 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7184 Var->hasGlobalStorage())
7185 ImplAS = LangAS::opencl_global;
7186 Var->assignAddressSpace(Context, ImplAS);
7187}
7188
7190 const WeakAttr &Attr) {
7191 const NamedDecl *D = &ND;
7192 // IFuncAttr is not inherited, so a redeclaration may need to check the
7193 // attributes on the definition instead.
7194 if (const auto *FD = dyn_cast<FunctionDecl>(&ND))
7195 if (const FunctionDecl *Def = FD->getDefinition())
7196 D = Def;
7197 return DiagnoseMutualExclusions(S, D, &Attr);
7198}
7199
7200static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7201 // 'weak' only applies to declarations with external linkage.
7202 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7203 if (!ND.isExternallyVisible()) {
7204 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7205 ND.dropAttr<WeakAttr>();
7206 } else if (!checkWeakAttrCompatibility(S, ND, *Attr)) {
7207 // A forward #pragma weak adds the attribute without checking mutual
7208 // exclusions during attribute processing.
7209 ND.dropAttr<WeakAttr>();
7210 }
7211 }
7212}
7213
7214static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7215 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7216 if (ND.isExternallyVisible()) {
7217 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7218 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7219 }
7220 }
7221}
7222
7223static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7224 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7225 if (VD->hasInit()) {
7226 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7227 assert(VD->isThisDeclarationADefinition() &&
7228 "Broken AliasAttr handled late!");
7229 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7230 VD->dropAttr<AliasAttr>();
7231 }
7232 }
7233 }
7234}
7235
7236static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7237 // 'selectany' only applies to externally visible variable declarations.
7238 // It does not apply to functions.
7239 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7240 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7241 S.Diag(Attr->getLocation(),
7242 diag::err_attribute_selectany_non_extern_data);
7243 ND.dropAttr<SelectAnyAttr>();
7244 }
7245 }
7246}
7247
7249 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7250 if (!ND.isExternallyVisible())
7251 S.Diag(Attr->getLocation(),
7252 diag::warn_attribute_hybrid_patchable_non_extern);
7253 }
7254}
7255
7257 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7258 auto *VD = dyn_cast<VarDecl>(&ND);
7259 bool IsAnonymousNS = false;
7260 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7261 if (VD) {
7262 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7263 while (NS && !IsAnonymousNS) {
7264 IsAnonymousNS = NS->isAnonymousNamespace();
7265 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7266 }
7267 }
7268 // dll attributes require external linkage. Static locals may have external
7269 // linkage but still cannot be explicitly imported or exported.
7270 // In Microsoft mode, a variable defined in anonymous namespace must have
7271 // external linkage in order to be exported.
7272 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7273 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7274 (!AnonNSInMicrosoftMode &&
7275 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7276 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7277 << &ND << Attr;
7278 ND.setInvalidDecl();
7279 }
7280 }
7281}
7282
7284 // Check the attributes on the function type and function params, if any.
7285 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7286 FD = FD->getMostRecentDecl();
7287 // Don't declare this variable in the second operand of the for-statement;
7288 // GCC miscompiles that by ending its lifetime before evaluating the
7289 // third operand. See gcc.gnu.org/PR86769.
7291 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7292 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7293 TL = ATL.getModifiedLoc()) {
7294 // The [[lifetimebound]] attribute can be applied to the implicit object
7295 // parameter of a non-static member function (other than a ctor or dtor)
7296 // by applying it to the function type.
7297 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7298 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7299 int NoImplicitObjectError = -1;
7300 if (!MD)
7301 NoImplicitObjectError = 0;
7302 else if (MD->isStatic())
7303 NoImplicitObjectError = 1;
7304 else if (MD->isExplicitObjectMemberFunction())
7305 NoImplicitObjectError = 2;
7306 if (NoImplicitObjectError != -1) {
7307 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7308 << NoImplicitObjectError << A->getRange();
7309 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7310 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7311 << isa<CXXDestructorDecl>(MD) << A->getRange();
7312 } else if (MD->getReturnType()->isVoidType()) {
7313 S.Diag(
7314 MD->getLocation(),
7315 diag::
7316 err_lifetimebound_implicit_object_parameter_void_return_type);
7317 }
7318 }
7319 }
7320
7321 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7322 const ParmVarDecl *P = FD->getParamDecl(I);
7323
7324 // The [[lifetimebound]] attribute can be applied to a function parameter
7325 // only if the function returns a value.
7326 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7327 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7328 S.Diag(A->getLocation(),
7329 diag::err_lifetimebound_parameter_void_return_type);
7330 }
7331 }
7332 }
7333 }
7334}
7335
7337 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7338 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7339}
7340
7342 // Ensure that an auto decl is deduced otherwise the checks below might cache
7343 // the wrong linkage.
7344 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7345
7346 checkWeakAttr(S, ND);
7347 checkWeakRefAttr(S, ND);
7348 checkAliasAttr(S, ND);
7349 checkSelectAnyAttr(S, ND);
7351 checkInheritableAttr(S, ND);
7353}
7354
7356 NamedDecl *NewDecl,
7357 bool IsSpecialization,
7358 bool IsDefinition) {
7359 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7360 return;
7361
7362 bool IsTemplate = false;
7363 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7364 OldDecl = OldTD->getTemplatedDecl();
7365 IsTemplate = true;
7366 if (!IsSpecialization)
7367 IsDefinition = false;
7368 }
7369 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7370 NewDecl = NewTD->getTemplatedDecl();
7371 IsTemplate = true;
7372 }
7373
7374 if (!OldDecl || !NewDecl)
7375 return;
7376
7377 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7378 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7379 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7380 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7381
7382 // dllimport and dllexport are inheritable attributes so we have to exclude
7383 // inherited attribute instances.
7384 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7385 (NewExportAttr && !NewExportAttr->isInherited());
7386
7387 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7388 // the only exception being explicit specializations.
7389 // Implicitly generated declarations are also excluded for now because there
7390 // is no other way to switch these to use dllimport or dllexport.
7391 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7392
7393 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7394 // Allow with a warning for free functions and global variables.
7395 bool JustWarn = false;
7396 if (!OldDecl->isCXXClassMember()) {
7397 auto *VD = dyn_cast<VarDecl>(OldDecl);
7398 if (VD && !VD->getDescribedVarTemplate())
7399 JustWarn = true;
7400 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7401 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7402 JustWarn = true;
7403 }
7404
7405 // We cannot change a declaration that's been used because IR has already
7406 // been emitted. Dllimported functions will still work though (modulo
7407 // address equality) as they can use the thunk.
7408 if (OldDecl->isUsed())
7409 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7410 JustWarn = false;
7411
7412 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7413 : diag::err_attribute_dll_redeclaration;
7414 S.Diag(NewDecl->getLocation(), DiagID)
7415 << NewDecl
7416 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7417 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7418 if (!JustWarn) {
7419 NewDecl->setInvalidDecl();
7420 return;
7421 }
7422 }
7423
7424 // A redeclaration is not allowed to drop a dllimport attribute, the only
7425 // exceptions being inline function definitions (except for function
7426 // templates), local extern declarations, qualified friend declarations or
7427 // special MSVC extension: in the last case, the declaration is treated as if
7428 // it were marked dllexport.
7429 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7430 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7431 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7432 // Ignore static data because out-of-line definitions are diagnosed
7433 // separately.
7434 IsStaticDataMember = VD->isStaticDataMember();
7435 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7437 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7438 IsInline = FD->isInlined();
7439 IsQualifiedFriend = FD->getQualifier() &&
7440 FD->getFriendObjectKind() == Decl::FOK_Declared;
7441 }
7442
7443 if (OldImportAttr && !HasNewAttr &&
7444 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7445 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7446 if (IsMicrosoftABI && IsDefinition) {
7447 if (IsSpecialization) {
7448 S.Diag(
7449 NewDecl->getLocation(),
7450 diag::err_attribute_dllimport_function_specialization_definition);
7451 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7452 NewDecl->dropAttr<DLLImportAttr>();
7453 } else {
7454 S.Diag(NewDecl->getLocation(),
7455 diag::warn_redeclaration_without_import_attribute)
7456 << NewDecl;
7457 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7458 NewDecl->dropAttr<DLLImportAttr>();
7459 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7460 S.Context, NewImportAttr->getRange()));
7461 }
7462 } else if (IsMicrosoftABI && IsSpecialization) {
7463 assert(!IsDefinition);
7464 // MSVC allows this. Keep the inherited attribute.
7465 } else {
7466 S.Diag(NewDecl->getLocation(),
7467 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7468 << NewDecl << OldImportAttr;
7469 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7470 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7471 OldDecl->dropAttr<DLLImportAttr>();
7472 NewDecl->dropAttr<DLLImportAttr>();
7473 }
7474 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7475 // In MinGW, seeing a function declared inline drops the dllimport
7476 // attribute.
7477 OldDecl->dropAttr<DLLImportAttr>();
7478 NewDecl->dropAttr<DLLImportAttr>();
7479 S.Diag(NewDecl->getLocation(),
7480 diag::warn_dllimport_dropped_from_inline_function)
7481 << NewDecl << OldImportAttr;
7482 }
7483
7484 // A specialization of a class template member function is processed here
7485 // since it's a redeclaration. If the parent class is dllexport, the
7486 // specialization inherits that attribute. This doesn't happen automatically
7487 // since the parent class isn't instantiated until later.
7488 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7489 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7490 !NewImportAttr && !NewExportAttr) {
7491 if (const DLLExportAttr *ParentExportAttr =
7492 MD->getParent()->getAttr<DLLExportAttr>()) {
7493 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7494 NewAttr->setInherited(true);
7495 NewDecl->addAttr(NewAttr);
7496 }
7497 }
7498 }
7499}
7500
7501/// Given that we are within the definition of the given function,
7502/// will that definition behave like C99's 'inline', where the
7503/// definition is discarded except for optimization purposes?
7505 // Try to avoid calling GetGVALinkageForFunction.
7506
7507 // All cases of this require the 'inline' keyword.
7508 if (!FD->isInlined()) return false;
7509
7510 // This is only possible in C++ with the gnu_inline attribute.
7511 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7512 return false;
7513
7514 // Okay, go ahead and call the relatively-more-expensive function.
7516}
7517
7518/// Determine whether a variable is extern "C" prior to attaching
7519/// an initializer. We can't just call isExternC() here, because that
7520/// will also compute and cache whether the declaration is externally
7521/// visible, which might change when we attach the initializer.
7522///
7523/// This can only be used if the declaration is known to not be a
7524/// redeclaration of an internal linkage declaration.
7525///
7526/// For instance:
7527///
7528/// auto x = []{};
7529///
7530/// Attaching the initializer here makes this declaration not externally
7531/// visible, because its type has internal linkage.
7532///
7533/// FIXME: This is a hack.
7534template<typename T>
7535static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7536 if (S.getLangOpts().CPlusPlus) {
7537 // In C++, the overloadable attribute negates the effects of extern "C".
7538 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7539 return false;
7540
7541 // So do CUDA's host/device attributes.
7542 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7543 D->template hasAttr<CUDAHostAttr>()))
7544 return false;
7545 }
7546 return D->isExternC();
7547}
7548
7549static bool shouldConsiderLinkage(const VarDecl *VD) {
7550 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7553 return VD->hasExternalStorage();
7554 if (DC->isFileContext())
7555 return true;
7556 if (DC->isRecord())
7557 return false;
7558 if (DC->getDeclKind() == Decl::HLSLBuffer)
7559 return false;
7560
7562 return false;
7563 llvm_unreachable("Unexpected context");
7564}
7565
7566static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7567 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7568 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7570 return true;
7571 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(DC))
7572 return false;
7573 llvm_unreachable("Unexpected context");
7574}
7575
7576static bool hasParsedAttr(Scope *S, const Declarator &PD,
7577 ParsedAttr::Kind Kind) {
7578 // Check decl attributes on the DeclSpec.
7579 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7580 return true;
7581
7582 // Walk the declarator structure, checking decl attributes that were in a type
7583 // position to the decl itself.
7584 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7585 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7586 return true;
7587 }
7588
7589 // Finally, check attributes on the decl itself.
7590 return PD.getAttributes().hasAttribute(Kind) ||
7592}
7593
7595 if (!DC->isFunctionOrMethod())
7596 return false;
7597
7598 // If this is a local extern function or variable declared within a function
7599 // template, don't add it into the enclosing namespace scope until it is
7600 // instantiated; it might have a dependent type right now.
7601 if (DC->isDependentContext())
7602 return true;
7603
7604 // C++11 [basic.link]p7:
7605 // When a block scope declaration of an entity with linkage is not found to
7606 // refer to some other declaration, then that entity is a member of the
7607 // innermost enclosing namespace.
7608 //
7609 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7610 // semantically-enclosing namespace, not a lexically-enclosing one.
7611 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7612 DC = DC->getParent();
7613 return true;
7614}
7615
7616/// Returns true if given declaration has external C language linkage.
7617static bool isDeclExternC(const Decl *D) {
7618 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7619 return FD->isExternC();
7620 if (const auto *VD = dyn_cast<VarDecl>(D))
7621 return VD->isExternC();
7622
7623 llvm_unreachable("Unknown type of decl!");
7624}
7625
7626/// Returns true if there hasn't been any invalid type diagnosed.
7627static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7628 DeclContext *DC = NewVD->getDeclContext();
7629 QualType R = NewVD->getType();
7630
7631 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7632 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7633 // argument.
7634 if (R->isImageType() || R->isPipeType()) {
7635 Se.Diag(NewVD->getLocation(),
7636 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7637 << R;
7638 NewVD->setInvalidDecl();
7639 return false;
7640 }
7641
7642 // OpenCL v1.2 s6.9.r:
7643 // The event type cannot be used to declare a program scope variable.
7644 // OpenCL v2.0 s6.9.q:
7645 // The clk_event_t and reserve_id_t types cannot be declared in program
7646 // scope.
7647 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7648 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7649 Se.Diag(NewVD->getLocation(),
7650 diag::err_invalid_type_for_program_scope_var)
7651 << R;
7652 NewVD->setInvalidDecl();
7653 return false;
7654 }
7655 }
7656
7657 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7658 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7659 Se.getLangOpts())) {
7660 QualType NR = R.getCanonicalType();
7661 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7662 NR->isReferenceType()) {
7665 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7666 << NR->isReferenceType();
7667 NewVD->setInvalidDecl();
7668 return false;
7669 }
7670 NR = NR->getPointeeType();
7671 }
7672 }
7673
7674 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7675 Se.getLangOpts())) {
7676 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7677 // half array type (unless the cl_khr_fp16 extension is enabled).
7678 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7679 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7680 NewVD->setInvalidDecl();
7681 return false;
7682 }
7683 }
7684
7685 // OpenCL v1.2 s6.9.r:
7686 // The event type cannot be used with the __local, __constant and __global
7687 // address space qualifiers.
7688 if (R->isEventT()) {
7689 if (R.getAddressSpace() != LangAS::opencl_private) {
7690 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7691 NewVD->setInvalidDecl();
7692 return false;
7693 }
7694 }
7695
7696 if (R->isSamplerT()) {
7697 // OpenCL v1.2 s6.9.b p4:
7698 // The sampler type cannot be used with the __local and __global address
7699 // space qualifiers.
7700 if (R.getAddressSpace() == LangAS::opencl_local ||
7701 R.getAddressSpace() == LangAS::opencl_global) {
7702 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7703 NewVD->setInvalidDecl();
7704 }
7705
7706 // OpenCL v1.2 s6.12.14.1:
7707 // A global sampler must be declared with either the constant address
7708 // space qualifier or with the const qualifier.
7709 if (DC->isTranslationUnit() &&
7710 !(R.getAddressSpace() == LangAS::opencl_constant ||
7711 R.isConstQualified())) {
7712 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7713 NewVD->setInvalidDecl();
7714 }
7715 if (NewVD->isInvalidDecl())
7716 return false;
7717 }
7718
7719 return true;
7720}
7721
7722template <typename AttrTy>
7723static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7724 const TypedefNameDecl *TND = TT->getDecl();
7725 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7726 AttrTy *Clone = Attribute->clone(S.Context);
7727 Clone->setInherited(true);
7728 D->addAttr(Clone);
7729 }
7730}
7731
7732// This function emits warning and a corresponding note based on the
7733// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7734// declarations of an annotated type must be const qualified.
7736 QualType VarType = VD->getType().getCanonicalType();
7737
7738 // Ignore local declarations (for now) and those with const qualification.
7739 // TODO: Local variables should not be allowed if their type declaration has
7740 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7741 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7742 return;
7743
7744 if (VarType->isArrayType()) {
7745 // Retrieve element type for array declarations.
7746 VarType = S.getASTContext().getBaseElementType(VarType);
7747 }
7748
7749 const RecordDecl *RD = VarType->getAsRecordDecl();
7750
7751 // Check if the record declaration is present and if it has any attributes.
7752 if (RD == nullptr)
7753 return;
7754
7755 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7756 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7757 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7758 return;
7759 }
7760}
7761
7763 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7764 "NewD is not a function or variable");
7765
7766 if (PendingExportedNames.empty())
7767 return;
7768 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7769 if (getLangOpts().CPlusPlus && !FD->isExternC())
7770 return;
7771 }
7772 IdentifierInfo *IdentName = NewD->getIdentifier();
7773 if (IdentName == nullptr)
7774 return;
7775 auto PendingName = PendingExportedNames.find(IdentName);
7776 if (PendingName != PendingExportedNames.end()) {
7777 auto &Label = PendingName->second;
7778 if (!Label.Used) {
7779 Label.Used = true;
7780 if (NewD->hasExternalFormalLinkage())
7781 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7782 else
7783 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7784 }
7785 }
7786}
7787
7788// Checks if VD is declared at global scope or with C language linkage.
7789static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7790 return Name.getAsIdentifierInfo() &&
7791 Name.getAsIdentifierInfo()->isStr("main") &&
7792 !VD->getDescribedVarTemplate() &&
7793 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7794 VD->isExternC());
7795}
7796
7797void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7798 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7799
7800 // Quickly return if the function does not have an `asm` attribute.
7801 if (E == nullptr)
7802 return;
7803
7804 // The parser guarantees this is a string.
7805 StringLiteral *SE = cast<StringLiteral>(E);
7806 StringRef Label = SE->getString();
7807 QualType R = TInfo->getType();
7808 if (R->isIncompleteType())
7809 return;
7810 if (S->getFnParent() != nullptr) {
7811 switch (SC) {
7812 case SC_None:
7813 case SC_Auto:
7814 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7815 break;
7816 case SC_Register:
7817 // Local Named register
7819 const auto &TI = Context.getTargetInfo();
7820 if (!TI.isValidGCCRegisterName(Label))
7821 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7822 else if (!TI.validateLocalRegisterVariable(
7823 TI.getNormalizedGCCRegisterName(Label,
7824 /*ReturnCanonical=*/true)))
7825 Diag(E->getExprLoc(), diag::err_asm_invalid_local_var_reg) << Label;
7826 }
7827 break;
7828 case SC_Static:
7829 case SC_Extern:
7830 case SC_PrivateExtern:
7831 break;
7832 }
7833 } else if (SC == SC_Register) {
7834 // Global Named register
7835 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7836 const auto &TI = Context.getTargetInfo();
7837 bool HasSizeMismatch;
7838
7839 if (!TI.isValidGCCRegisterName(Label))
7840 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7841 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7842 HasSizeMismatch))
7843 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7844 else if (HasSizeMismatch)
7845 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7846 }
7847
7848 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7849 Diag(TInfo->getTypeLoc().getBeginLoc(),
7850 diag::err_asm_unsupported_register_type)
7851 << TInfo->getTypeLoc().getSourceRange();
7852 NewVD->setInvalidDecl(true);
7853 }
7854 }
7855}
7856
7858 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7859 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7860 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7861 QualType R = TInfo->getType();
7863
7865 bool IsPlaceholderVariable = false;
7866
7867 if (D.isDecompositionDeclarator()) {
7868 // Take the name of the first declarator as our name for diagnostic
7869 // purposes.
7870 auto &Decomp = D.getDecompositionDeclarator();
7871 if (!Decomp.bindings().empty()) {
7872 II = Decomp.bindings()[0].Name;
7873 Name = II;
7874 }
7875 } else if (!II) {
7876 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7877 return nullptr;
7878 }
7879
7880
7883 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7884 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7885
7886 IsPlaceholderVariable = true;
7887
7888 if (!Previous.empty()) {
7889 NamedDecl *PrevDecl = *Previous.begin();
7890 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7891 DC->getRedeclContext());
7892 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7893 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7894 if (IsPlaceholderVariable)
7896 }
7897 }
7898 }
7899
7900 // dllimport globals without explicit storage class are treated as extern. We
7901 // have to change the storage class this early to get the right DeclContext.
7902 if (SC == SC_None && !DC->isRecord() &&
7903 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7904 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7905 SC = SC_Extern;
7906
7907 DeclContext *OriginalDC = DC;
7908 bool IsLocalExternDecl = SC == SC_Extern &&
7910
7911 if (SCSpec == DeclSpec::SCS_mutable) {
7912 // mutable can only appear on non-static class members, so it's always
7913 // an error here
7914 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7915 D.setInvalidType();
7916 SC = SC_None;
7917 }
7918
7919 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7920 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7922 // In C++11, the 'register' storage class specifier is deprecated.
7923 // Suppress the warning in system macros, it's used in macros in some
7924 // popular C system headers, such as in glibc's htonl() macro.
7926 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7927 : diag::warn_deprecated_register)
7929 }
7930
7932
7933 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7934 // C99 6.9p2: The storage-class specifiers auto and register shall not
7935 // appear in the declaration specifiers in an external declaration.
7936 // Global Register+Asm is a GNU extension we support.
7937 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7938 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7939 D.setInvalidType();
7940 }
7941 }
7942
7943 // If this variable has a VLA type and an initializer, try to
7944 // fold to a constant-sized type. This is otherwise invalid.
7945 if (D.hasInitializer() && R->isVariableArrayType())
7947 /*DiagID=*/0);
7948
7949 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7950 const AutoType *AT = TL.getTypePtr();
7951 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7952 }
7953
7954 bool IsMemberSpecialization = false;
7955 bool IsVariableTemplateSpecialization = false;
7956 bool IsPartialSpecialization = false;
7957 bool IsVariableTemplate = false;
7958 VarDecl *NewVD = nullptr;
7959 VarTemplateDecl *NewTemplate = nullptr;
7960 TemplateParameterList *TemplateParams = nullptr;
7961 if (!getLangOpts().CPlusPlus) {
7963 II, R, TInfo, SC);
7964
7965 if (R->getContainedDeducedType())
7966 ParsingInitForAutoVars.insert(NewVD);
7967
7968 if (D.isInvalidType())
7969 NewVD->setInvalidDecl();
7970
7972 NewVD->hasLocalStorage())
7973 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7975 } else {
7976 bool Invalid = false;
7977 // Match up the template parameter lists with the scope specifier, then
7978 // determine whether we have a template or a template specialization.
7981 D.getCXXScopeSpec(),
7983 ? D.getName().TemplateId
7984 : nullptr,
7985 TemplateParamLists,
7986 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7987
7988 if (TemplateParams) {
7989 if (DC->isDependentContext()) {
7990 ContextRAII SavedContext(*this, DC);
7992 Invalid = true;
7993 }
7994
7995 if (!TemplateParams->size() &&
7997 // There is an extraneous 'template<>' for this variable. Complain
7998 // about it, but allow the declaration of the variable.
7999 Diag(TemplateParams->getTemplateLoc(),
8000 diag::err_template_variable_noparams)
8001 << II
8002 << SourceRange(TemplateParams->getTemplateLoc(),
8003 TemplateParams->getRAngleLoc());
8004 TemplateParams = nullptr;
8005 } else {
8006 // Check that we can declare a template here.
8007 if (CheckTemplateDeclScope(S, TemplateParams))
8008 return nullptr;
8009
8011 // This is an explicit specialization or a partial specialization.
8012 IsVariableTemplateSpecialization = true;
8013 IsPartialSpecialization = TemplateParams->size() > 0;
8014 } else { // if (TemplateParams->size() > 0)
8015 // This is a template declaration.
8016 IsVariableTemplate = true;
8017
8018 // Only C++1y supports variable templates (N3651).
8019 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
8020 }
8021 }
8022 } else {
8023 // Check that we can declare a member specialization here.
8024 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
8025 CheckTemplateDeclScope(S, TemplateParamLists.back()))
8026 return nullptr;
8027 assert((Invalid ||
8029 "should have a 'template<>' for this decl");
8030 }
8031
8032 bool IsExplicitSpecialization =
8033 IsVariableTemplateSpecialization && !IsPartialSpecialization;
8034
8035 // C++ [temp.expl.spec]p2:
8036 // The declaration in an explicit-specialization shall not be an
8037 // export-declaration. An explicit specialization shall not use a
8038 // storage-class-specifier other than thread_local.
8039 //
8040 // We use the storage-class-specifier from DeclSpec because we may have
8041 // added implicit 'extern' for declarations with __declspec(dllimport)!
8042 if (SCSpec != DeclSpec::SCS_unspecified &&
8043 (IsExplicitSpecialization || IsMemberSpecialization)) {
8045 diag::ext_explicit_specialization_storage_class)
8047 }
8048
8049 if (CurContext->isRecord()) {
8050 if (SC == SC_Static) {
8051 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
8052 // Walk up the enclosing DeclContexts to check for any that are
8053 // incompatible with static data members.
8054 const DeclContext *FunctionOrMethod = nullptr;
8055 const CXXRecordDecl *AnonStruct = nullptr;
8056 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8057 if (Ctxt->isFunctionOrMethod()) {
8058 FunctionOrMethod = Ctxt;
8059 break;
8060 }
8061 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
8062 if (ParentDecl && !ParentDecl->getDeclName()) {
8063 AnonStruct = ParentDecl;
8064 break;
8065 }
8066 }
8067 if (FunctionOrMethod) {
8068 // C++ [class.static.data]p5: A local class shall not have static
8069 // data members.
8071 diag::err_static_data_member_not_allowed_in_local_class)
8072 << Name << RD->getDeclName() << RD->getTagKind();
8073 Invalid = true;
8074 } else if (AnonStruct) {
8075 // C++ [class.static.data]p4: Unnamed classes and classes contained
8076 // directly or indirectly within unnamed classes shall not contain
8077 // static data members.
8079 diag::err_static_data_member_not_allowed_in_anon_struct)
8080 << Name << AnonStruct->getTagKind();
8081 Invalid = true;
8082 } else if (RD->isUnion()) {
8083 // C++98 [class.union]p1: If a union contains a static data member,
8084 // the program is ill-formed. C++11 drops this restriction.
8086 diag_compat::static_data_member_in_union)
8087 << Name;
8088 }
8089 }
8090 } else if (IsVariableTemplate || IsPartialSpecialization) {
8091 // There is no such thing as a member field template.
8092 Diag(D.getIdentifierLoc(), diag::err_template_member)
8093 << II << TemplateParams->getSourceRange();
8094 // Recover by pretending this is a static data member template.
8095 SC = SC_Static;
8096 }
8097 } else if (DC->isRecord()) {
8098 // This is an out-of-line definition of a static data member.
8099 switch (SC) {
8100 case SC_None:
8101 break;
8102 case SC_Static:
8104 diag::err_static_out_of_line)
8107 break;
8108 case SC_Auto:
8109 case SC_Register:
8110 case SC_Extern:
8111 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8112 // to names of variables declared in a block or to function parameters.
8113 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8114 // of class members
8115
8117 diag::err_storage_class_for_static_member)
8120 break;
8121 case SC_PrivateExtern:
8122 llvm_unreachable("C storage class in c++!");
8123 }
8124 }
8125
8126 if (IsVariableTemplateSpecialization) {
8127 SourceLocation TemplateKWLoc =
8128 TemplateParamLists.size() > 0
8129 ? TemplateParamLists[0]->getTemplateLoc()
8130 : SourceLocation();
8132 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8134 if (Res.isInvalid())
8135 return nullptr;
8136 NewVD = cast<VarDecl>(Res.get());
8137 AddToScope = false;
8138 } else if (D.isDecompositionDeclarator()) {
8140 D.getIdentifierLoc(), D.getEndLoc(), R,
8141 TInfo, SC, Bindings);
8142 } else
8143 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8144 D.getIdentifierLoc(), II, R, TInfo, SC);
8145
8146 // If this is supposed to be a variable template, create it as such.
8147 if (IsVariableTemplate) {
8148 NewTemplate =
8150 TemplateParams, NewVD);
8151 NewVD->setDescribedVarTemplate(NewTemplate);
8152 }
8153
8154 // If this decl has an auto type in need of deduction, make a note of the
8155 // Decl so we can diagnose uses of it in its own initializer.
8156 if (R->getContainedDeducedType())
8157 ParsingInitForAutoVars.insert(NewVD);
8158
8159 if (D.isInvalidType() || Invalid) {
8160 NewVD->setInvalidDecl();
8161 if (NewTemplate)
8162 NewTemplate->setInvalidDecl();
8163 }
8164
8165 SetNestedNameSpecifier(*this, NewVD, D);
8166
8167 // If we have any template parameter lists that don't directly belong to
8168 // the variable (matching the scope specifier), store them.
8169 // An explicit variable template specialization does not own any template
8170 // parameter lists.
8171 unsigned VDTemplateParamLists =
8172 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8173 if (TemplateParamLists.size() > VDTemplateParamLists)
8175 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8176 }
8177
8178 if (D.getDeclSpec().isInlineSpecified()) {
8179 if (!getLangOpts().CPlusPlus) {
8180 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8181 << 0;
8182 } else if (CurContext->isFunctionOrMethod()) {
8183 // 'inline' is not allowed on block scope variable declaration.
8185 diag::err_inline_declaration_block_scope) << Name
8187 } else {
8189 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8190 : diag::compat_pre_cxx17_inline_variable);
8191 NewVD->setInlineSpecified();
8192 }
8193 }
8194
8195 // Set the lexical context. If the declarator has a C++ scope specifier, the
8196 // lexical context will be different from the semantic context.
8198 if (NewTemplate)
8199 NewTemplate->setLexicalDeclContext(CurContext);
8200
8201 if (IsLocalExternDecl) {
8203 for (auto *B : Bindings)
8204 B->setLocalExternDecl();
8205 else
8206 NewVD->setLocalExternDecl();
8207 }
8208
8209 bool EmitTLSUnsupportedError = false;
8211 // C++11 [dcl.stc]p4:
8212 // When thread_local is applied to a variable of block scope the
8213 // storage-class-specifier static is implied if it does not appear
8214 // explicitly.
8215 // Core issue: 'static' is not implied if the variable is declared
8216 // 'extern'.
8217 if (NewVD->hasLocalStorage() &&
8218 (SCSpec != DeclSpec::SCS_unspecified ||
8220 !DC->isFunctionOrMethod()))
8222 diag::err_thread_non_global)
8224 else if (!Context.getTargetInfo().isTLSSupported()) {
8225 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8226 // Postpone error emission until we've collected attributes required to
8227 // figure out whether it's a host or device variable and whether the
8228 // error should be ignored.
8229 EmitTLSUnsupportedError = true;
8230 // We still need to mark the variable as TLS so it shows up in AST with
8231 // proper storage class for other tools to use even if we're not going
8232 // to emit any code for it.
8233 NewVD->setTSCSpec(TSCS);
8234 } else
8236 diag::err_thread_unsupported);
8237 } else
8238 NewVD->setTSCSpec(TSCS);
8239 }
8240
8241 switch (D.getDeclSpec().getConstexprSpecifier()) {
8243 break;
8244
8247 diag::err_constexpr_wrong_decl_kind)
8248 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8249 [[fallthrough]];
8250
8252 NewVD->setConstexpr(true);
8253 // C++1z [dcl.spec.constexpr]p1:
8254 // A static data member declared with the constexpr specifier is
8255 // implicitly an inline variable.
8256 if (NewVD->isStaticDataMember() &&
8258 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8259 NewVD->setImplicitlyInline();
8260 break;
8261
8263 if (!NewVD->hasGlobalStorage())
8265 diag::err_constinit_local_variable);
8266 else
8267 NewVD->addAttr(
8268 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8269 ConstInitAttr::Keyword_constinit));
8270 break;
8271 }
8272
8273 // C99 6.7.4p3
8274 // An inline definition of a function with external linkage shall
8275 // not contain a definition of a modifiable object with static or
8276 // thread storage duration...
8277 // We only apply this when the function is required to be defined
8278 // elsewhere, i.e. when the function is not 'extern inline'. Note
8279 // that a local variable with thread storage duration still has to
8280 // be marked 'static'. Also note that it's possible to get these
8281 // semantics in C++ using __attribute__((gnu_inline)).
8282 if (SC == SC_Static && S->getFnParent() != nullptr &&
8283 !NewVD->getType().isConstQualified()) {
8285 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8287 diag::warn_static_local_in_extern_inline);
8289 }
8290 }
8291
8293 if (IsVariableTemplateSpecialization)
8294 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8295 << (IsPartialSpecialization ? 1 : 0)
8298 else if (IsMemberSpecialization)
8299 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8300 << 2
8302 else if (NewVD->hasLocalStorage())
8303 Diag(NewVD->getLocation(), diag::err_module_private_local)
8304 << 0 << NewVD
8308 else {
8309 NewVD->setModulePrivate();
8310 if (NewTemplate)
8311 NewTemplate->setModulePrivate();
8312 for (auto *B : Bindings)
8313 B->setModulePrivate();
8314 }
8315 }
8316
8317 if (getLangOpts().OpenCL) {
8319
8321 if (TSC != TSCS_unspecified) {
8323 diag::err_opencl_unknown_type_specifier)
8325 << DeclSpec::getSpecifierName(TSC) << 1;
8326 NewVD->setInvalidDecl();
8327 }
8328 }
8329
8330 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8331 // address space if the table has local storage (semantic checks elsewhere
8332 // will produce an error anyway).
8333 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8334 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8335 !NewVD->hasLocalStorage()) {
8336 QualType Type = Context.getAddrSpaceQualType(
8337 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8338 NewVD->setType(Type);
8339 }
8340 }
8341
8343
8344 if (Expr *E = D.getAsmLabel()) {
8345 // The parser guarantees this is a string.
8347 StringRef Label = SE->getString();
8348
8349 // Insert the asm attribute.
8350 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8351 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8352 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8354 if (I != ExtnameUndeclaredIdentifiers.end()) {
8355 if (isDeclExternC(NewVD)) {
8356 NewVD->addAttr(I->second);
8358 } else if (NewVD->getDeclContext()
8361 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8362 << /*Variable*/ 1 << NewVD;
8363 }
8364 }
8365
8366 // Handle attributes prior to checking for duplicates in MergeVarDecl
8367 ProcessDeclAttributes(S, NewVD, D);
8368
8369 if (getLangOpts().HLSL)
8371
8372 if (getLangOpts().OpenACC)
8374
8375 // FIXME: This is probably the wrong location to be doing this and we should
8376 // probably be doing this for more attributes (especially for function
8377 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8378 // the code to copy attributes would be generated by TableGen.
8379 if (R->isFunctionPointerType())
8380 if (const auto *TT = R->getAs<TypedefType>())
8382
8383 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8384 if (EmitTLSUnsupportedError &&
8386 (getLangOpts().OpenMPIsTargetDevice &&
8387 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8389 diag::err_thread_unsupported);
8390
8391 if (EmitTLSUnsupportedError &&
8392 (LangOpts.SYCLIsDevice ||
8393 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8394 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8395 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8396 // storage [duration]."
8397 if (SC == SC_None && S->getFnParent() != nullptr &&
8398 (NewVD->hasAttr<CUDASharedAttr>() ||
8399 NewVD->hasAttr<CUDAConstantAttr>())) {
8400 NewVD->setStorageClass(SC_Static);
8401 }
8402 }
8403
8404 // Ensure that dllimport globals without explicit storage class are treated as
8405 // extern. The storage class is set above using parsed attributes. Now we can
8406 // check the VarDecl itself.
8407 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8408 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8409 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8410
8411 // In auto-retain/release, infer strong retension for variables of
8412 // retainable type.
8413 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8414 NewVD->setInvalidDecl();
8415
8416 // Check the ASM label here, as we need to know all other attributes of the
8417 // Decl first. Otherwise, we can't know if the asm label refers to the
8418 // host or device in a CUDA context. The device has other registers than
8419 // host and we must know where the function will be placed.
8420 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8421
8422 // Find the shadowed declaration before filtering for scope.
8423 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8425 : nullptr;
8426
8427 // Don't consider existing declarations that are in a different
8428 // scope and are out-of-semantic-context declarations (if the new
8429 // declaration has linkage).
8432 IsMemberSpecialization ||
8433 IsVariableTemplateSpecialization);
8434
8435 // Check whether the previous declaration is in the same block scope. This
8436 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8437 if (getLangOpts().CPlusPlus &&
8438 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8440 Previous.isSingleResult() && !Previous.isShadowed() &&
8441 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8442
8443 if (!getLangOpts().CPlusPlus) {
8445 } else {
8446 // If this is an explicit specialization of a static data member, check it.
8447 if (IsMemberSpecialization && !IsVariableTemplate &&
8448 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8450 NewVD->setInvalidDecl();
8451
8452 // Merge the decl with the existing one if appropriate.
8453 if (!Previous.empty()) {
8454 if (Previous.isSingleResult() &&
8455 isa<FieldDecl>(Previous.getFoundDecl()) &&
8456 D.getCXXScopeSpec().isSet()) {
8457 // The user tried to define a non-static data member
8458 // out-of-line (C++ [dcl.meaning]p1).
8459 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8460 << D.getCXXScopeSpec().getRange();
8461 Previous.clear();
8462 NewVD->setInvalidDecl();
8463 }
8464 } else if (D.getCXXScopeSpec().isSet() &&
8465 !IsVariableTemplateSpecialization) {
8466 // No previous declaration in the qualifying scope.
8467 Diag(D.getIdentifierLoc(), diag::err_no_member)
8468 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8469 << D.getCXXScopeSpec().getRange();
8470 NewVD->setInvalidDecl();
8471
8472 // if this is a member specialization, we don't have any primary template
8473 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8474 // that anything that attempts to refer to this invalid declaration can
8475 // act as if there IS a primary instantiation.
8476 if (NewTemplate && IsMemberSpecialization) {
8477 VarDecl *FakeVD =
8479 II, R, TInfo, SC);
8480 FakeVD->setInvalidDecl();
8481 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8482 Context, DC, D.getIdentifierLoc(), Name, TemplateParams, FakeVD);
8483 FakeInstantiatedFrom->setInvalidDecl();
8484 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8485 }
8486 }
8487
8488 if (!IsPlaceholderVariable)
8490
8491 // CheckVariableDeclaration will set NewVD as invalid if something is in
8492 // error like WebAssembly tables being declared as arrays with a non-zero
8493 // size, but then parsing continues and emits further errors on that line.
8494 // To avoid that we check here if it happened and return nullptr.
8495 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8496 return nullptr;
8497
8498 if (NewTemplate) {
8499 VarTemplateDecl *PrevVarTemplate =
8500 NewVD->getPreviousDecl()
8502 : nullptr;
8503
8504 // Check the template parameter list of this declaration, possibly
8505 // merging in the template parameter list from the previous variable
8506 // template declaration.
8508 TemplateParams,
8509 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8510 : nullptr,
8511 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8512 DC->isDependentContext())
8514 : TPC_Other))
8515 NewVD->setInvalidDecl();
8516 }
8517 }
8518
8519 if (IsMemberSpecialization) {
8520 if (NewTemplate && NewVD->getPreviousDecl()) {
8521 NewTemplate->setMemberSpecialization();
8522 } else if (IsPartialSpecialization) {
8524 ->setMemberSpecialization();
8525 }
8526 }
8527
8528 // Diagnose shadowed variables iff this isn't a redeclaration.
8529 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8530 CheckShadow(NewVD, ShadowedDecl, Previous);
8531
8532 ProcessPragmaWeak(S, NewVD);
8533 ProcessPragmaExport(NewVD);
8534
8535 // If this is the first declaration of an extern C variable, update
8536 // the map of such variables.
8537 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8538 isIncompleteDeclExternC(*this, NewVD))
8540
8541 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8543 Decl *ManglingContextDecl;
8544 std::tie(MCtx, ManglingContextDecl) =
8546 if (MCtx) {
8547 Context.setManglingNumber(
8548 NewVD, MCtx->getManglingNumber(
8549 NewVD, getMSManglingNumber(getLangOpts(), S)));
8550 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8551 }
8552 }
8553
8554 // Special handling of variable named 'main'.
8555 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8556 // C++ [basic.start.main]p3:
8557 // A program that declares
8558 // - a variable main at global scope, or
8559 // - an entity named main with C language linkage (in any namespace)
8560 // is ill-formed
8561 if (getLangOpts().CPlusPlus)
8562 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8563 << NewVD->isExternC();
8564
8565 // In C, and external-linkage variable named main results in undefined
8566 // behavior.
8567 else if (NewVD->hasExternalFormalLinkage())
8568 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8569 }
8570
8571 if (D.isRedeclaration() && !Previous.empty()) {
8572 NamedDecl *Prev = Previous.getRepresentativeDecl();
8573 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8575 }
8576
8577 if (NewTemplate) {
8578 if (NewVD->isInvalidDecl())
8579 NewTemplate->setInvalidDecl();
8580 ActOnDocumentableDecl(NewTemplate);
8581 return NewTemplate;
8582 }
8583
8584 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8586
8588
8589 return NewVD;
8590}
8591
8592/// Enum describing the %select options in diag::warn_decl_shadow.
8602
8603/// Determine what kind of declaration we're shadowing.
8605 const DeclContext *OldDC) {
8606 if (isa<TypeAliasDecl>(ShadowedDecl))
8607 return SDK_Using;
8608 else if (isa<TypedefDecl>(ShadowedDecl))
8609 return SDK_Typedef;
8610 else if (isa<BindingDecl>(ShadowedDecl))
8611 return SDK_StructuredBinding;
8612 else if (isa<RecordDecl>(OldDC))
8613 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8614
8615 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8616}
8617
8618/// Return the location of the capture if the given lambda captures the given
8619/// variable \p VD, or an invalid source location otherwise.
8621 const ValueDecl *VD) {
8622 for (const Capture &Capture : LSI->Captures) {
8624 return Capture.getLocation();
8625 }
8626 return SourceLocation();
8627}
8628
8630 const LookupResult &R) {
8631 // Only diagnose if we're shadowing an unambiguous field or variable.
8632 if (R.getResultKind() != LookupResultKind::Found)
8633 return false;
8634
8635 // Return false if warning is ignored.
8636 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8637}
8638
8640 const LookupResult &R) {
8642 return nullptr;
8643
8644 // Don't diagnose declarations at file scope.
8645 if (D->hasGlobalStorage() && !D->isStaticLocal())
8646 return nullptr;
8647
8648 NamedDecl *ShadowedDecl = R.getFoundDecl();
8649 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8650 : nullptr;
8651}
8652
8654 const LookupResult &R) {
8655 // Don't warn if typedef declaration is part of a class
8656 if (D->getDeclContext()->isRecord())
8657 return nullptr;
8658
8660 return nullptr;
8661
8662 NamedDecl *ShadowedDecl = R.getFoundDecl();
8663 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8664}
8665
8667 const LookupResult &R) {
8669 return nullptr;
8670
8671 NamedDecl *ShadowedDecl = R.getFoundDecl();
8672 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8673 : nullptr;
8674}
8675
8677 const LookupResult &R) {
8678 DeclContext *NewDC = D->getDeclContext();
8679
8680 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8682 if (const auto *MD = dyn_cast<CXXMethodDecl>(FnDC)) {
8683 // Fields aren't shadowed in C++ static members or in member functions
8684 // with an explicit object parameter.
8685 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8686 return;
8687 } else if (isa<FunctionDecl>(FnDC)) {
8688 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8689 // inline-defined friend function, since that's the only way to
8690 // introduce a non-member function inside a class body. Friends have
8691 // no implicit `this`, so nothing here can shadow a field.
8692 return;
8693 }
8694 // Fields shadowed by constructor parameters are a special case. Usually
8695 // the constructor initializes the field with the parameter.
8696 if (isa<CXXConstructorDecl>(NewDC))
8697 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8698 // Remember that this was shadowed so we can either warn about its
8699 // modification or its existence depending on warning settings.
8700 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8701 return;
8702 }
8703 }
8704
8705 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8706 if (shadowedVar->isExternC()) {
8707 // For shadowing external vars, make sure that we point to the global
8708 // declaration, not a locally scoped extern declaration.
8709 for (auto *I : shadowedVar->redecls())
8710 if (I->isFileVarDecl()) {
8711 ShadowedDecl = I;
8712 break;
8713 }
8714 }
8715
8716 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8717
8718 unsigned WarningDiag = diag::warn_decl_shadow;
8719 SourceLocation CaptureLoc;
8720 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8721 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8722 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8723 // Handle both VarDecl and BindingDecl in lambda contexts
8724 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8725 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8726 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8727 if (RD->getLambdaCaptureDefault() == LCD_None) {
8728 // Try to avoid warnings for lambdas with an explicit capture
8729 // list. Warn only when the lambda captures the shadowed decl
8730 // explicitly.
8731 CaptureLoc = getCaptureLocation(LSI, VD);
8732 if (CaptureLoc.isInvalid())
8733 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8734 } else {
8735 // Remember that this was shadowed so we can avoid the warning if
8736 // the shadowed decl isn't captured and the warning settings allow
8737 // it.
8739 ->ShadowingDecls.push_back({D, VD});
8740 return;
8741 }
8742 }
8743 if (isa<FieldDecl>(ShadowedDecl)) {
8744 // If lambda can capture this, then emit default shadowing warning,
8745 // Otherwise it is not really a shadowing case since field is not
8746 // available in lambda's body.
8747 // At this point we don't know that lambda can capture this, so
8748 // remember that this was shadowed and delay until we know.
8750 ->ShadowingDecls.push_back({D, ShadowedDecl});
8751 return;
8752 }
8753 }
8754 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8755 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8756 bool HasLocalStorage = false;
8757 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8758 HasLocalStorage = VD->hasLocalStorage();
8759 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8760 HasLocalStorage =
8761 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8762
8763 if (HasLocalStorage) {
8764 // A variable can't shadow a local variable or binding in an enclosing
8765 // scope, if they are separated by a non-capturing declaration
8766 // context.
8767 for (DeclContext *ParentDC = NewDC;
8768 ParentDC && !ParentDC->Equals(OldDC);
8769 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8770 // Only block literals, captured statements, and lambda expressions
8771 // can capture; other scopes don't.
8772 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8773 !isLambdaCallOperator(ParentDC))
8774 return;
8775 }
8776 }
8777 }
8778 }
8779 }
8780
8781 // Never warn about shadowing a placeholder variable.
8782 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8783 return;
8784
8785 // Only warn about certain kinds of shadowing for class members.
8786 if (NewDC) {
8787 // In particular, don't warn about shadowing non-class members.
8788 if (NewDC->isRecord() && !OldDC->isRecord())
8789 return;
8790
8791 // Skip shadowing check if we're in a class scope, dealing with an enum
8792 // constant in a different context.
8793 DeclContext *ReDC = NewDC->getRedeclContext();
8794 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8795 return;
8796
8797 // TODO: should we warn about static data members shadowing
8798 // static data members from base classes?
8799
8800 // TODO: don't diagnose for inaccessible shadowed members.
8801 // This is hard to do perfectly because we might friend the
8802 // shadowing context, but that's just a false negative.
8803 }
8804
8805 DeclarationName Name = R.getLookupName();
8806
8807 // Emit warning and note.
8808 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8809 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8810 if (!CaptureLoc.isInvalid())
8811 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8812 << Name << /*explicitly*/ 1;
8813 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8814}
8815
8817 for (const auto &Shadow : LSI->ShadowingDecls) {
8818 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8819 // Try to avoid the warning when the shadowed decl isn't captured.
8820 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8821 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8822 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8823 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8824 Diag(Shadow.VD->getLocation(),
8825 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8826 : diag::warn_decl_shadow)
8827 << Shadow.VD->getDeclName()
8828 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8829 if (CaptureLoc.isValid())
8830 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8831 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8832 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8833 } else if (isa<FieldDecl>(ShadowedDecl)) {
8834 Diag(Shadow.VD->getLocation(),
8835 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8836 : diag::warn_decl_shadow_uncaptured_local)
8837 << Shadow.VD->getDeclName()
8838 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8839 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8840 }
8841 }
8842}
8843
8845 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8846 return;
8847
8848 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8851 LookupName(R, S);
8852 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8853 CheckShadow(D, ShadowedDecl, R);
8854}
8855
8856/// Check if 'E', which is an expression that is about to be modified, refers
8857/// to a constructor parameter that shadows a field.
8859 // Quickly ignore expressions that can't be shadowing ctor parameters.
8860 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8861 return;
8862 E = E->IgnoreParenImpCasts();
8863 auto *DRE = dyn_cast<DeclRefExpr>(E);
8864 if (!DRE)
8865 return;
8866 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8867 auto I = ShadowingDecls.find(D);
8868 if (I == ShadowingDecls.end())
8869 return;
8870 const NamedDecl *ShadowedDecl = I->second;
8871 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8872 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8873 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8874 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8875
8876 // Avoid issuing multiple warnings about the same decl.
8877 ShadowingDecls.erase(I);
8878}
8879
8880/// Check for conflict between this global or extern "C" declaration and
8881/// previous global or extern "C" declarations. This is only used in C++.
8882template<typename T>
8884 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8885 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8886 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8887
8888 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8889 // The common case: this global doesn't conflict with any extern "C"
8890 // declaration.
8891 return false;
8892 }
8893
8894 if (Prev) {
8895 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8896 // Both the old and new declarations have C language linkage. This is a
8897 // redeclaration.
8898 Previous.clear();
8899 Previous.addDecl(Prev);
8900 return true;
8901 }
8902
8903 // This is a global, non-extern "C" declaration, and there is a previous
8904 // non-global extern "C" declaration. Diagnose if this is a variable
8905 // declaration.
8906 if (!isa<VarDecl>(ND))
8907 return false;
8908 } else {
8909 // The declaration is extern "C". Check for any declaration in the
8910 // translation unit which might conflict.
8911 if (IsGlobal) {
8912 // We have already performed the lookup into the translation unit.
8913 IsGlobal = false;
8914 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8915 I != E; ++I) {
8916 if (isa<VarDecl>(*I)) {
8917 Prev = *I;
8918 break;
8919 }
8920 }
8921 } else {
8923 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8924 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8925 I != E; ++I) {
8926 if (isa<VarDecl>(*I)) {
8927 Prev = *I;
8928 break;
8929 }
8930 // FIXME: If we have any other entity with this name in global scope,
8931 // the declaration is ill-formed, but that is a defect: it breaks the
8932 // 'stat' hack, for instance. Only variables can have mangled name
8933 // clashes with extern "C" declarations, so only they deserve a
8934 // diagnostic.
8935 }
8936 }
8937
8938 if (!Prev)
8939 return false;
8940 }
8941
8942 // Use the first declaration's location to ensure we point at something which
8943 // is lexically inside an extern "C" linkage-spec.
8944 assert(Prev && "should have found a previous declaration to diagnose");
8945 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8946 Prev = FD->getFirstDecl();
8947 else
8948 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8949
8950 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8951 << IsGlobal << ND;
8952 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8953 << IsGlobal;
8954 return false;
8955}
8956
8957/// Apply special rules for handling extern "C" declarations. Returns \c true
8958/// if we have found that this is a redeclaration of some prior entity.
8959///
8960/// Per C++ [dcl.link]p6:
8961/// Two declarations [for a function or variable] with C language linkage
8962/// with the same name that appear in different scopes refer to the same
8963/// [entity]. An entity with C language linkage shall not be declared with
8964/// the same name as an entity in global scope.
8965template<typename T>
8968 if (!S.getLangOpts().CPlusPlus) {
8969 // In C, when declaring a global variable, look for a corresponding 'extern'
8970 // variable declared in function scope. We don't need this in C++, because
8971 // we find local extern decls in the surrounding file-scope DeclContext.
8972 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8973 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8974 Previous.clear();
8975 Previous.addDecl(Prev);
8976 return true;
8977 }
8978 }
8979 return false;
8980 }
8981
8982 // A declaration in the translation unit can conflict with an extern "C"
8983 // declaration.
8984 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8985 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8986
8987 // An extern "C" declaration can conflict with a declaration in the
8988 // translation unit or can be a redeclaration of an extern "C" declaration
8989 // in another scope.
8990 if (isIncompleteDeclExternC(S,ND))
8991 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8992
8993 // Neither global nor extern "C": nothing to do.
8994 return false;
8995}
8996
8997static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8998 QualType T) {
8999 QualType CanonT = SemaRef.Context.getCanonicalType(T);
9000 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
9001 // any of its members, even recursively, shall not have an atomic type, or a
9002 // variably modified type, or a type that is volatile or restrict qualified.
9003 if (CanonT->isVariablyModifiedType()) {
9004 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
9005 return true;
9006 }
9007
9008 // Arrays are qualified by their element type, so get the base type (this
9009 // works on non-arrays as well).
9010 CanonT = SemaRef.Context.getBaseElementType(CanonT);
9011
9012 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
9013 CanonT.isRestrictQualified()) {
9014 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
9015 return true;
9016 }
9017
9018 if (CanonT->isRecordType()) {
9019 const RecordDecl *RD = CanonT->getAsRecordDecl();
9020 if (!RD->isInvalidDecl() &&
9021 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
9022 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
9023 }))
9024 return true;
9025 }
9026
9027 return false;
9028}
9029
9031 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
9032}
9033
9035 // If the decl is already known invalid, don't check it.
9036 if (NewVD->isInvalidDecl())
9037 return;
9038
9039 QualType T = NewVD->getType();
9040
9041 // Defer checking an 'auto' type until its initializer is attached.
9042 if (T->isUndeducedType())
9043 return;
9044
9045 if (NewVD->hasAttrs())
9047
9048 if (T->isObjCObjectType()) {
9049 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
9050 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
9051 T = Context.getObjCObjectPointerType(T);
9052 NewVD->setType(T);
9053 }
9054
9055 // The top-level type of a variable declaration cannot have a SYCL address
9056 // space qualifier.
9057 if (getLangOpts().isSYCL()) {
9058 LangAS AS = Context.getBaseElementType(T).getAddressSpace();
9059 if (isSYCLAddressSpace(AS)) {
9060 Diag(NewVD->getLocation(), diag::err_sycl_address_space_qualified_object)
9062 NewVD->setInvalidDecl();
9063 return;
9064 }
9065 }
9066
9067 // Emit an error if an address space was applied to decl with local storage.
9068 // This includes arrays of objects with address space qualifiers, but not
9069 // automatic variables that point to other address spaces.
9070 // ISO/IEC TR 18037 S5.1.2
9071 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9072 T.getAddressSpace() != LangAS::Default) {
9073 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
9074 NewVD->setInvalidDecl();
9075 return;
9076 }
9077
9078 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9079 // scope.
9080 if (getLangOpts().OpenCLVersion == 120 &&
9081 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
9082 getLangOpts()) &&
9083 NewVD->isStaticLocal()) {
9084 Diag(NewVD->getLocation(), diag::err_static_function_scope);
9085 NewVD->setInvalidDecl();
9086 return;
9087 }
9088
9089 if (getLangOpts().OpenCL) {
9090 if (!diagnoseOpenCLTypes(*this, NewVD))
9091 return;
9092
9093 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9094 if (NewVD->hasAttr<BlocksAttr>()) {
9095 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
9096 return;
9097 }
9098
9099 if (T->isBlockPointerType()) {
9100 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9101 // can't use 'extern' storage class.
9102 if (!T.isConstQualified()) {
9103 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
9104 << 0 /*const*/;
9105 NewVD->setInvalidDecl();
9106 return;
9107 }
9108 if (NewVD->hasExternalStorage()) {
9109 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
9110 NewVD->setInvalidDecl();
9111 return;
9112 }
9113 }
9114
9115 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9116 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9117 NewVD->hasExternalStorage()) {
9118 if (!T->isSamplerT() && !T->isDependentType() &&
9119 !(T.getAddressSpace() == LangAS::opencl_constant ||
9120 (T.getAddressSpace() == LangAS::opencl_global &&
9121 getOpenCLOptions().areProgramScopeVariablesSupported(
9122 getLangOpts())))) {
9123 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9124 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
9125 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9126 << Scope << "global or constant";
9127 else
9128 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9129 << Scope << "constant";
9130 NewVD->setInvalidDecl();
9131 return;
9132 }
9133 } else {
9134 if (T.getAddressSpace() == LangAS::opencl_global) {
9135 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9136 << 1 /*is any function*/ << "global";
9137 NewVD->setInvalidDecl();
9138 return;
9139 }
9140 // When this extension is enabled, 'local' variables are permitted in
9141 // non-kernel functions and within nested scopes of kernel functions,
9142 // bypassing standard OpenCL address space restrictions.
9143 bool AllowFunctionScopeLocalVariables =
9144 T.getAddressSpace() == LangAS::opencl_local &&
9146 "__cl_clang_function_scope_local_variables", getLangOpts());
9147 if (AllowFunctionScopeLocalVariables) {
9148 // Direct pass: No further diagnostics needed for this specific case.
9149 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9150 T.getAddressSpace() == LangAS::opencl_local) {
9152 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9153 // in functions.
9154 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9155 if (T.getAddressSpace() == LangAS::opencl_constant)
9156 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9157 << 0 /*non-kernel only*/ << "constant";
9158 else
9159 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9160 << 0 /*non-kernel only*/ << "local";
9161 NewVD->setInvalidDecl();
9162 return;
9163 }
9164 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9165 // in the outermost scope of a kernel function.
9166 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9167 if (!getCurScope()->isFunctionScope()) {
9168 if (T.getAddressSpace() == LangAS::opencl_constant)
9169 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9170 << "constant";
9171 else
9172 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9173 << "local";
9174 NewVD->setInvalidDecl();
9175 return;
9176 }
9177 }
9178 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9179 // If we are parsing a template we didn't deduce an addr
9180 // space yet.
9181 T.getAddressSpace() != LangAS::Default) {
9182 // Do not allow other address spaces on automatic variable.
9183 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9184 NewVD->setInvalidDecl();
9185 return;
9186 }
9187 }
9188 }
9189
9190 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9191 && !NewVD->hasAttr<BlocksAttr>()) {
9192 if (getLangOpts().getGC() != LangOptions::NonGC)
9193 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9194 else {
9195 assert(!getLangOpts().ObjCAutoRefCount);
9196 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9197 }
9198 }
9199
9200 // WebAssembly tables must be static with a zero length and can't be
9201 // declared within functions.
9202 if (T->isWebAssemblyTableType()) {
9203 if (getCurScope()->getParent()) { // Parent is null at top-level
9204 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9205 NewVD->setInvalidDecl();
9206 return;
9207 }
9208 if (NewVD->getStorageClass() != SC_Static) {
9209 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9210 NewVD->setInvalidDecl();
9211 return;
9212 }
9213 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9214 if (!ATy || ATy->getZExtSize() != 0) {
9215 Diag(NewVD->getLocation(),
9216 diag::err_typecheck_wasm_table_must_have_zero_length);
9217 NewVD->setInvalidDecl();
9218 return;
9219 }
9220 }
9221
9222 // zero sized static arrays are not allowed in HIP device functions
9223 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9224 if (FunctionDecl *FD = getCurFunctionDecl();
9225 FD &&
9226 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9227 if (const ConstantArrayType *ArrayT =
9228 getASTContext().getAsConstantArrayType(T);
9229 ArrayT && ArrayT->isZeroSize()) {
9230 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9231 }
9232 }
9233 }
9234
9235 bool isVM = T->isVariablyModifiedType();
9236 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9237 NewVD->hasAttr<BlocksAttr>())
9239
9240 if ((isVM && NewVD->hasLinkage()) ||
9241 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9242 bool SizeIsNegative;
9243 llvm::APSInt Oversized;
9245 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9246 QualType FixedT;
9247 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9248 FixedT = FixedTInfo->getType();
9249 else if (FixedTInfo) {
9250 // Type and type-as-written are canonically different. We need to fix up
9251 // both types separately.
9252 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9253 Oversized);
9254 }
9255 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9256 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9257 // FIXME: This won't give the correct result for
9258 // int a[10][n];
9259 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9260
9261 if (NewVD->isFileVarDecl())
9262 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9263 << SizeRange;
9264 else if (NewVD->isStaticLocal())
9265 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9266 << SizeRange;
9267 else
9268 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9269 << SizeRange;
9270 NewVD->setInvalidDecl();
9271 return;
9272 }
9273
9274 if (!FixedTInfo) {
9275 if (NewVD->isFileVarDecl())
9276 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9277 else
9278 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9279 NewVD->setInvalidDecl();
9280 return;
9281 }
9282
9283 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9284 NewVD->setType(FixedT);
9285 NewVD->setTypeSourceInfo(FixedTInfo);
9286 }
9287
9288 if (T->isVoidType()) {
9289 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9290 // of objects and functions.
9292 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9293 << T;
9294 NewVD->setInvalidDecl();
9295 return;
9296 }
9297 }
9298
9299 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9300 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9301 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9302 NewVD->setInvalidDecl();
9303 return;
9304 }
9305
9306 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9307 Diag(NewVD->getLocation(), diag::err_block_not_allowed_on)
9308 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9309 NewVD->setInvalidDecl();
9310 return;
9311 }
9312
9313 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9314 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9315 NewVD->setInvalidDecl();
9316 return;
9317 }
9318
9319 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9320 !T->isDependentType() &&
9322 diag::err_constexpr_var_non_literal)) {
9323 NewVD->setInvalidDecl();
9324 return;
9325 }
9326
9327 // PPC MMA non-pointer types are not allowed as non-local variable types.
9328 if (Context.getTargetInfo().getTriple().isPPC64() &&
9329 !NewVD->isLocalVarDecl() &&
9330 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9331 NewVD->setInvalidDecl();
9332 return;
9333 }
9334
9335 // Check that SVE types are only used in functions with SVE available.
9336 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9338 llvm::StringMap<bool> CallerFeatureMap;
9339 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9340 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9341 CallerFeatureMap)) {
9342 NewVD->setInvalidDecl();
9343 return;
9344 }
9345 }
9346
9347 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9349 llvm::StringMap<bool> CallerFeatureMap;
9350 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9352 CallerFeatureMap);
9353 }
9354
9355 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9356 if (!AMDGPU().checkAMDGPUTypeSupport(T, NewVD->getLocation())) {
9357 NewVD->setInvalidDecl();
9358 return;
9359 }
9360 }
9361
9362 if (T.hasAddressSpace() &&
9363 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9364 NewVD->setInvalidDecl();
9365 return;
9366 }
9367}
9368
9371
9372 // If the decl is already known invalid, don't check it.
9373 if (NewVD->isInvalidDecl())
9374 return false;
9375
9376 // If we did not find anything by this name, look for a non-visible
9377 // extern "C" declaration with the same name.
9378 if (Previous.empty() &&
9380 Previous.setShadowed();
9381
9382 if (!Previous.empty()) {
9383 MergeVarDecl(NewVD, Previous);
9384 return true;
9385 }
9386 return false;
9387}
9388
9391
9392 // Look for methods in base classes that this method might override.
9393 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9394 /*DetectVirtual=*/false);
9395 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9396 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9397 DeclarationName Name = MD->getDeclName();
9398
9400 // We really want to find the base class destructor here.
9401 Name = Context.DeclarationNames.getCXXDestructorName(
9402 Context.getCanonicalTagType(BaseRecord));
9403 }
9404
9405 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9406 CXXMethodDecl *BaseMD =
9407 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9408 if (!BaseMD || !BaseMD->isVirtual() ||
9409 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9410 /*ConsiderCudaAttrs=*/true))
9411 continue;
9412 if (!CheckExplicitObjectOverride(MD, BaseMD))
9413 continue;
9414 if (Overridden.insert(BaseMD).second) {
9415 MD->addOverriddenMethod(BaseMD);
9420 }
9421
9422 // A method can only override one function from each base class. We
9423 // don't track indirectly overridden methods from bases of bases.
9424 return true;
9425 }
9426
9427 return false;
9428 };
9429
9430 DC->lookupInBases(VisitBase, Paths);
9431 return !Overridden.empty();
9432}
9433
9434namespace {
9435 // Struct for holding all of the extra arguments needed by
9436 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9437 struct ActOnFDArgs {
9438 Scope *S;
9439 Declarator &D;
9440 MultiTemplateParamsArg TemplateParamLists;
9441 bool AddToScope;
9442 };
9443} // end anonymous namespace
9444
9445namespace {
9446
9447// Callback to only accept typo corrections that have a non-zero edit distance.
9448// Also only accept corrections that have the same parent decl.
9449class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9450 public:
9451 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9452 CXXRecordDecl *Parent)
9453 : Context(Context), OriginalFD(TypoFD),
9454 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9455
9456 bool ValidateCandidate(const TypoCorrection &candidate) override {
9457 if (candidate.getEditDistance() == 0)
9458 return false;
9459
9460 SmallVector<unsigned, 1> MismatchedParams;
9461 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9462 CDeclEnd = candidate.end();
9463 CDecl != CDeclEnd; ++CDecl) {
9464 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9465
9466 if (FD && !FD->hasBody() &&
9467 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9468 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9469 CXXRecordDecl *Parent = MD->getParent();
9470 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9471 return true;
9472 } else if (!ExpectedParent) {
9473 return true;
9474 }
9475 }
9476 }
9477
9478 return false;
9479 }
9480
9481 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9482 return std::make_unique<DifferentNameValidatorCCC>(*this);
9483 }
9484
9485 private:
9486 ASTContext &Context;
9487 FunctionDecl *OriginalFD;
9488 CXXRecordDecl *ExpectedParent;
9489};
9490
9491} // end anonymous namespace
9492
9496
9497/// Generate diagnostics for an invalid function redeclaration.
9498///
9499/// This routine handles generating the diagnostic messages for an invalid
9500/// function redeclaration, including finding possible similar declarations
9501/// or performing typo correction if there are no previous declarations with
9502/// the same name.
9503///
9504/// Returns a NamedDecl iff typo correction was performed and substituting in
9505/// the new declaration name does not cause new errors.
9507 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9508 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9509 DeclarationName Name = NewFD->getDeclName();
9510 DeclContext *NewDC = NewFD->getDeclContext();
9511 SmallVector<unsigned, 1> MismatchedParams;
9513 TypoCorrection Correction;
9514 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9515 unsigned DiagMsg =
9516 IsLocalFriend ? diag::err_no_matching_local_friend :
9517 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9518 diag::err_member_decl_does_not_match;
9519 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9520 IsLocalFriend ? Sema::LookupLocalFriendName
9523
9524 NewFD->setInvalidDecl();
9525 if (IsLocalFriend)
9526 SemaRef.LookupName(Prev, S);
9527 else
9528 SemaRef.LookupQualifiedName(Prev, NewDC);
9529 assert(!Prev.isAmbiguous() &&
9530 "Cannot have an ambiguity in previous-declaration lookup");
9531 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9532 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9533 MD ? MD->getParent() : nullptr);
9534 if (!Prev.empty()) {
9535 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9536 Func != FuncEnd; ++Func) {
9537 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9538 if (FD &&
9539 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9540 // Add 1 to the index so that 0 can mean the mismatch didn't
9541 // involve a parameter
9542 unsigned ParamNum =
9543 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9544 NearMatches.push_back(std::make_pair(FD, ParamNum));
9545 }
9546 }
9547 // If the qualified name lookup yielded nothing, try typo correction
9548 } else if ((Correction = SemaRef.CorrectTypo(
9549 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9550 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9552 IsLocalFriend ? nullptr : NewDC))) {
9553 // Set up everything for the call to ActOnFunctionDeclarator
9554 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9555 ExtraArgs.D.getIdentifierLoc());
9556 Previous.clear();
9557 Previous.setLookupName(Correction.getCorrection());
9558 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9559 CDeclEnd = Correction.end();
9560 CDecl != CDeclEnd; ++CDecl) {
9561 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9562 if (FD && !FD->hasBody() &&
9563 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9564 Previous.addDecl(FD);
9565 }
9566 }
9567 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9568
9570 // Retry building the function declaration with the new previous
9571 // declarations, and with errors suppressed.
9572 {
9573 // Trap errors.
9574 Sema::SFINAETrap Trap(SemaRef);
9575
9576 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9577 // pieces need to verify the typo-corrected C++ declaration and hopefully
9578 // eliminate the need for the parameter pack ExtraArgs.
9580 ExtraArgs.S, ExtraArgs.D,
9581 Correction.getCorrectionDecl()->getDeclContext(),
9582 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9583 ExtraArgs.AddToScope);
9584
9585 if (Trap.hasErrorOccurred())
9586 Result = nullptr;
9587 }
9588
9589 if (Result) {
9590 // Determine which correction we picked.
9591 Decl *Canonical = Result->getCanonicalDecl();
9592 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9593 I != E; ++I)
9594 if ((*I)->getCanonicalDecl() == Canonical)
9595 Correction.setCorrectionDecl(*I);
9596
9597 // Let Sema know about the correction.
9599 SemaRef.diagnoseTypo(
9600 Correction,
9601 SemaRef.PDiag(IsLocalFriend
9602 ? diag::err_no_matching_local_friend_suggest
9603 : diag::err_member_decl_does_not_match_suggest)
9604 << Name << NewDC << IsDefinition);
9605 return Result;
9606 }
9607
9608 // Pretend the typo correction never occurred
9609 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9610 ExtraArgs.D.getIdentifierLoc());
9611 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9612 Previous.clear();
9613 Previous.setLookupName(Name);
9614 }
9615
9616 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9617 << Name << NewDC << IsDefinition << NewFD->getLocation();
9618
9619 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9620 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9621 CXXRecordDecl *RD = NewMD->getParent();
9622 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9623 << RD->getName() << RD->getLocation();
9624 }
9625
9626 bool NewFDisConst = NewMD && NewMD->isConst();
9627
9628 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9629 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9630 NearMatch != NearMatchEnd; ++NearMatch) {
9631 FunctionDecl *FD = NearMatch->first;
9632 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9633 bool FDisConst = MD && MD->isConst();
9634 bool IsMember = MD || !IsLocalFriend;
9635
9636 // FIXME: These notes are poorly worded for the local friend case.
9637 if (unsigned Idx = NearMatch->second) {
9638 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9639 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9640 if (Loc.isInvalid()) Loc = FD->getLocation();
9641 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9642 : diag::note_local_decl_close_param_match)
9643 << Idx << FDParam->getType()
9644 << NewFD->getParamDecl(Idx - 1)->getType();
9645 } else if (FDisConst != NewFDisConst) {
9646 auto DB = SemaRef.Diag(FD->getLocation(),
9647 diag::note_member_def_close_const_match)
9648 << NewFDisConst << FD->getSourceRange().getEnd();
9649 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9650 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9651 " const");
9652 else if (FTI.hasMethodTypeQualifiers() &&
9653 FTI.getConstQualifierLoc().isValid())
9654 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9655 } else {
9656 SemaRef.Diag(FD->getLocation(),
9657 IsMember ? diag::note_member_def_close_match
9658 : diag::note_local_decl_close_match);
9659 }
9660 }
9661 return nullptr;
9662}
9663
9665 switch (D.getDeclSpec().getStorageClassSpec()) {
9666 default: llvm_unreachable("Unknown storage class!");
9667 case DeclSpec::SCS_auto:
9671 diag::err_typecheck_sclass_func);
9673 D.setInvalidType();
9674 break;
9675 case DeclSpec::SCS_unspecified: break;
9678 return SC_None;
9679 return SC_Extern;
9680 case DeclSpec::SCS_static: {
9682 // C99 6.7.1p5:
9683 // The declaration of an identifier for a function that has
9684 // block scope shall have no explicit storage-class specifier
9685 // other than extern
9686 // See also (C++ [dcl.stc]p4).
9688 diag::err_static_block_func);
9689 break;
9690 } else
9691 return SC_Static;
9692 }
9694 }
9695
9696 // No explicit storage class has already been returned
9697 return SC_None;
9698}
9699
9701 DeclContext *DC, QualType &R,
9702 TypeSourceInfo *TInfo,
9703 StorageClass SC,
9704 bool &IsVirtualOkay) {
9705 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9706 DeclarationName Name = NameInfo.getName();
9707
9708 FunctionDecl *NewFD = nullptr;
9709 bool isInline = D.getDeclSpec().isInlineSpecified();
9710
9712 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9713 (SemaRef.getLangOpts().C23 &&
9714 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9715
9716 if (SemaRef.getLangOpts().C23)
9717 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9718 diag::err_c23_constexpr_not_variable);
9719 else
9720 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9721 diag::err_constexpr_wrong_decl_kind)
9722 << static_cast<int>(ConstexprKind);
9723 ConstexprKind = ConstexprSpecKind::Unspecified;
9725 }
9726
9727 if (!SemaRef.getLangOpts().CPlusPlus) {
9728 // Determine whether the function was written with a prototype. This is
9729 // true when:
9730 // - there is a prototype in the declarator, or
9731 // - the type R of the function is some kind of typedef or other non-
9732 // attributed reference to a type name (which eventually refers to a
9733 // function type). Note, we can't always look at the adjusted type to
9734 // check this case because attributes may cause a non-function
9735 // declarator to still have a function type. e.g.,
9736 // typedef void func(int a);
9737 // __attribute__((noreturn)) func other_func; // This has a prototype
9738 bool HasPrototype =
9740 (D.getDeclSpec().isTypeRep() &&
9741 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9742 ->isFunctionProtoType()) ||
9743 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9744 assert(
9745 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9746 "Strict prototypes are required");
9747
9748 NewFD = FunctionDecl::Create(
9749 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9750 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9752 /*TrailingRequiresClause=*/{});
9753 if (D.isInvalidType())
9754 NewFD->setInvalidDecl();
9755
9756 return NewFD;
9757 }
9758
9760 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9761
9762 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9763
9765 // This is a C++ constructor declaration.
9766 assert(DC->isRecord() &&
9767 "Constructors can only be declared in a member context");
9768
9769 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9771 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9773 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9774 InheritedConstructor(), TrailingRequiresClause);
9775
9776 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9777 // This is a C++ destructor declaration.
9778 if (DC->isRecord()) {
9779 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9782 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9783 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9784 /*isImplicitlyDeclared=*/false, ConstexprKind,
9785 TrailingRequiresClause);
9786 // User defined destructors start as not selected if the class definition is still
9787 // not done.
9788 if (Record->isBeingDefined())
9789 NewDD->setIneligibleOrNotSelected(true);
9790
9791 // If the destructor needs an implicit exception specification, set it
9792 // now. FIXME: It'd be nice to be able to create the right type to start
9793 // with, but the type needs to reference the destructor declaration.
9794 if (SemaRef.getLangOpts().CPlusPlus11)
9795 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9796
9797 IsVirtualOkay = true;
9798 return NewDD;
9799
9800 } else {
9801 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9802 D.setInvalidType();
9803
9804 // Create a FunctionDecl to satisfy the function definition parsing
9805 // code path.
9806 return FunctionDecl::Create(
9807 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9808 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9809 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9810 }
9811
9813 if (!DC->isRecord()) {
9814 SemaRef.Diag(D.getIdentifierLoc(),
9815 diag::err_conv_function_not_member);
9816 return nullptr;
9817 }
9818
9819 SemaRef.CheckConversionDeclarator(D, R, SC);
9820 if (D.isInvalidType())
9821 return nullptr;
9822
9823 IsVirtualOkay = true;
9825 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9826 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9827 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9828 TrailingRequiresClause);
9829
9831 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9832 return nullptr;
9834 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9835 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9836 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9837 } else if (DC->isRecord()) {
9838 // If the name of the function is the same as the name of the record,
9839 // then this must be an invalid constructor that has a return type.
9840 // (The parser checks for a return type and makes the declarator a
9841 // constructor if it has no return type).
9842 if (Name.getAsIdentifierInfo() &&
9843 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9844 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9847 return nullptr;
9848 }
9849
9850 // This is a C++ method declaration.
9852 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9853 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9854 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9855 IsVirtualOkay = !Ret->isStatic();
9856 return Ret;
9857 } else {
9858 bool isFriend =
9859 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9860 if (!isFriend && SemaRef.CurContext->isRecord())
9861 return nullptr;
9862
9863 // Determine whether the function was written with a
9864 // prototype. This true when:
9865 // - we're in C++ (where every function has a prototype),
9866 return FunctionDecl::Create(
9867 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9868 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9869 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9870 }
9871}
9872
9881
9883 // Size dependent types are just typedefs to normal integer types
9884 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9885 // integers other than by their names.
9886 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9887
9888 // Remove typedefs one by one until we reach a typedef
9889 // for a size dependent type.
9890 QualType DesugaredTy = Ty;
9891 do {
9892 ArrayRef<StringRef> Names(SizeTypeNames);
9893 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9894 if (Names.end() != Match)
9895 return true;
9896
9897 Ty = DesugaredTy;
9898 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9899 } while (DesugaredTy != Ty);
9900
9901 return false;
9902}
9903
9905 if (PT->isDependentType())
9906 return InvalidKernelParam;
9907
9908 if (PT->isPointerOrReferenceType()) {
9909 QualType PointeeType = PT->getPointeeType();
9910 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9911 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9912 PointeeType.getAddressSpace() == LangAS::Default)
9914
9915 if (PointeeType->isPointerType()) {
9916 // This is a pointer to pointer parameter.
9917 // Recursively check inner type.
9918 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9919 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9920 ParamKind == InvalidKernelParam)
9921 return ParamKind;
9922
9923 // OpenCL v3.0 s6.11.a:
9924 // A restriction to pass pointers to pointers only applies to OpenCL C
9925 // v1.2 or below.
9927 return ValidKernelParam;
9928
9929 return PtrPtrKernelParam;
9930 }
9931
9932 // C++ for OpenCL v1.0 s2.4:
9933 // Moreover the types used in parameters of the kernel functions must be:
9934 // Standard layout types for pointer parameters. The same applies to
9935 // reference if an implementation supports them in kernel parameters.
9936 if (S.getLangOpts().OpenCLCPlusPlus &&
9938 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9939 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9940 bool IsStandardLayoutType = true;
9941 if (CXXRec) {
9942 // If template type is not ODR-used its definition is only available
9943 // in the template definition not its instantiation.
9944 // FIXME: This logic doesn't work for types that depend on template
9945 // parameter (PR58590).
9946 if (!CXXRec->hasDefinition())
9947 CXXRec = CXXRec->getTemplateInstantiationPattern();
9948 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9949 IsStandardLayoutType = false;
9950 }
9951 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9952 !IsStandardLayoutType)
9953 return InvalidKernelParam;
9954 }
9955
9956 // OpenCL v1.2 s6.9.p:
9957 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9959 return ValidKernelParam;
9960
9961 return PtrKernelParam;
9962 }
9963
9964 // OpenCL v1.2 s6.9.k:
9965 // Arguments to kernel functions in a program cannot be declared with the
9966 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9967 // uintptr_t or a struct and/or union that contain fields declared to be one
9968 // of these built-in scalar types.
9970 return InvalidKernelParam;
9971
9972 if (PT->isImageType())
9973 return PtrKernelParam;
9974
9975 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9976 return InvalidKernelParam;
9977
9978 // OpenCL extension spec v1.2 s9.5:
9979 // This extension adds support for half scalar and vector types as built-in
9980 // types that can be used for arithmetic operations, conversions etc.
9981 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9982 PT->isHalfType())
9983 return InvalidKernelParam;
9984
9985 // Look into an array argument to check if it has a forbidden type.
9986 if (PT->isArrayType()) {
9987 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9988 // Call ourself to check an underlying type of an array. Since the
9989 // getPointeeOrArrayElementType returns an innermost type which is not an
9990 // array, this recursive call only happens once.
9991 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9992 }
9993
9994 // C++ for OpenCL v1.0 s2.4:
9995 // Moreover the types used in parameters of the kernel functions must be:
9996 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9997 // types) for parameters passed by value;
9998 if (S.getLangOpts().OpenCLCPlusPlus &&
10000 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
10001 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
10002 return InvalidKernelParam;
10003
10004 if (PT->isRecordType())
10005 return RecordKernelParam;
10006
10007 return ValidKernelParam;
10008}
10009
10011 Sema &S,
10012 Declarator &D,
10013 ParmVarDecl *Param,
10014 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
10015 QualType PT = Param->getType();
10016
10017 // Cache the valid types we encounter to avoid rechecking structs that are
10018 // used again
10019 if (ValidTypes.count(PT.getTypePtr()))
10020 return;
10021
10022 switch (getOpenCLKernelParameterType(S, PT)) {
10023 case PtrPtrKernelParam:
10024 // OpenCL v3.0 s6.11.a:
10025 // A kernel function argument cannot be declared as a pointer to a pointer
10026 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
10027 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
10028 D.setInvalidType();
10029 return;
10030
10032 // OpenCL v1.0 s6.5:
10033 // __kernel function arguments declared to be a pointer of a type can point
10034 // to one of the following address spaces only : __global, __local or
10035 // __constant.
10036 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
10037 D.setInvalidType();
10038 return;
10039
10040 // OpenCL v1.2 s6.9.k:
10041 // Arguments to kernel functions in a program cannot be declared with the
10042 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10043 // uintptr_t or a struct and/or union that contain fields declared to be
10044 // one of these built-in scalar types.
10045
10046 case InvalidKernelParam:
10047 // OpenCL v1.2 s6.8 n:
10048 // A kernel function argument cannot be declared
10049 // of event_t type.
10050 // Do not diagnose half type since it is diagnosed as invalid argument
10051 // type for any function elsewhere.
10052 if (!PT->isHalfType()) {
10053 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10054
10055 // Explain what typedefs are involved.
10056 const TypedefType *Typedef = nullptr;
10057 while ((Typedef = PT->getAs<TypedefType>())) {
10058 SourceLocation Loc = Typedef->getDecl()->getLocation();
10059 // SourceLocation may be invalid for a built-in type.
10060 if (Loc.isValid())
10061 S.Diag(Loc, diag::note_entity_declared_at) << PT;
10062 PT = Typedef->desugar();
10063 }
10064 }
10065
10066 D.setInvalidType();
10067 return;
10068
10069 case PtrKernelParam:
10070 case ValidKernelParam:
10071 ValidTypes.insert(PT.getTypePtr());
10072 return;
10073
10074 case RecordKernelParam:
10075 break;
10076 }
10077
10078 // Track nested structs we will inspect
10080
10081 // Track where we are in the nested structs. Items will migrate from
10082 // VisitStack to HistoryStack as we do the DFS for bad field.
10084 HistoryStack.push_back(nullptr);
10085
10086 // At this point we already handled everything except of a RecordType.
10087 assert(PT->isRecordType() && "Unexpected type.");
10088 const auto *PD = PT->castAsRecordDecl();
10089 VisitStack.push_back(PD);
10090 assert(VisitStack.back() && "First decl null?");
10091
10092 do {
10093 const Decl *Next = VisitStack.pop_back_val();
10094 if (!Next) {
10095 assert(!HistoryStack.empty());
10096 // Found a marker, we have gone up a level
10097 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10098 ValidTypes.insert(Hist->getType().getTypePtr());
10099
10100 continue;
10101 }
10102
10103 // Adds everything except the original parameter declaration (which is not a
10104 // field itself) to the history stack.
10105 const RecordDecl *RD;
10106 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
10107 HistoryStack.push_back(Field);
10108
10109 QualType FieldTy = Field->getType();
10110 // Other field types (known to be valid or invalid) are handled while we
10111 // walk around RecordDecl::fields().
10112 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10113 "Unexpected type.");
10114 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10115
10116 RD = FieldRecTy->castAsRecordDecl();
10117 } else {
10118 RD = cast<RecordDecl>(Next);
10119 }
10120
10121 // Add a null marker so we know when we've gone back up a level
10122 VisitStack.push_back(nullptr);
10123
10124 for (const auto *FD : RD->fields()) {
10125 QualType QT = FD->getType();
10126
10127 if (ValidTypes.count(QT.getTypePtr()))
10128 continue;
10129
10131 if (ParamType == ValidKernelParam)
10132 continue;
10133
10134 if (ParamType == RecordKernelParam) {
10135 VisitStack.push_back(FD);
10136 continue;
10137 }
10138
10139 // OpenCL v1.2 s6.9.p:
10140 // Arguments to kernel functions that are declared to be a struct or union
10141 // do not allow OpenCL objects to be passed as elements of the struct or
10142 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10143 // of SVM.
10144 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10145 ParamType == InvalidAddrSpacePtrKernelParam) {
10146 S.Diag(Param->getLocation(),
10147 diag::err_record_with_pointers_kernel_param)
10148 << PT->isUnionType()
10149 << PT;
10150 } else {
10151 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10152 }
10153
10154 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10155 << PD->getDeclName();
10156
10157 // We have an error, now let's go back up through history and show where
10158 // the offending field came from
10160 I = HistoryStack.begin() + 1,
10161 E = HistoryStack.end();
10162 I != E; ++I) {
10163 const FieldDecl *OuterField = *I;
10164 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10165 << OuterField->getType();
10166 }
10167
10168 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10169 << QT->isPointerType()
10170 << QT;
10171 D.setInvalidType();
10172 return;
10173 }
10174 } while (!VisitStack.empty());
10175}
10176
10177/// Find the DeclContext in which a tag is implicitly declared if we see an
10178/// elaborated type specifier in the specified context, and lookup finds
10179/// nothing.
10181 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10182 DC = DC->getParent();
10183 return DC;
10184}
10185
10186/// Find the Scope in which a tag is implicitly declared if we see an
10187/// elaborated type specifier in the specified context, and lookup finds
10188/// nothing.
10189static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10190 while (S->isClassScope() ||
10191 (LangOpts.CPlusPlus &&
10193 ((S->getFlags() & Scope::DeclScope) == 0) ||
10194 (S->getEntity() && S->getEntity()->isTransparentContext()))
10195 S = S->getParent();
10196 return S;
10197}
10198
10199/// Determine whether a declaration matches a known function in namespace std.
10201 unsigned BuiltinID) {
10202 switch (BuiltinID) {
10203 case Builtin::BI__GetExceptionInfo:
10204 // No type checking whatsoever.
10205 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10206
10207 case Builtin::BIaddressof:
10208 case Builtin::BI__addressof:
10209 case Builtin::BIforward:
10210 case Builtin::BIforward_like:
10211 case Builtin::BImove:
10212 case Builtin::BImove_if_noexcept:
10213 case Builtin::BIas_const: {
10214 // Ensure that we don't treat the algorithm
10215 // OutputIt std::move(InputIt, InputIt, OutputIt)
10216 // as the builtin std::move.
10217 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10218 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10219 }
10220
10221 default:
10222 return false;
10223 }
10224}
10225
10227 const auto *FT = FD->getType()->getAs<FunctionType>();
10228 if (!FT)
10229 return;
10230
10231 StringRef Tag;
10232 switch (FT->getCallConv()) {
10233#define CC_VLS_CASE(ABI_VLEN) \
10234 case CC_RISCVVLSCall_##ABI_VLEN: \
10235 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10236 break;
10237 CC_VLS_CASE(32)
10238 CC_VLS_CASE(64)
10239 CC_VLS_CASE(128)
10240 CC_VLS_CASE(256)
10241 CC_VLS_CASE(512)
10242 CC_VLS_CASE(1024)
10243 CC_VLS_CASE(2048)
10244 CC_VLS_CASE(4096)
10245 CC_VLS_CASE(8192)
10246 CC_VLS_CASE(16384)
10247 CC_VLS_CASE(32768)
10248 CC_VLS_CASE(65536)
10249#undef CC_VLS_CASE
10250 default:
10251 return;
10252 }
10253
10254 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10255 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10256
10258 if (Old)
10259 llvm::append_range(Tags, Old->tags());
10260 if (llvm::is_contained(Tags, Tag))
10261 return;
10262 Tags.push_back(Tag);
10263
10264 AbiTagAttr *Merged =
10265 Old ? AbiTagAttr::Create(Context, Tags.data(), Tags.size(), *Old)
10266 : AbiTagAttr::CreateImplicit(Context, Tags.data(), Tags.size(),
10267 FD->getLocation());
10268 FD->dropAttr<AbiTagAttr>();
10269 FD->addAttr(Merged);
10270 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10271 FD->addAttr(Existing[I]);
10272}
10273
10274NamedDecl*
10277 MultiTemplateParamsArg TemplateParamListsRef,
10278 bool &AddToScope) {
10279 QualType R = TInfo->getType();
10280
10281 assert(R->isFunctionType());
10282 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10283 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10284
10285 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10286 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10288 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10289 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10290 TemplateParamLists.back() = Invented;
10291 else
10292 TemplateParamLists.push_back(Invented);
10293 }
10294
10295 // TODO: consider using NameInfo for diagnostic.
10297 DeclarationName Name = NameInfo.getName();
10299
10302 diag::err_invalid_thread)
10304
10309
10310 bool isFriend = false;
10312 bool isMemberSpecialization = false;
10313 bool isFunctionTemplateSpecialization = false;
10314
10315 bool HasExplicitTemplateArgs = false;
10316 TemplateArgumentListInfo TemplateArgs;
10317
10318 bool isVirtualOkay = false;
10319
10320 DeclContext *OriginalDC = DC;
10321 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10322
10323 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10324 isVirtualOkay);
10325 if (!NewFD) return nullptr;
10326
10327 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10329
10330 // Set the lexical context. If this is a function-scope declaration, or has a
10331 // C++ scope specifier, or is the object of a friend declaration, the lexical
10332 // context will be different from the semantic context.
10334
10335 if (IsLocalExternDecl)
10336 NewFD->setLocalExternDecl();
10337
10338 if (getLangOpts().CPlusPlus) {
10339 // The rules for implicit inlines changed in C++20 for methods and friends
10340 // with an in-class definition (when such a definition is not attached to
10341 // the global module). This does not affect declarations that are already
10342 // inline (whether explicitly or implicitly by being declared constexpr,
10343 // consteval, etc).
10344 // FIXME: We need a better way to separate C++ standard and clang modules.
10345 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10346 !NewFD->getOwningModule() ||
10347 NewFD->isFromGlobalModule() ||
10349 bool isInline = D.getDeclSpec().isInlineSpecified();
10350 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10351 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10352 isFriend = D.getDeclSpec().isFriendSpecified();
10353 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10354 // Pre-C++20 [class.friend]p5
10355 // A function can be defined in a friend declaration of a
10356 // class . . . . Such a function is implicitly inline.
10357 // Post C++20 [class.friend]p7
10358 // Such a function is implicitly an inline function if it is attached
10359 // to the global module.
10360 NewFD->setImplicitlyInline();
10361 }
10362
10363 // If this is a method defined in an __interface, and is not a constructor
10364 // or an overloaded operator, then set the pure flag (isVirtual will already
10365 // return true).
10366 if (const CXXRecordDecl *Parent =
10367 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10368 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10369 NewFD->setIsPureVirtual(true);
10370
10371 // C++ [class.union]p2
10372 // A union can have member functions, but not virtual functions.
10373 if (isVirtual && Parent->isUnion()) {
10374 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10375 NewFD->setInvalidDecl();
10376 }
10377 if ((Parent->isClass() || Parent->isStruct()) &&
10378 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10379 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10380 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10381 if (auto *Def = Parent->getDefinition())
10382 Def->setInitMethod(true);
10383 }
10384 }
10385
10386 SetNestedNameSpecifier(*this, NewFD, D);
10387 isMemberSpecialization = false;
10388 isFunctionTemplateSpecialization = false;
10389 if (D.isInvalidType())
10390 NewFD->setInvalidDecl();
10391
10392 // Match up the template parameter lists with the scope specifier, then
10393 // determine whether we have a template or a template specialization.
10394 bool Invalid = false;
10395 TemplateIdAnnotation *TemplateId =
10397 ? D.getName().TemplateId
10398 : nullptr;
10399 TemplateParameterList *TemplateParams =
10402 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10403 isMemberSpecialization, Invalid);
10404 if (TemplateParams) {
10405 // Check that we can declare a template here.
10406 if (CheckTemplateDeclScope(S, TemplateParams))
10407 NewFD->setInvalidDecl();
10408
10409 if (TemplateParams->size() > 0) {
10410 // This is a function template
10411
10412 // A destructor cannot be a template.
10414 Diag(NewFD->getLocation(), diag::err_destructor_template);
10415 NewFD->setInvalidDecl();
10416 // Function template with explicit template arguments.
10417 } else if (TemplateId) {
10418 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10419 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10420 NewFD->setInvalidDecl();
10421 }
10422
10423 // If we're adding a template to a dependent context, we may need to
10424 // rebuilding some of the types used within the template parameter list,
10425 // now that we know what the current instantiation is.
10426 if (DC->isDependentContext()) {
10427 ContextRAII SavedContext(*this, DC);
10429 Invalid = true;
10430 }
10431
10433 NewFD->getLocation(),
10434 Name, TemplateParams,
10435 NewFD);
10436 FunctionTemplate->setLexicalDeclContext(CurContext);
10438
10439 // For source fidelity, store the other template param lists.
10440 if (TemplateParamLists.size() > 1) {
10442 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10443 .drop_back(1));
10444 }
10445 } else {
10446 // This is a function template specialization.
10447 isFunctionTemplateSpecialization = true;
10448 // For source fidelity, store all the template param lists.
10449 if (TemplateParamLists.size() > 0)
10450 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10451
10452 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10453 if (isFriend) {
10454 // We want to remove the "template<>", found here.
10455 SourceRange RemoveRange = TemplateParams->getSourceRange();
10456
10457 // If we remove the template<> and the name is not a
10458 // template-id, we're actually silently creating a problem:
10459 // the friend declaration will refer to an untemplated decl,
10460 // and clearly the user wants a template specialization. So
10461 // we need to insert '<>' after the name.
10462 SourceLocation InsertLoc;
10464 InsertLoc = D.getName().getSourceRange().getEnd();
10465 InsertLoc = getLocForEndOfToken(InsertLoc);
10466 }
10467
10468 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10469 << Name << RemoveRange
10470 << FixItHint::CreateRemoval(RemoveRange)
10471 << FixItHint::CreateInsertion(InsertLoc, "<>");
10472 Invalid = true;
10473
10474 // Recover by faking up an empty template argument list.
10475 HasExplicitTemplateArgs = true;
10476 TemplateArgs.setLAngleLoc(InsertLoc);
10477 TemplateArgs.setRAngleLoc(InsertLoc);
10478 }
10479 }
10480 } else {
10481 // Check that we can declare a template here.
10482 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10483 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10484 NewFD->setInvalidDecl();
10485
10486 // All template param lists were matched against the scope specifier:
10487 // this is NOT (an explicit specialization of) a template.
10488 if (TemplateParamLists.size() > 0)
10489 // For source fidelity, store all the template param lists.
10490 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10491
10492 // "friend void foo<>(int);" is an implicit specialization decl.
10493 if (isFriend && TemplateId)
10494 isFunctionTemplateSpecialization = true;
10495 }
10496
10497 // If this is a function template specialization and the unqualified-id of
10498 // the declarator-id is a template-id, convert the template argument list
10499 // into our AST format and check for unexpanded packs.
10500 if (isFunctionTemplateSpecialization && TemplateId) {
10501 HasExplicitTemplateArgs = true;
10502
10503 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10504 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10505 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10506 TemplateId->NumArgs);
10507 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10508
10509 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10510 // declaration of a function template partial specialization? Should we
10511 // consider the unexpanded pack context to be a partial specialization?
10512 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10514 ArgLoc, isFriend ? UPPC_FriendDeclaration
10516 NewFD->setInvalidDecl();
10517 }
10518 }
10519
10520 if (Invalid) {
10521 NewFD->setInvalidDecl();
10522 if (FunctionTemplate)
10523 FunctionTemplate->setInvalidDecl();
10524 }
10525
10526 // C++ [dcl.fct.spec]p5:
10527 // The virtual specifier shall only be used in declarations of
10528 // nonstatic class member functions that appear within a
10529 // member-specification of a class declaration; see 10.3.
10530 //
10531 if (isVirtual && !NewFD->isInvalidDecl()) {
10532 if (!isVirtualOkay) {
10534 diag::err_virtual_non_function);
10535 } else if (!CurContext->isRecord()) {
10536 // 'virtual' was specified outside of the class.
10538 diag::err_virtual_out_of_class)
10540 } else if (NewFD->getDescribedFunctionTemplate()) {
10541 // C++ [temp.mem]p3:
10542 // A member function template shall not be virtual.
10544 diag::err_virtual_member_function_template)
10546 } else {
10547 // Okay: Add virtual to the method.
10548 NewFD->setVirtualAsWritten(true);
10549 }
10550
10551 if (getLangOpts().CPlusPlus14 &&
10552 NewFD->getReturnType()->isUndeducedType())
10553 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10554 }
10555
10556 // C++ [dcl.fct.spec]p3:
10557 // The inline specifier shall not appear on a block scope function
10558 // declaration.
10559 if (isInline && !NewFD->isInvalidDecl()) {
10560 if (CurContext->isFunctionOrMethod()) {
10561 // 'inline' is not allowed on block scope function declaration.
10563 diag::err_inline_declaration_block_scope) << Name
10565 }
10566 }
10567
10568 // C++ [dcl.fct.spec]p6:
10569 // The explicit specifier shall be used only in the declaration of a
10570 // constructor or conversion function within its class definition;
10571 // see 12.3.1 and 12.3.2.
10572 if (hasExplicit && !NewFD->isInvalidDecl() &&
10574 if (!CurContext->isRecord()) {
10575 // 'explicit' was specified outside of the class.
10577 diag::err_explicit_out_of_class)
10579 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10580 !isa<CXXConversionDecl>(NewFD)) {
10581 // 'explicit' was specified on a function that wasn't a constructor
10582 // or conversion function.
10584 diag::err_explicit_non_ctor_or_conv_function)
10586 }
10587 }
10588
10590 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10591 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10592 // are implicitly inline.
10593 NewFD->setImplicitlyInline();
10594
10595 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10596 // be either constructors or to return a literal type. Therefore,
10597 // destructors cannot be declared constexpr.
10598 if (isa<CXXDestructorDecl>(NewFD) &&
10600 ConstexprKind == ConstexprSpecKind::Consteval)) {
10601 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10602 << static_cast<int>(ConstexprKind);
10606 }
10607 // C++20 [dcl.constexpr]p2: An allocation function, or a
10608 // deallocation function shall not be declared with the consteval
10609 // specifier.
10610 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10613 diag::err_invalid_consteval_decl_kind)
10614 << NewFD;
10616 }
10617 }
10618
10619 // If __module_private__ was specified, mark the function accordingly.
10621 if (isFunctionTemplateSpecialization) {
10622 SourceLocation ModulePrivateLoc
10624 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10625 << 0
10626 << FixItHint::CreateRemoval(ModulePrivateLoc);
10627 } else {
10628 NewFD->setModulePrivate();
10629 if (FunctionTemplate)
10630 FunctionTemplate->setModulePrivate();
10631 }
10632 }
10633
10634 if (isFriend) {
10635 if (FunctionTemplate) {
10636 FunctionTemplate->setObjectOfFriendDecl();
10637 FunctionTemplate->setAccess(AS_public);
10638 }
10639 NewFD->setObjectOfFriendDecl();
10640 NewFD->setAccess(AS_public);
10641 }
10642
10643 // If a function is defined as defaulted or deleted, mark it as such now.
10644 // We'll do the relevant checks on defaulted / deleted functions later.
10645 switch (D.getFunctionDefinitionKind()) {
10648 break;
10649
10651 NewFD->setDefaulted();
10652 break;
10653
10655 NewFD->setDeletedAsWritten();
10656 break;
10657 }
10658
10659 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10661 // Pre C++20 [class.mfct]p2:
10662 // A member function may be defined (8.4) in its class definition, in
10663 // which case it is an inline member function (7.1.2)
10664 // Post C++20 [class.mfct]p1:
10665 // If a member function is attached to the global module and is defined
10666 // in its class definition, it is inline.
10667 NewFD->setImplicitlyInline();
10668 }
10669
10670 if (!isFriend && SC != SC_None) {
10671 // C++ [temp.expl.spec]p2:
10672 // The declaration in an explicit-specialization shall not be an
10673 // export-declaration. An explicit specialization shall not use a
10674 // storage-class-specifier other than thread_local.
10675 //
10676 // We diagnose friend declarations with storage-class-specifiers
10677 // elsewhere.
10678 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10680 diag::ext_explicit_specialization_storage_class)
10683 }
10684
10685 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10686 assert(isa<CXXMethodDecl>(NewFD) &&
10687 "Out-of-line member function should be a CXXMethodDecl");
10688 // C++ [class.static]p1:
10689 // A data or function member of a class may be declared static
10690 // in a class definition, in which case it is a static member of
10691 // the class.
10692
10693 // Complain about the 'static' specifier if it's on an out-of-line
10694 // member function definition.
10695
10696 // MSVC permits the use of a 'static' storage specifier on an
10697 // out-of-line member function template declaration and class member
10698 // template declaration (MSVC versions before 2015), warn about this.
10700 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10701 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10702 (getLangOpts().MSVCCompat &&
10704 ? diag::ext_static_out_of_line
10705 : diag::err_static_out_of_line)
10708 }
10709 }
10710
10711 // C++11 [except.spec]p15:
10712 // A deallocation function with no exception-specification is treated
10713 // as if it were specified with noexcept(true).
10714 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10715 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10716 !FPT->hasExceptionSpec())
10717 NewFD->setType(Context.getFunctionType(
10718 FPT->getReturnType(), FPT->getParamTypes(),
10720
10721 // C++20 [dcl.inline]/7
10722 // If an inline function or variable that is attached to a named module
10723 // is declared in a definition domain, it shall be defined in that
10724 // domain.
10725 // So, if the current declaration does not have a definition, we must
10726 // check at the end of the TU (or when the PMF starts) to see that we
10727 // have a definition at that point.
10728 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10729 NewFD->isInNamedModule()) {
10730 PendingInlineFuncDecls.insert(NewFD);
10731 }
10732 }
10733
10734 // Filter out previous declarations that don't match the scope.
10737 isMemberSpecialization ||
10738 isFunctionTemplateSpecialization);
10739
10741
10742 // Handle GNU asm-label extension (encoded as an attribute).
10743 if (Expr *E = D.getAsmLabel()) {
10744 // The parser guarantees this is a string.
10746 NewFD->addAttr(
10747 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10748 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10749 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10751 if (I != ExtnameUndeclaredIdentifiers.end()) {
10752 if (isDeclExternC(NewFD)) {
10753 NewFD->addAttr(I->second);
10755 } else if (NewFD->getDeclContext()
10758 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10759 << /*Variable*/0 << NewFD;
10760 }
10761 }
10762
10763 // Copy the parameter declarations from the declarator D to the function
10764 // declaration NewFD, if they are available. First scavenge them into Params.
10766 unsigned FTIIdx;
10767 if (D.isFunctionDeclarator(FTIIdx)) {
10769
10770 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10771 // function that takes no arguments, not a function that takes a
10772 // single void argument.
10773 // We let through "const void" here because Sema::GetTypeForDeclarator
10774 // already checks for that case.
10775 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10776 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10777 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10778 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10779 Param->setDeclContext(NewFD);
10780 Params.push_back(Param);
10781
10782 if (Param->isInvalidDecl())
10783 NewFD->setInvalidDecl();
10784 }
10785 }
10786
10787 if (!getLangOpts().CPlusPlus) {
10788 // In C, find all the tag declarations from the prototype and move them
10789 // into the function DeclContext. Remove them from the surrounding tag
10790 // injection context of the function, which is typically but not always
10791 // the TU.
10792 DeclContext *PrototypeTagContext =
10794 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10795 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10796
10797 // We don't want to reparent enumerators. Look at their parent enum
10798 // instead.
10799 if (!TD) {
10800 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10801 TD = cast<EnumDecl>(ECD->getDeclContext());
10802 }
10803 if (!TD)
10804 continue;
10805 DeclContext *TagDC = TD->getLexicalDeclContext();
10806 if (!TagDC->containsDecl(TD))
10807 continue;
10808 TagDC->removeDecl(TD);
10809 TD->setDeclContext(NewFD);
10810 NewFD->addDecl(TD);
10811
10812 // Preserve the lexical DeclContext if it is not the surrounding tag
10813 // injection context of the FD. In this example, the semantic context of
10814 // E will be f and the lexical context will be S, while both the
10815 // semantic and lexical contexts of S will be f:
10816 // void f(struct S { enum E { a } f; } s);
10817 if (TagDC != PrototypeTagContext)
10818 TD->setLexicalDeclContext(TagDC);
10819 }
10820 }
10821 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10822 // When we're declaring a function with a typedef, typeof, etc as in the
10823 // following example, we'll need to synthesize (unnamed)
10824 // parameters for use in the declaration.
10825 //
10826 // @code
10827 // typedef void fn(int);
10828 // fn f;
10829 // @endcode
10830
10831 // Synthesize a parameter for each argument type.
10832 for (const auto &AI : FT->param_types()) {
10833 ParmVarDecl *Param =
10835 Param->setScopeInfo(0, Params.size());
10836 Params.push_back(Param);
10837 }
10838 } else {
10839 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10840 "Should not need args for typedef of non-prototype fn");
10841 }
10842
10843 // Finally, we know we have the right number of parameters, install them.
10844 NewFD->setParams(Params);
10845
10846 // If this declarator is a declaration and not a definition, its parameters
10847 // will not be pushed onto a scope chain. That means we will not issue any
10848 // reserved identifier warnings for the declaration, but we will for the
10849 // definition. Handle those here.
10850 if (!D.isFunctionDefinition()) {
10851 for (const ParmVarDecl *PVD : Params)
10853 }
10854
10856 NewFD->addAttr(
10857 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10858
10859 // Functions returning a variably modified type violate C99 6.7.5.2p2
10860 // because all functions have linkage.
10861 if (!NewFD->isInvalidDecl() &&
10863 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10864 NewFD->setInvalidDecl();
10865 }
10866
10867 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10869 !NewFD->hasAttr<SectionAttr>())
10870 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10871 Context, PragmaClangTextSection.SectionName,
10872 PragmaClangTextSection.PragmaLocation));
10873
10874 // Apply an implicit SectionAttr if #pragma code_seg is active.
10875 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10876 !NewFD->hasAttr<SectionAttr>()) {
10877 NewFD->addAttr(SectionAttr::CreateImplicit(
10878 Context, CodeSegStack.CurrentValue->getString(),
10879 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10880 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10883 NewFD))
10884 NewFD->dropAttr<SectionAttr>();
10885 }
10886
10887 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10888 // active.
10889 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10890 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10891 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10892 Context, PragmaClangTextSection.PragmaLocation));
10893
10894 // Apply an implicit CodeSegAttr from class declspec or
10895 // apply an implicit SectionAttr from #pragma code_seg if active.
10896 if (!NewFD->hasAttr<CodeSegAttr>()) {
10898 D.isFunctionDefinition())) {
10899 NewFD->addAttr(SAttr);
10900 }
10901 }
10902
10903 // Handle attributes.
10904 ProcessDeclAttributes(S, NewFD, D);
10906 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10907 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10908 !NewTVA->isDefaultVersion() &&
10909 !Context.getTargetInfo().hasFeature("fmv")) {
10910 // Don't add to scope fmv functions declarations if fmv disabled
10911 AddToScope = false;
10912 return NewFD;
10913 }
10914
10915 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10916 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10917 // type.
10918 //
10919 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10920 // type declaration will generate a compilation error.
10921 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10922 if (AddressSpace != LangAS::Default) {
10923 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10924 NewFD->setInvalidDecl();
10925 }
10926 }
10927
10928 if (!getLangOpts().CPlusPlus) {
10929 // Perform semantic checking on the function declaration.
10930 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10931 CheckMain(NewFD, D.getDeclSpec());
10932
10933 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10934 CheckMSVCRTEntryPoint(NewFD);
10935
10936 if (!NewFD->isInvalidDecl())
10938 isMemberSpecialization,
10940 else if (!Previous.empty())
10941 // Recover gracefully from an invalid redeclaration.
10942 D.setRedeclaration(true);
10943 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10944 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10945 "previous declaration set still overloaded");
10946
10947 // Diagnose no-prototype function declarations with calling conventions that
10948 // don't support variadic calls. Only do this in C and do it after merging
10949 // possibly prototyped redeclarations.
10950 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10952 CallingConv CC = FT->getExtInfo().getCC();
10953 if (!supportsVariadicCall(CC)) {
10954 // Windows system headers sometimes accidentally use stdcall without
10955 // (void) parameters, so we relax this to a warning.
10956 int DiagID =
10957 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10958 Diag(NewFD->getLocation(), DiagID)
10960 }
10961 }
10962
10966 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10968 } else {
10969 // C++11 [replacement.functions]p3:
10970 // The program's definitions shall not be specified as inline.
10971 //
10972 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10973 //
10974 // Suppress the diagnostic if the function is __attribute__((used)), since
10975 // that forces an external definition to be emitted.
10976 if (D.getDeclSpec().isInlineSpecified() &&
10978 !NewFD->hasAttr<UsedAttr>())
10980 diag::ext_operator_new_delete_declared_inline)
10981 << NewFD->getDeclName();
10982
10983 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10984 // C++20 [dcl.decl.general]p4:
10985 // The optional requires-clause in an init-declarator or
10986 // member-declarator shall be present only if the declarator declares a
10987 // templated function.
10988 //
10989 // C++20 [temp.pre]p8:
10990 // An entity is templated if it is
10991 // - a template,
10992 // - an entity defined or created in a templated entity,
10993 // - a member of a templated entity,
10994 // - an enumerator for an enumeration that is a templated entity, or
10995 // - the closure type of a lambda-expression appearing in the
10996 // declaration of a templated entity.
10997 //
10998 // [Note 6: A local class, a local or block variable, or a friend
10999 // function defined in a templated entity is a templated entity.
11000 // — end note]
11001 //
11002 // A templated function is a function template or a function that is
11003 // templated. A templated class is a class template or a class that is
11004 // templated. A templated variable is a variable template or a variable
11005 // that is templated.
11006 if (!FunctionTemplate) {
11007 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
11008 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
11009 // An explicit specialization shall not have a trailing
11010 // requires-clause unless it declares a function template.
11011 //
11012 // Since a friend function template specialization cannot be
11013 // definition, and since a non-template friend declaration with a
11014 // trailing requires-clause must be a definition, we diagnose
11015 // friend function template specializations with trailing
11016 // requires-clauses on the same path as explicit specializations
11017 // even though they aren't necessarily prohibited by the same
11018 // language rule.
11019 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
11020 << isFriend;
11021 } else if (isFriend && NewFD->isTemplated() &&
11022 !D.isFunctionDefinition()) {
11023 // C++ [temp.friend]p9:
11024 // A non-template friend declaration with a requires-clause shall be
11025 // a definition.
11026 Diag(NewFD->getBeginLoc(),
11027 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
11028 NewFD->setInvalidDecl();
11029 } else if (!NewFD->isTemplated() ||
11030 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
11031 Diag(TRC->getBeginLoc(),
11032 diag::err_constrained_non_templated_function);
11033 }
11034 }
11035 }
11036
11037 // We do not add HD attributes to specializations here because
11038 // they may have different constexpr-ness compared to their
11039 // templates and, after maybeAddHostDeviceAttrs() is applied,
11040 // may end up with different effective targets. Instead, a
11041 // specialization inherits its target attributes from its template
11042 // in the CheckFunctionTemplateSpecialization() call below.
11043 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11045
11046 // Handle explicit specializations of function templates
11047 // and friend function declarations with an explicit
11048 // template argument list.
11049 if (isFunctionTemplateSpecialization) {
11050 bool isDependentSpecialization = false;
11051 if (isFriend) {
11052 // For friend function specializations, this is a dependent
11053 // specialization if its semantic context is dependent, its
11054 // qualifier is dependent, its type is dependent, or its template-id is
11055 // dependent.
11056 isDependentSpecialization =
11057 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11058 NewFD->getType()->isDependentType() ||
11059 (HasExplicitTemplateArgs &&
11060 TemplateSpecializationType::
11061 anyInstantiationDependentTemplateArguments(
11062 TemplateArgs.arguments()));
11063 assert((!isDependentSpecialization ||
11064 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11065 "dependent friend function specialization without template "
11066 "args");
11067 } else {
11068 // For class-scope explicit specializations of function templates,
11069 // if the lexical context is dependent, then the specialization
11070 // is dependent.
11071 isDependentSpecialization =
11072 CurContext->isRecord() && CurContext->isDependentContext();
11073 }
11074
11075 TemplateArgumentListInfo *ExplicitTemplateArgs =
11076 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11077 if (isDependentSpecialization) {
11078 // If it's a dependent specialization, it may not be possible
11079 // to determine the primary template (for explicit specializations)
11080 // or befriended declaration (for friends) until the enclosing
11081 // template is instantiated. In such cases, we store the declarations
11082 // found by name lookup and defer resolution until instantiation.
11084 NewFD, ExplicitTemplateArgs, Previous))
11085 NewFD->setInvalidDecl();
11086 } else if (!NewFD->isInvalidDecl()) {
11087 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
11088 Previous))
11089 NewFD->setInvalidDecl();
11090 }
11091 } else if (isMemberSpecialization && !FunctionTemplate) {
11093 NewFD->setInvalidDecl();
11094 }
11095
11096 // Perform semantic checking on the function declaration.
11097 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11098 CheckMain(NewFD, D.getDeclSpec());
11099
11100 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11101 CheckMSVCRTEntryPoint(NewFD);
11102
11103 if (!NewFD->isInvalidDecl())
11105 isMemberSpecialization,
11107 else if (!Previous.empty())
11108 // Recover gracefully from an invalid redeclaration.
11109 D.setRedeclaration(true);
11110
11111 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11112 !D.isRedeclaration() ||
11113 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11114 "previous declaration set still overloaded");
11115
11116 NamedDecl *PrincipalDecl = (FunctionTemplate
11118 : NewFD);
11119
11120 if (isFriend && NewFD->getPreviousDecl()) {
11121 AccessSpecifier Access = AS_public;
11122 if (!NewFD->isInvalidDecl())
11123 Access = NewFD->getPreviousDecl()->getAccess();
11124
11125 NewFD->setAccess(Access);
11126 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11127 }
11128
11129 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11131 PrincipalDecl->setNonMemberOperator();
11132
11133 // If we have a function template, check the template parameter
11134 // list. This will check and merge default template arguments.
11135 if (FunctionTemplate) {
11136 FunctionTemplateDecl *PrevTemplate =
11137 FunctionTemplate->getPreviousDecl();
11138 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
11139 PrevTemplate ? PrevTemplate->getTemplateParameters()
11140 : nullptr,
11145 : (D.getCXXScopeSpec().isSet() &&
11146 DC && DC->isRecord() &&
11147 DC->isDependentContext())
11150 }
11151
11152 if (NewFD->isInvalidDecl()) {
11153 // Ignore all the rest of this.
11154 } else if (!D.isRedeclaration()) {
11155 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
11156 AddToScope };
11157 // Fake up an access specifier if it's supposed to be a class member.
11158 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
11159 NewFD->setAccess(AS_public);
11160
11161 // Qualified decls generally require a previous declaration.
11162 if (D.getCXXScopeSpec().isSet()) {
11163 // ...with the major exception of templated-scope or
11164 // dependent-scope friend declarations.
11165
11166 // TODO: we currently also suppress this check in dependent
11167 // contexts because (1) the parameter depth will be off when
11168 // matching friend templates and (2) we might actually be
11169 // selecting a friend based on a dependent factor. But there
11170 // are situations where these conditions don't apply and we
11171 // can actually do this check immediately.
11172 //
11173 // Unless the scope is dependent, it's always an error if qualified
11174 // redeclaration lookup found nothing at all. Diagnose that now;
11175 // nothing will diagnose that error later.
11176 if (isFriend &&
11178 (!Previous.empty() && CurContext->isDependentContext()))) {
11179 // ignore these
11180 } else if (NewFD->isCPUDispatchMultiVersion() ||
11181 NewFD->isCPUSpecificMultiVersion()) {
11182 // ignore this, we allow the redeclaration behavior here to create new
11183 // versions of the function.
11184 } else {
11185 // The user tried to provide an out-of-line definition for a
11186 // function that is a member of a class or namespace, but there
11187 // was no such member function declared (C++ [class.mfct]p2,
11188 // C++ [namespace.memdef]p2). For example:
11189 //
11190 // class X {
11191 // void f() const;
11192 // };
11193 //
11194 // void X::f() { } // ill-formed
11195 //
11196 // Complain about this problem, and attempt to suggest close
11197 // matches (e.g., those that differ only in cv-qualifiers and
11198 // whether the parameter types are references).
11199
11201 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
11202 AddToScope = ExtraArgs.AddToScope;
11203 return Result;
11204 }
11205 }
11206
11207 // Unqualified local friend declarations are required to resolve
11208 // to something.
11209 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11211 *this, Previous, NewFD, ExtraArgs, true, S)) {
11212 AddToScope = ExtraArgs.AddToScope;
11213 return Result;
11214 }
11215 }
11216 } else if (!D.isFunctionDefinition() &&
11217 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11218 !isFriend && !isFunctionTemplateSpecialization &&
11219 !isMemberSpecialization) {
11220 // An out-of-line member function declaration must also be a
11221 // definition (C++ [class.mfct]p2).
11222 // Note that this is not the case for explicit specializations of
11223 // function templates or member functions of class templates, per
11224 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11225 // extension for compatibility with old SWIG code which likes to
11226 // generate them.
11227 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11228 << D.getCXXScopeSpec().getRange();
11229 }
11230 }
11231
11232 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11233 // Any top level function could potentially be specified as an entry.
11234 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11235 HLSL().ActOnTopLevelFunction(NewFD);
11236
11237 if (NewFD->hasAttr<HLSLShaderAttr>())
11238 HLSL().CheckEntryPoint(NewFD);
11239
11240 // Resources cannot be passed to functions that are not inlined.
11241 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11242 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11243 QualType ParamTy = PVD->getType().getNonReferenceType();
11244 QualType EltTy = Context.getBaseElementType(ParamTy);
11245 // `isCompleteType` forces completion of the element type without
11246 // reporting an error (diagnosed elsewhere) so the resource parameter
11247 // check is valid.
11248 if (!EltTy->isDependentType() &&
11249 isCompleteType(PVD->getLocation(), EltTy) &&
11250 ParamTy->isHLSLIntangibleType()) {
11251 Diag(PVD->getLocation(),
11252 diag::err_hlsl_resource_param_in_noinline_function)
11253 << ParamTy;
11254 Diag(NoInline->getLocation(), diag::note_attribute);
11255 }
11256 }
11257 }
11258 }
11259
11260 // If this is the first declaration of a library builtin function, add
11261 // attributes as appropriate.
11262 if (!D.isRedeclaration()) {
11263 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11264 if (unsigned BuiltinID = II->getBuiltinID()) {
11265 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11266 if (!InStdNamespace &&
11268 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11269 // Validate the type matches unless this builtin is specified as
11270 // matching regardless of its declared type.
11271 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11272 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11273 } else {
11275 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11276 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11277
11278 if (!Error && !BuiltinType.isNull() &&
11279 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11280 NewFD->getType(), BuiltinType))
11281 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11282 }
11283 }
11284 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11285 isStdBuiltin(Context, NewFD, BuiltinID)) {
11286 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11287 }
11288 }
11289 }
11290 }
11291
11292 ProcessPragmaWeak(S, NewFD);
11293 ProcessPragmaExport(NewFD);
11294 checkAttributesAfterMerging(*this, *NewFD);
11295
11297 // The above can add the format attribute for known builtin/library functions
11298 // which is required by the modular_format attribute, thus
11299 // validate modular_format now after those attributes have been added.
11300 checkModularFormatAttr(*this, *NewFD);
11301
11302 if (NewFD->hasAttr<OverloadableAttr>() &&
11303 !NewFD->getType()->getAs<FunctionProtoType>()) {
11304 Diag(NewFD->getLocation(),
11305 diag::err_attribute_overloadable_no_prototype)
11306 << NewFD;
11307 NewFD->dropAttr<OverloadableAttr>();
11308 }
11309
11310 // If there's a #pragma GCC visibility in scope, and this isn't a class
11311 // member, set the visibility of this function.
11312 if (!DC->isRecord() && NewFD->isExternallyVisible())
11314
11315 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11316 // marking the function.
11317 ObjC().AddCFAuditedAttribute(NewFD);
11318
11319 // If this is a function definition, check if we have to apply any
11320 // attributes (i.e. optnone and no_builtin) due to a pragma.
11321 if (D.isFunctionDefinition()) {
11322 AddRangeBasedOptnone(NewFD);
11324 AddSectionMSAllocText(NewFD);
11326 }
11327
11328 // If this is the first declaration of an extern C variable, update
11329 // the map of such variables.
11330 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11331 isIncompleteDeclExternC(*this, NewFD))
11333
11334 // Set this FunctionDecl's range up to the right paren.
11335 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11336
11337 if (D.isRedeclaration() && !Previous.empty()) {
11338 NamedDecl *Prev = Previous.getRepresentativeDecl();
11339 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11340 isMemberSpecialization ||
11341 isFunctionTemplateSpecialization,
11343 }
11344
11345 if (getLangOpts().CUDA) {
11346 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11347 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11349 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11350 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11352 Context.setcudaConfigureCallDecl(NewFD);
11353 }
11354 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11355 !NewFD->isInvalidDecl() &&
11357 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11358 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11360 Context.setcudaGetParameterBufferDecl(NewFD);
11361 }
11362 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11363 !NewFD->isInvalidDecl() &&
11365 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11366 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11368 Context.setcudaLaunchDeviceDecl(NewFD);
11369 }
11370 }
11371 }
11372
11374
11375 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11376 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11377 if (SC == SC_Static) {
11378 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11379 D.setInvalidType();
11380 }
11381
11382 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11383 if (!NewFD->getReturnType()->isVoidType()) {
11384 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11385 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11386 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11387 : FixItHint());
11388 D.setInvalidType();
11389 }
11390
11392 for (auto *Param : NewFD->parameters())
11393 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11394
11395 if (getLangOpts().OpenCLCPlusPlus) {
11396 if (DC->isRecord()) {
11397 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11398 D.setInvalidType();
11399 }
11400 if (FunctionTemplate) {
11401 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11402 D.setInvalidType();
11403 }
11404 }
11405 }
11406
11407 if (getLangOpts().CPlusPlus) {
11408 // Precalculate whether this is a friend function template with a constraint
11409 // that depends on an enclosing template, per [temp.friend]p9.
11410 if (isFriend && FunctionTemplate &&
11413
11414 // C++ [temp.friend]p9:
11415 // A friend function template with a constraint that depends on a
11416 // template parameter from an enclosing template shall be a definition.
11417 if (!D.isFunctionDefinition()) {
11418 Diag(NewFD->getBeginLoc(),
11419 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11420 NewFD->setInvalidDecl();
11421 }
11422 }
11423
11424 if (FunctionTemplate) {
11425 if (NewFD->isInvalidDecl())
11426 FunctionTemplate->setInvalidDecl();
11427 return FunctionTemplate;
11428 }
11429
11430 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11432 }
11433
11434 for (const ParmVarDecl *Param : NewFD->parameters()) {
11435 QualType PT = Param->getType();
11436
11437 // WebAssembly tables can't be used as function parameters.
11438 if (Context.getTargetInfo().getTriple().isWasm()) {
11440 Diag(Param->getTypeSpecStartLoc(),
11441 diag::err_wasm_table_as_function_parameter);
11442 D.setInvalidType();
11443 }
11444 }
11445 }
11446
11447 // Diagnose availability attributes. Availability cannot be used on functions
11448 // that are run during load/unload.
11449 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11450 if (NewFD->hasAttr<ConstructorAttr>()) {
11451 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11452 << 1;
11453 NewFD->dropAttr<AvailabilityAttr>();
11454 }
11455 if (NewFD->hasAttr<DestructorAttr>()) {
11456 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11457 << 2;
11458 NewFD->dropAttr<AvailabilityAttr>();
11459 }
11460 }
11461
11462 // Diagnose no_builtin attribute on function declaration that are not a
11463 // definition.
11464 // FIXME: We should really be doing this in
11465 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11466 // the FunctionDecl and at this point of the code
11467 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11468 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11469 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11470 switch (D.getFunctionDefinitionKind()) {
11473 Diag(NBA->getLocation(),
11474 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11475 << NBA->getSpelling();
11476 break;
11478 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11479 << NBA->getSpelling();
11480 break;
11482 break;
11483 }
11484
11485 // Similar to no_builtin logic above, at this point of the code
11486 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11487 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11488 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11489 !NewFD->isInvalidDecl() &&
11491 ExternalDeclarations.push_back(NewFD);
11492
11493 // Used for a warning on the 'next' declaration when used with a
11494 // `routine(name)`.
11495 if (getLangOpts().OpenACC)
11497
11498 return NewFD;
11499}
11500
11501/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11502/// when __declspec(code_seg) "is applied to a class, all member functions of
11503/// the class and nested classes -- this includes compiler-generated special
11504/// member functions -- are put in the specified segment."
11505/// The actual behavior is a little more complicated. The Microsoft compiler
11506/// won't check outer classes if there is an active value from #pragma code_seg.
11507/// The CodeSeg is always applied from the direct parent but only from outer
11508/// classes when the #pragma code_seg stack is empty. See:
11509/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11510/// available since MS has removed the page.
11512 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11513 if (!Method)
11514 return nullptr;
11515 const CXXRecordDecl *Parent = Method->getParent();
11516 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11517 Attr *NewAttr = SAttr->clone(S.getASTContext());
11518 NewAttr->setImplicit(true);
11519 return NewAttr;
11520 }
11521
11522 // The Microsoft compiler won't check outer classes for the CodeSeg
11523 // when the #pragma code_seg stack is active.
11524 if (S.CodeSegStack.CurrentValue)
11525 return nullptr;
11526
11527 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11528 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11529 Attr *NewAttr = SAttr->clone(S.getASTContext());
11530 NewAttr->setImplicit(true);
11531 return NewAttr;
11532 }
11533 }
11534 return nullptr;
11535}
11536
11538 bool IsDefinition) {
11539 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11540 return A;
11541 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11542 CodeSegStack.CurrentValue)
11543 return SectionAttr::CreateImplicit(
11544 getASTContext(), CodeSegStack.CurrentValue->getString(),
11545 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11546 return nullptr;
11547}
11548
11550 QualType NewT, QualType OldT) {
11552 return true;
11553
11554 // For dependently-typed local extern declarations and friends, we can't
11555 // perform a correct type check in general until instantiation:
11556 //
11557 // int f();
11558 // template<typename T> void g() { T f(); }
11559 //
11560 // (valid if g() is only instantiated with T = int).
11561 if (NewT->isDependentType() &&
11562 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11563 return false;
11564
11565 // Similarly, if the previous declaration was a dependent local extern
11566 // declaration, we don't really know its type yet.
11567 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11568 return false;
11569
11570 return true;
11571}
11572
11575 return true;
11576
11577 // Don't chain dependent friend function definitions until instantiation, to
11578 // permit cases like
11579 //
11580 // void func();
11581 // template<typename T> class C1 { friend void func() {} };
11582 // template<typename T> class C2 { friend void func() {} };
11583 //
11584 // ... which is valid if only one of C1 and C2 is ever instantiated.
11585 //
11586 // FIXME: This need only apply to function definitions. For now, we proxy
11587 // this by checking for a file-scope function. We do not want this to apply
11588 // to friend declarations nominating member functions, because that gets in
11589 // the way of access checks.
11591 return false;
11592
11593 auto *VD = dyn_cast<ValueDecl>(D);
11594 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11595 return !VD || !PrevVD ||
11596 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11597 PrevVD->getType());
11598}
11599
11600/// Check the target or target_version attribute of the function for
11601/// MultiVersion validity.
11602///
11603/// Returns true if there was an error, false otherwise.
11604static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11605 const auto *TA = FD->getAttr<TargetAttr>();
11606 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11607
11608 assert((TA || TVA) && "Expecting target or target_version attribute");
11609
11611 enum ErrType { Feature = 0, Architecture = 1 };
11612
11613 if (TA) {
11614 ParsedTargetAttr ParseInfo =
11615 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11616 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11617 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11618 << Architecture << ParseInfo.CPU;
11619 return true;
11620 }
11621 for (const auto &Feat : ParseInfo.Features) {
11622 auto BareFeat = StringRef{Feat}.substr(1);
11623 if (Feat[0] == '-') {
11624 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11625 << Feature << ("no-" + BareFeat);
11626 return true;
11627 }
11628
11629 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11630 !TargetInfo.isValidFeatureName(BareFeat) ||
11631 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11632 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11633 << Feature << BareFeat;
11634 return true;
11635 }
11636 }
11637 }
11638
11639 if (TVA) {
11641 ParsedTargetAttr ParseInfo;
11642 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11643 ParseInfo =
11644 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11645 for (auto &Feat : ParseInfo.Features)
11646 Feats.push_back(StringRef{Feat}.substr(1));
11647 } else {
11648 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11649 TVA->getFeatures(Feats);
11650 }
11651 for (const auto &Feat : Feats) {
11652 if (!TargetInfo.validateCpuSupports(Feat)) {
11653 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11654 << Feature << Feat;
11655 return true;
11656 }
11657 }
11658 }
11659 return false;
11660}
11661
11662// Provide a white-list of attributes that are allowed to be combined with
11663// multiversion functions.
11665 MultiVersionKind MVKind) {
11666 // Note: this list/diagnosis must match the list in
11667 // checkMultiversionAttributesAllSame.
11668 switch (Kind) {
11669 default:
11670 return false;
11671 case attr::ArmLocallyStreaming:
11672 return MVKind == MultiVersionKind::TargetVersion ||
11674 case attr::Used:
11675 return MVKind == MultiVersionKind::Target;
11676 case attr::NonNull:
11677 case attr::NoThrow:
11678 return true;
11679 }
11680}
11681
11683 const FunctionDecl *FD,
11684 const FunctionDecl *CausedFD,
11685 MultiVersionKind MVKind) {
11686 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11687 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11688 << static_cast<unsigned>(MVKind) << A;
11689 if (CausedFD)
11690 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11691 return true;
11692 };
11693
11694 for (const Attr *A : FD->attrs()) {
11695 switch (A->getKind()) {
11696 case attr::CPUDispatch:
11697 case attr::CPUSpecific:
11698 if (MVKind != MultiVersionKind::CPUDispatch &&
11700 return Diagnose(S, A);
11701 break;
11702 case attr::Target:
11703 if (MVKind != MultiVersionKind::Target)
11704 return Diagnose(S, A);
11705 break;
11706 case attr::TargetVersion:
11707 if (MVKind != MultiVersionKind::TargetVersion &&
11709 return Diagnose(S, A);
11710 break;
11711 case attr::TargetClones:
11712 if (MVKind != MultiVersionKind::TargetClones &&
11714 return Diagnose(S, A);
11715 break;
11716 default:
11717 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11718 return Diagnose(S, A);
11719 break;
11720 }
11721 }
11722 return false;
11723}
11724
11726 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11727 const PartialDiagnostic &NoProtoDiagID,
11728 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11729 const PartialDiagnosticAt &NoSupportDiagIDAt,
11730 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11731 bool ConstexprSupported, bool CLinkageMayDiffer) {
11732 enum DoesntSupport {
11733 FuncTemplates = 0,
11734 VirtFuncs = 1,
11735 DeducedReturn = 2,
11736 Constructors = 3,
11737 Destructors = 4,
11738 DeletedFuncs = 5,
11739 DefaultedFuncs = 6,
11740 ConstexprFuncs = 7,
11741 ConstevalFuncs = 8,
11742 Lambda = 9,
11743 };
11744 enum Different {
11745 CallingConv = 0,
11746 ReturnType = 1,
11747 ConstexprSpec = 2,
11748 InlineSpec = 3,
11749 Linkage = 4,
11750 LanguageLinkage = 5,
11751 };
11752
11753 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11754 !OldFD->getType()->getAs<FunctionProtoType>()) {
11755 Diag(OldFD->getLocation(), NoProtoDiagID);
11756 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11757 return true;
11758 }
11759
11760 if (NoProtoDiagID.getDiagID() != 0 &&
11761 !NewFD->getType()->getAs<FunctionProtoType>())
11762 return Diag(NewFD->getLocation(), NoProtoDiagID);
11763
11764 if (!TemplatesSupported &&
11766 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11767 << FuncTemplates;
11768
11769 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11770 if (NewCXXFD->isVirtual())
11771 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11772 << VirtFuncs;
11773
11774 if (isa<CXXConstructorDecl>(NewCXXFD))
11775 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11776 << Constructors;
11777
11778 if (isa<CXXDestructorDecl>(NewCXXFD))
11779 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11780 << Destructors;
11781 }
11782
11783 if (NewFD->isDeleted())
11784 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11785 << DeletedFuncs;
11786
11787 if (NewFD->isDefaulted())
11788 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11789 << DefaultedFuncs;
11790
11791 if (!ConstexprSupported && NewFD->isConstexpr())
11792 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11793 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11794
11795 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11796 const auto *NewType = cast<FunctionType>(NewQType);
11797 QualType NewReturnType = NewType->getReturnType();
11798
11799 if (NewReturnType->isUndeducedType())
11800 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11801 << DeducedReturn;
11802
11803 // Ensure the return type is identical.
11804 if (OldFD) {
11805 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11806 const auto *OldType = cast<FunctionType>(OldQType);
11807 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11808 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11809
11810 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11811 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11812
11813 bool ArmStreamingCCMismatched = false;
11814 if (OldFPT && NewFPT) {
11815 unsigned Diff =
11816 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11817 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11818 // cannot be mixed.
11821 ArmStreamingCCMismatched = true;
11822 }
11823
11824 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11825 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11826
11827 QualType OldReturnType = OldType->getReturnType();
11828
11829 if (OldReturnType != NewReturnType)
11830 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11831
11832 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11833 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11834
11835 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11836 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11837
11838 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11839 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11840
11841 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11842 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11843
11844 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11845 NewFD->getLocation()))
11846 return true;
11847 }
11848 return false;
11849}
11850
11852 const FunctionDecl *NewFD,
11853 bool CausesMV,
11854 MultiVersionKind MVKind) {
11856 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11857 if (OldFD)
11858 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11859 return true;
11860 }
11861
11862 bool IsCPUSpecificCPUDispatchMVKind =
11865
11866 if (CausesMV && OldFD &&
11867 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11868 return true;
11869
11870 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11871 return true;
11872
11873 // Only allow transition to MultiVersion if it hasn't been used.
11874 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11875 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11876 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11877 return true;
11878 }
11879
11881 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11883 S.PDiag(diag::note_multiversioning_caused_here)),
11885 S.PDiag(diag::err_multiversion_doesnt_support)
11886 << static_cast<unsigned>(MVKind)),
11888 S.PDiag(diag::err_multiversion_diff)),
11889 /*TemplatesSupported=*/false,
11890 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11891 /*CLinkageMayDiffer=*/false);
11892}
11893
11894/// Check the validity of a multiversion function declaration that is the
11895/// first of its kind. Also sets the multiversion'ness' of the function itself.
11896///
11897/// This sets NewFD->isInvalidDecl() to true if there was an error.
11898///
11899/// Returns true if there was an error, false otherwise.
11902 assert(MVKind != MultiVersionKind::None &&
11903 "Function lacks multiversion attribute");
11904 const auto *TA = FD->getAttr<TargetAttr>();
11905 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11906 // The target attribute only causes MV if this declaration is the default,
11907 // otherwise it is treated as a normal function.
11908 if (TA && !TA->isDefaultVersion())
11909 return false;
11910
11911 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11912 FD->setInvalidDecl();
11913 return true;
11914 }
11915
11916 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11917 FD->setInvalidDecl();
11918 return true;
11919 }
11920
11921 FD->setIsMultiVersion();
11922 return false;
11923}
11924
11926 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11928 return true;
11929 }
11930
11931 return false;
11932}
11933
11935 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11936 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11937 return;
11938
11939 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11940 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11941
11942 if (MVKindTo == MultiVersionKind::None &&
11943 (MVKindFrom == MultiVersionKind::TargetVersion ||
11944 MVKindFrom == MultiVersionKind::TargetClones))
11945 To->addAttr(TargetVersionAttr::CreateImplicit(
11946 To->getASTContext(), "default", To->getSourceRange()));
11947}
11948
11950 FunctionDecl *NewFD,
11951 bool &Redeclaration,
11952 NamedDecl *&OldDecl,
11954 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11955
11956 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11957 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11958 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11959 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11960
11961 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11962
11963 // The definitions should be allowed in any order. If we have discovered
11964 // a new target version and the preceeding was the default, then add the
11965 // corresponding attribute to it.
11966 patchDefaultTargetVersion(NewFD, OldFD);
11967
11968 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11969 // to change, this is a simple redeclaration.
11970 if (NewTA && !NewTA->isDefaultVersion() &&
11971 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11972 return false;
11973
11974 // Otherwise, this decl causes MultiVersioning.
11975 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11978 NewFD->setInvalidDecl();
11979 return true;
11980 }
11981
11982 if (CheckMultiVersionValue(S, NewFD)) {
11983 NewFD->setInvalidDecl();
11984 return true;
11985 }
11986
11987 // If this is 'default', permit the forward declaration.
11988 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11989 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11990 Redeclaration = true;
11991 OldDecl = OldFD;
11992 OldFD->setIsMultiVersion();
11993 NewFD->setIsMultiVersion();
11994 return false;
11995 }
11996
11997 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11998 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11999 NewFD->setInvalidDecl();
12000 return true;
12001 }
12002
12003 if (NewTA) {
12004 ParsedTargetAttr OldParsed =
12006 OldTA->getFeaturesStr());
12007 llvm::sort(OldParsed.Features);
12008 ParsedTargetAttr NewParsed =
12010 NewTA->getFeaturesStr());
12011 // Sort order doesn't matter, it just needs to be consistent.
12012 llvm::sort(NewParsed.Features);
12013 if (OldParsed == NewParsed) {
12014 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12015 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
12016 NewFD->setInvalidDecl();
12017 return true;
12018 }
12019 }
12020
12021 for (const auto *FD : OldFD->redecls()) {
12022 const auto *CurTA = FD->getAttr<TargetAttr>();
12023 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
12024 // We allow forward declarations before ANY multiversioning attributes, but
12025 // nothing after the fact.
12027 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12028 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12029 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
12030 << (NewTA ? 0 : 2);
12031 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
12032 NewFD->setInvalidDecl();
12033 return true;
12034 }
12035 }
12036
12037 OldFD->setIsMultiVersion();
12038 NewFD->setIsMultiVersion();
12039 Redeclaration = false;
12040 OldDecl = nullptr;
12041 Previous.clear();
12042 return false;
12043}
12044
12046 MultiVersionKind OldKind = Old->getMultiVersionKind();
12047 MultiVersionKind NewKind = New->getMultiVersionKind();
12048
12049 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12050 NewKind == MultiVersionKind::None)
12051 return true;
12052
12053 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12054 switch (OldKind) {
12056 return NewKind == MultiVersionKind::TargetClones;
12058 return NewKind == MultiVersionKind::TargetVersion;
12059 default:
12060 return false;
12061 }
12062 } else {
12063 switch (OldKind) {
12065 return NewKind == MultiVersionKind::CPUSpecific;
12067 return NewKind == MultiVersionKind::CPUDispatch;
12068 default:
12069 return false;
12070 }
12071 }
12072}
12073
12074/// Check the validity of a new function declaration being added to an existing
12075/// multiversioned declaration collection.
12077 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12078 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12079 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12081
12082 // Disallow mixing of multiversioning types.
12083 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
12084 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
12085 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
12086 NewFD->setInvalidDecl();
12087 return true;
12088 }
12089
12090 // Add the default target_version attribute if it's missing.
12091 patchDefaultTargetVersion(OldFD, NewFD);
12092 patchDefaultTargetVersion(NewFD, OldFD);
12093
12094 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12095 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12096 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12097 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12098
12099 ParsedTargetAttr NewParsed;
12100 if (NewTA) {
12102 NewTA->getFeaturesStr());
12103 llvm::sort(NewParsed.Features);
12104 }
12106 if (NewTVA) {
12107 NewTVA->getFeatures(NewFeats);
12108 llvm::sort(NewFeats);
12109 }
12110
12111 bool UseMemberUsingDeclRules =
12112 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12113
12114 bool MayNeedOverloadableChecks =
12116
12117 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12118 // of a previous member of the MultiVersion set.
12119 for (NamedDecl *ND : Previous) {
12120 FunctionDecl *CurFD = ND->getAsFunction();
12121 if (!CurFD || CurFD->isInvalidDecl())
12122 continue;
12123 if (MayNeedOverloadableChecks &&
12124 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
12125 continue;
12126
12127 switch (NewMVKind) {
12129 assert(OldMVKind == MultiVersionKind::TargetClones &&
12130 "Only target_clones can be omitted in subsequent declarations");
12131 break;
12133 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12134 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12135 NewFD->setIsMultiVersion();
12136 Redeclaration = true;
12137 OldDecl = ND;
12138 return false;
12139 }
12140
12141 ParsedTargetAttr CurParsed =
12143 CurTA->getFeaturesStr());
12144 llvm::sort(CurParsed.Features);
12145 if (CurParsed == NewParsed) {
12146 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12147 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12148 NewFD->setInvalidDecl();
12149 return true;
12150 }
12151 break;
12152 }
12154 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12155 if (CurTVA->getName() == NewTVA->getName()) {
12156 NewFD->setIsMultiVersion();
12157 Redeclaration = true;
12158 OldDecl = ND;
12159 return false;
12160 }
12162 CurTVA->getFeatures(CurFeats);
12163 llvm::sort(CurFeats);
12164
12165 if (CurFeats == NewFeats) {
12166 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12167 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12168 NewFD->setInvalidDecl();
12169 return true;
12170 }
12171 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12172 // Default
12173 if (NewFeats.empty())
12174 break;
12175
12176 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12178 CurClones->getFeatures(CurFeats, I);
12179 llvm::sort(CurFeats);
12180
12181 if (CurFeats == NewFeats) {
12182 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12183 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12184 NewFD->setInvalidDecl();
12185 return true;
12186 }
12187 }
12188 }
12189 break;
12190 }
12192 assert(NewClones && "MultiVersionKind does not match attribute type");
12193 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12194 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12195 !std::equal(CurClones->featuresStrs_begin(),
12196 CurClones->featuresStrs_end(),
12197 NewClones->featuresStrs_begin())) {
12198 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
12199 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12200 NewFD->setInvalidDecl();
12201 return true;
12202 }
12203 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12205 CurTVA->getFeatures(CurFeats);
12206 llvm::sort(CurFeats);
12207
12208 // Default
12209 if (CurFeats.empty())
12210 break;
12211
12212 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12213 NewFeats.clear();
12214 NewClones->getFeatures(NewFeats, I);
12215 llvm::sort(NewFeats);
12216
12217 if (CurFeats == NewFeats) {
12218 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12219 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12220 NewFD->setInvalidDecl();
12221 return true;
12222 }
12223 }
12224 break;
12225 }
12226 Redeclaration = true;
12227 OldDecl = CurFD;
12228 NewFD->setIsMultiVersion();
12229 return false;
12230 }
12233 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12234 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12235 // Handle CPUDispatch/CPUSpecific versions.
12236 // Only 1 CPUDispatch function is allowed, this will make it go through
12237 // the redeclaration errors.
12238 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12239 CurFD->hasAttr<CPUDispatchAttr>()) {
12240 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12241 std::equal(
12242 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12243 NewCPUDisp->cpus_begin(),
12244 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12245 return Cur->getName() == New->getName();
12246 })) {
12247 NewFD->setIsMultiVersion();
12248 Redeclaration = true;
12249 OldDecl = ND;
12250 return false;
12251 }
12252
12253 // If the declarations don't match, this is an error condition.
12254 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12255 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12256 NewFD->setInvalidDecl();
12257 return true;
12258 }
12259 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12260 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12261 std::equal(
12262 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12263 NewCPUSpec->cpus_begin(),
12264 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12265 return Cur->getName() == New->getName();
12266 })) {
12267 NewFD->setIsMultiVersion();
12268 Redeclaration = true;
12269 OldDecl = ND;
12270 return false;
12271 }
12272
12273 // Only 1 version of CPUSpecific is allowed for each CPU.
12274 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12275 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12276 if (CurII == NewII) {
12277 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12278 << NewII;
12279 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12280 NewFD->setInvalidDecl();
12281 return true;
12282 }
12283 }
12284 }
12285 }
12286 break;
12287 }
12288 }
12289 }
12290
12291 // Redeclarations of a target_clones function may omit the attribute, in which
12292 // case it will be inherited during declaration merging.
12293 if (NewMVKind == MultiVersionKind::None &&
12294 OldMVKind == MultiVersionKind::TargetClones) {
12295 NewFD->setIsMultiVersion();
12296 Redeclaration = true;
12297 OldDecl = OldFD;
12298 return false;
12299 }
12300
12301 // Else, this is simply a non-redecl case. Checking the 'value' is only
12302 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12303 // handled in the attribute adding step.
12304 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12305 NewFD->setInvalidDecl();
12306 return true;
12307 }
12308
12309 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12310 !OldFD->isMultiVersion(), NewMVKind)) {
12311 NewFD->setInvalidDecl();
12312 return true;
12313 }
12314
12315 // Permit forward declarations in the case where these two are compatible.
12316 if (!OldFD->isMultiVersion()) {
12317 OldFD->setIsMultiVersion();
12318 NewFD->setIsMultiVersion();
12319 Redeclaration = true;
12320 OldDecl = OldFD;
12321 return false;
12322 }
12323
12324 NewFD->setIsMultiVersion();
12325 Redeclaration = false;
12326 OldDecl = nullptr;
12327 Previous.clear();
12328 return false;
12329}
12330
12331/// Check the validity of a mulitversion function declaration.
12332/// Also sets the multiversion'ness' of the function itself.
12333///
12334/// This sets NewFD->isInvalidDecl() to true if there was an error.
12335///
12336/// Returns true if there was an error, false otherwise.
12338 bool &Redeclaration, NamedDecl *&OldDecl,
12340 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12341
12342 // Check if FMV is disabled.
12343 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12344 return false;
12345
12346 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12347 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12348 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12349 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12350 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12351 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12352
12353 // Main isn't allowed to become a multiversion function, however it IS
12354 // permitted to have 'main' be marked with the 'target' optimization hint,
12355 // for 'target_version' only default is allowed.
12356 if (NewFD->isMain()) {
12357 if (MVKind != MultiVersionKind::None &&
12358 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12359 !(MVKind == MultiVersionKind::TargetVersion &&
12360 NewTVA->isDefaultVersion())) {
12361 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12362 NewFD->setInvalidDecl();
12363 return true;
12364 }
12365 return false;
12366 }
12367
12368 // Target attribute on AArch64 is not used for multiversioning
12369 if (NewTA && TI.getTriple().isAArch64())
12370 return false;
12371
12372 // Target attribute on RISCV is not used for multiversioning
12373 if (NewTA && TI.getTriple().isRISCV())
12374 return false;
12375
12376 if (!OldDecl || !OldDecl->getAsFunction() ||
12377 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12378 NewFD->getDeclContext()->getRedeclContext())) {
12379 // If there's no previous declaration, AND this isn't attempting to cause
12380 // multiversioning, this isn't an error condition.
12381 if (MVKind == MultiVersionKind::None)
12382 return false;
12383 return CheckMultiVersionFirstFunction(S, NewFD);
12384 }
12385
12386 FunctionDecl *OldFD = OldDecl->getAsFunction();
12387
12388 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12389 return false;
12390
12391 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12392 // for target_clones and target_version.
12393 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12396 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12398 NewFD->setInvalidDecl();
12399 return true;
12400 }
12401
12402 if (!OldFD->isMultiVersion()) {
12403 switch (MVKind) {
12407 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12409 if (OldFD->isUsed(false)) {
12410 NewFD->setInvalidDecl();
12411 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12412 }
12413 OldFD->setIsMultiVersion();
12414 break;
12415
12419 break;
12420 }
12421 }
12422
12423 // At this point, we have a multiversion function decl (in OldFD) AND an
12424 // appropriate attribute in the current function decl (unless it's allowed to
12425 // omit the attribute). Resolve that these are still compatible with previous
12426 // declarations.
12427 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12428 NewCPUSpec, NewClones, Redeclaration,
12429 OldDecl, Previous);
12430}
12431
12433 bool IsPure = NewFD->hasAttr<PureAttr>();
12434 bool IsConst = NewFD->hasAttr<ConstAttr>();
12435
12436 // If there are no pure or const attributes, there's nothing to check.
12437 if (!IsPure && !IsConst)
12438 return;
12439
12440 // If the function is marked both pure and const, we retain the const
12441 // attribute because it makes stronger guarantees than the pure attribute, and
12442 // we drop the pure attribute explicitly to prevent later confusion about
12443 // semantics.
12444 if (IsPure && IsConst) {
12445 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12446 NewFD->dropAttrs<PureAttr>();
12447 }
12448
12449 // Constructors and destructors are functions which return void, so are
12450 // handled here as well.
12451 if (NewFD->getReturnType()->isVoidType()) {
12452 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12453 << IsConst;
12454 NewFD->dropAttrs<PureAttr, ConstAttr>();
12455 }
12456}
12457
12460 bool IsMemberSpecialization,
12461 bool DeclIsDefn) {
12462 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12463 "Variably modified return types are not handled here");
12464
12465 // Determine whether the type of this function should be merged with
12466 // a previous visible declaration. This never happens for functions in C++,
12467 // and always happens in C if the previous declaration was visible.
12468 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12469 !Previous.isShadowed();
12470
12471 bool Redeclaration = false;
12472 NamedDecl *OldDecl = nullptr;
12473 bool MayNeedOverloadableChecks = false;
12474
12476 // Merge or overload the declaration with an existing declaration of
12477 // the same name, if appropriate.
12478 if (!Previous.empty()) {
12479 // Determine whether NewFD is an overload of PrevDecl or
12480 // a declaration that requires merging. If it's an overload,
12481 // there's no more work to do here; we'll just add the new
12482 // function to the scope.
12484 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12485 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12486 Redeclaration = true;
12487 OldDecl = Candidate;
12488 }
12489 } else {
12490 MayNeedOverloadableChecks = true;
12491 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12492 /*NewIsUsingDecl*/ false)) {
12494 Redeclaration = true;
12495 break;
12496
12498 Redeclaration = true;
12499 break;
12500
12502 Redeclaration = false;
12503 break;
12504 }
12505 }
12506 }
12507
12508 // Check for a previous extern "C" declaration with this name.
12509 if (!Redeclaration &&
12511 if (!Previous.empty()) {
12512 // This is an extern "C" declaration with the same name as a previous
12513 // declaration, and thus redeclares that entity...
12514 Redeclaration = true;
12515 OldDecl = Previous.getFoundDecl();
12516 MergeTypeWithPrevious = false;
12517
12518 // ... except in the presence of __attribute__((overloadable)).
12519 if (OldDecl->hasAttr<OverloadableAttr>() ||
12520 NewFD->hasAttr<OverloadableAttr>()) {
12521 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12522 MayNeedOverloadableChecks = true;
12523 Redeclaration = false;
12524 OldDecl = nullptr;
12525 }
12526 }
12527 }
12528 }
12529
12530 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12531 return Redeclaration;
12532
12533 // PPC MMA non-pointer types are not allowed as function return types.
12534 if (Context.getTargetInfo().getTriple().isPPC64() &&
12535 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12536 NewFD->setInvalidDecl();
12537 }
12538
12539 CheckConstPureAttributesUsage(*this, NewFD);
12540
12541 // C++ [dcl.spec.auto.general]p12:
12542 // Return type deduction for a templated function with a placeholder in its
12543 // declared type occurs when the definition is instantiated even if the
12544 // function body contains a return statement with a non-type-dependent
12545 // operand.
12546 //
12547 // C++ [temp.dep.expr]p3:
12548 // An id-expression is type-dependent if it is a template-id that is not a
12549 // concept-id and is dependent; or if its terminal name is:
12550 // - [...]
12551 // - associated by name lookup with one or more declarations of member
12552 // functions of a class that is the current instantiation declared with a
12553 // return type that contains a placeholder type,
12554 // - [...]
12555 //
12556 // If this is a templated function with a placeholder in its return type,
12557 // make the placeholder type dependent since it won't be deduced until the
12558 // definition is instantiated. We do this here because it needs to happen
12559 // for implicitly instantiated member functions/member function templates.
12560 if (getLangOpts().CPlusPlus14 &&
12561 (NewFD->isDependentContext() &&
12562 NewFD->getReturnType()->isUndeducedType())) {
12563 const FunctionProtoType *FPT =
12564 NewFD->getType()->castAs<FunctionProtoType>();
12565 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12566 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12567 FPT->getExtProtoInfo()));
12568 }
12569
12570 // C++11 [dcl.constexpr]p8:
12571 // A constexpr specifier for a non-static member function that is not
12572 // a constructor declares that member function to be const.
12573 //
12574 // This needs to be delayed until we know whether this is an out-of-line
12575 // definition of a static member function.
12576 //
12577 // This rule is not present in C++1y, so we produce a backwards
12578 // compatibility warning whenever it happens in C++11.
12579 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12580 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12581 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12583 CXXMethodDecl *OldMD = nullptr;
12584 if (OldDecl)
12585 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12586 if (!OldMD || !OldMD->isStatic()) {
12587 const FunctionProtoType *FPT =
12590 EPI.TypeQuals.addConst();
12591 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12592 FPT->getParamTypes(), EPI));
12593
12594 // Warn that we did this, if we're not performing template instantiation.
12595 // In that case, we'll have warned already when the template was defined.
12596 if (!inTemplateInstantiation()) {
12597 SourceLocation AddConstLoc;
12600 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12601
12602 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12603 << FixItHint::CreateInsertion(AddConstLoc, " const");
12604 }
12605 }
12606 }
12607
12608 if (Redeclaration) {
12609 // NewFD and OldDecl represent declarations that need to be
12610 // merged.
12611 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12612 DeclIsDefn)) {
12613 NewFD->setInvalidDecl();
12614 return Redeclaration;
12615 }
12616
12617 Previous.clear();
12618 Previous.addDecl(OldDecl);
12619
12620 if (FunctionTemplateDecl *OldTemplateDecl =
12621 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12622 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12623 FunctionTemplateDecl *NewTemplateDecl
12625 assert(NewTemplateDecl && "Template/non-template mismatch");
12626
12627 // The call to MergeFunctionDecl above may have created some state in
12628 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12629 // can add it as a redeclaration.
12630 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12631
12632 NewFD->setPreviousDeclaration(OldFD);
12633 if (NewFD->isCXXClassMember()) {
12634 NewFD->setAccess(OldTemplateDecl->getAccess());
12635 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12636 }
12637
12638 // If this is an explicit specialization of a member that is a function
12639 // template, mark it as a member specialization.
12640 if (IsMemberSpecialization &&
12641 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12642 NewTemplateDecl->setMemberSpecialization();
12643 assert(OldTemplateDecl->isMemberSpecialization());
12644 // Explicit specializations of a member template do not inherit deleted
12645 // status from the parent member template that they are specializing.
12646 if (OldFD->isDeleted()) {
12647 // FIXME: This assert will not hold in the presence of modules.
12648 assert(OldFD->getCanonicalDecl() == OldFD);
12649 // FIXME: We need an update record for this AST mutation.
12650 OldFD->setDeletedAsWritten(false);
12651 }
12652 }
12653
12654 } else {
12655 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12656 auto *OldFD = cast<FunctionDecl>(OldDecl);
12657 // This needs to happen first so that 'inline' propagates.
12658 NewFD->setPreviousDeclaration(OldFD);
12659 if (NewFD->isCXXClassMember())
12660 NewFD->setAccess(OldFD->getAccess());
12661 }
12662 }
12663 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12664 !NewFD->getAttr<OverloadableAttr>()) {
12665 assert((Previous.empty() ||
12666 llvm::any_of(Previous,
12667 [](const NamedDecl *ND) {
12668 return ND->hasAttr<OverloadableAttr>();
12669 })) &&
12670 "Non-redecls shouldn't happen without overloadable present");
12671
12672 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12673 const auto *FD = dyn_cast<FunctionDecl>(ND);
12674 return FD && !FD->hasAttr<OverloadableAttr>();
12675 });
12676
12677 if (OtherUnmarkedIter != Previous.end()) {
12678 Diag(NewFD->getLocation(),
12679 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12680 Diag((*OtherUnmarkedIter)->getLocation(),
12681 diag::note_attribute_overloadable_prev_overload)
12682 << false;
12683
12684 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12685 }
12686 }
12687
12688 if (LangOpts.OpenMP)
12690
12691 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12693
12694 if (NewFD->hasAttr<SYCLExternalAttr>())
12696
12697 // Semantic checking for this function declaration (in isolation).
12698
12699 if (getLangOpts().CPlusPlus) {
12700 // C++-specific checks.
12701 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12703 } else if (CXXDestructorDecl *Destructor =
12704 dyn_cast<CXXDestructorDecl>(NewFD)) {
12705 // We check here for invalid destructor names.
12706 // If we have a friend destructor declaration that is dependent, we can't
12707 // diagnose right away because cases like this are still valid:
12708 // template <class T> struct A { friend T::X::~Y(); };
12709 // struct B { struct Y { ~Y(); }; using X = Y; };
12710 // template struct A<B>;
12712 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12713 !Destructor->getDeclName().isDependentName())) {
12714 CanQualType ClassType =
12715 Context.getCanonicalTagType(Destructor->getParent());
12716
12717 DeclarationName Name =
12718 Context.DeclarationNames.getCXXDestructorName(ClassType);
12719 if (NewFD->getDeclName() != Name) {
12720 Diag(NewFD->getLocation(), diag::err_destructor_name);
12721 NewFD->setInvalidDecl();
12722 return Redeclaration;
12723 }
12724 }
12725 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12726 if (auto *TD = Guide->getDescribedFunctionTemplate())
12728
12729 // A deduction guide is not on the list of entities that can be
12730 // explicitly specialized.
12731 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12732 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12733 << /*explicit specialization*/ 1;
12734 }
12735
12736 // Find any virtual functions that this function overrides.
12737 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12738 if (!Method->isFunctionTemplateSpecialization() &&
12739 !Method->getDescribedFunctionTemplate() &&
12740 Method->isCanonicalDecl()) {
12741 AddOverriddenMethods(Method->getParent(), Method);
12742 }
12743 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12744 // C++2a [class.virtual]p6
12745 // A virtual method shall not have a requires-clause.
12747 diag::err_constrained_virtual_method);
12748
12749 if (Method->isStatic())
12751 }
12752
12753 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12754 ActOnConversionDeclarator(Conversion);
12755
12756 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12757 if (NewFD->isOverloadedOperator() &&
12759 NewFD->setInvalidDecl();
12760 return Redeclaration;
12761 }
12762
12763 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12764 if (NewFD->getLiteralIdentifier() &&
12766 NewFD->setInvalidDecl();
12767 return Redeclaration;
12768 }
12769
12770 // In C++, check default arguments now that we have merged decls. Unless
12771 // the lexical context is the class, because in this case this is done
12772 // during delayed parsing anyway.
12773 if (!CurContext->isRecord())
12775
12776 // If this function is declared as being extern "C", then check to see if
12777 // the function returns a UDT (class, struct, or union type) that is not C
12778 // compatible, and if it does, warn the user.
12779 // But, issue any diagnostic on the first declaration only.
12780 if (Previous.empty() && NewFD->isExternC()) {
12781 QualType R = NewFD->getReturnType();
12782 if (R->isIncompleteType() && !R->isVoidType())
12783 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12784 << NewFD << R;
12785 else if (!R.isPODType(Context) && !R->isVoidType() &&
12786 !R->isObjCObjectPointerType())
12787 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12788 }
12789
12790 // C++1z [dcl.fct]p6:
12791 // [...] whether the function has a non-throwing exception-specification
12792 // [is] part of the function type
12793 //
12794 // This results in an ABI break between C++14 and C++17 for functions whose
12795 // declared type includes an exception-specification in a parameter or
12796 // return type. (Exception specifications on the function itself are OK in
12797 // most cases, and exception specifications are not permitted in most other
12798 // contexts where they could make it into a mangling.)
12799 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12800 auto HasNoexcept = [&](QualType T) -> bool {
12801 // Strip off declarator chunks that could be between us and a function
12802 // type. We don't need to look far, exception specifications are very
12803 // restricted prior to C++17.
12804 if (auto *RT = T->getAs<ReferenceType>())
12805 T = RT->getPointeeType();
12806 else if (T->isAnyPointerType())
12807 T = T->getPointeeType();
12808 else if (auto *MPT = T->getAs<MemberPointerType>())
12809 T = MPT->getPointeeType();
12810 if (auto *FPT = T->getAs<FunctionProtoType>())
12811 if (FPT->isNothrow())
12812 return true;
12813 return false;
12814 };
12815
12816 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12817 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12818 for (QualType T : FPT->param_types())
12819 AnyNoexcept |= HasNoexcept(T);
12820 if (AnyNoexcept)
12821 Diag(NewFD->getLocation(),
12822 diag::warn_cxx17_compat_exception_spec_in_signature)
12823 << NewFD;
12824 }
12825
12826 if (!Redeclaration && LangOpts.CUDA) {
12827 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12828 for (auto *Parm : NewFD->parameters()) {
12829 if (!Parm->getType()->isDependentType() &&
12830 Parm->hasAttr<CUDAGridConstantAttr>() &&
12831 !(IsKernel && Parm->getType().isConstQualified()))
12832 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12833 diag::err_cuda_grid_constant_not_allowed);
12834 }
12836 }
12837 }
12838
12839 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12841
12842 return Redeclaration;
12843}
12844
12846 // [basic.start.main]p3
12847 // The main function shall not be declared with C linkage-specification.
12848 if (FD->isExternCContext())
12849 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12850
12851 // C++11 [basic.start.main]p3:
12852 // A program that [...] declares main to be inline, static or
12853 // constexpr is ill-formed.
12854 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12855 // appear in a declaration of main.
12856 // static main is not an error under C99, but we should warn about it.
12857 // We accept _Noreturn main as an extension.
12858 if (FD->getStorageClass() == SC_Static)
12860 ? diag::err_static_main : diag::warn_static_main)
12862 if (FD->isInlineSpecified())
12863 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12865 if (DS.isNoreturnSpecified()) {
12866 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12867 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12868 Diag(NoreturnLoc, diag::ext_noreturn_main);
12869 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12870 << FixItHint::CreateRemoval(NoreturnRange);
12871 }
12872 if (FD->isConstexpr()) {
12873 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12874 << FD->isConsteval()
12877 }
12878
12879 if (getLangOpts().OpenCL) {
12880 Diag(FD->getLocation(), diag::err_opencl_no_main)
12881 << FD->hasAttr<DeviceKernelAttr>();
12882 FD->setInvalidDecl();
12883 return;
12884 }
12885
12886 if (FD->hasAttr<SYCLExternalAttr>()) {
12887 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12888 << FD->getAttr<SYCLExternalAttr>();
12889 FD->setInvalidDecl();
12890 return;
12891 }
12892
12893 // Functions named main in hlsl are default entries, but don't have specific
12894 // signatures they are required to conform to.
12895 if (getLangOpts().HLSL)
12896 return;
12897
12898 QualType T = FD->getType();
12899 assert(T->isFunctionType() && "function decl is not of function type");
12900 const FunctionType* FT = T->castAs<FunctionType>();
12901
12902 // Set default calling convention for main()
12903 if (FT->getCallConv() != CC_C) {
12904 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12905 FD->setType(QualType(FT, 0));
12906 T = Context.getCanonicalType(FD->getType());
12907 }
12908
12910 // In C with GNU extensions we allow main() to have non-integer return
12911 // type, but we should warn about the extension, and we disable the
12912 // implicit-return-zero rule.
12913
12914 // GCC in C mode accepts qualified 'int'.
12915 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12916 FD->setHasImplicitReturnZero(true);
12917 else {
12918 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12919 SourceRange RTRange = FD->getReturnTypeSourceRange();
12920 if (RTRange.isValid())
12921 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12922 << FixItHint::CreateReplacement(RTRange, "int");
12923 }
12924 } else {
12925 // In C and C++, main magically returns 0 if you fall off the end;
12926 // set the flag which tells us that.
12927 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12928
12929 // All the standards say that main() should return 'int'.
12930 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12931 FD->setHasImplicitReturnZero(true);
12932 else {
12933 // Otherwise, this is just a flat-out error.
12934 SourceRange RTRange = FD->getReturnTypeSourceRange();
12935 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12936 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12937 : FixItHint());
12938 FD->setInvalidDecl(true);
12939 }
12940
12941 // [basic.start.main]p3:
12942 // A program that declares a function main that belongs to the global scope
12943 // and is attached to a named module is ill-formed.
12944 if (FD->isInNamedModule()) {
12945 const SourceLocation start = FD->getTypeSpecStartLoc();
12946 Diag(start, diag::warn_main_in_named_module)
12947 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12948 }
12949 }
12950
12951 // Treat protoless main() as nullary.
12952 if (isa<FunctionNoProtoType>(FT)) return;
12953
12955 unsigned nparams = FTP->getNumParams();
12956 assert(FD->getNumParams() == nparams);
12957
12958 bool HasExtraParameters = (nparams > 3);
12959
12960 if (FTP->isVariadic()) {
12961 Diag(FD->getLocation(), diag::ext_variadic_main);
12962 // FIXME: if we had information about the location of the ellipsis, we
12963 // could add a FixIt hint to remove it as a parameter.
12964 }
12965
12966 // Darwin passes an undocumented fourth argument of type char**. If
12967 // other platforms start sprouting these, the logic below will start
12968 // getting shifty.
12969 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12970 HasExtraParameters = false;
12971
12972 if (HasExtraParameters) {
12973 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12974 FD->setInvalidDecl(true);
12975 nparams = 3;
12976 }
12977
12978 // FIXME: a lot of the following diagnostics would be improved
12979 // if we had some location information about types.
12980
12981 QualType CharPP =
12982 Context.getPointerType(Context.getPointerType(Context.CharTy));
12983 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12984
12985 for (unsigned i = 0; i < nparams; ++i) {
12986 QualType AT = FTP->getParamType(i);
12987
12988 bool mismatch = true;
12989
12990 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12991 mismatch = false;
12992 else if (Expected[i] == CharPP) {
12993 // As an extension, the following forms are okay:
12994 // char const **
12995 // char const * const *
12996 // char * const *
12997
12999 const PointerType* PT;
13000 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
13001 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
13002 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
13003 Context.CharTy)) {
13004 qs.removeConst();
13005 mismatch = !qs.empty();
13006 }
13007 }
13008
13009 if (mismatch) {
13010 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
13011 // TODO: suggest replacing given type with expected type
13012 FD->setInvalidDecl(true);
13013 }
13014 }
13015
13016 if (nparams == 1 && !FD->isInvalidDecl()) {
13017 Diag(FD->getLocation(), diag::warn_main_one_arg);
13018 }
13019
13020 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13021 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
13022 FD->setInvalidDecl();
13023 }
13024}
13025
13026static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
13027
13028 // Default calling convention for main and wmain is __cdecl
13029 if (FD->getName() == "main" || FD->getName() == "wmain")
13030 return false;
13031
13032 // Default calling convention for MinGW and Cygwin is __cdecl
13033 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13034 if (T.isOSCygMing())
13035 return false;
13036
13037 // Default calling convention for WinMain, wWinMain and DllMain
13038 // is __stdcall on 32 bit Windows
13039 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13040 return true;
13041
13042 return false;
13043}
13044
13046 QualType T = FD->getType();
13047 assert(T->isFunctionType() && "function decl is not of function type");
13048 const FunctionType *FT = T->castAs<FunctionType>();
13049
13050 // Set an implicit return of 'zero' if the function can return some integral,
13051 // enumeration, pointer or nullptr type.
13055 // DllMain is exempt because a return value of zero means it failed.
13056 if (FD->getName() != "DllMain")
13057 FD->setHasImplicitReturnZero(true);
13058
13059 // Explicitly specified calling conventions are applied to MSVC entry points
13060 if (!hasExplicitCallingConv(T)) {
13061 if (isDefaultStdCall(FD, *this)) {
13062 if (FT->getCallConv() != CC_X86StdCall) {
13063 FT = Context.adjustFunctionType(
13065 FD->setType(QualType(FT, 0));
13066 }
13067 } else if (FT->getCallConv() != CC_C) {
13068 FT = Context.adjustFunctionType(FT,
13070 FD->setType(QualType(FT, 0));
13071 }
13072 }
13073
13074 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13075 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
13076 FD->setInvalidDecl();
13077 }
13078}
13079
13081 // FIXME: Need strict checking. In C89, we need to check for
13082 // any assignment, increment, decrement, function-calls, or
13083 // commas outside of a sizeof. In C99, it's the same list,
13084 // except that the aforementioned are allowed in unevaluated
13085 // expressions. Everything else falls under the
13086 // "may accept other forms of constant expressions" exception.
13087 //
13088 // Regular C++ code will not end up here (exceptions: language extensions,
13089 // OpenCL C++ etc), so the constant expression rules there don't matter.
13090 if (Init->isValueDependent()) {
13091 assert(Init->containsErrors() &&
13092 "Dependent code should only occur in error-recovery path.");
13093 return true;
13094 }
13095 const Expr *Culprit;
13096 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
13097 return false;
13098
13099 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13100 // casts and parentheses that it does not look through: under ARC an
13101 // object-pointer initializer is an `ImplicitCastExpr
13102 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13103 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13104 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13105 // the ObjC-specific classification and per-element reporting below can see
13106 // the underlying literal regardless of how it is wrapped.
13107 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13108
13109 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13110 if (getLangOpts().ObjCConstantLiterals &&
13111 isa<ObjCObjectLiteral>(CulpritLiteral)) {
13112
13113 // For collection literals, iterate the elements to point at the specific
13114 // offender. These per-element checks mirror the constant-initializer rules
13115 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13116 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13117 // constant object literal, and dictionary keys must additionally be string
13118 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13119 // `id`, so the isa<> classification is done on the unwrapped expression.
13120 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(CulpritLiteral)) {
13121 for (const Expr *Elm : ALE->elements()) {
13122 if (!isa<ObjCObjectLiteral>(Elm->IgnoreImpCasts()) ||
13123 !Elm->isConstantInitializer(Context)) {
13124 Diag(Elm->getExprLoc(),
13125 diag::err_objc_literal_nonconstant_at_file_scope)
13126 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
13127 return true;
13128 }
13129 }
13130 }
13131
13132 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(CulpritLiteral)) {
13133 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13134 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
13135
13136 // Keys must be constant string literals.
13139 Diag(Elm.Key->getExprLoc(),
13140 diag::err_objc_literal_nonconstant_at_file_scope)
13142 return true;
13143 }
13144
13145 // Values must be constant object literals.
13148 Diag(Elm.Value->getExprLoc(),
13149 diag::err_objc_literal_nonconstant_at_file_scope)
13151 return true;
13152 }
13153 }
13154 }
13155
13156 Diag(CulpritLiteral->getExprLoc(),
13157 diag::err_objc_literal_nonconstant_at_file_scope)
13158 << ObjC().CheckLiteralKind(Init) << CulpritLiteral->getSourceRange();
13159 return true;
13160 }
13161
13162 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13163 return true;
13164}
13165
13166namespace {
13167 // Visits an initialization expression to see if OrigDecl is evaluated in
13168 // its own initialization and throws a warning if it does.
13169 class SelfReferenceChecker
13170 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13171 Sema &S;
13172 Decl *OrigDecl;
13173 bool isRecordType;
13174 bool isPODType;
13175 bool isReferenceType;
13176 bool isInCXXOperatorCall;
13177
13178 bool isInitList;
13179 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13180
13181 public:
13183
13184 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13185 S(S), OrigDecl(OrigDecl) {
13186 isPODType = false;
13187 isRecordType = false;
13188 isReferenceType = false;
13189 isInCXXOperatorCall = false;
13190 isInitList = false;
13191 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
13192 isPODType = VD->getType().isPODType(S.Context);
13193 isRecordType = VD->getType()->isRecordType();
13194 isReferenceType = VD->getType()->isReferenceType();
13195 }
13196 }
13197
13198 // For most expressions, just call the visitor. For initializer lists,
13199 // track the index of the field being initialized since fields are
13200 // initialized in order allowing use of previously initialized fields.
13201 void CheckExpr(Expr *E) {
13202 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
13203 if (!InitList) {
13204 Visit(E);
13205 return;
13206 }
13207
13208 // Track and increment the index here.
13209 isInitList = true;
13210 InitFieldIndex.push_back(0);
13211 for (auto *Child : InitList->children()) {
13212 CheckExpr(cast<Expr>(Child));
13213 ++InitFieldIndex.back();
13214 }
13215 InitFieldIndex.pop_back();
13216 }
13217
13218 // Returns true if MemberExpr is checked and no further checking is needed.
13219 // Returns false if additional checking is required.
13220 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13221 llvm::SmallVector<FieldDecl*, 4> Fields;
13222 Expr *Base = E;
13223 bool ReferenceField = false;
13224
13225 // Get the field members used.
13226 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13227 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13228 if (!FD)
13229 return false;
13230 Fields.push_back(FD);
13231 if (FD->getType()->isReferenceType())
13232 ReferenceField = true;
13233 Base = ME->getBase()->IgnoreParenImpCasts();
13234 }
13235
13236 // Keep checking only if the base Decl is the same.
13237 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
13238 if (!DRE || DRE->getDecl() != OrigDecl)
13239 return false;
13240
13241 // A reference field can be bound to an unininitialized field.
13242 if (CheckReference && !ReferenceField)
13243 return true;
13244
13245 // Convert FieldDecls to their index number.
13246 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13247 for (const FieldDecl *I : llvm::reverse(Fields))
13248 UsedFieldIndex.push_back(I->getFieldIndex());
13249
13250 // See if a warning is needed by checking the first difference in index
13251 // numbers. If field being used has index less than the field being
13252 // initialized, then the use is safe.
13253 for (auto UsedIter = UsedFieldIndex.begin(),
13254 UsedEnd = UsedFieldIndex.end(),
13255 OrigIter = InitFieldIndex.begin(),
13256 OrigEnd = InitFieldIndex.end();
13257 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13258 if (*UsedIter < *OrigIter)
13259 return true;
13260 if (*UsedIter > *OrigIter)
13261 break;
13262 }
13263
13264 // TODO: Add a different warning which will print the field names.
13265 HandleDeclRefExpr(DRE);
13266 return true;
13267 }
13268
13269 // For most expressions, the cast is directly above the DeclRefExpr.
13270 // For conditional operators, the cast can be outside the conditional
13271 // operator if both expressions are DeclRefExpr's.
13272 void HandleValue(Expr *E) {
13273 E = E->IgnoreParens();
13274 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13275 HandleDeclRefExpr(DRE);
13276 return;
13277 }
13278
13279 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13280 Visit(CO->getCond());
13281 HandleValue(CO->getTrueExpr());
13282 HandleValue(CO->getFalseExpr());
13283 return;
13284 }
13285
13286 if (BinaryConditionalOperator *BCO =
13287 dyn_cast<BinaryConditionalOperator>(E)) {
13288 Visit(BCO->getCond());
13289 HandleValue(BCO->getFalseExpr());
13290 return;
13291 }
13292
13293 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13294 if (Expr *SE = OVE->getSourceExpr())
13295 HandleValue(SE);
13296 return;
13297 }
13298
13299 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13300 if (BO->getOpcode() == BO_Comma) {
13301 Visit(BO->getLHS());
13302 HandleValue(BO->getRHS());
13303 return;
13304 }
13305 }
13306
13307 if (isa<MemberExpr>(E)) {
13308 if (isInitList) {
13309 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13310 false /*CheckReference*/))
13311 return;
13312 }
13313
13314 Expr *Base = E->IgnoreParenImpCasts();
13315 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13316 // Check for static member variables and don't warn on them.
13317 if (!isa<FieldDecl>(ME->getMemberDecl()))
13318 return;
13319 Base = ME->getBase()->IgnoreParenImpCasts();
13320 }
13321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13322 HandleDeclRefExpr(DRE);
13323 return;
13324 }
13325
13326 Visit(E);
13327 }
13328
13329 // Reference types not handled in HandleValue are handled here since all
13330 // uses of references are bad, not just r-value uses.
13331 void VisitDeclRefExpr(DeclRefExpr *E) {
13332 if (isReferenceType)
13333 HandleDeclRefExpr(E);
13334 }
13335
13336 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13337 if (E->getCastKind() == CK_LValueToRValue) {
13338 HandleValue(E->getSubExpr());
13339 return;
13340 }
13341
13342 Inherited::VisitImplicitCastExpr(E);
13343 }
13344
13345 void VisitMemberExpr(MemberExpr *E) {
13346 if (isInitList) {
13347 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13348 return;
13349 }
13350
13351 // Don't warn on arrays since they can be treated as pointers.
13352 if (E->getType()->canDecayToPointerType()) return;
13353
13354 // Warn when a non-static method call is followed by non-static member
13355 // field accesses, which is followed by a DeclRefExpr.
13356 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13357 bool Warn = (MD && !MD->isStatic());
13358 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13359 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13360 if (!isa<FieldDecl>(ME->getMemberDecl()))
13361 Warn = false;
13362 Base = ME->getBase()->IgnoreParenImpCasts();
13363 }
13364
13365 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13366 if (Warn)
13367 HandleDeclRefExpr(DRE);
13368 return;
13369 }
13370
13371 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13372 // Visit that expression.
13373 Visit(Base);
13374 }
13375
13376 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13377 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13378 Expr *Callee = E->getCallee();
13379
13380 if (isa<UnresolvedLookupExpr>(Callee))
13381 return Inherited::VisitCXXOperatorCallExpr(E);
13382
13383 Visit(Callee);
13384 for (auto Arg: E->arguments())
13385 HandleValue(Arg->IgnoreParenImpCasts());
13386 }
13387
13388 void VisitLambdaExpr(LambdaExpr *E) {
13389 if (!isInCXXOperatorCall) {
13390 Inherited::VisitLambdaExpr(E);
13391 return;
13392 }
13393
13394 for (Expr *Init : E->capture_inits())
13395 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13396 HandleDeclRefExpr(DRE);
13397 else if (Init)
13398 Visit(Init);
13399 }
13400
13401 void VisitUnaryOperator(UnaryOperator *E) {
13402 // For POD record types, addresses of its own members are well-defined.
13403 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13405 if (!isPODType)
13406 HandleValue(E->getSubExpr());
13407 return;
13408 }
13409
13410 if (E->isIncrementDecrementOp()) {
13411 HandleValue(E->getSubExpr());
13412 return;
13413 }
13414
13415 Inherited::VisitUnaryOperator(E);
13416 }
13417
13418 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13419
13420 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13421 if (E->getConstructor()->isCopyConstructor()) {
13422 Expr *ArgExpr = E->getArg(0);
13423 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13424 if (ILE->getNumInits() == 1)
13425 ArgExpr = ILE->getInit(0);
13426 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13427 if (ICE->getCastKind() == CK_NoOp)
13428 ArgExpr = ICE->getSubExpr();
13429 HandleValue(ArgExpr);
13430 return;
13431 }
13432 Inherited::VisitCXXConstructExpr(E);
13433 }
13434
13435 void VisitCallExpr(CallExpr *E) {
13436 // Treat std::move as a use.
13437 if (E->isCallToStdMove()) {
13438 HandleValue(E->getArg(0));
13439 return;
13440 }
13441
13442 Inherited::VisitCallExpr(E);
13443 }
13444
13445 void VisitBinaryOperator(BinaryOperator *E) {
13446 if (E->isCompoundAssignmentOp()) {
13447 HandleValue(E->getLHS());
13448 Visit(E->getRHS());
13449 return;
13450 }
13451
13452 Inherited::VisitBinaryOperator(E);
13453 }
13454
13455 // A custom visitor for BinaryConditionalOperator is needed because the
13456 // regular visitor would check the condition and true expression separately
13457 // but both point to the same place giving duplicate diagnostics.
13458 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13459 Visit(E->getCond());
13460 Visit(E->getFalseExpr());
13461 }
13462
13463 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13464 Decl* ReferenceDecl = DRE->getDecl();
13465 if (OrigDecl != ReferenceDecl) return;
13466 unsigned diag;
13467 if (isReferenceType) {
13468 diag = diag::warn_uninit_self_reference_in_reference_init;
13469 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13470 diag = diag::warn_static_self_reference_in_init;
13471 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13472 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13473 DRE->getDecl()->getType()->isRecordType()) {
13474 diag = diag::warn_uninit_self_reference_in_init;
13475 } else {
13476 // Local variables will be handled by the CFG analysis.
13477 return;
13478 }
13479
13480 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13481 S.PDiag(diag)
13482 << DRE->getDecl() << OrigDecl->getLocation()
13483 << DRE->getSourceRange());
13484 }
13485 };
13486
13487 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13488 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13489 bool DirectInit) {
13490 // Parameters arguments are occassionially constructed with itself,
13491 // for instance, in recursive functions. Skip them.
13492 if (isa<ParmVarDecl>(OrigDecl))
13493 return;
13494
13495 // Skip checking for file-scope constexpr variables - constant evaluation
13496 // will produce appropriate errors without needing runtime diagnostics.
13497 // Local constexpr should still emit runtime warnings.
13498 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13499 VD && VD->isConstexpr() && VD->isFileVarDecl())
13500 return;
13501
13502 E = E->IgnoreParens();
13503
13504 // Skip checking T a = a where T is not a record or reference type.
13505 // Doing so is a way to silence uninitialized warnings.
13506 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13507 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13508 if (ICE->getCastKind() == CK_LValueToRValue)
13509 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13510 if (DRE->getDecl() == OrigDecl)
13511 return;
13512
13513 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13514 }
13515} // end anonymous namespace
13516
13517namespace {
13518 // Simple wrapper to add the name of a variable or (if no variable is
13519 // available) a DeclarationName into a diagnostic.
13520 struct VarDeclOrName {
13521 VarDecl *VDecl;
13522 DeclarationName Name;
13523
13524 friend const Sema::SemaDiagnosticBuilder &
13525 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13526 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13527 }
13528 };
13529} // end anonymous namespace
13530
13533 TypeSourceInfo *TSI,
13534 SourceRange Range, bool DirectInit,
13535 Expr *Init) {
13536 bool IsInitCapture = !VDecl;
13537 assert((!VDecl || !VDecl->isInitCapture()) &&
13538 "init captures are expected to be deduced prior to initialization");
13539
13540 VarDeclOrName VN{VDecl, Name};
13541
13542 DeducedType *Deduced = Type->getContainedDeducedType();
13543 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13544
13545 // Diagnose auto array declarations in C23, unless it's a supported extension.
13546 if (getLangOpts().C23 && Type->isArrayType() &&
13547 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13548 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13549 << (int)Deduced->getContainedAutoType()->getKeyword()
13550 << /*in array decl*/ 23 << Range;
13551 return QualType();
13552 }
13553
13554 // C++11 [dcl.spec.auto]p3
13555 if (!Init) {
13556 assert(VDecl && "no init for init capture deduction?");
13557
13558 // Except for class argument deduction, and then for an initializing
13559 // declaration only, i.e. no static at class scope or extern.
13561 VDecl->hasExternalStorage() ||
13562 VDecl->isStaticDataMember()) {
13563 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13564 << VDecl->getDeclName() << Type;
13565 return QualType();
13566 }
13567 }
13568
13569 ArrayRef<Expr*> DeduceInits;
13570 if (Init)
13571 DeduceInits = Init;
13572
13573 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13574 if (DirectInit && PL)
13575 DeduceInits = PL->exprs();
13576
13578 assert(VDecl && "non-auto type for init capture deduction?");
13581 VDecl->getLocation(), DirectInit, Init);
13582 // FIXME: Initialization should not be taking a mutable list of inits.
13583 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13584 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13585 InitsCopy);
13586 }
13587
13588 if (DirectInit) {
13589 if (auto *IL = dyn_cast<InitListExpr>(Init))
13590 DeduceInits = IL->inits();
13591 }
13592
13593 // Deduction only works if we have exactly one source expression.
13594 if (DeduceInits.empty()) {
13595 // It isn't possible to write this directly, but it is possible to
13596 // end up in this situation with "auto x(some_pack...);"
13597 Diag(Init->getBeginLoc(), IsInitCapture
13598 ? diag::err_init_capture_no_expression
13599 : diag::err_auto_var_init_no_expression)
13600 << VN << Type << Range;
13601 return QualType();
13602 }
13603
13604 if (DeduceInits.size() > 1) {
13605 Diag(DeduceInits[1]->getBeginLoc(),
13606 IsInitCapture ? diag::err_init_capture_multiple_expressions
13607 : diag::err_auto_var_init_multiple_expressions)
13608 << VN << Type << Range;
13609 return QualType();
13610 }
13611
13612 Expr *DeduceInit = DeduceInits[0];
13613 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13614 Diag(Init->getBeginLoc(), IsInitCapture
13615 ? diag::err_init_capture_paren_braces
13616 : diag::err_auto_var_init_paren_braces)
13617 << isa<InitListExpr>(Init) << VN << Type << Range;
13618 return QualType();
13619 }
13620
13621 // Expressions default to 'id' when we're in a debugger.
13622 bool DefaultedAnyToId = false;
13623 if (getLangOpts().DebuggerCastResultToId &&
13624 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13626 if (Result.isInvalid()) {
13627 return QualType();
13628 }
13629 Init = Result.get();
13630 DefaultedAnyToId = true;
13631 }
13632
13633 // C++ [dcl.decomp]p1:
13634 // If the assignment-expression [...] has array type A and no ref-qualifier
13635 // is present, e has type cv A
13636 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13637 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13638 DeduceInit->getType()->isConstantArrayType())
13639 return Context.getQualifiedType(DeduceInit->getType(),
13640 Type.getQualifiers());
13641
13642 QualType DeducedType;
13643 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13645 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13648 if (!IsInitCapture)
13649 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13650 else if (isa<InitListExpr>(Init))
13651 Diag(Range.getBegin(),
13652 diag::err_init_capture_deduction_failure_from_init_list)
13653 << VN
13654 << (DeduceInit->getType().isNull() ? TSI->getType()
13655 : DeduceInit->getType())
13656 << DeduceInit->getSourceRange();
13657 else
13658 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13659 << VN << TSI->getType()
13660 << (DeduceInit->getType().isNull() ? TSI->getType()
13661 : DeduceInit->getType())
13662 << DeduceInit->getSourceRange();
13663 }
13664
13665 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13666 // 'id' instead of a specific object type prevents most of our usual
13667 // checks.
13668 // We only want to warn outside of template instantiations, though:
13669 // inside a template, the 'id' could have come from a parameter.
13670 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13671 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13672 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13673 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13674 }
13675
13676 return DeducedType;
13677}
13678
13680 Expr *Init) {
13681 assert(!Init || !Init->containsErrors());
13683 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13684 VDecl->getSourceRange(), DirectInit, Init);
13685 if (DeducedType.isNull()) {
13686 VDecl->setInvalidDecl();
13687 return true;
13688 }
13689
13690 VDecl->setType(DeducedType);
13691 assert(VDecl->isLinkageValid());
13692
13693 // In ARC, infer lifetime.
13694 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13695 VDecl->setInvalidDecl();
13696
13697 if (getLangOpts().OpenCL)
13699
13700 if (getLangOpts().HLSL)
13701 HLSL().deduceAddressSpace(VDecl);
13702
13703 // If this is a redeclaration, check that the type we just deduced matches
13704 // the previously declared type.
13705 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13706 // We never need to merge the type, because we cannot form an incomplete
13707 // array of auto, nor deduce such a type.
13708 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13709 }
13710
13711 // Check the deduced type is valid for a variable declaration.
13713 return VDecl->isInvalidDecl();
13714}
13715
13717 SourceLocation Loc) {
13718 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13719 Init = EWC->getSubExpr();
13720
13721 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13722 Init = CE->getSubExpr();
13723
13724 QualType InitType = Init->getType();
13727 "shouldn't be called if type doesn't have a non-trivial C struct");
13728 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13729 for (auto *I : ILE->inits()) {
13730 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13731 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13732 continue;
13733 SourceLocation SL = I->getExprLoc();
13734 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13735 }
13736 return;
13737 }
13738
13741 checkNonTrivialCUnion(InitType, Loc,
13743 NTCUK_Init);
13744 } else {
13745 // Assume all other explicit initializers involving copying some existing
13746 // object.
13747 // TODO: ignore any explicit initializers where we can guarantee
13748 // copy-elision.
13751 NTCUK_Copy);
13752 }
13753}
13754
13755namespace {
13756
13757bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13758 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13759 // in the source code or implicitly by the compiler if it is in a union
13760 // defined in a system header and has non-trivial ObjC ownership
13761 // qualifications. We don't want those fields to participate in determining
13762 // whether the containing union is non-trivial.
13763 return FD->hasAttr<UnavailableAttr>();
13764}
13765
13766struct DiagNonTrivalCUnionDefaultInitializeVisitor
13767 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13768 void> {
13769 using Super =
13770 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13771 void>;
13772
13773 DiagNonTrivalCUnionDefaultInitializeVisitor(
13774 QualType OrigTy, SourceLocation OrigLoc,
13775 NonTrivialCUnionContext UseContext, Sema &S)
13776 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13777
13778 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13779 const FieldDecl *FD, bool InNonTrivialUnion) {
13780 if (const auto *AT = S.Context.getAsArrayType(QT))
13781 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13782 InNonTrivialUnion);
13783 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13784 }
13785
13786 void visitARCStrong(QualType QT, const FieldDecl *FD,
13787 bool InNonTrivialUnion) {
13788 if (InNonTrivialUnion)
13789 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13790 << 1 << 0 << QT << FD->getName();
13791 }
13792
13793 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13794 if (InNonTrivialUnion)
13795 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13796 << 1 << 0 << QT << FD->getName();
13797 }
13798
13799 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13800 const auto *RD = QT->castAsRecordDecl();
13801 if (RD->isUnion()) {
13802 if (OrigLoc.isValid()) {
13803 bool IsUnion = false;
13804 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13805 IsUnion = OrigRD->isUnion();
13806 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13807 << 0 << OrigTy << IsUnion << UseContext;
13808 // Reset OrigLoc so that this diagnostic is emitted only once.
13809 OrigLoc = SourceLocation();
13810 }
13811 InNonTrivialUnion = true;
13812 }
13813
13814 if (InNonTrivialUnion)
13815 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13816 << 0 << 0 << QT.getUnqualifiedType() << "";
13817
13818 for (const FieldDecl *FD : RD->fields())
13819 if (!shouldIgnoreForRecordTriviality(FD))
13820 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13821 }
13822
13823 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13824
13825 // The non-trivial C union type or the struct/union type that contains a
13826 // non-trivial C union.
13827 QualType OrigTy;
13828 SourceLocation OrigLoc;
13829 NonTrivialCUnionContext UseContext;
13830 Sema &S;
13831};
13832
13833struct DiagNonTrivalCUnionDestructedTypeVisitor
13834 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13835 using Super =
13836 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13837
13838 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13839 SourceLocation OrigLoc,
13840 NonTrivialCUnionContext UseContext,
13841 Sema &S)
13842 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13843
13844 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13845 const FieldDecl *FD, bool InNonTrivialUnion) {
13846 if (const auto *AT = S.Context.getAsArrayType(QT))
13847 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13848 InNonTrivialUnion);
13849 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13850 }
13851
13852 void visitARCStrong(QualType QT, const FieldDecl *FD,
13853 bool InNonTrivialUnion) {
13854 if (InNonTrivialUnion)
13855 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13856 << 1 << 1 << QT << FD->getName();
13857 }
13858
13859 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13860 if (InNonTrivialUnion)
13861 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13862 << 1 << 1 << QT << FD->getName();
13863 }
13864
13865 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13866 const auto *RD = QT->castAsRecordDecl();
13867 if (RD->isUnion()) {
13868 if (OrigLoc.isValid()) {
13869 bool IsUnion = false;
13870 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13871 IsUnion = OrigRD->isUnion();
13872 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13873 << 1 << OrigTy << IsUnion << UseContext;
13874 // Reset OrigLoc so that this diagnostic is emitted only once.
13875 OrigLoc = SourceLocation();
13876 }
13877 InNonTrivialUnion = true;
13878 }
13879
13880 if (InNonTrivialUnion)
13881 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13882 << 0 << 1 << QT.getUnqualifiedType() << "";
13883
13884 for (const FieldDecl *FD : RD->fields())
13885 if (!shouldIgnoreForRecordTriviality(FD))
13886 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13887 }
13888
13889 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13890 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13891 bool InNonTrivialUnion) {}
13892
13893 // The non-trivial C union type or the struct/union type that contains a
13894 // non-trivial C union.
13895 QualType OrigTy;
13896 SourceLocation OrigLoc;
13897 NonTrivialCUnionContext UseContext;
13898 Sema &S;
13899};
13900
13901struct DiagNonTrivalCUnionCopyVisitor
13902 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13903 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13904
13905 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13906 NonTrivialCUnionContext UseContext, Sema &S)
13907 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13908
13909 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13910 const FieldDecl *FD, bool InNonTrivialUnion) {
13911 if (const auto *AT = S.Context.getAsArrayType(QT))
13912 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13913 InNonTrivialUnion);
13914 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13915 }
13916
13917 void visitARCStrong(QualType QT, const FieldDecl *FD,
13918 bool InNonTrivialUnion) {
13919 if (InNonTrivialUnion)
13920 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13921 << 1 << 2 << QT << FD->getName();
13922 }
13923
13924 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13925 if (InNonTrivialUnion)
13926 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13927 << 1 << 2 << QT << FD->getName();
13928 }
13929
13930 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13931 const auto *RD = QT->castAsRecordDecl();
13932 if (RD->isUnion()) {
13933 if (OrigLoc.isValid()) {
13934 bool IsUnion = false;
13935 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13936 IsUnion = OrigRD->isUnion();
13937 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13938 << 2 << OrigTy << IsUnion << UseContext;
13939 // Reset OrigLoc so that this diagnostic is emitted only once.
13940 OrigLoc = SourceLocation();
13941 }
13942 InNonTrivialUnion = true;
13943 }
13944
13945 if (InNonTrivialUnion)
13946 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13947 << 0 << 2 << QT.getUnqualifiedType() << "";
13948
13949 for (const FieldDecl *FD : RD->fields())
13950 if (!shouldIgnoreForRecordTriviality(FD))
13951 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13952 }
13953
13954 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13955 if (InNonTrivialUnion)
13956 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13957 << 1 << 2 << QT << FD->getName();
13958 }
13959
13960 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13961 const FieldDecl *FD, bool InNonTrivialUnion) {}
13962 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13963 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13964 bool InNonTrivialUnion) {}
13965
13966 // The non-trivial C union type or the struct/union type that contains a
13967 // non-trivial C union.
13968 QualType OrigTy;
13969 SourceLocation OrigLoc;
13970 NonTrivialCUnionContext UseContext;
13971 Sema &S;
13972};
13973
13974} // namespace
13975
13977 NonTrivialCUnionContext UseContext,
13978 unsigned NonTrivialKind) {
13982 "shouldn't be called if type doesn't have a non-trivial C union");
13983
13984 if ((NonTrivialKind & NTCUK_Init) &&
13986 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13987 .visit(QT, nullptr, false);
13988 if ((NonTrivialKind & NTCUK_Destruct) &&
13990 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13991 .visit(QT, nullptr, false);
13992 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13993 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13994 .visit(QT, nullptr, false);
13995}
13996
13998 const VarDecl *Dcl) {
13999 if (!getLangOpts().CPlusPlus)
14000 return false;
14001
14002 // We only need to warn if the definition is in a header file, so wait to
14003 // diagnose until we've seen the definition.
14004 if (!Dcl->isThisDeclarationADefinition())
14005 return false;
14006
14007 // If an object is defined in a source file, its definition can't get
14008 // duplicated since it will never appear in more than one TU.
14010 return false;
14011
14012 // If the variable we're looking at is a static local, then we actually care
14013 // about the properties of the function containing it.
14014 const ValueDecl *Target = Dcl;
14015 // VarDecls and FunctionDecls have different functions for checking
14016 // inline-ness, and whether they were originally templated, so we have to
14017 // call the appropriate functions manually.
14018 bool TargetIsInline = Dcl->isInline();
14019 bool TargetWasTemplated =
14021
14022 // Update the Target and TargetIsInline property if necessary
14023 if (Dcl->isStaticLocal()) {
14024 const DeclContext *Ctx = Dcl->getDeclContext();
14025 if (!Ctx)
14026 return false;
14027
14028 const FunctionDecl *FunDcl =
14029 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
14030 if (!FunDcl)
14031 return false;
14032
14033 Target = FunDcl;
14034 // IsInlined() checks for the C++ inline property
14035 TargetIsInline = FunDcl->isInlined();
14036 TargetWasTemplated =
14038 }
14039
14040 // Non-inline functions/variables can only legally appear in one TU
14041 // unless they were part of a template. Unfortunately, making complex
14042 // template instantiations visible is infeasible in practice, since
14043 // everything the template depends on also has to be visible. To avoid
14044 // giving impractical-to-fix warnings, don't warn if we're inside
14045 // something that was templated, even on inline stuff.
14046 if (!TargetIsInline || TargetWasTemplated)
14047 return false;
14048
14049 // If the object isn't hidden, the dynamic linker will prevent duplication.
14050 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14051
14052 // The target is "hidden" (from the dynamic linker) if:
14053 // 1. On posix, it has hidden visibility, or
14054 // 2. On windows, it has no import/export annotation, and neither does the
14055 // class which directly contains it.
14056 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14057 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14058 return false;
14059
14060 // If the variable isn't directly annotated, check to see if it's a member
14061 // of an annotated class.
14062 const CXXRecordDecl *Ctx =
14063 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
14064 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14065 return false;
14066
14067 } else if (Lnk.getVisibility() != HiddenVisibility) {
14068 // Posix case
14069 return false;
14070 }
14071
14072 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14074 return false;
14075
14076 return true;
14077}
14078
14079// Determine whether the object seems mutable for the purpose of diagnosing
14080// possible unique object duplication, i.e. non-const-qualified, and
14081// not an always-constant type like a function.
14082// Not perfect: doesn't account for mutable members, for example, or
14083// elements of container types.
14084// For nested pointers, any individual level being non-const is sufficient.
14085static bool looksMutable(QualType T, const ASTContext &Ctx) {
14086 T = T.getNonReferenceType();
14087 if (T->isFunctionType())
14088 return false;
14089 if (!T.isConstant(Ctx))
14090 return true;
14091 if (T->isPointerType())
14092 return looksMutable(T->getPointeeType(), Ctx);
14093 return false;
14094}
14095
14097 // If this object has external linkage and hidden visibility, it might be
14098 // duplicated when built into a shared library, which causes problems if it's
14099 // mutable (since the copies won't be in sync) or its initialization has side
14100 // effects (since it will run once per copy instead of once globally).
14101
14102 // Don't diagnose if we're inside a template, because it's not practical to
14103 // fix the warning in most cases.
14104 if (!VD->isTemplated() &&
14106
14107 QualType Type = VD->getType();
14108 if (looksMutable(Type, VD->getASTContext())) {
14109 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
14110 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14111 }
14112
14113 // To keep false positives low, only warn if we're certain that the
14114 // initializer has side effects. Don't warn on operator new, since a mutable
14115 // pointer will trigger the previous warning, and an immutable pointer
14116 // getting duplicated just results in a little extra memory usage.
14117 const Expr *Init = VD->getAnyInitializer();
14118 if (Init &&
14119 Init->HasSideEffects(VD->getASTContext(),
14120 /*IncludePossibleEffects=*/false) &&
14121 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
14122 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
14123 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14124 }
14125 }
14126}
14127
14129 llvm::scope_exit ResetDeclForInitializer([this]() {
14130 if (!this->ExprEvalContexts.empty())
14131 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14132 });
14133
14134 // If there is no declaration, there was an error parsing it. Just ignore
14135 // the initializer.
14136 if (!RealDecl) {
14137 return;
14138 }
14139
14140 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
14141 if (!Method->isInvalidDecl()) {
14142 // Pure-specifiers are handled in ActOnPureSpecifier.
14143 Diag(Method->getLocation(), diag::err_member_function_initialization)
14144 << Method->getDeclName() << Init->getSourceRange();
14145 Method->setInvalidDecl();
14146 }
14147 return;
14148 }
14149
14150 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
14151 if (!VDecl) {
14152 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14153 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
14154 RealDecl->setInvalidDecl();
14155 return;
14156 }
14157
14158 if (VDecl->isInvalidDecl()) {
14159 ExprResult Recovery =
14160 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
14161 if (Expr *E = Recovery.get())
14162 VDecl->setInit(E);
14163 return;
14164 }
14165
14166 // __amdgpu_feature_predicate_t cannot be initialised
14167 if (VDecl->getType().getDesugaredType(Context) ==
14168 Context.AMDGPUFeaturePredicateTy) {
14169 Diag(VDecl->getLocation(),
14170 diag::err_amdgcn_predicate_type_is_not_constructible)
14171 << VDecl;
14172 VDecl->setInvalidDecl();
14173 return;
14174 }
14175
14176 // WebAssembly tables can't be used to initialise a variable.
14177 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14178 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
14179 VDecl->setInvalidDecl();
14180 return;
14181 }
14182
14183 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14184 if (VDecl->getType()->isUndeducedType()) {
14185 if (Init->containsErrors()) {
14186 // Invalidate the decl as we don't know the type for recovery-expr yet.
14187 RealDecl->setInvalidDecl();
14188 VDecl->setInit(Init);
14189 return;
14190 }
14191
14193 assert(VDecl->isInvalidDecl() &&
14194 "decl should be invalidated when deduce fails");
14195 if (auto *RecoveryExpr =
14196 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
14197 .get())
14198 VDecl->setInit(RecoveryExpr);
14199 return;
14200 }
14201 }
14202
14203 this->CheckAttributesOnDeducedType(RealDecl);
14204
14205 // we don't initialize groupshared variables so warn and return
14206 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14207 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
14208 return;
14209 }
14210
14211 // dllimport cannot be used on variable definitions.
14212 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14213 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
14214 VDecl->setInvalidDecl();
14215 return;
14216 }
14217
14218 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14219 // the identifier has external or internal linkage, the declaration shall
14220 // have no initializer for the identifier.
14221 // C++14 [dcl.init]p5 is the same restriction for C++.
14222 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14223 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
14224 VDecl->setInvalidDecl();
14225 return;
14226 }
14227
14228 if (!VDecl->getType()->isDependentType()) {
14229 // A definition must end up with a complete type, which means it must be
14230 // complete with the restriction that an array type might be completed by
14231 // the initializer; note that later code assumes this restriction.
14232 QualType BaseDeclType = VDecl->getType();
14233 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
14234 BaseDeclType = Array->getElementType();
14235 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
14236 diag::err_typecheck_decl_incomplete_type)) {
14237 RealDecl->setInvalidDecl();
14238 return;
14239 }
14240
14241 // The variable can not have an abstract class type.
14242 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
14243 diag::err_abstract_type_in_decl,
14245 VDecl->setInvalidDecl();
14246 }
14247
14248 // C++ [module.import/6]
14249 // ...
14250 // A header unit shall not contain a definition of a non-inline function or
14251 // variable whose name has external linkage.
14252 //
14253 // We choose to allow weak & selectany definitions, as they are common in
14254 // headers, and have semantics similar to inline definitions which are allowed
14255 // in header units.
14256 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14257 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14258 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14259 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14261 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14262 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14263 VDecl->setInvalidDecl();
14264 }
14265
14266 // If adding the initializer will turn this declaration into a definition,
14267 // and we already have a definition for this variable, diagnose or otherwise
14268 // handle the situation.
14269 if (VarDecl *Def = VDecl->getDefinition())
14270 if (Def != VDecl &&
14271 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14273 checkVarDeclRedefinition(Def, VDecl))
14274 return;
14275
14276 if (getLangOpts().CPlusPlus) {
14277 // C++ [class.static.data]p4
14278 // If a static data member is of const integral or const
14279 // enumeration type, its declaration in the class definition can
14280 // specify a constant-initializer which shall be an integral
14281 // constant expression (5.19). In that case, the member can appear
14282 // in integral constant expressions. The member shall still be
14283 // defined in a namespace scope if it is used in the program and the
14284 // namespace scope definition shall not contain an initializer.
14285 //
14286 // We already performed a redefinition check above, but for static
14287 // data members we also need to check whether there was an in-class
14288 // declaration with an initializer.
14289 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14290 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14291 << VDecl->getDeclName();
14292 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14293 diag::note_previous_initializer)
14294 << 0;
14295 return;
14296 }
14297
14299 VDecl->setInvalidDecl();
14300 return;
14301 }
14302 }
14303
14304 // If the variable has an initializer and local storage, check whether
14305 // anything jumps over the initialization.
14306 if (VDecl->hasLocalStorage())
14308
14309 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14310 // a kernel function cannot be initialized."
14311 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14312 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14313 VDecl->setInvalidDecl();
14314 return;
14315 }
14316
14317 // The LoaderUninitialized attribute acts as a definition (of undef).
14318 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14319 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14320 VDecl->setInvalidDecl();
14321 return;
14322 }
14323
14324 if (getLangOpts().HLSL)
14325 if (!HLSL().handleInitialization(VDecl, Init))
14326 return;
14327
14328 // Get the decls type and save a reference for later, since
14329 // CheckInitializerTypes may change it.
14330 QualType DclT = VDecl->getType(), SavT = DclT;
14331
14332 // Expressions default to 'id' when we're in a debugger
14333 // and we are assigning it to a variable of Objective-C pointer type.
14334 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14335 Init->getType() == Context.UnknownAnyTy) {
14337 if (!Result.isUsable()) {
14338 VDecl->setInvalidDecl();
14339 return;
14340 }
14341 Init = Result.get();
14342 }
14343
14344 // Perform the initialization.
14345 bool InitializedFromParenListExpr = false;
14346 bool IsParenListInit = false;
14347 if (!VDecl->isInvalidDecl()) {
14350 VDecl->getLocation(), DirectInit, Init);
14351
14352 MultiExprArg Args = Init;
14353 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14354 Args =
14355 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14356 InitializedFromParenListExpr = true;
14357 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14358 Args = CXXDirectInit->getInitExprs();
14359 InitializedFromParenListExpr = true;
14360 }
14361
14362 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14363 /*TopLevelOfInitList=*/false,
14364 /*TreatUnavailableAsInvalid=*/false);
14365 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14366 if (!Result.isUsable()) {
14367 // If the provided initializer fails to initialize the var decl,
14368 // we attach a recovery expr for better recovery.
14369 auto RecoveryExpr =
14370 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14371 if (RecoveryExpr.get())
14372 VDecl->setInit(RecoveryExpr.get());
14373 // In general, for error recovery purposes, the initializer doesn't play
14374 // part in the valid bit of the declaration. There are a few exceptions:
14375 // 1) if the var decl has a deduced auto type, and the type cannot be
14376 // deduced by an invalid initializer;
14377 // 2) if the var decl is a decomposition decl with a non-deduced type,
14378 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14379 // Case 1) was already handled elsewhere.
14380 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14381 VDecl->setInvalidDecl();
14382 return;
14383 }
14384
14385 Init = Result.getAs<Expr>();
14386 IsParenListInit = !InitSeq.steps().empty() &&
14387 InitSeq.step_begin()->Kind ==
14389 QualType VDeclType = VDecl->getType();
14390 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14391 !VDeclType->isDependentType() &&
14392 Context.getAsIncompleteArrayType(VDeclType) &&
14393 Context.getAsIncompleteArrayType(Init->getType())) {
14394 // Bail out if it is not possible to deduce array size from the
14395 // initializer.
14396 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14397 << VDeclType;
14398 VDecl->setInvalidDecl();
14399 return;
14400 }
14401 }
14402
14403 // Check for self-references within variable initializers.
14404 // Variables declared within a function/method body (except for references)
14405 // are handled by a dataflow analysis.
14406 // This is undefined behavior in C++, but valid in C.
14407 if (getLangOpts().CPlusPlus)
14408 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14409 VDecl->getType()->isReferenceType())
14410 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14411
14412 // If the type changed, it means we had an incomplete type that was
14413 // completed by the initializer. For example:
14414 // int ary[] = { 1, 3, 5 };
14415 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14416 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14417 VDecl->setType(DclT);
14418
14419 if (!VDecl->isInvalidDecl()) {
14420 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14421
14422 if (VDecl->hasAttr<BlocksAttr>())
14423 ObjC().checkRetainCycles(VDecl, Init);
14424
14425 // It is safe to assign a weak reference into a strong variable.
14426 // Although this code can still have problems:
14427 // id x = self.weakProp;
14428 // id y = self.weakProp;
14429 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14430 // paths through the function. This should be revisited if
14431 // -Wrepeated-use-of-weak is made flow-sensitive.
14432 if (FunctionScopeInfo *FSI = getCurFunction())
14433 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14435 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14436 Init->getBeginLoc()))
14437 FSI->markSafeWeakUse(Init);
14438 }
14439
14440 // The initialization is usually a full-expression.
14441 //
14442 // FIXME: If this is a braced initialization of an aggregate, it is not
14443 // an expression, and each individual field initializer is a separate
14444 // full-expression. For instance, in:
14445 //
14446 // struct Temp { ~Temp(); };
14447 // struct S { S(Temp); };
14448 // struct T { S a, b; } t = { Temp(), Temp() }
14449 //
14450 // we should destroy the first Temp before constructing the second.
14451
14452 // Set context flag for OverflowBehaviorType initialization analysis
14454 true);
14457 /*DiscardedValue*/ false, VDecl->isConstexpr());
14458 if (!Result.isUsable()) {
14459 VDecl->setInvalidDecl();
14460 return;
14461 }
14462 Init = Result.get();
14463
14464 // Attach the initializer to the decl.
14465 VDecl->setInit(Init);
14466
14467 if (VDecl->isLocalVarDecl()) {
14468 // Don't check the initializer if the declaration is malformed.
14469 if (VDecl->isInvalidDecl()) {
14470 // do nothing
14471
14472 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14473 // This is true even in C++ for OpenCL.
14474 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14476
14477 // Otherwise, C++ does not restrict the initializer.
14478 } else if (getLangOpts().CPlusPlus) {
14479 // do nothing
14480
14481 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14482 // static storage duration shall be constant expressions or string literals.
14483 } else if (VDecl->getStorageClass() == SC_Static) {
14484 // Avoid evaluating the initializer twice for constexpr variables. It will
14485 // be evaluated later.
14486 if (!VDecl->isConstexpr())
14488
14489 // C89 is stricter than C99 for aggregate initializers.
14490 // C89 6.5.7p3: All the expressions [...] in an initializer list
14491 // for an object that has aggregate or union type shall be
14492 // constant expressions.
14493 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14495 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14496 }
14497
14498 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14499 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14500 if (VDecl->hasLocalStorage())
14501 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14502 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14503 VDecl->getLexicalDeclContext()->isRecord()) {
14504 // This is an in-class initialization for a static data member, e.g.,
14505 //
14506 // struct S {
14507 // static const int value = 17;
14508 // };
14509
14510 // C++ [class.mem]p4:
14511 // A member-declarator can contain a constant-initializer only
14512 // if it declares a static member (9.4) of const integral or
14513 // const enumeration type, see 9.4.2.
14514 //
14515 // C++11 [class.static.data]p3:
14516 // If a non-volatile non-inline const static data member is of integral
14517 // or enumeration type, its declaration in the class definition can
14518 // specify a brace-or-equal-initializer in which every initializer-clause
14519 // that is an assignment-expression is a constant expression. A static
14520 // data member of literal type can be declared in the class definition
14521 // with the constexpr specifier; if so, its declaration shall specify a
14522 // brace-or-equal-initializer in which every initializer-clause that is
14523 // an assignment-expression is a constant expression.
14524
14525 // Do nothing on dependent types.
14526 if (DclT->isDependentType()) {
14527
14528 // Allow any 'static constexpr' members, whether or not they are of literal
14529 // type. We separately check that every constexpr variable is of literal
14530 // type.
14531 } else if (VDecl->isConstexpr()) {
14532
14533 // Require constness.
14534 } else if (!DclT.isConstQualified()) {
14535 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14536 << Init->getSourceRange();
14537 VDecl->setInvalidDecl();
14538
14539 // We allow integer constant expressions in all cases.
14540 } else if (DclT->isIntegralOrEnumerationType()) {
14542 // In C++11, a non-constexpr const static data member with an
14543 // in-class initializer cannot be volatile.
14544 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14545
14546 // We allow foldable floating-point constants as an extension.
14547 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14548 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14549 // it anyway and provide a fixit to add the 'constexpr'.
14550 if (getLangOpts().CPlusPlus11) {
14551 Diag(VDecl->getLocation(),
14552 diag::ext_in_class_initializer_float_type_cxx11)
14553 << DclT << Init->getSourceRange();
14554 Diag(VDecl->getBeginLoc(),
14555 diag::note_in_class_initializer_float_type_cxx11)
14556 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14557 } else {
14558 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14559 << DclT << Init->getSourceRange();
14560
14561 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14562 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14563 << Init->getSourceRange();
14564 VDecl->setInvalidDecl();
14565 }
14566 }
14567
14568 // Suggest adding 'constexpr' in C++11 for literal types.
14569 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14570 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14571 << DclT << Init->getSourceRange()
14572 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14573 VDecl->setConstexpr(true);
14574
14575 } else {
14576 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14577 << DclT << Init->getSourceRange();
14578 VDecl->setInvalidDecl();
14579 }
14580 } else if (VDecl->isFileVarDecl()) {
14581 // In C, extern is typically used to avoid tentative definitions when
14582 // declaring variables in headers, but adding an initializer makes it a
14583 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14584 // In C++, extern is often used to give implicitly static const variables
14585 // external linkage, so don't warn in that case. If selectany is present,
14586 // this might be header code intended for C and C++ inclusion, so apply the
14587 // C++ rules.
14588 if (VDecl->getStorageClass() == SC_Extern &&
14589 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14590 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14591 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14593 Diag(VDecl->getLocation(), diag::warn_extern_init);
14594
14595 // In Microsoft C++ mode, a const variable defined in namespace scope has
14596 // external linkage by default if the variable is declared with
14597 // __declspec(dllexport).
14598 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14600 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14601 VDecl->setStorageClass(SC_Extern);
14602
14603 // C99 6.7.8p4. All file scoped initializers need to be constant.
14604 // Avoid duplicate diagnostics for constexpr variables.
14605 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14606 !VDecl->isConstexpr())
14608 }
14609
14610 QualType InitType = Init->getType();
14611 if (!InitType.isNull() &&
14615
14616 // We will represent direct-initialization similarly to copy-initialization:
14617 // int x(1); -as-> int x = 1;
14618 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14619 //
14620 // Clients that want to distinguish between the two forms, can check for
14621 // direct initializer using VarDecl::getInitStyle().
14622 // A major benefit is that clients that don't particularly care about which
14623 // exactly form was it (like the CodeGen) can handle both cases without
14624 // special case code.
14625
14626 // C++ 8.5p11:
14627 // The form of initialization (using parentheses or '=') matters
14628 // when the entity being initialized has class type.
14629 if (InitializedFromParenListExpr) {
14630 assert(DirectInit && "Call-style initializer must be direct init.");
14631 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14633 } else if (DirectInit) {
14634 // This must be list-initialization. No other way is direct-initialization.
14636 }
14637
14638 if (LangOpts.OpenMP &&
14639 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14640 VDecl->isFileVarDecl())
14641 DeclsToCheckForDeferredDiags.insert(VDecl);
14643
14644 if (LangOpts.OpenACC && !InitType.isNull())
14645 OpenACC().ActOnVariableInit(VDecl, InitType);
14646}
14647
14649 // Our main concern here is re-establishing invariants like "a
14650 // variable's type is either dependent or complete".
14651 if (!D || D->isInvalidDecl()) return;
14652
14653 VarDecl *VD = dyn_cast<VarDecl>(D);
14654 if (!VD) return;
14655
14656 // Bindings are not usable if we can't make sense of the initializer.
14657 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14658 for (auto *BD : DD->bindings())
14659 BD->setInvalidDecl();
14660
14661 // Auto types are meaningless if we can't make sense of the initializer.
14662 if (VD->getType()->isUndeducedType()) {
14663 D->setInvalidDecl();
14664 return;
14665 }
14666
14667 QualType Ty = VD->getType();
14668 if (Ty->isDependentType()) return;
14669
14670 // Require a complete type.
14672 Context.getBaseElementType(Ty),
14673 diag::err_typecheck_decl_incomplete_type)) {
14674 VD->setInvalidDecl();
14675 return;
14676 }
14677
14678 // Require a non-abstract type.
14679 if (RequireNonAbstractType(VD->getLocation(), Ty,
14680 diag::err_abstract_type_in_decl,
14682 VD->setInvalidDecl();
14683 return;
14684 }
14685
14686 // Don't bother complaining about constructors or destructors,
14687 // though.
14688}
14689
14691 // If there is no declaration, there was an error parsing it. Just ignore it.
14692 if (!RealDecl)
14693 return;
14694
14695 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14696 QualType Type = Var->getType();
14697
14698 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14699 Diag(Var->getLocation(),
14700 diag::err_amdgcn_predicate_type_is_not_constructible)
14701 << Var;
14702 Var->setInvalidDecl();
14703 return;
14704 }
14705 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14706 if (isa<DecompositionDecl>(RealDecl)) {
14707 // Point the caret to the token immediately after the closing bracket if
14708 // it can be found; otherwise fall back to the declaration's location.
14709 SourceLocation Loc = Var->getLocation();
14710 SourceLocation RSquareLoc =
14711 dyn_cast<DecompositionDecl>(RealDecl)->getRSquareLoc();
14712 if (std::optional<Token> Next = Lexer::findNextToken(
14713 RSquareLoc, PP.getSourceManager(), PP.getLangOpts()))
14714 Loc = Next->getLocation();
14715 Diag(Loc, diag::err_decomp_decl_requires_init) << Var;
14716 Var->setInvalidDecl();
14717 return;
14718 }
14719
14720 if (Type->isUndeducedType() &&
14721 DeduceVariableDeclarationType(Var, false, nullptr))
14722 return;
14723
14724 this->CheckAttributesOnDeducedType(RealDecl);
14725
14726 // C++11 [class.static.data]p3: A static data member can be declared with
14727 // the constexpr specifier; if so, its declaration shall specify
14728 // a brace-or-equal-initializer.
14729 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14730 // the definition of a variable [...] or the declaration of a static data
14731 // member.
14732 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14733 !Var->isThisDeclarationADemotedDefinition()) {
14734 if (Var->isStaticDataMember()) {
14735 // C++1z removes the relevant rule; the in-class declaration is always
14736 // a definition there.
14737 if (!getLangOpts().CPlusPlus17 &&
14738 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14739 Diag(Var->getLocation(),
14740 diag::err_constexpr_static_mem_var_requires_init)
14741 << Var;
14742 Var->setInvalidDecl();
14743 return;
14744 }
14745 } else {
14746 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14747 Var->setInvalidDecl();
14748 return;
14749 }
14750 }
14751
14752 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14753 // be initialized.
14754 if (!Var->isInvalidDecl() &&
14755 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14756 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14757 bool HasConstExprDefaultConstructor = false;
14758 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14759 for (auto *Ctor : RD->ctors()) {
14760 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14761 Ctor->getMethodQualifiers().getAddressSpace() ==
14763 HasConstExprDefaultConstructor = true;
14764 }
14765 }
14766 }
14767 if (!HasConstExprDefaultConstructor) {
14768 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14769 Var->setInvalidDecl();
14770 return;
14771 }
14772 }
14773
14774 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14775 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14776 Diag(Var->getLocation(), diag::err_specialization_const);
14777 Var->setInvalidDecl();
14778 return;
14779 }
14780
14781 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14782 if (Var->getStorageClass() == SC_Extern) {
14783 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14784 << Var;
14785 Var->setInvalidDecl();
14786 return;
14787 }
14788 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14789 diag::err_typecheck_decl_incomplete_type)) {
14790 Var->setInvalidDecl();
14791 return;
14792 }
14793 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14794 if (!RD->hasTrivialDefaultConstructor()) {
14795 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14796 Var->setInvalidDecl();
14797 return;
14798 }
14799 }
14800 // The declaration is uninitialized, no need for further checks.
14801 return;
14802 }
14803
14804 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14805 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14806 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14807 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14809 NTCUK_Init);
14810
14811 switch (DefKind) {
14813 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14814 break;
14815
14816 // We have an out-of-line definition of a static data member
14817 // that has an in-class initializer, so we type-check this like
14818 // a declaration.
14819 //
14820 [[fallthrough]];
14821
14823 // It's only a declaration.
14824
14825 // Block scope. C99 6.7p7: If an identifier for an object is
14826 // declared with no linkage (C99 6.2.2p6), the type for the
14827 // object shall be complete.
14828 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14829 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14830 RequireCompleteType(Var->getLocation(), Type,
14831 diag::err_typecheck_decl_incomplete_type))
14832 Var->setInvalidDecl();
14833
14834 // Make sure that the type is not abstract.
14835 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14836 RequireNonAbstractType(Var->getLocation(), Type,
14837 diag::err_abstract_type_in_decl,
14839 Var->setInvalidDecl();
14840 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14841 Var->getStorageClass() == SC_PrivateExtern) {
14842 Diag(Var->getLocation(), diag::warn_private_extern);
14843 Diag(Var->getLocation(), diag::note_private_extern);
14844 }
14845
14846 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14847 !Var->isInvalidDecl())
14848 ExternalDeclarations.push_back(Var);
14849
14850 return;
14851
14853 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14854 // object that has file scope without an initializer, and without a
14855 // storage-class specifier or with the storage-class specifier "static",
14856 // constitutes a tentative definition. Note: A tentative definition with
14857 // external linkage is valid (C99 6.2.2p5).
14858 if (!Var->isInvalidDecl()) {
14859 if (const IncompleteArrayType *ArrayT
14860 = Context.getAsIncompleteArrayType(Type)) {
14862 Var->getLocation(), ArrayT->getElementType(),
14863 diag::err_array_incomplete_or_sizeless_type))
14864 Var->setInvalidDecl();
14865 }
14866 if (Var->getStorageClass() == SC_Static) {
14867 // C99 6.9.2p3: If the declaration of an identifier for an object is
14868 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14869 // declared type shall not be an incomplete type.
14870 // NOTE: code such as the following
14871 // static struct s;
14872 // struct s { int a; };
14873 // is accepted by gcc. Hence here we issue a warning instead of
14874 // an error and we do not invalidate the static declaration.
14875 // NOTE: to avoid multiple warnings, only check the first declaration.
14876 if (Var->isFirstDecl())
14877 RequireCompleteType(Var->getLocation(), Type,
14878 diag::ext_typecheck_decl_incomplete_type,
14879 Type->isArrayType());
14880 }
14881 }
14882
14883 // Record the tentative definition; we're done.
14884 if (!Var->isInvalidDecl())
14885 TentativeDefinitions.push_back(Var);
14886 return;
14887 }
14888
14889 // Provide a specific diagnostic for uninitialized variable definitions
14890 // with incomplete array type, unless it is a global unbounded HLSL resource
14891 // array.
14892 if (Type->isIncompleteArrayType() &&
14893 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14895 if (Var->isConstexpr())
14896 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14897 << Var;
14898 else
14899 Diag(Var->getLocation(),
14900 diag::err_typecheck_incomplete_array_needs_initializer);
14901 Var->setInvalidDecl();
14902 return;
14903 }
14904
14905 // Provide a specific diagnostic for uninitialized variable
14906 // definitions with reference type.
14907 if (Type->isReferenceType()) {
14908 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14909 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14910 return;
14911 }
14912
14913 // Do not attempt to type-check the default initializer for a
14914 // variable with dependent type.
14915 if (Type->isDependentType())
14916 return;
14917
14918 if (Var->isInvalidDecl())
14919 return;
14920
14921 if (!Var->hasAttr<AliasAttr>()) {
14922 if (RequireCompleteType(Var->getLocation(),
14923 Context.getBaseElementType(Type),
14924 diag::err_typecheck_decl_incomplete_type)) {
14925 Var->setInvalidDecl();
14926 return;
14927 }
14928 } else {
14929 return;
14930 }
14931
14932 // The variable can not have an abstract class type.
14933 if (RequireNonAbstractType(Var->getLocation(), Type,
14934 diag::err_abstract_type_in_decl,
14936 Var->setInvalidDecl();
14937 return;
14938 }
14939
14940 // In C, if the definition is const-qualified and has no initializer, it
14941 // is left uninitialized unless it has static or thread storage duration.
14942 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14943 unsigned DiagID = diag::warn_default_init_const_unsafe;
14944 if (Var->getStorageDuration() == SD_Static ||
14945 Var->getStorageDuration() == SD_Thread)
14946 DiagID = diag::warn_default_init_const;
14947
14948 bool EmitCppCompat = !Diags.isIgnored(
14949 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14950 Var->getLocation());
14951
14952 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14953 }
14954
14955 // Check for jumps past the implicit initializer. C++0x
14956 // clarifies that this applies to a "variable with automatic
14957 // storage duration", not a "local variable".
14958 // C++11 [stmt.dcl]p3
14959 // A program that jumps from a point where a variable with automatic
14960 // storage duration is not in scope to a point where it is in scope is
14961 // ill-formed unless the variable has scalar type, class type with a
14962 // trivial default constructor and a trivial destructor, a cv-qualified
14963 // version of one of these types, or an array of one of the preceding
14964 // types and is declared without an initializer.
14965 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14966 if (const auto *CXXRecord =
14967 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14968 // Mark the function (if we're in one) for further checking even if the
14969 // looser rules of C++11 do not require such checks, so that we can
14970 // diagnose incompatibilities with C++98.
14971 if (!CXXRecord->isPOD())
14973 }
14974 }
14975 // In OpenCL, we can't initialize objects in the __local address space,
14976 // even implicitly, so don't synthesize an implicit initializer.
14977 if (getLangOpts().OpenCL &&
14978 Var->getType().getAddressSpace() == LangAS::opencl_local)
14979 return;
14980
14981 // Handle HLSL uninitialized decls
14982 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14983 return;
14984
14985 // HLSL input & push-constant variables are expected to be externally
14986 // initialized, even when marked `static`.
14987 if (getLangOpts().HLSL &&
14988 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14989 return;
14990
14991 // C++03 [dcl.init]p9:
14992 // If no initializer is specified for an object, and the
14993 // object is of (possibly cv-qualified) non-POD class type (or
14994 // array thereof), the object shall be default-initialized; if
14995 // the object is of const-qualified type, the underlying class
14996 // type shall have a user-declared default
14997 // constructor. Otherwise, if no initializer is specified for
14998 // a non- static object, the object and its subobjects, if
14999 // any, have an indeterminate initial value); if the object
15000 // or any of its subobjects are of const-qualified type, the
15001 // program is ill-formed.
15002 // C++0x [dcl.init]p11:
15003 // If no initializer is specified for an object, the object is
15004 // default-initialized; [...].
15007 = InitializationKind::CreateDefault(Var->getLocation());
15008
15009 InitializationSequence InitSeq(*this, Entity, Kind, {});
15010 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
15011
15012 if (Init.get()) {
15013 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
15014 // This is important for template substitution.
15015 Var->setInitStyle(VarDecl::CallInit);
15016 } else if (Init.isInvalid()) {
15017 // If default-init fails, attach a recovery-expr initializer to track
15018 // that initialization was attempted and failed.
15019 auto RecoveryExpr =
15020 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
15021 if (RecoveryExpr.get())
15022 Var->setInit(RecoveryExpr.get());
15023 }
15024
15026 }
15027}
15028
15029void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15030 // If there is no declaration, there was an error parsing it. Ignore it.
15031 if (!D)
15032 return;
15033
15034 VarDecl *VD = dyn_cast<VarDecl>(D);
15035 if (!VD) {
15036 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var)
15037 << InExpansionStmt;
15038 D->setInvalidDecl();
15039 return;
15040 }
15041
15042 VD->setCXXForRangeDecl(true);
15043
15044 // for-range-declaration cannot be given a storage class specifier.
15045 int Error = -1;
15046 switch (VD->getStorageClass()) {
15047 case SC_None:
15048 break;
15049 case SC_Extern:
15050 Error = 0;
15051 break;
15052 case SC_Static:
15053 Error = 1;
15054 break;
15055 case SC_PrivateExtern:
15056 Error = 2;
15057 break;
15058 case SC_Auto:
15059 Error = 3;
15060 break;
15061 case SC_Register:
15062 Error = 4;
15063 break;
15064 }
15065
15066 // for-range-declaration cannot be given a storage class specifier con't.
15067 switch (VD->getTSCSpec()) {
15068 case TSCS_thread_local:
15069 Error = 6;
15070 break;
15071 case TSCS___thread:
15072 case TSCS__Thread_local:
15073 case TSCS_unspecified:
15074 break;
15075 }
15076
15077 if (Error != -1) {
15078 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
15079 << InExpansionStmt << VD << Error;
15080 D->setInvalidDecl();
15081 }
15082}
15083
15085 IdentifierInfo *Ident,
15086 ParsedAttributes &Attrs) {
15087 // C++1y [stmt.iter]p1:
15088 // A range-based for statement of the form
15089 // for ( for-range-identifier : for-range-initializer ) statement
15090 // is equivalent to
15091 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15092 DeclSpec DS(Attrs.getPool().getFactory());
15093
15094 const char *PrevSpec;
15095 unsigned DiagID;
15096 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
15098
15100 D.SetIdentifier(Ident, IdentLoc);
15101 D.takeAttributesAppending(Attrs);
15102
15103 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
15104 IdentLoc);
15105 Decl *Var = ActOnDeclarator(S, D);
15106 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
15108 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
15109 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15110 : IdentLoc);
15111}
15112
15115 return;
15116 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
15117 QualType MethodType = MD->getType();
15118 QualType AttributedType =
15119 Context.getAttributedType(Attr, MethodType, MethodType);
15120 TypeLocBuilder TLB;
15121 TypeSourceInfo *TSI = MD->getTypeSourceInfo();
15122 if (TSI && TSI->getTypeLoc().getType() == MethodType) {
15123 TLB.pushFullCopy(TSI->getTypeLoc());
15124 } else {
15125 // The written type-source info can disagree with the method's type. For
15126 // example, a deduced 'auto' return type keeps the 'auto' placeholder in its
15127 // TypeSourceInfo while the method's type has already been resolved to the
15128 // deduced type. Pushing the stale TypeLoc would make the wrapping
15129 // AttributedTypeLoc's inner type inconsistent with MethodType. Build a
15130 // trivial TypeLoc that matches MethodType instead.
15131 TLB.pushTrivial(Context, MethodType,
15132 TSI ? TSI->getTypeLoc().getBeginLoc() : MD->getLocation());
15133 }
15134 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
15135 TyLoc.setAttr(Attr);
15136 MD->setType(AttributedType);
15137 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
15138 // A trivial TypeLoc has no parameter decls, but AST visitors rely on them.
15139 if (FunctionTypeLoc FTL = MD->getFunctionTypeLoc())
15140 for (unsigned I = 0, E = MD->getNumParams(); I != E; ++I)
15141 FTL.setParam(I, MD->getParamDecl(I));
15142}
15143
15145 if (var->isInvalidDecl()) return;
15146
15148
15149 if (getLangOpts().OpenCL) {
15150 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15151 // initialiser
15152 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15153 !var->hasInit()) {
15154 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
15155 << 1 /*Init*/;
15156 var->setInvalidDecl();
15157 return;
15158 }
15159 }
15160
15161 // In Objective-C, don't allow jumps past the implicit initialization of a
15162 // local retaining variable.
15163 if (getLangOpts().ObjC &&
15164 var->hasLocalStorage()) {
15165 switch (var->getType().getObjCLifetime()) {
15169 break;
15170
15174 break;
15175 }
15176 }
15177
15178 if (var->hasLocalStorage() &&
15179 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15181
15182 // Warn about externally-visible variables being defined without a
15183 // prior declaration. We only want to do this for global
15184 // declarations, but we also specifically need to avoid doing it for
15185 // class members because the linkage of an anonymous class can
15186 // change if it's later given a typedef name.
15187 if (var->isThisDeclarationADefinition() &&
15188 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15189 var->isExternallyVisible() && var->hasLinkage() &&
15190 !var->isInline() && !var->getDescribedVarTemplate() &&
15191 var->getStorageClass() != SC_Register &&
15193 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
15194 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
15195 var->getLocation())) {
15196 // Find a previous declaration that's not a definition.
15197 VarDecl *prev = var->getPreviousDecl();
15198 while (prev && prev->isThisDeclarationADefinition())
15199 prev = prev->getPreviousDecl();
15200
15201 if (!prev) {
15202 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
15203 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
15204 << /* variable */ 0;
15205 }
15206 }
15207
15208 // Cache the result of checking for constant initialization.
15209 std::optional<bool> CacheHasConstInit;
15210 const Expr *CacheCulprit = nullptr;
15211 auto checkConstInit = [&]() mutable {
15212 const Expr *Init = var->getInit();
15213 if (Init->isInstantiationDependent())
15214 return true;
15215
15216 if (!CacheHasConstInit)
15217 CacheHasConstInit = var->getInit()->isConstantInitializer(
15218 Context, var->getType()->isReferenceType(), &CacheCulprit);
15219 return *CacheHasConstInit;
15220 };
15221
15222 if (var->getTLSKind() == VarDecl::TLS_Static) {
15223 if (var->getType().isDestructedType()) {
15224 // GNU C++98 edits for __thread, [basic.start.term]p3:
15225 // The type of an object with thread storage duration shall not
15226 // have a non-trivial destructor.
15227 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
15229 Diag(var->getLocation(), diag::note_use_thread_local);
15230 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15231 if (!checkConstInit()) {
15232 // GNU C++98 edits for __thread, [basic.start.init]p4:
15233 // An object of thread storage duration shall not require dynamic
15234 // initialization.
15235 // FIXME: Need strict checking here.
15236 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
15237 << CacheCulprit->getSourceRange();
15239 Diag(var->getLocation(), diag::note_use_thread_local);
15240 }
15241 }
15242 }
15243
15244
15245 if (!var->getType()->isStructureType() && var->hasInit() &&
15246 isa<InitListExpr>(var->getInit())) {
15247 const auto *ILE = cast<InitListExpr>(var->getInit());
15248 unsigned NumInits = ILE->getNumInits();
15249 if (NumInits > 2)
15250 for (unsigned I = 0; I < NumInits; ++I) {
15251 const auto *Init = ILE->getInit(I);
15252 if (!Init)
15253 break;
15254 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15255 if (!SL)
15256 break;
15257
15258 unsigned NumConcat = SL->getNumConcatenated();
15259 // Diagnose missing comma in string array initialization.
15260 // Do not warn when all the elements in the initializer are concatenated
15261 // together. Do not warn for macros too.
15262 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15263 bool OnlyOneMissingComma = true;
15264 for (unsigned J = I + 1; J < NumInits; ++J) {
15265 const auto *Init = ILE->getInit(J);
15266 if (!Init)
15267 break;
15268 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15269 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15270 OnlyOneMissingComma = false;
15271 break;
15272 }
15273 }
15274
15275 if (OnlyOneMissingComma) {
15277 for (unsigned i = 0; i < NumConcat - 1; ++i)
15278 Hints.push_back(FixItHint::CreateInsertion(
15279 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15280
15281 Diag(SL->getStrTokenLoc(1),
15282 diag::warn_concatenated_literal_array_init)
15283 << Hints;
15284 Diag(SL->getBeginLoc(),
15285 diag::note_concatenated_string_literal_silence);
15286 }
15287 // In any case, stop now.
15288 break;
15289 }
15290 }
15291 }
15292
15293
15294 QualType type = var->getType();
15295
15296 if (var->hasAttr<BlocksAttr>())
15298
15299 Expr *Init = var->getInit();
15300 bool GlobalStorage = var->hasGlobalStorage();
15301 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15302 QualType baseType = Context.getBaseElementType(type);
15303 bool HasConstInit = true;
15304
15305 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15306 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15307 << var;
15308
15309 // Check whether the initializer is sufficiently constant.
15310 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15311 !type->isDependentType() && Init && !Init->isValueDependent() &&
15312 (GlobalStorage || var->isConstexpr() ||
15313 var->mightBeUsableInConstantExpressions(Context))) {
15314 // If this variable might have a constant initializer or might be usable in
15315 // constant expressions, check whether or not it actually is now. We can't
15316 // do this lazily, because the result might depend on things that change
15317 // later, such as which constexpr functions happen to be defined.
15319 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15320 // Prior to C++11, in contexts where a constant initializer is required,
15321 // the set of valid constant initializers is described by syntactic rules
15322 // in [expr.const]p2-6.
15323 // FIXME: Stricter checking for these rules would be useful for constinit /
15324 // -Wglobal-constructors.
15325 HasConstInit = checkConstInit();
15326
15327 // Compute and cache the constant value, and remember that we have a
15328 // constant initializer.
15329 if (HasConstInit) {
15330 if (var->isStaticDataMember() && !var->isInline() &&
15331 var->getLexicalDeclContext()->isRecord() &&
15332 type->isIntegralOrEnumerationType()) {
15333 // In C++98, in-class initialization for a static data member must
15334 // be an integer constant expression.
15335 if (!Init->isIntegerConstantExpr(Context)) {
15336 Diag(Init->getExprLoc(),
15337 diag::ext_in_class_initializer_non_constant)
15338 << Init->getSourceRange();
15339 }
15340 }
15341 EvalProxy SProxy(*this);
15342 (void)var->checkForConstantInitialization(Notes, SProxy);
15343 Notes.clear();
15344 } else if (CacheCulprit) {
15345 Notes.emplace_back(CacheCulprit->getExprLoc(),
15346 PDiag(diag::note_invalid_subexpr_in_const_expr));
15347 Notes.back().second << CacheCulprit->getSourceRange();
15348 }
15349 } else {
15350 // Evaluate the initializer to see if it's a constant initializer.
15351 EvalProxy SProxy(*this);
15352 HasConstInit = var->checkForConstantInitialization(Notes, SProxy);
15353 }
15354
15355 if (HasConstInit) {
15356 // FIXME: Consider replacing the initializer with a ConstantExpr.
15357 } else if (var->isConstexpr()) {
15358 SourceLocation DiagLoc = var->getLocation();
15359 // If the note doesn't add any useful information other than a source
15360 // location, fold it into the primary diagnostic.
15361 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15362 diag::note_invalid_subexpr_in_const_expr) {
15363 DiagLoc = Notes[0].first;
15364 Notes.clear();
15365 }
15366 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15367 << var << Init->getSourceRange();
15368 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15369 Diag(Notes[I].first, Notes[I].second);
15370 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15371 auto *Attr = var->getAttr<ConstInitAttr>();
15372 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15373 << Init->getSourceRange();
15374 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15375 << Attr->getRange() << Attr->isConstinit();
15376 for (auto &it : Notes)
15377 Diag(it.first, it.second);
15378 } else if (var->isStaticDataMember() && !var->isInline() &&
15379 var->getLexicalDeclContext()->isRecord()) {
15380 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15381 << Init->getSourceRange();
15382 for (auto &it : Notes)
15383 Diag(it.first, it.second);
15384 var->setInvalidDecl();
15385 } else if (IsGlobal &&
15386 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15387 var->getLocation())) {
15388 // Warn about globals which don't have a constant initializer. Don't
15389 // warn about globals with a non-trivial destructor because we already
15390 // warned about them.
15391 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15392 if (!(RD && !RD->hasTrivialDestructor())) {
15393 // checkConstInit() here permits trivial default initialization even in
15394 // C++11 onwards, where such an initializer is not a constant initializer
15395 // but nonetheless doesn't require a global constructor.
15396 if (!checkConstInit())
15397 Diag(var->getLocation(), diag::warn_global_constructor)
15398 << Init->getSourceRange();
15399 }
15400 }
15401 }
15402
15403 // Apply section attributes and pragmas to global variables.
15404 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15406 PragmaStack<StringLiteral *> *Stack = nullptr;
15407 int SectionFlags = ASTContext::PSF_Read;
15408 bool MSVCEnv =
15409 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15410 std::optional<QualType::NonConstantStorageReason> Reason;
15411 if (HasConstInit &&
15412 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15413 Stack = &ConstSegStack;
15414 } else {
15415 SectionFlags |= ASTContext::PSF_Write;
15416 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15417 }
15418 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15419 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15420 SectionFlags |= ASTContext::PSF_Implicit;
15421 UnifySection(SA->getName(), SectionFlags, var);
15422 } else if (Stack->CurrentValue) {
15423 if (Stack != &ConstSegStack && MSVCEnv &&
15424 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15425 var->getType().isConstQualified()) {
15426 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15427 NonConstNonReferenceType) &&
15428 "This case should've already been handled elsewhere");
15429 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15430 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15432 : *Reason);
15433 }
15434 SectionFlags |= ASTContext::PSF_Implicit;
15435 auto SectionName = Stack->CurrentValue->getString();
15436 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15437 Stack->CurrentPragmaLocation,
15438 SectionAttr::Declspec_allocate));
15439 if (UnifySection(SectionName, SectionFlags, var))
15440 var->dropAttr<SectionAttr>();
15441 }
15442
15443 // Apply the init_seg attribute if this has an initializer. If the
15444 // initializer turns out to not be dynamic, we'll end up ignoring this
15445 // attribute.
15446 if (CurInitSeg.Segment && var->getInit())
15447 var->addAttr(InitSegAttr::CreateImplicit(
15448 Context, CurInitSeg.Segment->getString(), CurInitSeg.Func,
15449 CurInitSeg.PragmaLocation));
15450 }
15451
15452 // All the following checks are C++ only.
15453 if (!getLangOpts().CPlusPlus) {
15454 // If this variable must be emitted, add it as an initializer for the
15455 // current module.
15456 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15457 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15458 return;
15459 }
15460
15462
15463 // Require the destructor.
15464 if (!type->isDependentType())
15465 if (auto *RD = baseType->getAsCXXRecordDecl())
15467
15468 // If this variable must be emitted, add it as an initializer for the current
15469 // module. For named modules, discardable inline variables may be deferred
15470 // until they are odr-used. Non-inline variables that must be emitted,
15471 // including those with side-effecting initialization, must still be emitted
15472 // even if they have internal linkage.
15473 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) {
15474 GVALinkage Linkage = Context.GetGVALinkageForVariable(var);
15475 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15477 (Linkage == GVA_Internal && !var->isInline()))
15478 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15479 }
15480
15481 // Build the bindings if this is a structured binding declaration.
15482 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15484}
15485
15487 assert(VD->isStaticLocal());
15488
15489 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15490
15491 // Find outermost function when VD is in lambda function.
15492 while (FD && !getDLLAttr(FD) &&
15493 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15494 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15495 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15496 }
15497
15498 if (!FD)
15499 return;
15500
15501 // Static locals inherit dll attributes from their function.
15502 if (Attr *A = getDLLAttr(FD)) {
15503 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15504 NewAttr->setInherited(true);
15505 VD->addAttr(NewAttr);
15506 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15507 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15508 NewAttr->setInherited(true);
15509 VD->addAttr(NewAttr);
15510
15511 // Export this function to enforce exporting this static variable even
15512 // if it is not used in this compilation unit.
15513 if (!FD->hasAttr<DLLExportAttr>())
15514 FD->addAttr(NewAttr);
15515
15516 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15517 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15518 NewAttr->setInherited(true);
15519 VD->addAttr(NewAttr);
15520 }
15521}
15522
15524 assert(VD->getTLSKind());
15525
15526 // Perform TLS alignment check here after attributes attached to the variable
15527 // which may affect the alignment have been processed. Only perform the check
15528 // if the target has a maximum TLS alignment (zero means no constraints).
15529 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15530 // Protect the check so that it's not performed on dependent types and
15531 // dependent alignments (we can't determine the alignment in that case).
15532 if (!VD->hasDependentAlignment()) {
15533 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15534 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15535 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15536 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15537 << (unsigned)MaxAlignChars.getQuantity();
15538 }
15539 }
15540 }
15541}
15542
15544 // Note that we are no longer parsing the initializer for this declaration.
15545 ParsingInitForAutoVars.erase(ThisDecl);
15546
15547 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15548 if (!VD)
15549 return;
15550
15551 // Emit any deferred warnings for the variable's initializer, even if the
15552 // variable is invalid
15553 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15554
15555 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15557 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15558 if (PragmaClangBSSSection.Valid)
15559 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15560 Context, PragmaClangBSSSection.SectionName,
15561 PragmaClangBSSSection.PragmaLocation));
15562 if (PragmaClangDataSection.Valid)
15563 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15564 Context, PragmaClangDataSection.SectionName,
15565 PragmaClangDataSection.PragmaLocation));
15566 if (PragmaClangRodataSection.Valid)
15567 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15568 Context, PragmaClangRodataSection.SectionName,
15569 PragmaClangRodataSection.PragmaLocation));
15570 if (PragmaClangRelroSection.Valid)
15571 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15572 Context, PragmaClangRelroSection.SectionName,
15573 PragmaClangRelroSection.PragmaLocation));
15574 }
15575
15576 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15577 for (auto *BD : DD->bindings()) {
15579 }
15580 }
15581
15582 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15584
15585 checkAttributesAfterMerging(*this, *VD);
15586
15587 if (VD->isStaticLocal())
15589
15590 if (VD->getTLSKind())
15592
15593 // Perform check for initializers of device-side global variables.
15594 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15595 // 7.5). We must also apply the same checks to all __shared__
15596 // variables whether they are local or not. CUDA also allows
15597 // constant initializers for __constant__ and __device__ variables.
15598 if (getLangOpts().CUDA)
15600
15601 // Grab the dllimport or dllexport attribute off of the VarDecl.
15602 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15603
15604 // Imported static data members cannot be defined out-of-line.
15605 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15606 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15608 // We allow definitions of dllimport class template static data members
15609 // with a warning.
15612 bool IsClassTemplateMember =
15614 Context->getDescribedClassTemplate();
15615
15616 Diag(VD->getLocation(),
15617 IsClassTemplateMember
15618 ? diag::warn_attribute_dllimport_static_field_definition
15619 : diag::err_attribute_dllimport_static_field_definition);
15620 Diag(IA->getLocation(), diag::note_attribute);
15621 if (!IsClassTemplateMember)
15622 VD->setInvalidDecl();
15623 }
15624 }
15625
15626 // dllimport/dllexport variables cannot be thread local, their TLS index
15627 // isn't exported with the variable.
15628 if (DLLAttr && VD->getTLSKind()) {
15629 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15630 if (F && getDLLAttr(F)) {
15631 assert(VD->isStaticLocal());
15632 // But if this is a static local in a dlimport/dllexport function, the
15633 // function will never be inlined, which means the var would never be
15634 // imported, so having it marked import/export is safe.
15635 } else {
15636 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15637 << DLLAttr;
15638 VD->setInvalidDecl();
15639 }
15640 }
15641
15642 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15643 if (!Attr->isInherited() && !Attr->isImplicit() &&
15645 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15646 << Attr;
15647 VD->dropAttr<UsedAttr>();
15648 }
15649 }
15650 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15651 if (!Attr->isInherited() && !Attr->isImplicit() &&
15653 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15654 << Attr;
15655 VD->dropAttr<RetainAttr>();
15656 }
15657 }
15658
15659 const DeclContext *DC = VD->getDeclContext();
15660 // If there's a #pragma GCC visibility in scope, and this isn't a class
15661 // member, set the visibility of this variable.
15664
15665 // FIXME: Warn on unused var template partial specializations.
15668
15669 // Now we have parsed the initializer and can update the table of magic
15670 // tag values.
15671 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15673 return;
15674
15675 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15676 const Expr *MagicValueExpr = VD->getInit();
15677 if (!MagicValueExpr) {
15678 continue;
15679 }
15680 std::optional<llvm::APSInt> MagicValueInt;
15681 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15682 Diag(I->getRange().getBegin(),
15683 diag::err_type_tag_for_datatype_not_ice)
15684 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15685 continue;
15686 }
15687 if (MagicValueInt->getActiveBits() > 64) {
15688 Diag(I->getRange().getBegin(),
15689 diag::err_type_tag_for_datatype_too_large)
15690 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15691 continue;
15692 }
15693 uint64_t MagicValue = MagicValueInt->getZExtValue();
15694 RegisterTypeTagForDatatype(I->getArgumentKind(),
15695 MagicValue,
15696 I->getMatchingCType(),
15697 I->getLayoutCompatible(),
15698 I->getMustBeNull());
15699 }
15700}
15701
15703 auto *VD = dyn_cast<VarDecl>(DD);
15704 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15705}
15706
15708 ArrayRef<Decl *> Group) {
15710
15711 if (DS.isTypeSpecOwned())
15712 Decls.push_back(DS.getRepAsDecl());
15713
15714 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15715 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15716 bool DiagnosedMultipleDecomps = false;
15717 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15718 bool DiagnosedNonDeducedAuto = false;
15719
15720 for (Decl *D : Group) {
15721 if (!D)
15722 continue;
15723 // Check if the Decl has been declared in '#pragma omp declare target'
15724 // directive and has static storage duration.
15725 if (auto *VD = dyn_cast<VarDecl>(D);
15726 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15727 VD->hasGlobalStorage())
15729 // For declarators, there are some additional syntactic-ish checks we need
15730 // to perform.
15731 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15732 if (!FirstDeclaratorInGroup)
15733 FirstDeclaratorInGroup = DD;
15734 if (!FirstDecompDeclaratorInGroup)
15735 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15736 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15737 !hasDeducedAuto(DD))
15738 FirstNonDeducedAutoInGroup = DD;
15739
15740 if (FirstDeclaratorInGroup != DD) {
15741 // A decomposition declaration cannot be combined with any other
15742 // declaration in the same group.
15743 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15744 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15745 diag::err_decomp_decl_not_alone)
15746 << FirstDeclaratorInGroup->getSourceRange()
15747 << DD->getSourceRange();
15748 DiagnosedMultipleDecomps = true;
15749 }
15750
15751 // A declarator that uses 'auto' in any way other than to declare a
15752 // variable with a deduced type cannot be combined with any other
15753 // declarator in the same group.
15754 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15755 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15756 diag::err_auto_non_deduced_not_alone)
15757 << FirstNonDeducedAutoInGroup->getType()
15759 << FirstDeclaratorInGroup->getSourceRange()
15760 << DD->getSourceRange();
15761 DiagnosedNonDeducedAuto = true;
15762 }
15763 }
15764 }
15765
15766 Decls.push_back(D);
15767 }
15768
15770 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15771 handleTagNumbering(Tag, S);
15772 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15774 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15775 }
15776 }
15777
15778 return BuildDeclaratorGroup(Decls);
15779}
15780
15783 // C++14 [dcl.spec.auto]p7: (DR1347)
15784 // If the type that replaces the placeholder type is not the same in each
15785 // deduction, the program is ill-formed.
15786 if (Group.size() > 1) {
15788 VarDecl *DeducedDecl = nullptr;
15789 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15790 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15791 if (!D || D->isInvalidDecl())
15792 break;
15793 DeducedType *DT = D->getType()->getContainedDeducedType();
15794 if (!DT || DT->getDeducedType().isNull())
15795 continue;
15796 if (Deduced.isNull()) {
15797 Deduced = DT->getDeducedType();
15798 DeducedDecl = D;
15799 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15800 auto *AT = dyn_cast<AutoType>(DT);
15801 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15802 diag::err_auto_different_deductions)
15803 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15804 << DeducedDecl->getDeclName() << DT->getDeducedType()
15805 << D->getDeclName();
15806 if (DeducedDecl->hasInit())
15807 Dia << DeducedDecl->getInit()->getSourceRange();
15808 if (D->getInit())
15809 Dia << D->getInit()->getSourceRange();
15810 D->setInvalidDecl();
15811 break;
15812 }
15813 }
15814 }
15815
15817
15818 return DeclGroupPtrTy::make(
15819 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15820}
15821
15825
15827 // Don't parse the comment if Doxygen diagnostics are ignored.
15828 if (Group.empty() || !Group[0])
15829 return;
15830
15831 if (!areDocumentationDiagsEnabled(Group[0]->getLocation()))
15832 return;
15833
15834 if (Group.size() >= 2) {
15835 // This is a decl group. Normally it will contain only declarations
15836 // produced from declarator list. But in case we have any definitions or
15837 // additional declaration references:
15838 // 'typedef struct S {} S;'
15839 // 'typedef struct S *S;'
15840 // 'struct S *pS;'
15841 // FinalizeDeclaratorGroup adds these as separate declarations.
15842 Decl *MaybeTagDecl = Group[0];
15843 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15844 Group = Group.slice(1);
15845 }
15846 }
15847
15848 // FIXME: We assume every Decl in the group is in the same file.
15849 // This is false when preprocessor constructs the group from decls in
15850 // different files (e. g. macros or #include).
15851 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15852}
15853
15855 // Check that there are no default arguments inside the type of this
15856 // parameter.
15857 if (getLangOpts().CPlusPlus)
15859
15860 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15861 if (D.getCXXScopeSpec().isSet()) {
15862 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15863 << D.getCXXScopeSpec().getRange();
15864 }
15865
15866 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15867 // simple identifier except [...irrelevant cases...].
15868 switch (D.getName().getKind()) {
15870 break;
15871
15879 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15881 break;
15882
15885 // GetNameForDeclarator would not produce a useful name in this case.
15886 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15887 break;
15888 }
15889}
15890
15892 // This only matters in C.
15893 if (getLangOpts().CPlusPlus)
15894 return;
15895
15896 // This only matters if the declaration has a type.
15897 const auto *VD = dyn_cast<ValueDecl>(D);
15898 if (!VD)
15899 return;
15900
15901 // Get the type, this only matters for tag types.
15902 QualType QT = VD->getType();
15903 const auto *TD = QT->getAsTagDecl();
15904 if (!TD)
15905 return;
15906
15907 // Check if the tag declaration is lexically declared somewhere different
15908 // from the lexical declaration of the given object, then it will be hidden
15909 // in C++ and we should warn on it.
15910 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15911 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15912 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15913 Diag(TD->getLocation(), diag::note_declared_at);
15914 }
15915}
15916
15918 SourceLocation ExplicitThisLoc) {
15919 if (!ExplicitThisLoc.isValid())
15920 return;
15921 assert(S.getLangOpts().CPlusPlus &&
15922 "explicit parameter in non-cplusplus mode");
15923 if (!S.getLangOpts().CPlusPlus23)
15924 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15925 << P->getSourceRange();
15926
15927 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15928 // parameter pack.
15929 if (P->isParameterPack()) {
15930 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15931 << P->getSourceRange();
15932 return;
15933 }
15934 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15935 if (LambdaScopeInfo *LSI = S.getCurLambda())
15936 LSI->ExplicitObjectParameter = P;
15937}
15938
15940 SourceLocation ExplicitThisLoc) {
15941 const DeclSpec &DS = D.getDeclSpec();
15942
15943 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15944 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15945 // except for the special case of a single unnamed parameter of type void
15946 // with no storage class specifier, no type qualifier, and no following
15947 // ellipsis terminator.
15948 // Clang applies the C2y rules for 'register void' in all C language modes,
15949 // same as GCC, because it's questionable what that could possibly mean.
15950
15951 // C++03 [dcl.stc]p2 also permits 'auto'.
15952 StorageClass SC = SC_None;
15954 SC = SC_Register;
15955 // In C++11, the 'register' storage class specifier is deprecated.
15956 // In C++17, it is not allowed, but we tolerate it as an extension.
15957 if (getLangOpts().CPlusPlus11) {
15959 ? diag::ext_register_storage_class
15960 : diag::warn_deprecated_register)
15962 } else if (!getLangOpts().CPlusPlus &&
15964 D.getNumTypeObjects() == 0) {
15966 diag::err_invalid_storage_class_in_func_decl)
15969 }
15970 } else if (getLangOpts().CPlusPlus &&
15972 SC = SC_Auto;
15975 diag::err_invalid_storage_class_in_func_decl);
15977 }
15978
15980 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15982 if (DS.isInlineSpecified())
15983 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15984 << getLangOpts().CPlusPlus17;
15985 if (DS.hasConstexprSpecifier())
15986 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15987 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15988
15990
15992
15994 QualType parmDeclType = TInfo->getType();
15995
15996 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15997 const IdentifierInfo *II = D.getIdentifier();
15998 if (II) {
16001 LookupName(R, S);
16002 if (!R.empty()) {
16003 NamedDecl *PrevDecl = *R.begin();
16004 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
16005 // Maybe we will complain about the shadowed template parameter.
16007 // Just pretend that we didn't see the previous declaration.
16008 PrevDecl = nullptr;
16009 }
16010 if (PrevDecl && S->isDeclScope(PrevDecl)) {
16011 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
16012 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16013 // Recover by removing the name
16014 II = nullptr;
16015 D.SetIdentifier(nullptr, D.getIdentifierLoc());
16016 D.setInvalidType(true);
16017 }
16018 }
16019 }
16020
16021 // Incomplete resource arrays are not allowed as function parameters in HLSL
16022 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
16023 QualType EltTy = Context.getBaseElementType(parmDeclType);
16024 // `isCompleteType` forces completion of the element type so the resource
16025 // check is valid.
16026 if (!EltTy->isDependentType() &&
16027 isCompleteType(D.getIdentifierLoc(), EltTy) &&
16028 parmDeclType->isHLSLResourceRecordArray()) {
16030 diag::err_hlsl_incomplete_resource_array_in_function_param);
16031 D.setInvalidType(true);
16032 }
16033 }
16034
16035 // Temporarily put parameter variables in the translation unit, not
16036 // the enclosing context. This prevents them from accidentally
16037 // looking like class members in C++.
16038 ParmVarDecl *New =
16039 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
16040 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
16041
16042 if (D.isInvalidType())
16043 New->setInvalidDecl();
16044
16045 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
16046
16047 assert(S->isFunctionPrototypeScope());
16048 assert(S->getFunctionPrototypeDepth() >= 1);
16049 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
16051
16053
16054 // Add the parameter declaration into this scope.
16055 S->AddDecl(New);
16056 if (II)
16057 IdResolver.AddDecl(New);
16058
16060
16062 Diag(New->getLocation(), diag::err_module_private_local)
16065
16066 if (New->hasAttr<BlocksAttr>())
16067 Diag(New->getLocation(), diag::err_block_not_allowed_on)
16068 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16069
16070 New->deduceParmAddressSpace(Context);
16071
16072 return New;
16073}
16074
16076 SourceLocation Loc,
16077 QualType T) {
16078 /* FIXME: setting StartLoc == Loc.
16079 Would it be worth to modify callers so as to provide proper source
16080 location for the unnamed parameters, embedding the parameter's type? */
16081 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
16082 T, Context.getTrivialTypeSourceInfo(T, Loc),
16083 SC_None, nullptr);
16084 Param->setImplicit();
16085 return Param;
16086}
16087
16089 // Don't diagnose unused-parameter errors in template instantiations; we
16090 // will already have done so in the template itself.
16092 return;
16093
16094 for (const ParmVarDecl *Parameter : Parameters) {
16095 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16096 !Parameter->hasAttr<UnusedAttr>() &&
16097 !Parameter->getIdentifier()->isPlaceholder()) {
16098 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
16099 << Parameter->getDeclName();
16100 }
16101 }
16102}
16103
16105 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16106 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16107 return;
16108
16109 // Warn if the return value is pass-by-value and larger than the specified
16110 // threshold.
16111 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16112 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
16113 if (Size > LangOpts.NumLargeByValueCopy)
16114 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
16115 }
16116
16117 // Warn if any parameter is pass-by-value and larger than the specified
16118 // threshold.
16119 for (const ParmVarDecl *Parameter : Parameters) {
16120 QualType T = Parameter->getType();
16121 if (T->isDependentType() || !T.isPODType(Context))
16122 continue;
16123 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16124 if (Size > LangOpts.NumLargeByValueCopy)
16125 Diag(Parameter->getLocation(), diag::warn_parameter_size)
16126 << Parameter << Size;
16127 }
16128}
16129
16131 SourceLocation NameLoc,
16132 const IdentifierInfo *Name, QualType T,
16133 TypeSourceInfo *TSInfo, StorageClass SC) {
16134 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16135 if (getLangOpts().ObjCAutoRefCount &&
16136 T.getObjCLifetime() == Qualifiers::OCL_None &&
16137 T->isObjCLifetimeType()) {
16138
16139 Qualifiers::ObjCLifetime lifetime;
16140
16141 // Special cases for arrays:
16142 // - if it's const, use __unsafe_unretained
16143 // - otherwise, it's an error
16144 if (T->isArrayType()) {
16145 if (!T.isConstQualified()) {
16149 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
16150 else
16151 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
16152 << TSInfo->getTypeLoc().getSourceRange();
16153 }
16155 } else {
16156 lifetime = T->getObjCARCImplicitLifetime();
16157 }
16158 T = Context.getLifetimeQualifiedType(T, lifetime);
16159 }
16160
16161 if (getLangOpts().OpenCL) {
16162 assert(!isa<DecayedType>(T));
16163 if (T->isArrayType() && !T.hasAddressSpace()) {
16164 QualType ET = Context.getAsArrayType(T)->getElementType();
16165 if (!ET.hasAddressSpace()) {
16166 // Add the private address space to the contents of the pointer when a
16167 // pointer parameter is declared as an array and not declared.
16169 T = Context.getAddrSpaceQualType(T, ImplAS);
16170 T = QualType(Context.getAsArrayType(T), 0);
16171 }
16172 }
16173 }
16174
16175 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
16176 Context.getAdjustedParameterType(T),
16177 TSInfo, SC, nullptr);
16178
16179 // Make a note if we created a new pack in the scope of a lambda, so that
16180 // we know that references to that pack must also be expanded within the
16181 // lambda scope.
16182 if (New->isParameterPack())
16183 if (auto *CSI = getEnclosingLambdaOrBlock())
16184 CSI->LocalPacks.push_back(New);
16185
16186 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16187 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16188 checkNonTrivialCUnion(New->getType(), New->getLocation(),
16191
16192 // Parameter declarators cannot be interface types. All ObjC objects are
16193 // passed by reference.
16194 if (T->isObjCObjectType()) {
16195 SourceLocation TypeEndLoc =
16197 Diag(NameLoc,
16198 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16199 << FixItHint::CreateInsertion(TypeEndLoc, "*");
16200 T = Context.getObjCObjectPointerType(T);
16201 New->setType(T);
16202 }
16203
16204 // __ptrauth is forbidden on parameters.
16205 if (T.getPointerAuth()) {
16206 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
16207 New->setInvalidDecl();
16208 }
16209
16210 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16211 // duration shall not be qualified by an address-space qualifier."
16212 // Since all parameters have automatic store duration, they can not have
16213 // an address space.
16214 if (T.getAddressSpace() != LangAS::Default &&
16215 // OpenCL allows function arguments declared to be an array of a type
16216 // to be qualified with an address space.
16217 !(getLangOpts().OpenCL &&
16218 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16219 // WebAssembly allows reference types as parameters. Funcref in particular
16220 // lives in a different address space.
16221 !(T->isFunctionPointerType() &&
16222 T.getAddressSpace() == LangAS::wasm_funcref) &&
16223 // HLSL allows function arguments to be qualified with an address space
16224 // if the groupshared annotation is used.
16225 !(getLangOpts().HLSL &&
16226 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16227 Diag(NameLoc, diag::err_arg_with_address_space);
16228 New->setInvalidDecl();
16229 }
16230
16231 // PPC MMA non-pointer types are not allowed as function argument types.
16232 if (Context.getTargetInfo().getTriple().isPPC64() &&
16233 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
16234 New->setInvalidDecl();
16235 }
16236
16237 return New;
16238}
16239
16241 SourceLocation LocAfterDecls) {
16243
16244 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16245 // in the declaration list shall have at least one declarator, those
16246 // declarators shall only declare identifiers from the identifier list, and
16247 // every identifier in the identifier list shall be declared.
16248 //
16249 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16250 // identifiers it names shall be declared in the declaration list."
16251 //
16252 // This is why we only diagnose in C99 and later. Note, the other conditions
16253 // listed are checked elsewhere.
16254 if (!FTI.hasPrototype) {
16255 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16256 --i;
16257 if (FTI.Params[i].Param == nullptr) {
16258 if (getLangOpts().C99) {
16259 SmallString<256> Code;
16260 llvm::raw_svector_ostream(Code)
16261 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16262 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
16263 << FTI.Params[i].Ident
16264 << FixItHint::CreateInsertion(LocAfterDecls, Code);
16265 }
16266
16267 // Implicitly declare the argument as type 'int' for lack of a better
16268 // type.
16269 AttributeFactory attrs;
16270 DeclSpec DS(attrs);
16271 const char* PrevSpec; // unused
16272 unsigned DiagID; // unused
16273 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
16274 DiagID, Context.getPrintingPolicy());
16275 // Use the identifier location for the type source range.
16276 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16277 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16280 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
16281 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
16282 }
16283 }
16284 }
16285}
16286
16287Decl *
16289 MultiTemplateParamsArg TemplateParameterLists,
16290 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16291 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16292 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16293 Scope *ParentScope = FnBodyScope->getParent();
16294
16295 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16296 // we define a non-templated function definition, we will create a declaration
16297 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16298 // The base function declaration will have the equivalent of an `omp declare
16299 // variant` annotation which specifies the mangled definition as a
16300 // specialization function under the OpenMP context defined as part of the
16301 // `omp begin declare variant`.
16303 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16305 ParentScope, D, TemplateParameterLists, Bases);
16306
16308 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16309 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16310
16311 if (!Bases.empty())
16313 Bases);
16314
16315 return Dcl;
16316}
16317
16319 Consumer.HandleInlineFunctionDefinition(D);
16320}
16321
16323 const FunctionDecl *&PossiblePrototype) {
16324 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16325 Prev = Prev->getPreviousDecl()) {
16326 // Ignore any declarations that occur in function or method
16327 // scope, because they aren't visible from the header.
16328 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16329 continue;
16330
16331 PossiblePrototype = Prev;
16332 return Prev->getType()->isFunctionProtoType();
16333 }
16334 return false;
16335}
16336
16337static bool
16339 const FunctionDecl *&PossiblePrototype) {
16340 // Don't warn about invalid declarations.
16341 if (FD->isInvalidDecl())
16342 return false;
16343
16344 // Or declarations that aren't global.
16345 if (!FD->isGlobal())
16346 return false;
16347
16348 // Don't warn about C++ member functions.
16349 if (isa<CXXMethodDecl>(FD))
16350 return false;
16351
16352 // Don't warn about 'main'.
16354 if (IdentifierInfo *II = FD->getIdentifier())
16355 if (II->isStr("main") || II->isStr("efi_main"))
16356 return false;
16357
16358 if (FD->isMSVCRTEntryPoint())
16359 return false;
16360
16361 // Don't warn about inline functions.
16362 if (FD->isInlined())
16363 return false;
16364
16365 // Don't warn about function templates.
16367 return false;
16368
16369 // Don't warn about function template specializations.
16371 return false;
16372
16373 // Don't warn for OpenCL kernels.
16374 if (FD->hasAttr<DeviceKernelAttr>())
16375 return false;
16376
16377 // Don't warn on explicitly deleted functions.
16378 if (FD->isDeleted())
16379 return false;
16380
16381 // Don't warn on implicitly local functions (such as having local-typed
16382 // parameters).
16383 if (!FD->isExternallyVisible())
16384 return false;
16385
16386 // If we were able to find a potential prototype, don't warn.
16387 if (FindPossiblePrototype(FD, PossiblePrototype))
16388 return false;
16389
16390 return true;
16391}
16392
16393void
16395 const FunctionDecl *EffectiveDefinition,
16396 SkipBodyInfo *SkipBody) {
16397 const FunctionDecl *Definition = EffectiveDefinition;
16398 if (!Definition &&
16399 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16400 return;
16401
16402 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16403 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16404 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16405 // A merged copy of the same function, instantiated as a member of
16406 // the same class, is OK.
16407 if (declaresSameEntity(OrigFD, OrigDef) &&
16408 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16410 return;
16411 }
16412 }
16413 }
16414
16416 return;
16417
16418 // Don't emit an error when this is redefinition of a typo-corrected
16419 // definition.
16421 return;
16422
16423 bool DefinitionVisible = false;
16424 if (SkipBody &&
16426 DefinitionVisible) &&
16427 (Definition->getFormalLinkage() == Linkage::Internal ||
16428 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16429 !Definition->getTemplateParameterLists().empty())) {
16430 SkipBody->ShouldSkip = true;
16431 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16432 if (!DefinitionVisible) {
16433 if (auto *TD = Definition->getDescribedFunctionTemplate())
16436 }
16437 return;
16438 }
16439
16440 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16441 Definition->getStorageClass() == SC_Extern)
16442 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16443 << FD << getLangOpts().CPlusPlus;
16444 else
16445 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16446
16447 Diag(Definition->getLocation(), diag::note_previous_definition);
16448 FD->setInvalidDecl();
16449}
16450
16452 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16453
16455 LSI->CallOperator = CallOperator;
16456 LSI->Lambda = LambdaClass;
16457 LSI->ReturnType = CallOperator->getReturnType();
16458 // When this function is called in situation where the context of the call
16459 // operator is not entered, we set AfterParameterList to false, so that
16460 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16461 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16462 // where we would set the CurContext to the lambda operator before
16463 // substituting into it. In this case the flag needs to be true such that
16464 // tryCaptureVariable can correctly handle potential captures thereof.
16465 LSI->AfterParameterList = CurContext == CallOperator;
16466 LSI->BeforeCompoundStatement = false;
16467
16468 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16469 // used at the point of dealing with potential captures.
16470 //
16471 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16472 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16473 // associated. (Technically, we could recover that list from their
16474 // instantiation patterns, but for now, the GLTemplateParameterList seems
16475 // unnecessary in these cases.)
16476 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16477 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16478 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16479
16480 if (LCD == LCD_None)
16482 else if (LCD == LCD_ByCopy)
16484 else if (LCD == LCD_ByRef)
16486 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16487
16489 LSI->Mutable = !CallOperator->isConst();
16490 if (CallOperator->isExplicitObjectMemberFunction())
16491 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16492
16493 // Add the captures to the LSI so they can be noted as already
16494 // captured within tryCaptureVar.
16495 auto I = LambdaClass->field_begin();
16496 for (const auto &C : LambdaClass->captures()) {
16497 if (C.capturesVariable()) {
16498 ValueDecl *VD = C.getCapturedVar();
16499 if (VD->isInitCapture())
16500 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16501 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16502 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16503 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16504 /*EllipsisLoc*/C.isPackExpansion()
16505 ? C.getEllipsisLoc() : SourceLocation(),
16506 I->getType(), /*Invalid*/false);
16507
16508 } else if (C.capturesThis()) {
16509 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16510 C.getCaptureKind() == LCK_StarThis);
16511 } else {
16512 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16513 I->getType());
16514 }
16515 ++I;
16516 }
16517 return LSI;
16518}
16519
16521 SkipBodyInfo *SkipBody,
16522 FnBodyKind BodyKind) {
16523 if (!D) {
16524 // Parsing the function declaration failed in some way. Push on a fake scope
16525 // anyway so we can try to parse the function body.
16528 return D;
16529 }
16530
16531 FunctionDecl *FD = nullptr;
16532
16533 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16534 FD = FunTmpl->getTemplatedDecl();
16535 else
16536 FD = cast<FunctionDecl>(D);
16537
16538 // Do not push if it is a lambda because one is already pushed when building
16539 // the lambda in ActOnStartOfLambdaDefinition().
16540 if (!isLambdaCallOperator(FD))
16542 FD);
16543
16544 // Check for defining attributes before the check for redefinition.
16545 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16546 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16547 FD->dropAttr<AliasAttr>();
16548 FD->setInvalidDecl();
16549 }
16550 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16551 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16552 FD->dropAttr<IFuncAttr>();
16553 FD->setInvalidDecl();
16554 }
16555 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16556 if (Context.getTargetInfo().getTriple().isAArch64() &&
16557 !Context.getTargetInfo().hasFeature("fmv") &&
16558 !Attr->isDefaultVersion()) {
16559 // If function multi versioning disabled skip parsing function body
16560 // defined with non-default target_version attribute
16561 if (SkipBody)
16562 SkipBody->ShouldSkip = true;
16563 return nullptr;
16564 }
16565 }
16566
16567 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16568 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16569 Ctor->isDefaultConstructor() &&
16570 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16571 // If this is an MS ABI dllexport default constructor, instantiate any
16572 // default arguments.
16573 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16575 }
16576 }
16577
16578 // See if this is a redefinition. If 'will have body' (or similar) is already
16579 // set, then these checks were already performed when it was set.
16580 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16582 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16583
16584 // If we're skipping the body, we're done. Don't enter the scope.
16585 if (SkipBody && SkipBody->ShouldSkip)
16586 return D;
16587 }
16588
16589 // Mark this function as "will have a body eventually". This lets users to
16590 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16591 // this function.
16592 FD->setWillHaveBody();
16593
16594 // If we are instantiating a generic lambda call operator, push
16595 // a LambdaScopeInfo onto the function stack. But use the information
16596 // that's already been calculated (ActOnLambdaExpr) to prime the current
16597 // LambdaScopeInfo.
16598 // When the template operator is being specialized, the LambdaScopeInfo,
16599 // has to be properly restored so that tryCaptureVariable doesn't try
16600 // and capture any new variables. In addition when calculating potential
16601 // captures during transformation of nested lambdas, it is necessary to
16602 // have the LSI properly restored.
16604 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16605 // specialized.
16607 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16608 << /*specialization*/ 0;
16610 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16611
16612 FD->setInvalidDecl();
16614 } else {
16615 assert(inTemplateInstantiation() &&
16616 "There should be an active template instantiation on the stack "
16617 "when instantiating a generic lambda!");
16619 }
16620 } else {
16621 // Enter a new function scope
16623 }
16624
16625 // Builtin functions cannot be defined.
16626 if (unsigned BuiltinID = FD->getBuiltinID()) {
16627 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16628 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16629 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16630 FD->setInvalidDecl();
16631 }
16632 }
16633
16634 // The return type of a function definition must be complete (C99 6.9.1p3).
16635 // C++23 [dcl.fct.def.general]/p2
16636 // The type of [...] the return for a function definition
16637 // shall not be a (possibly cv-qualified) class type that is incomplete
16638 // or abstract within the function body unless the function is deleted.
16639 QualType ResultType = FD->getReturnType();
16640 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16641 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16642 (RequireCompleteType(FD->getLocation(), ResultType,
16643 diag::err_func_def_incomplete_result) ||
16645 diag::err_abstract_type_in_decl,
16647 FD->setInvalidDecl();
16648
16649 if (FnBodyScope)
16650 PushDeclContext(FnBodyScope, FD);
16651
16652 // Check the validity of our function parameters
16653 if (BodyKind != FnBodyKind::Delete)
16655 /*CheckParameterNames=*/true);
16656
16657 // Add non-parameter declarations already in the function to the current
16658 // scope.
16659 if (FnBodyScope) {
16660 for (Decl *NPD : FD->decls()) {
16661 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16662 if (!NonParmDecl)
16663 continue;
16664 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16665 "parameters should not be in newly created FD yet");
16666
16667 // If the decl has a name, make it accessible in the current scope.
16668 if (NonParmDecl->getDeclName())
16669 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16670
16671 // Similarly, dive into enums and fish their constants out, making them
16672 // accessible in this scope.
16673 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16674 for (auto *EI : ED->enumerators())
16675 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16676 }
16677 }
16678 }
16679
16680 // Introduce our parameters into the function scope
16681 for (auto *Param : FD->parameters()) {
16682 Param->setOwningFunction(FD);
16683
16684 // If this has an identifier, add it to the scope stack.
16685 if (Param->getIdentifier() && FnBodyScope) {
16686 CheckShadow(FnBodyScope, Param);
16687
16688 PushOnScopeChains(Param, FnBodyScope);
16689 }
16690 }
16691
16692 // C++ [module.import/6]
16693 // ...
16694 // A header unit shall not contain a definition of a non-inline function or
16695 // variable whose name has external linkage.
16696 //
16697 // Deleted and Defaulted functions are implicitly inline (but the
16698 // inline state is not set at this point, so check the BodyKind explicitly).
16699 // We choose to allow weak & selectany definitions, as they are common in
16700 // headers, and have semantics similar to inline definitions which are allowed
16701 // in header units.
16702 // FIXME: Consider an alternate location for the test where the inlined()
16703 // state is complete.
16704 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16705 !FD->isInvalidDecl() && !FD->isInlined() &&
16706 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16707 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16708 !FD->isTemplateInstantiation() &&
16709 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16710 assert(FD->isThisDeclarationADefinition());
16711 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16712 FD->setInvalidDecl();
16713 }
16714
16715 // Ensure that the function's exception specification is instantiated.
16716 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16718
16719 // dllimport cannot be applied to non-inline function definitions.
16720 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16721 !FD->isTemplateInstantiation()) {
16722 assert(!FD->hasAttr<DLLExportAttr>());
16723 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16724 FD->setInvalidDecl();
16725 return D;
16726 }
16727
16728 // Some function attributes (like OptimizeNoneAttr) need actions before
16729 // parsing body started.
16731
16732 // We want to attach documentation to original Decl (which might be
16733 // a function template).
16735 if (getCurLexicalContext()->isObjCContainer() &&
16736 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16737 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16738 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16739
16741
16742 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16743 FnBodyScope) {
16744 // An implicit call expression is synthesized for functions declared with
16745 // the sycl_kernel_entry_point attribute. The call may resolve to a
16746 // function template, a member function template, or a call operator
16747 // of a variable template depending on the results of unqualified lookup
16748 // for 'sycl_kernel_launch' from the beginning of the function body.
16749 // Performing that lookup requires the stack of parsing scopes active
16750 // when the definition is parsed and is thus done here; the result is
16751 // cached in FunctionScopeInfo and used to synthesize the (possibly
16752 // unresolved) call expression after the function body has been parsed.
16753 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16754 if (!SKEPAttr->isInvalidAttr()) {
16755 ExprResult LaunchIdExpr =
16756 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16757 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16758 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16759 // treated as an error in the definition of 'FD'; treating it as an error
16760 // of the declaration would affect overload resolution which would
16761 // potentially result in additional errors. If construction of
16762 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16763 // a null pointer value below; that is expected.
16764 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16765 }
16766 }
16767
16768 return D;
16769}
16770
16772 if (!FD || FD->isInvalidDecl())
16773 return;
16774 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16775 FD = TD->getTemplatedDecl();
16776 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16779 CurFPFeatures.applyChanges(FPO);
16780 FpPragmaStack.CurrentValue =
16781 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16782 }
16783}
16784
16786 ReturnStmt **Returns = Scope->Returns.data();
16787
16788 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16789 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16790 if (!NRVOCandidate->isNRVOVariable()) {
16791 Diag(Returns[I]->getRetValue()->getExprLoc(),
16792 diag::warn_not_eliding_copy_on_return);
16793 Returns[I]->setNRVOCandidate(nullptr);
16794 }
16795 }
16796 }
16797}
16798
16800 // We can't delay parsing the body of a constexpr function template (yet).
16802 return false;
16803
16804 // We can't delay parsing the body of a function template with a deduced
16805 // return type (yet).
16806 if (D.getDeclSpec().hasAutoTypeSpec()) {
16807 // If the placeholder introduces a non-deduced trailing return type,
16808 // we can still delay parsing it.
16809 if (D.getNumTypeObjects()) {
16810 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16811 if (Outer.Kind == DeclaratorChunk::Function &&
16812 Outer.Fun.hasTrailingReturnType()) {
16813 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16814 return Ty.isNull() || !Ty->isUndeducedType();
16815 }
16816 }
16817 return false;
16818 }
16819
16820 return true;
16821}
16822
16824 // We cannot skip the body of a function (or function template) which is
16825 // constexpr, since we may need to evaluate its body in order to parse the
16826 // rest of the file.
16827 // We cannot skip the body of a function with an undeduced return type,
16828 // because any callers of that function need to know the type.
16829 if (const FunctionDecl *FD = D->getAsFunction()) {
16830 if (FD->isConstexpr())
16831 return false;
16832 // We can't simply call Type::isUndeducedType here, because inside template
16833 // auto can be deduced to a dependent type, which is not considered
16834 // "undeduced".
16835 if (FD->getReturnType()->getContainedDeducedType())
16836 return false;
16837 }
16838 return Consumer.shouldSkipFunctionBody(D);
16839}
16840
16842 if (!Decl)
16843 return nullptr;
16844 if (FunctionDecl *FD = Decl->getAsFunction())
16845 FD->setHasSkippedBody();
16846 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16847 MD->setHasSkippedBody();
16848 return Decl;
16849}
16850
16851/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16852/// body.
16854public:
16855 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16857 if (!IsLambda)
16858 S.PopExpressionEvaluationContext();
16859 }
16860
16861private:
16862 Sema &S;
16863 bool IsLambda = false;
16864};
16865
16867 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16868
16869 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16870 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16871 if (!Inserted)
16872 return It->second;
16873
16874 bool R = false;
16875 const BlockDecl *CurBD = BD;
16876
16877 do {
16878 R = !CurBD->doesNotEscape();
16879 if (R)
16880 break;
16881 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16882 } while (CurBD);
16883
16884 return It->second = R;
16885 };
16886
16887 // If the location where 'self' is implicitly retained is inside a escaping
16888 // block, emit a diagnostic.
16889 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16891 if (IsOrNestedInEscapingBlock(P.second))
16892 S.Diag(P.first, diag::warn_implicitly_retains_self)
16893 << FixItHint::CreateInsertion(P.first, "self->");
16894}
16895
16896static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16897 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16898 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16899}
16900
16902 return methodHasName(FD, "get_return_object");
16903}
16904
16906 return FD->isStatic() &&
16907 methodHasName(FD, "get_return_object_on_allocation_failure");
16908}
16909
16912 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16913 return;
16914 // Allow some_promise_type::get_return_object().
16916 return;
16917 if (!FD->hasAttr<CoroWrapperAttr>())
16918 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16919}
16920
16921Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16922 bool RetainFunctionScopeInfo) {
16924 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16925
16926 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16927 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16928
16929 SourceLocation AnalysisLoc;
16930 if (Body)
16931 AnalysisLoc = Body->getEndLoc();
16932 else if (FD)
16933 AnalysisLoc = FD->getEndLoc();
16935 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16936 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16937
16938 // If we skip function body, we can't tell if a function is a coroutine.
16939 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16940 if (FSI->isCoroutine())
16942 else
16944 }
16945
16946 // Diagnose invalid SYCL kernel entry point function declarations
16947 // and build SYCLKernelCallStmts for valid ones.
16948 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16949 SYCLKernelEntryPointAttr *SKEPAttr =
16950 FD->getAttr<SYCLKernelEntryPointAttr>();
16951 if (FD->isDefaulted()) {
16952 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16953 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16954 SKEPAttr->setInvalidAttr();
16955 } else if (FD->isDeleted()) {
16956 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16957 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16958 SKEPAttr->setInvalidAttr();
16959 } else if (FSI->isCoroutine()) {
16960 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16961 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16962 SKEPAttr->setInvalidAttr();
16963 } else if (Body && isa<CXXTryStmt>(Body)) {
16964 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16965 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16966 SKEPAttr->setInvalidAttr();
16967 }
16968
16969 // Build an unresolved SYCL kernel call statement for a function template,
16970 // validate that a SYCL kernel call statement was instantiated for an
16971 // (implicit or explicit) instantiation of a function template, or otherwise
16972 // build a (resolved) SYCL kernel call statement for a non-templated
16973 // function or an explicit specialization.
16974 if (Body && !SKEPAttr->isInvalidAttr()) {
16975 StmtResult SR;
16976 if (FD->isTemplateInstantiation()) {
16977 // The function body should already be a SYCLKernelCallStmt in this
16978 // case, but might not be if there were previous errors.
16979 SR = Body;
16980 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16981 // If name lookup for a template named sycl_kernel_launch failed
16982 // earlier, don't try to build a SYCL kernel call statement as that
16983 // would cause additional errors to be issued; just proceed with the
16984 // original function body.
16985 SR = Body;
16986 } else if (FD->isTemplated()) {
16988 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16989 } else {
16991 FD, cast<CompoundStmt>(Body),
16992 getCurFunction()->SYCLKernelLaunchIdExpr);
16993 }
16994 // If construction of the replacement body fails, just continue with the
16995 // original function body. An early error return here is not valid; the
16996 // current declaration context and function scopes must be popped before
16997 // returning.
16998 if (SR.isUsable())
16999 Body = SR.get();
17000 }
17001 }
17002
17003 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
17004 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
17005 if (FD->isDeletedAsWritten())
17006 Diag(SEAttr->getLocation(),
17007 diag::err_sycl_external_invalid_deleted_function)
17008 << SEAttr;
17009 }
17010
17011 {
17012 // Do not call PopExpressionEvaluationContext() if it is a lambda because
17013 // one is already popped when finishing the lambda in BuildLambdaExpr().
17014 // This is meant to pop the context added in ActOnStartOfFunctionDef().
17015 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
17016 if (FD) {
17017 // The function body and the DefaultedOrDeletedInfo, if present, use
17018 // the same storage; don't overwrite the latter if the former is null
17019 // (the body is initialised to null anyway, so even if the latter isn't
17020 // present, this would still be a no-op).
17021 if (Body)
17022 FD->setBody(Body);
17023 FD->setWillHaveBody(false);
17024
17025 if (getLangOpts().CPlusPlus14) {
17026 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
17027 FD->getReturnType()->isUndeducedType()) {
17028 // For a function with a deduced result type to return void,
17029 // the result type as written must be 'auto' or 'decltype(auto)',
17030 // possibly cv-qualified or constrained, but not ref-qualified.
17031 if (!FD->getReturnType()->getAs<AutoType>()) {
17032 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
17033 << FD->getReturnType();
17034 FD->setInvalidDecl();
17035 } else {
17036 // Falling off the end of the function is the same as 'return;'.
17037 Expr *Dummy = nullptr;
17039 FD, dcl->getLocation(), Dummy,
17040 FD->getReturnType()->getAs<AutoType>()))
17041 FD->setInvalidDecl();
17042 }
17043 }
17044 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
17045 // In C++11, we don't use 'auto' deduction rules for lambda call
17046 // operators because we don't support return type deduction.
17047 auto *LSI = getCurLambda();
17048 if (LSI->HasImplicitReturnType) {
17050
17051 // C++11 [expr.prim.lambda]p4:
17052 // [...] if there are no return statements in the compound-statement
17053 // [the deduced type is] the type void
17054 QualType RetType =
17055 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17056
17057 // Update the return type to the deduced type.
17058 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17059 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
17060 Proto->getExtProtoInfo()));
17061 }
17062 }
17063
17064 // If the function implicitly returns zero (like 'main') or is naked,
17065 // don't complain about missing return statements.
17066 // Clang implicitly returns 0 in C89 mode, but that's considered an
17067 // extension. The check is necessary to ensure the expected extension
17068 // warning is emitted in C89 mode.
17069 if ((FD->hasImplicitReturnZero() &&
17070 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17071 FD->hasAttr<NakedAttr>())
17073
17074 // MSVC permits the use of pure specifier (=0) on function definition,
17075 // defined at class scope, warn about this non-standard construct.
17076 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17077 !FD->isOutOfLine())
17078 Diag(FD->getLocation(), diag::ext_pure_function_definition);
17079
17080 if (!FD->isInvalidDecl()) {
17081 // Don't diagnose unused parameters of defaulted, deleted or naked
17082 // functions.
17083 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17084 !FD->hasAttr<NakedAttr>())
17087 FD->getReturnType(), FD);
17088
17089 // If this is a structor, we need a vtable.
17090 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
17091 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
17092 else if (CXXDestructorDecl *Destructor =
17093 dyn_cast<CXXDestructorDecl>(FD))
17094 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
17095
17096 // Try to apply the named return value optimization. We have to check
17097 // if we can do this here because lambdas keep return statements around
17098 // to deduce an implicit return type.
17099 if (FD->getReturnType()->isRecordType() &&
17101 computeNRVO(Body, FSI);
17102 }
17103
17104 // GNU warning -Wmissing-prototypes:
17105 // Warn if a global function is defined without a previous
17106 // prototype declaration. This warning is issued even if the
17107 // definition itself provides a prototype. The aim is to detect
17108 // global functions that fail to be declared in header files.
17109 const FunctionDecl *PossiblePrototype = nullptr;
17110 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17111 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
17112
17113 if (PossiblePrototype) {
17114 // We found a declaration that is not a prototype,
17115 // but that could be a zero-parameter prototype
17116 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17117 TypeLoc TL = TI->getTypeLoc();
17119 Diag(PossiblePrototype->getLocation(),
17120 diag::note_declaration_not_a_prototype)
17121 << (FD->getNumParams() != 0)
17123 FTL.getRParenLoc(), "void")
17124 : FixItHint{});
17125 }
17126 } else {
17127 // Returns true if the token beginning at this Loc is `const`.
17128 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17129 const LangOptions &LangOpts) {
17130 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17131 if (LocInfo.first.isInvalid())
17132 return false;
17133
17134 bool Invalid = false;
17135 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
17136 if (Invalid)
17137 return false;
17138
17139 if (LocInfo.second > Buffer.size())
17140 return false;
17141
17142 const char *LexStart = Buffer.data() + LocInfo.second;
17143 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17144
17145 return StartTok.consume_front("const") &&
17146 (StartTok.empty() || isWhitespace(StartTok[0]) ||
17147 StartTok.starts_with("/*") || StartTok.starts_with("//"));
17148 };
17149
17150 auto findBeginLoc = [&]() {
17151 // If the return type has `const` qualifier, we want to insert
17152 // `static` before `const` (and not before the typename).
17153 if ((FD->getReturnType()->isAnyPointerType() &&
17156 // But only do this if we can determine where the `const` is.
17157
17158 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17159 getLangOpts()))
17160
17161 return FD->getBeginLoc();
17162 }
17163 return FD->getTypeSpecStartLoc();
17164 };
17166 diag::note_static_for_internal_linkage)
17167 << /* function */ 1
17168 << (FD->getStorageClass() == SC_None
17169 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
17170 : FixItHint{});
17171 }
17172 }
17173
17174 // We might not have found a prototype because we didn't wish to warn on
17175 // the lack of a missing prototype. Try again without the checks for
17176 // whether we want to warn on the missing prototype.
17177 if (!PossiblePrototype)
17178 (void)FindPossiblePrototype(FD, PossiblePrototype);
17179
17180 // If the function being defined does not have a prototype, then we may
17181 // need to diagnose it as changing behavior in C23 because we now know
17182 // whether the function accepts arguments or not. This only handles the
17183 // case where the definition has no prototype but does have parameters
17184 // and either there is no previous potential prototype, or the previous
17185 // potential prototype also has no actual prototype. This handles cases
17186 // like:
17187 // void f(); void f(a) int a; {}
17188 // void g(a) int a; {}
17189 // See MergeFunctionDecl() for other cases of the behavior change
17190 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17191 // type without a prototype.
17192 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17193 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17194 !PossiblePrototype->isImplicit()))) {
17195 // The function definition has parameters, so this will change behavior
17196 // in C23. If there is a possible prototype, it comes before the
17197 // function definition.
17198 // FIXME: The declaration may have already been diagnosed as being
17199 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17200 // there's no way to test for the "changes behavior" condition in
17201 // SemaType.cpp when forming the declaration's function type. So, we do
17202 // this awkward dance instead.
17203 //
17204 // If we have a possible prototype and it declares a function with a
17205 // prototype, we don't want to diagnose it; if we have a possible
17206 // prototype and it has no prototype, it may have already been
17207 // diagnosed in SemaType.cpp as deprecated depending on whether
17208 // -Wstrict-prototypes is enabled. If we already warned about it being
17209 // deprecated, add a note that it also changes behavior. If we didn't
17210 // warn about it being deprecated (because the diagnostic is not
17211 // enabled), warn now that it is deprecated and changes behavior.
17212
17213 // This K&R C function definition definitely changes behavior in C23,
17214 // so diagnose it.
17215 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
17216 << /*definition*/ 1 << /* not supported in C23 */ 0;
17217
17218 // If we have a possible prototype for the function which is a user-
17219 // visible declaration, we already tested that it has no prototype.
17220 // This will change behavior in C23. This gets a warning rather than a
17221 // note because it's the same behavior-changing problem as with the
17222 // definition.
17223 if (PossiblePrototype)
17224 Diag(PossiblePrototype->getLocation(),
17225 diag::warn_non_prototype_changes_behavior)
17226 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17227 << /*definition*/ 1;
17228 }
17229
17230 // Warn on CPUDispatch with an actual body.
17231 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17232 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
17233 if (!CmpndBody->body_empty())
17234 Diag(CmpndBody->body_front()->getBeginLoc(),
17235 diag::warn_dispatch_body_ignored);
17236
17237 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
17238 const CXXMethodDecl *KeyFunction;
17239 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17240 MD->isVirtual() &&
17241 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
17242 MD == KeyFunction->getCanonicalDecl()) {
17243 // Update the key-function state if necessary for this ABI.
17244 if (FD->isInlined() &&
17245 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17246 Context.setNonKeyFunction(MD);
17247
17248 // If the newly-chosen key function is already defined, then we
17249 // need to mark the vtable as used retroactively.
17250 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
17251 const FunctionDecl *Definition;
17252 if (KeyFunction && KeyFunction->isDefined(Definition))
17253 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
17254 } else {
17255 // We just defined they key function; mark the vtable as used.
17256 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
17257 }
17258 }
17259 }
17260
17261 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17262 "Function parsing confused");
17263 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
17264 assert(MD == getCurMethodDecl() && "Method parsing confused");
17265 MD->setBody(Body);
17266 if (!MD->isInvalidDecl()) {
17268 MD->getReturnType(), MD);
17269
17270 if (Body)
17271 computeNRVO(Body, FSI);
17272 }
17273 if (FSI->ObjCShouldCallSuper) {
17274 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
17275 << MD->getSelector().getAsString();
17276 FSI->ObjCShouldCallSuper = false;
17277 }
17279 const ObjCMethodDecl *InitMethod = nullptr;
17280 bool isDesignated =
17281 MD->isDesignatedInitializerForTheInterface(&InitMethod);
17282 assert(isDesignated && InitMethod);
17283 (void)isDesignated;
17284
17285 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17286 auto IFace = MD->getClassInterface();
17287 if (!IFace)
17288 return false;
17289 auto SuperD = IFace->getSuperClass();
17290 if (!SuperD)
17291 return false;
17292 return SuperD->getIdentifier() ==
17293 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17294 };
17295 // Don't issue this warning for unavailable inits or direct subclasses
17296 // of NSObject.
17297 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17298 Diag(MD->getLocation(),
17299 diag::warn_objc_designated_init_missing_super_call);
17300 Diag(InitMethod->getLocation(),
17301 diag::note_objc_designated_init_marked_here);
17302 }
17304 }
17305 if (FSI->ObjCWarnForNoInitDelegation) {
17306 // Don't issue this warning for unavailable inits.
17307 if (!MD->isUnavailable())
17308 Diag(MD->getLocation(),
17309 diag::warn_objc_secondary_init_missing_init_call);
17310 FSI->ObjCWarnForNoInitDelegation = false;
17311 }
17312
17314 } else {
17315 // Parsing the function declaration failed in some way. Pop the fake scope
17316 // we pushed on.
17317 PopFunctionScopeInfo(ActivePolicy, dcl);
17318 return nullptr;
17319 }
17320
17321 if (Body) {
17324 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17326 }
17327
17328 assert(!FSI->ObjCShouldCallSuper &&
17329 "This should only be set for ObjC methods, which should have been "
17330 "handled in the block above.");
17331
17332 // Verify and clean out per-function state.
17333 if (Body && (!FD || !FD->isDefaulted())) {
17334 // C++ constructors that have function-try-blocks can't have return
17335 // statements in the handlers of that block. (C++ [except.handle]p14)
17336 // Verify this.
17337 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17339
17340 // Verify that gotos and switch cases don't jump into scopes illegally.
17341 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17343
17344 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17345 if (!Destructor->getParent()->isDependentType())
17347
17349 Destructor->getParent());
17350 }
17351
17352 // If any errors have occurred, clear out any temporaries that may have
17353 // been leftover. This ensures that these temporaries won't be picked up
17354 // for deletion in some later function.
17357 getDiagnostics().getSuppressAllDiagnostics()) {
17359 }
17361 // Since the body is valid, issue any analysis-based warnings that are
17362 // enabled.
17363 ActivePolicy = &WP;
17364 }
17365
17366 if (!IsInstantiation && FD &&
17367 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17368 !FD->isInvalidDecl() &&
17370 FD->setInvalidDecl();
17371
17372 if (FD && FD->hasAttr<NakedAttr>()) {
17373 for (const Stmt *S : Body->children()) {
17374 // Allow local register variables without initializer as they don't
17375 // require prologue.
17376 bool RegisterVariables = false;
17377 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17378 for (const auto *Decl : DS->decls()) {
17379 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17380 RegisterVariables =
17381 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17382 if (!RegisterVariables)
17383 break;
17384 }
17385 }
17386 }
17387 if (RegisterVariables)
17388 continue;
17389 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17390 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17391 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17392 FD->setInvalidDecl();
17393 break;
17394 }
17395 }
17396 }
17397
17398 assert(ExprCleanupObjects.size() ==
17399 ExprEvalContexts.back().NumCleanupObjects &&
17400 "Leftover temporaries in function");
17401 assert(!Cleanup.exprNeedsCleanups() &&
17402 "Unaccounted cleanups in function");
17403 assert(MaybeODRUseExprs.empty() &&
17404 "Leftover expressions for odr-use checking");
17405 }
17406 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17407 // the declaration context below. Otherwise, we're unable to transform
17408 // 'this' expressions when transforming immediate context functions.
17409
17410 if (FD)
17412
17413 if (!IsInstantiation)
17415
17416 if (!RetainFunctionScopeInfo)
17417 PopFunctionScopeInfo(ActivePolicy, dcl);
17418 // If any errors have occurred, clear out any temporaries that may have
17419 // been leftover. This ensures that these temporaries won't be picked up for
17420 // deletion in some later function.
17423 }
17424
17425 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17426 (LangOpts.OpenMP && !LangOpts.OpenMPSimd) ||
17427 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17428 auto ES = getEmissionStatus(FD);
17432 }
17433
17434 if (FD && !FD->isDeleted())
17435 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17436
17437 return dcl;
17438}
17439
17440/// When we finish delayed parsing of an attribute, we must attach it to the
17441/// relevant Decl.
17443 ParsedAttributes &Attrs) {
17444 // Always attach attributes to the underlying decl.
17445 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17446 D = TD->getTemplatedDecl();
17447 ProcessDeclAttributeList(S, D, Attrs);
17448 ProcessAPINotes(D);
17449
17450 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17451 if (Method->isStatic())
17453}
17454
17456 IdentifierInfo &II, Scope *S) {
17457 // It is not valid to implicitly define a function in C23.
17458 assert(LangOpts.implicitFunctionsAllowed() &&
17459 "Implicit function declarations aren't allowed in this language mode");
17460
17461 // Find the scope in which the identifier is injected and the corresponding
17462 // DeclContext.
17463 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17464 // In that case, we inject the declaration into the translation unit scope
17465 // instead.
17466 Scope *BlockScope = S;
17467 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17468 BlockScope = BlockScope->getParent();
17469
17470 // Loop until we find a DeclContext that is either a function/method or the
17471 // translation unit, which are the only two valid places to implicitly define
17472 // a function. This avoids accidentally defining the function within a tag
17473 // declaration, for example.
17474 Scope *ContextScope = BlockScope;
17475 while (!ContextScope->getEntity() ||
17476 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17477 !ContextScope->getEntity()->isTranslationUnit()))
17478 ContextScope = ContextScope->getParent();
17479 ContextRAII SavedContext(*this, ContextScope->getEntity());
17480
17481 // Before we produce a declaration for an implicitly defined
17482 // function, see whether there was a locally-scoped declaration of
17483 // this name as a function or variable. If so, use that
17484 // (non-visible) declaration, and complain about it.
17485 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17486 if (ExternCPrev) {
17487 // We still need to inject the function into the enclosing block scope so
17488 // that later (non-call) uses can see it.
17489 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17490
17491 // C89 footnote 38:
17492 // If in fact it is not defined as having type "function returning int",
17493 // the behavior is undefined.
17494 if (!isa<FunctionDecl>(ExternCPrev) ||
17495 !Context.typesAreCompatible(
17496 cast<FunctionDecl>(ExternCPrev)->getType(),
17497 Context.getFunctionNoProtoType(Context.IntTy))) {
17498 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17499 << ExternCPrev << !getLangOpts().C99;
17500 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17501 return ExternCPrev;
17502 }
17503 }
17504
17505 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17506 unsigned diag_id;
17507 if (II.getName().starts_with("__builtin_"))
17508 diag_id = diag::warn_builtin_unknown;
17509 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17510 else if (getLangOpts().C99)
17511 diag_id = diag::ext_implicit_function_decl_c99;
17512 else
17513 diag_id = diag::warn_implicit_function_decl;
17514
17515 TypoCorrection Corrected;
17516 // Because typo correction is expensive, only do it if the implicit
17517 // function declaration is going to be treated as an error.
17518 //
17519 // Perform the correction before issuing the main diagnostic, as some
17520 // consumers use typo-correction callbacks to enhance the main diagnostic.
17521 if (S && !ExternCPrev &&
17522 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17524 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17525 S, nullptr, CCC, CorrectTypoKind::NonError);
17526 }
17527
17528 Diag(Loc, diag_id) << &II;
17529 if (Corrected) {
17530 // If the correction is going to suggest an implicitly defined function,
17531 // skip the correction as not being a particularly good idea.
17532 bool Diagnose = true;
17533 if (const auto *D = Corrected.getCorrectionDecl())
17534 Diagnose = !D->isImplicit();
17535 if (Diagnose)
17536 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17537 /*ErrorRecovery*/ false);
17538 }
17539
17540 // If we found a prior declaration of this function, don't bother building
17541 // another one. We've already pushed that one into scope, so there's nothing
17542 // more to do.
17543 if (ExternCPrev)
17544 return ExternCPrev;
17545
17546 // Set a Declarator for the implicit definition: int foo();
17547 const char *Dummy;
17548 AttributeFactory attrFactory;
17549 DeclSpec DS(attrFactory);
17550 unsigned DiagID;
17551 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17552 Context.getPrintingPolicy());
17553 (void)Error; // Silence warning.
17554 assert(!Error && "Error setting up implicit decl!");
17555 SourceLocation NoLoc;
17557 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17558 /*IsAmbiguous=*/false,
17559 /*LParenLoc=*/NoLoc,
17560 /*Params=*/nullptr,
17561 /*NumParams=*/0,
17562 /*EllipsisLoc=*/NoLoc,
17563 /*RParenLoc=*/NoLoc,
17564 /*RefQualifierIsLvalueRef=*/true,
17565 /*RefQualifierLoc=*/NoLoc,
17566 /*MutableLoc=*/NoLoc, EST_None,
17567 /*ESpecRange=*/SourceRange(),
17568 /*Exceptions=*/nullptr,
17569 /*ExceptionRanges=*/nullptr,
17570 /*NumExceptions=*/0,
17571 /*NoexceptExpr=*/nullptr,
17572 /*ExceptionSpecTokens=*/nullptr,
17573 /*DeclsInPrototype=*/{}, Loc, Loc,
17574 D),
17575 std::move(DS.getAttributes()), SourceLocation());
17576 D.SetIdentifier(&II, Loc);
17577
17578 // Insert this function into the enclosing block scope.
17579 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17580 FD->setImplicit();
17581
17583
17584 return FD;
17585}
17586
17588 FunctionDecl *FD) {
17589 if (FD->isInvalidDecl())
17590 return;
17591
17592 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17593 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17594 return;
17595
17596 UnsignedOrNone AlignmentParam = std::nullopt;
17597 bool IsNothrow = false;
17598 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17599 return;
17600
17601 // C++2a [basic.stc.dynamic.allocation]p4:
17602 // An allocation function that has a non-throwing exception specification
17603 // indicates failure by returning a null pointer value. Any other allocation
17604 // function never returns a null pointer value and indicates failure only by
17605 // throwing an exception [...]
17606 //
17607 // However, -fcheck-new invalidates this possible assumption, so don't add
17608 // NonNull when that is enabled.
17609 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17610 !getLangOpts().CheckNew)
17611 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17612
17613 // C++2a [basic.stc.dynamic.allocation]p2:
17614 // An allocation function attempts to allocate the requested amount of
17615 // storage. [...] If the request succeeds, the value returned by a
17616 // replaceable allocation function is a [...] pointer value p0 different
17617 // from any previously returned value p1 [...]
17618 //
17619 // However, this particular information is being added in codegen,
17620 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17621
17622 // C++2a [basic.stc.dynamic.allocation]p2:
17623 // An allocation function attempts to allocate the requested amount of
17624 // storage. If it is successful, it returns the address of the start of a
17625 // block of storage whose length in bytes is at least as large as the
17626 // requested size.
17627 if (!FD->hasAttr<AllocSizeAttr>()) {
17628 FD->addAttr(AllocSizeAttr::CreateImplicit(
17629 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17630 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17631 }
17632
17633 // C++2a [basic.stc.dynamic.allocation]p3:
17634 // For an allocation function [...], the pointer returned on a successful
17635 // call shall represent the address of storage that is aligned as follows:
17636 // (3.1) If the allocation function takes an argument of type
17637 // std​::​align_­val_­t, the storage will have the alignment
17638 // specified by the value of this argument.
17639 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17640 FD->addAttr(AllocAlignAttr::CreateImplicit(
17641 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17642 }
17643
17644 // FIXME:
17645 // C++2a [basic.stc.dynamic.allocation]p3:
17646 // For an allocation function [...], the pointer returned on a successful
17647 // call shall represent the address of storage that is aligned as follows:
17648 // (3.2) Otherwise, if the allocation function is named operator new[],
17649 // the storage is aligned for any object that does not have
17650 // new-extended alignment ([basic.align]) and is no larger than the
17651 // requested size.
17652 // (3.3) Otherwise, the storage is aligned for any object that does not
17653 // have new-extended alignment and is of the requested size.
17654}
17655
17657 if (FD->isInvalidDecl())
17658 return;
17659
17660 // Both format and format_arg attributes require a function prototype.
17661 const bool HasPrototype = FD->getType()->isFunctionProtoType();
17662
17663 // If this is a built-in function, map its builtin attributes to
17664 // actual attributes.
17665 if (unsigned BuiltinID = FD->getBuiltinID()) {
17666 // Handle printf-formatting attributes.
17667 unsigned FormatIdx;
17668 bool HasVAListArg;
17669 if (HasPrototype &&
17670 Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17671 if (!FD->hasAttr<FormatAttr>() && FormatIdx < FD->getNumParams()) {
17672 const char *fmt = "printf";
17673 if (FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17674 fmt = "NSString";
17675 FD->addAttr(FormatAttr::CreateImplicit(Context,
17676 &Context.Idents.get(fmt),
17677 FormatIdx+1,
17678 HasVAListArg ? 0 : FormatIdx+2,
17679 FD->getLocation()));
17680 }
17681 }
17682 if (HasPrototype &&
17683 Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17684 if (!FD->hasAttr<FormatAttr>() && FormatIdx < FD->getNumParams())
17685 FD->addAttr(FormatAttr::CreateImplicit(
17686 Context, &Context.Idents.get("scanf"), FormatIdx + 1,
17687 HasVAListArg ? 0 : FormatIdx + 2, FD->getLocation()));
17688 }
17689
17690 // Handle automatically recognized callbacks.
17691 SmallVector<int, 4> Encoding;
17692 if (!FD->hasAttr<CallbackAttr>() &&
17693 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17694 FD->addAttr(CallbackAttr::CreateImplicit(
17695 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17696
17697 // Mark const if we don't care about errno and/or floating point exceptions
17698 // that are the only thing preventing the function from being const. This
17699 // allows IRgen to use LLVM intrinsics for such functions.
17700 bool NoExceptions =
17702 bool ConstWithoutErrnoAndExceptions =
17703 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17704 bool ConstWithoutExceptions =
17705 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17706 if (!FD->hasAttr<ConstAttr>() &&
17707 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17708 (!ConstWithoutErrnoAndExceptions ||
17709 (!getLangOpts().MathErrno && NoExceptions)) &&
17710 (!ConstWithoutExceptions || NoExceptions))
17711 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17712
17713 // We make "fma" on GNU or Windows const because we know it does not set
17714 // errno in those environments even though it could set errno based on the
17715 // C standard.
17716 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17717 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17718 !FD->hasAttr<ConstAttr>()) {
17719 switch (BuiltinID) {
17720 case Builtin::BI__builtin_fma:
17721 case Builtin::BI__builtin_fmaf:
17722 case Builtin::BI__builtin_fmal:
17723 case Builtin::BIfma:
17724 case Builtin::BIfmaf:
17725 case Builtin::BIfmal:
17726 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17727 break;
17728 default:
17729 break;
17730 }
17731 }
17732
17733 SmallVector<int, 4> Indxs;
17735 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17736 !FD->hasAttr<NonNullAttr>()) {
17738 for (int I : Indxs) {
17739 ParmVarDecl *PVD = FD->getParamDecl(I);
17740 QualType T = PVD->getType();
17741 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17742 PVD->setType(T);
17743 }
17744 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17746 for (int I : Indxs)
17747 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17748 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17749 ParamIndxs.size()));
17750 }
17751 }
17752 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17753 !FD->hasAttr<ReturnsTwiceAttr>())
17754 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17755 FD->getLocation()));
17756 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17757 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17758 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17759 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17760 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17761 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17762 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17763 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17764 // Add the appropriate attribute, depending on the CUDA compilation mode
17765 // and which target the builtin belongs to. For example, during host
17766 // compilation, aux builtins are __device__, while the rest are __host__.
17767 if (getLangOpts().CUDAIsDevice !=
17768 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17769 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17770 else
17771 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17772 }
17773
17774 // Add known guaranteed alignment for allocation functions.
17775 switch (BuiltinID) {
17776 case Builtin::BImemalign:
17777 case Builtin::BIaligned_alloc:
17778 if (!FD->hasAttr<AllocAlignAttr>())
17779 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17780 FD->getLocation()));
17781 break;
17782 default:
17783 break;
17784 }
17785
17786 // Add allocsize attribute for allocation functions.
17787 switch (BuiltinID) {
17788 case Builtin::BIcalloc:
17789 FD->addAttr(AllocSizeAttr::CreateImplicit(
17790 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17791 break;
17792 case Builtin::BImemalign:
17793 case Builtin::BIaligned_alloc:
17794 case Builtin::BIrealloc:
17795 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17796 ParamIdx(), FD->getLocation()));
17797 break;
17798 case Builtin::BImalloc:
17799 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17800 ParamIdx(), FD->getLocation()));
17801 break;
17802 default:
17803 break;
17804 }
17805 }
17806
17811
17812 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17813 // throw, add an implicit nothrow attribute to any extern "C" function we come
17814 // across.
17815 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17816 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17817 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17818 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17819 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17820 }
17821
17822 IdentifierInfo *Name = FD->getIdentifier();
17823 if (!Name)
17824 return;
17827 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17829 // Okay: this could be a libc/libm/Objective-C function we know
17830 // about.
17831 } else
17832 return;
17833
17834 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17835 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17836 // target-specific builtins, perhaps?
17837 if (HasPrototype && FD->getNumParams() >= 2 && !FD->hasAttr<FormatAttr>())
17838 FD->addAttr(FormatAttr::CreateImplicit(Context,
17839 &Context.Idents.get("printf"), 2,
17840 Name->isStr("vasprintf") ? 0 : 3,
17841 FD->getLocation()));
17842 }
17843
17844 if (Name->isStr("__CFStringMakeConstantString")) {
17845 // We already have a __builtin___CFStringMakeConstantString,
17846 // but builds that use -fno-constant-cfstrings don't go through that.
17847 if (HasPrototype && FD->getNumParams() >= 1 &&
17848 !FD->hasAttr<FormatArgAttr>())
17849 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17850 FD->getLocation()));
17851 }
17852}
17853
17855 TypeSourceInfo *TInfo) {
17856 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17857 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17858
17859 if (!TInfo) {
17860 assert(D.isInvalidType() && "no declarator info for valid type");
17861 TInfo = Context.getTrivialTypeSourceInfo(T);
17862 }
17863
17864 // Scope manipulation handled by caller.
17865 TypedefDecl *NewTD =
17867 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17868
17869 // Bail out immediately if we have an invalid declaration.
17870 if (D.isInvalidType()) {
17871 NewTD->setInvalidDecl();
17872 return NewTD;
17873 }
17874
17876 if (CurContext->isFunctionOrMethod())
17877 Diag(NewTD->getLocation(), diag::err_module_private_local)
17878 << 2 << NewTD
17882 else
17883 NewTD->setModulePrivate();
17884 }
17885
17886 // C++ [dcl.typedef]p8:
17887 // If the typedef declaration defines an unnamed class (or
17888 // enum), the first typedef-name declared by the declaration
17889 // to be that class type (or enum type) is used to denote the
17890 // class type (or enum type) for linkage purposes only.
17891 // We need to check whether the type was declared in the declaration.
17892 switch (D.getDeclSpec().getTypeSpecType()) {
17893 case TST_enum:
17894 case TST_struct:
17895 case TST_interface:
17896 case TST_union:
17897 case TST_class: {
17898 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17899 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17900 break;
17901 }
17902
17903 default:
17904 break;
17905 }
17906
17907 return NewTD;
17908}
17909
17911 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17912 QualType T = TI->getType();
17913
17914 if (T->isDependentType())
17915 return false;
17916
17917 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17918 // integral type; any cv-qualification is ignored.
17919 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17920 // non-atomic version of the type specified by the type specifiers in the
17921 // specifier qualifier list.
17922 // Because of how odd C's rule is, we'll let the user know that operations
17923 // involving the enumeration type will be non-atomic.
17924 if (T->isAtomicType())
17925 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17926
17927 Qualifiers Q = T.getQualifiers();
17928 std::optional<unsigned> QualSelect;
17929 if (Q.hasConst() && Q.hasVolatile())
17930 QualSelect = diag::CVQualList::Both;
17931 else if (Q.hasConst())
17932 QualSelect = diag::CVQualList::Const;
17933 else if (Q.hasVolatile())
17934 QualSelect = diag::CVQualList::Volatile;
17935
17936 if (QualSelect)
17937 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17938
17939 T = T.getAtomicUnqualifiedType();
17940
17941 // This doesn't use 'isIntegralType' despite the error message mentioning
17942 // integral type because isIntegralType would also allow enum types in C.
17943 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17944 if (BT->isInteger())
17945 return false;
17946
17947 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17948 << T << T->isBitIntType();
17949}
17950
17952 QualType EnumUnderlyingTy, bool IsFixed,
17953 const EnumDecl *Prev) {
17954 if (IsScoped != Prev->isScoped()) {
17955 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17956 << Prev->isScoped();
17957 Diag(Prev->getLocation(), diag::note_previous_declaration);
17958 return true;
17959 }
17960
17961 if (IsFixed && Prev->isFixed()) {
17962 if (!EnumUnderlyingTy->isDependentType() &&
17963 !Prev->getIntegerType()->isDependentType() &&
17964 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17965 Prev->getIntegerType())) {
17966 // TODO: Highlight the underlying type of the redeclaration.
17967 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17968 << EnumUnderlyingTy << Prev->getIntegerType();
17969 Diag(Prev->getLocation(), diag::note_previous_declaration)
17970 << Prev->getIntegerTypeRange();
17971 return true;
17972 }
17973 } else if (IsFixed != Prev->isFixed()) {
17974 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17975 << Prev->isFixed();
17976 Diag(Prev->getLocation(), diag::note_previous_declaration);
17977 return true;
17978 }
17979
17980 return false;
17981}
17982
17983/// Get diagnostic %select index for tag kind for
17984/// redeclaration diagnostic message.
17985/// WARNING: Indexes apply to particular diagnostics only!
17986///
17987/// \returns diagnostic %select index.
17989 switch (Tag) {
17991 return 0;
17993 return 1;
17994 case TagTypeKind::Class:
17995 return 2;
17996 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17997 }
17998}
17999
18000/// Determine if tag kind is a class-key compatible with
18001/// class for redeclaration (class, struct, or __interface).
18002///
18003/// \returns true iff the tag kind is compatible.
18005{
18006 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
18008}
18009
18011 if (isa<TypedefDecl>(PrevDecl))
18012 return NonTagKind::Typedef;
18013 else if (isa<TypeAliasDecl>(PrevDecl))
18014 return NonTagKind::TypeAlias;
18015 else if (isa<ClassTemplateDecl>(PrevDecl))
18016 return NonTagKind::Template;
18017 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
18019 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
18021 switch (TTK) {
18024 case TagTypeKind::Class:
18025 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
18027 case TagTypeKind::Union:
18028 return NonTagKind::NonUnion;
18029 case TagTypeKind::Enum:
18030 return NonTagKind::NonEnum;
18031 }
18032 llvm_unreachable("invalid TTK");
18033}
18034
18036 TagTypeKind NewTag, bool isDefinition,
18037 SourceLocation NewTagLoc,
18038 const IdentifierInfo *Name) {
18039 // C++ [dcl.type.elab]p3:
18040 // The class-key or enum keyword present in the
18041 // elaborated-type-specifier shall agree in kind with the
18042 // declaration to which the name in the elaborated-type-specifier
18043 // refers. This rule also applies to the form of
18044 // elaborated-type-specifier that declares a class-name or
18045 // friend class since it can be construed as referring to the
18046 // definition of the class. Thus, in any
18047 // elaborated-type-specifier, the enum keyword shall be used to
18048 // refer to an enumeration (7.2), the union class-key shall be
18049 // used to refer to a union (clause 9), and either the class or
18050 // struct class-key shall be used to refer to a class (clause 9)
18051 // declared using the class or struct class-key.
18052 TagTypeKind OldTag = Previous->getTagKind();
18053 if (OldTag != NewTag &&
18055 return false;
18056
18057 // Tags are compatible, but we might still want to warn on mismatched tags.
18058 // Non-class tags can't be mismatched at this point.
18060 return true;
18061
18062 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18063 // by our warning analysis. We don't want to warn about mismatches with (eg)
18064 // declarations in system headers that are designed to be specialized, but if
18065 // a user asks us to warn, we should warn if their code contains mismatched
18066 // declarations.
18067 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18068 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
18069 Loc);
18070 };
18071 if (IsIgnoredLoc(NewTagLoc))
18072 return true;
18073
18074 auto IsIgnored = [&](const TagDecl *Tag) {
18075 return IsIgnoredLoc(Tag->getLocation());
18076 };
18077 while (IsIgnored(Previous)) {
18078 Previous = Previous->getPreviousDecl();
18079 if (!Previous)
18080 return true;
18081 OldTag = Previous->getTagKind();
18082 }
18083
18084 bool isTemplate = false;
18085 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
18086 isTemplate = Record->getDescribedClassTemplate();
18087
18089 if (OldTag != NewTag) {
18090 // In a template instantiation, do not offer fix-its for tag mismatches
18091 // since they usually mess up the template instead of fixing the problem.
18092 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
18094 << getRedeclDiagFromTagKind(OldTag);
18095 // FIXME: Note previous location?
18096 }
18097 return true;
18098 }
18099
18100 if (isDefinition) {
18101 // On definitions, check all previous tags and issue a fix-it for each
18102 // one that doesn't match the current tag.
18103 if (Previous->getDefinition()) {
18104 // Don't suggest fix-its for redefinitions.
18105 return true;
18106 }
18107
18108 bool previousMismatch = false;
18109 for (const TagDecl *I : Previous->redecls()) {
18110 if (I->getTagKind() != NewTag) {
18111 // Ignore previous declarations for which the warning was disabled.
18112 if (IsIgnored(I))
18113 continue;
18114
18115 if (!previousMismatch) {
18116 previousMismatch = true;
18117 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
18119 << getRedeclDiagFromTagKind(I->getTagKind());
18120 }
18121 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
18123 << FixItHint::CreateReplacement(I->getInnerLocStart(),
18125 }
18126 }
18127 return true;
18128 }
18129
18130 // Identify the prevailing tag kind: this is the kind of the definition (if
18131 // there is a non-ignored definition), or otherwise the kind of the prior
18132 // (non-ignored) declaration.
18133 const TagDecl *PrevDef = Previous->getDefinition();
18134 if (PrevDef && IsIgnored(PrevDef))
18135 PrevDef = nullptr;
18136 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18137 if (Redecl->getTagKind() != NewTag) {
18138 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
18140 << getRedeclDiagFromTagKind(OldTag);
18141 Diag(Redecl->getLocation(), diag::note_previous_use);
18142
18143 // If there is a previous definition, suggest a fix-it.
18144 if (PrevDef) {
18145 Diag(NewTagLoc, diag::note_struct_class_suggestion)
18149 }
18150 }
18151
18152 return true;
18153}
18154
18155/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18156/// from an outer enclosing namespace or file scope inside a friend declaration.
18157/// This should provide the commented out code in the following snippet:
18158/// namespace N {
18159/// struct X;
18160/// namespace M {
18161/// struct Y { friend struct /*N::*/ X; };
18162/// }
18163/// }
18165 SourceLocation NameLoc) {
18166 // While the decl is in a namespace, do repeated lookup of that name and see
18167 // if we get the same namespace back. If we do not, continue until
18168 // translation unit scope, at which point we have a fully qualified NNS.
18171 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18172 // This tag should be declared in a namespace, which can only be enclosed by
18173 // other namespaces. Bail if there's an anonymous namespace in the chain.
18174 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
18175 if (!Namespace || Namespace->isAnonymousNamespace())
18176 return FixItHint();
18177 IdentifierInfo *II = Namespace->getIdentifier();
18178 Namespaces.push_back(II);
18179 NamedDecl *Lookup = SemaRef.LookupSingleName(
18180 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
18181 if (Lookup == Namespace)
18182 break;
18183 }
18184
18185 // Once we have all the namespaces, reverse them to go outermost first, and
18186 // build an NNS.
18187 SmallString<64> Insertion;
18188 llvm::raw_svector_ostream OS(Insertion);
18189 if (DC->isTranslationUnit())
18190 OS << "::";
18191 std::reverse(Namespaces.begin(), Namespaces.end());
18192 for (auto *II : Namespaces)
18193 OS << II->getName() << "::";
18194 return FixItHint::CreateInsertion(NameLoc, Insertion);
18195}
18196
18197/// Determine whether a tag originally declared in context \p OldDC can
18198/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18199/// found a declaration in \p OldDC as a previous decl, perhaps through a
18200/// using-declaration).
18202 DeclContext *NewDC) {
18203 OldDC = OldDC->getRedeclContext();
18204 NewDC = NewDC->getRedeclContext();
18205
18206 if (OldDC->Equals(NewDC))
18207 return true;
18208
18209 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18210 // encloses the other).
18211 if (S.getLangOpts().MSVCCompat &&
18212 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
18213 return true;
18214
18215 return false;
18216}
18217
18219Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18220 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18221 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18222 SourceLocation ModulePrivateLoc,
18223 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18224 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18225 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18226 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18227 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18228 // If this is not a definition, it must have a name.
18229 IdentifierInfo *OrigName = Name;
18230 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18231 "Nameless record must be a definition!");
18232 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18233
18234 OwnedDecl = false;
18236 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18237
18238 // FIXME: Check member specializations more carefully.
18239 bool isMemberSpecialization = false;
18240 bool IsInjectedClassName = false;
18241 bool Invalid = false;
18242
18243 // We only need to do this matching if we have template parameters
18244 // or a scope specifier, which also conveniently avoids this work
18245 // for non-C++ cases.
18246 if (TemplateParameterLists.size() > 0 ||
18247 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18248 TemplateParameterList *TemplateParams =
18250 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
18251 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
18252
18253 // C++23 [dcl.type.elab] p2:
18254 // If an elaborated-type-specifier is the sole constituent of a
18255 // declaration, the declaration is ill-formed unless it is an explicit
18256 // specialization, an explicit instantiation or it has one of the
18257 // following forms: [...]
18258 // C++23 [dcl.enum] p1:
18259 // If the enum-head-name of an opaque-enum-declaration contains a
18260 // nested-name-specifier, the declaration shall be an explicit
18261 // specialization.
18262 //
18263 // FIXME: Class template partial specializations can be forward declared
18264 // per CWG2213, but the resolution failed to allow qualified forward
18265 // declarations. This is almost certainly unintentional, so we allow them.
18266 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18267 !isMemberSpecialization)
18268 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
18270
18271 if (TemplateParams) {
18272 if (Kind == TagTypeKind::Enum) {
18273 Diag(KWLoc, diag::err_enum_template);
18274 return true;
18275 }
18276
18277 if (TemplateParams->size() > 0) {
18278 // This is a declaration or definition of a class template (which may
18279 // be a member of another template).
18280
18281 if (Invalid)
18282 return true;
18283
18284 OwnedDecl = false;
18286 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
18287 AS, ModulePrivateLoc,
18288 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
18289 TemplateParameterLists.data(), isMemberSpecialization, SkipBody);
18290 return Result.get();
18291 } else {
18292 // The "template<>" header is extraneous.
18293 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18294 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18295 isMemberSpecialization = true;
18296 }
18297 }
18298
18299 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18300 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18301 return true;
18302 }
18303
18304 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18305 // C++23 [dcl.type.elab]p4:
18306 // If an elaborated-type-specifier appears with the friend specifier as
18307 // an entire member-declaration, the member-declaration shall have one
18308 // of the following forms:
18309 // friend class-key nested-name-specifier(opt) identifier ;
18310 // friend class-key simple-template-id ;
18311 // friend class-key nested-name-specifier template(opt)
18312 // simple-template-id ;
18313 //
18314 // Since enum is not a class-key, so declarations like "friend enum E;"
18315 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18316 // invalid, most implementations accept so we issue a pedantic warning.
18317 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18318 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18319 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18320 Diag(KWLoc, diag::note_enum_friend)
18321 << (ScopedEnum + ScopedEnumUsesClassTag);
18322 }
18323
18324 // Figure out the underlying type if this a enum declaration. We need to do
18325 // this early, because it's needed to detect if this is an incompatible
18326 // redeclaration.
18327 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18328 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18329
18330 if (Kind == TagTypeKind::Enum) {
18331 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18332 Invalid) {
18333 // No underlying type explicitly specified, or we failed to parse the
18334 // type, default to int.
18335 EnumUnderlying = Context.IntTy.getTypePtr();
18336 } else if (UnderlyingType.get()) {
18337 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18338 // integral type; any cv-qualification is ignored.
18339 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18340 // unqualified, non-atomic version of the type specified by the type
18341 // specifiers in the specifier qualifier list.
18342 TypeSourceInfo *TI = nullptr;
18343 GetTypeFromParser(UnderlyingType.get(), &TI);
18344 EnumUnderlying = TI;
18345
18347 // Recover by falling back to int.
18348 EnumUnderlying = Context.IntTy.getTypePtr();
18349
18352 EnumUnderlying = Context.IntTy.getTypePtr();
18353
18354 // If the underlying type is atomic, we need to adjust the type before
18355 // continuing. This only happens in the case we stored a TypeSourceInfo
18356 // into EnumUnderlying because the other cases are error recovery up to
18357 // this point. But because it's not possible to gin up a TypeSourceInfo
18358 // for a non-atomic type from an atomic one, we'll store into the Type
18359 // field instead. FIXME: it would be nice to have an easy way to get a
18360 // derived TypeSourceInfo which strips qualifiers including the weird
18361 // ones like _Atomic where it forms a different type.
18362 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18363 TI && TI->getType()->isAtomicType())
18364 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18365
18366 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18367 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18368 // of 'int'. However, if this is an unfixed forward declaration, don't set
18369 // the underlying type unless the user enables -fms-compatibility. This
18370 // makes unfixed forward declared enums incomplete and is more conforming.
18371 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18372 EnumUnderlying = Context.IntTy.getTypePtr();
18373 }
18374 }
18375
18376 DeclContext *SearchDC = CurContext;
18377 DeclContext *DC = CurContext;
18378 bool isStdBadAlloc = false;
18379 bool isStdAlignValT = false;
18380
18382 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18384
18385 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18386 /// implemented asks for structural equivalence checking, the returned decl
18387 /// here is passed back to the parser, allowing the tag body to be parsed.
18388 auto createTagFromNewDecl = [&]() -> TagDecl * {
18389 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18390 // If there is an identifier, use the location of the identifier as the
18391 // location of the decl, otherwise use the location of the struct/union
18392 // keyword.
18393 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18394 TagDecl *New = nullptr;
18395
18396 if (Kind == TagTypeKind::Enum) {
18397 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18398 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18399 // If this is an undefined enum, bail.
18400 if (TUK != TagUseKind::Definition && !Invalid)
18401 return nullptr;
18402 if (EnumUnderlying) {
18404 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18406 else
18407 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18408 QualType EnumTy = ED->getIntegerType();
18409 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18410 ? Context.getPromotedIntegerType(EnumTy)
18411 : EnumTy);
18412 }
18413 } else { // struct/union
18414 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18415 nullptr);
18416 }
18417
18418 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18419 // Add alignment attributes if necessary; these attributes are checked
18420 // when the ASTContext lays out the structure.
18421 //
18422 // It is important for implementing the correct semantics that this
18423 // happen here (in ActOnTag). The #pragma pack stack is
18424 // maintained as a result of parser callbacks which can occur at
18425 // many points during the parsing of a struct declaration (because
18426 // the #pragma tokens are effectively skipped over during the
18427 // parsing of the struct).
18428 if (TUK == TagUseKind::Definition &&
18429 (!SkipBody || !SkipBody->ShouldSkip)) {
18430 if (LangOpts.HLSL)
18431 RD->addAttr(PackedAttr::CreateImplicit(Context));
18434 }
18435 }
18436 New->setLexicalDeclContext(CurContext);
18437 return New;
18438 };
18439
18440 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18441 if (Name && SS.isNotEmpty()) {
18442 // We have a nested-name tag ('struct foo::bar').
18443
18444 // Check for invalid 'foo::'.
18445 if (SS.isInvalid()) {
18446 Name = nullptr;
18447 goto CreateNewDecl;
18448 }
18449
18450 // If this is a friend or a reference to a class in a dependent
18451 // context, don't try to make a decl for it.
18452 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18453 DC = computeDeclContext(SS, false);
18454 if (!DC) {
18455 IsDependent = true;
18456 return true;
18457 }
18458 } else {
18459 DC = computeDeclContext(SS, true);
18460 if (!DC) {
18461 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18462 << SS.getRange();
18463 return true;
18464 }
18465 }
18466
18467 if (RequireCompleteDeclContext(SS, DC))
18468 return true;
18469
18470 SearchDC = DC;
18471 // Look-up name inside 'foo::'.
18473
18474 if (Previous.isAmbiguous())
18475 return true;
18476
18477 if (Previous.empty()) {
18478 // Name lookup did not find anything. However, if the
18479 // nested-name-specifier refers to the current instantiation,
18480 // and that current instantiation has any dependent base
18481 // classes, we might find something at instantiation time: treat
18482 // this as a dependent elaborated-type-specifier.
18483 // But this only makes any sense for reference-like lookups.
18484 if (Previous.wasNotFoundInCurrentInstantiation() &&
18485 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18486 IsDependent = true;
18487 return true;
18488 }
18489
18490 // A tag 'foo::bar' must already exist.
18491 Diag(NameLoc, diag::err_not_tag_in_scope)
18492 << Kind << Name << DC << SS.getRange();
18493 Name = nullptr;
18494 Invalid = true;
18495 goto CreateNewDecl;
18496 }
18497 } else if (Name) {
18498 // C++14 [class.mem]p14:
18499 // If T is the name of a class, then each of the following shall have a
18500 // name different from T:
18501 // -- every member of class T that is itself a type
18502 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18503 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18504 return true;
18505
18506 // If this is a named struct, check to see if there was a previous forward
18507 // declaration or definition.
18508 // FIXME: We're looking into outer scopes here, even when we
18509 // shouldn't be. Doing so can result in ambiguities that we
18510 // shouldn't be diagnosing.
18511 LookupName(Previous, S);
18512
18513 // When declaring or defining a tag, ignore ambiguities introduced
18514 // by types using'ed into this scope.
18515 if (Previous.isAmbiguous() &&
18517 LookupResult::Filter F = Previous.makeFilter();
18518 while (F.hasNext()) {
18519 NamedDecl *ND = F.next();
18520 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18521 SearchDC->getRedeclContext()))
18522 F.erase();
18523 }
18524 F.done();
18525 }
18526
18527 // C++11 [namespace.memdef]p3:
18528 // If the name in a friend declaration is neither qualified nor
18529 // a template-id and the declaration is a function or an
18530 // elaborated-type-specifier, the lookup to determine whether
18531 // the entity has been previously declared shall not consider
18532 // any scopes outside the innermost enclosing namespace.
18533 //
18534 // MSVC doesn't implement the above rule for types, so a friend tag
18535 // declaration may be a redeclaration of a type declared in an enclosing
18536 // scope. They do implement this rule for friend functions.
18537 //
18538 // Does it matter that this should be by scope instead of by
18539 // semantic context?
18540 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18541 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18542 LookupResult::Filter F = Previous.makeFilter();
18543 bool FriendSawTagOutsideEnclosingNamespace = false;
18544 while (F.hasNext()) {
18545 NamedDecl *ND = F.next();
18547 if (DC->isFileContext() &&
18548 !EnclosingNS->Encloses(ND->getDeclContext())) {
18549 if (getLangOpts().MSVCCompat)
18550 FriendSawTagOutsideEnclosingNamespace = true;
18551 else
18552 F.erase();
18553 }
18554 }
18555 F.done();
18556
18557 // Diagnose this MSVC extension in the easy case where lookup would have
18558 // unambiguously found something outside the enclosing namespace.
18559 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18560 NamedDecl *ND = Previous.getFoundDecl();
18561 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18562 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18563 }
18564 }
18565
18566 // Note: there used to be some attempt at recovery here.
18567 if (Previous.isAmbiguous())
18568 return true;
18569
18570 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18571 // FIXME: This makes sure that we ignore the contexts associated
18572 // with C structs, unions, and enums when looking for a matching
18573 // tag declaration or definition. See the similar lookup tweak
18574 // in Sema::LookupName; is there a better way to deal with this?
18576 SearchDC = SearchDC->getParent();
18577 } else if (getLangOpts().CPlusPlus) {
18578 // Inside ObjCContainer want to keep it as a lexical decl context but go
18579 // past it (most often to TranslationUnit) to find the semantic decl
18580 // context.
18581 while (isa<ObjCContainerDecl>(SearchDC))
18582 SearchDC = SearchDC->getParent();
18583 }
18584 } else if (getLangOpts().CPlusPlus) {
18585 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18586 // TagDecl the same way as we skip it for named TagDecl.
18587 while (isa<ObjCContainerDecl>(SearchDC))
18588 SearchDC = SearchDC->getParent();
18589 }
18590
18591 if (Previous.isSingleResult() &&
18592 Previous.getFoundDecl()->isTemplateParameter()) {
18593 // Maybe we will complain about the shadowed template parameter.
18594 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18595 // Just pretend that we didn't see the previous declaration.
18596 Previous.clear();
18597 }
18598
18599 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18601 if (Name->isStr("bad_alloc")) {
18602 // This is a declaration of or a reference to "std::bad_alloc".
18603 isStdBadAlloc = true;
18604
18605 // If std::bad_alloc has been implicitly declared (but made invisible to
18606 // name lookup), fill in this implicit declaration as the previous
18607 // declaration, so that the declarations get chained appropriately.
18608 if (Previous.empty() && StdBadAlloc)
18609 Previous.addDecl(getStdBadAlloc());
18610 } else if (Name->isStr("align_val_t")) {
18611 isStdAlignValT = true;
18612 if (Previous.empty() && StdAlignValT)
18613 Previous.addDecl(getStdAlignValT());
18614 }
18615 }
18616
18617 // If we didn't find a previous declaration, and this is a reference
18618 // (or friend reference), move to the correct scope. In C++, we
18619 // also need to do a redeclaration lookup there, just in case
18620 // there's a shadow friend decl.
18621 if (Name && Previous.empty() &&
18622 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18623 IsTemplateParamOrArg)) {
18624 if (Invalid) goto CreateNewDecl;
18625 assert(SS.isEmpty());
18626
18627 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18628 // C++ [basic.scope.pdecl]p5:
18629 // -- for an elaborated-type-specifier of the form
18630 //
18631 // class-key identifier
18632 //
18633 // if the elaborated-type-specifier is used in the
18634 // decl-specifier-seq or parameter-declaration-clause of a
18635 // function defined in namespace scope, the identifier is
18636 // declared as a class-name in the namespace that contains
18637 // the declaration; otherwise, except as a friend
18638 // declaration, the identifier is declared in the smallest
18639 // non-class, non-function-prototype scope that contains the
18640 // declaration.
18641 //
18642 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18643 // C structs and unions.
18644 //
18645 // It is an error in C++ to declare (rather than define) an enum
18646 // type, including via an elaborated type specifier. We'll
18647 // diagnose that later; for now, declare the enum in the same
18648 // scope as we would have picked for any other tag type.
18649 //
18650 // GNU C also supports this behavior as part of its incomplete
18651 // enum types extension, while GNU C++ does not.
18652 //
18653 // Find the context where we'll be declaring the tag.
18654 // FIXME: We would like to maintain the current DeclContext as the
18655 // lexical context,
18656 SearchDC = getTagInjectionContext(SearchDC);
18657
18658 // Find the scope where we'll be declaring the tag.
18660 } else {
18661 assert(TUK == TagUseKind::Friend);
18662 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18663
18664 // C++ [namespace.memdef]p3:
18665 // If a friend declaration in a non-local class first declares a
18666 // class or function, the friend class or function is a member of
18667 // the innermost enclosing namespace.
18668 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18669 : SearchDC->getEnclosingNamespaceContext();
18670 }
18671
18672 // In C++, we need to do a redeclaration lookup to properly
18673 // diagnose some problems.
18674 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18675 // hidden declaration so that we don't get ambiguity errors when using a
18676 // type declared by an elaborated-type-specifier. In C that is not correct
18677 // and we should instead merge compatible types found by lookup.
18678 if (getLangOpts().CPlusPlus) {
18679 // FIXME: This can perform qualified lookups into function contexts,
18680 // which are meaningless.
18681 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18682 LookupQualifiedName(Previous, SearchDC);
18683 } else {
18684 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18685 LookupName(Previous, S);
18686 }
18687 }
18688
18689 // If we have a known previous declaration to use, then use it.
18690 if (Previous.empty() && SkipBody && SkipBody->Previous)
18691 Previous.addDecl(SkipBody->Previous);
18692
18693 if (!Previous.empty()) {
18694 NamedDecl *PrevDecl = Previous.getFoundDecl();
18695 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18696
18697 // It's okay to have a tag decl in the same scope as a typedef
18698 // which hides a tag decl in the same scope. Finding this
18699 // with a redeclaration lookup can only actually happen in C++.
18700 //
18701 // This is also okay for elaborated-type-specifiers, which is
18702 // technically forbidden by the current standard but which is
18703 // okay according to the likely resolution of an open issue;
18704 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18705 if (getLangOpts().CPlusPlus) {
18706 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18707 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18708 if (Tag->getDeclName() == Name &&
18709 Tag->getDeclContext()->getRedeclContext()
18710 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18711 PrevDecl = Tag;
18712 Previous.clear();
18713 Previous.addDecl(Tag);
18714 Previous.resolveKind();
18715 }
18716 }
18717 }
18718 }
18719
18720 // If this is a redeclaration of a using shadow declaration, it must
18721 // declare a tag in the same context. In MSVC mode, we allow a
18722 // redefinition if either context is within the other.
18723 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18724 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18725 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18726 TUK != TagUseKind::Friend &&
18727 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18728 !(OldTag && isAcceptableTagRedeclContext(
18729 *this, OldTag->getDeclContext(), SearchDC))) {
18730 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18731 Diag(Shadow->getTargetDecl()->getLocation(),
18732 diag::note_using_decl_target);
18733 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18734 << 0;
18735 // Recover by ignoring the old declaration.
18736 Previous.clear();
18737 goto CreateNewDecl;
18738 }
18739 }
18740
18741 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18742 // If this is a use of a previous tag, or if the tag is already declared
18743 // in the same scope (so that the definition/declaration completes or
18744 // rementions the tag), reuse the decl.
18745 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18746 isTagRedeclarationInScope(DirectPrevDecl, SearchDC, S,
18747 SS.isNotEmpty() ||
18748 isMemberSpecialization)) {
18749
18750 if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18751 RD && RD->isInjectedClassName()) {
18752 // If lookup found the injected class name, the previous declaration
18753 // is the class being injected into.
18754 Previous.clear();
18755 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(RD->getDeclContext());
18756 Previous.addDecl(PrevDecl);
18757 Previous.resolveKind();
18758 IsInjectedClassName = true;
18759 }
18760
18761 // Make sure that this wasn't declared as an enum and now used as a
18762 // struct or something similar.
18763 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18764 TUK == TagUseKind::Definition, KWLoc,
18765 Name)) {
18766 bool SafeToContinue =
18767 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18768 Kind != TagTypeKind::Enum);
18769 if (SafeToContinue)
18770 Diag(KWLoc, diag::err_use_with_wrong_tag)
18771 << Name
18773 PrevTagDecl->getKindName());
18774 else
18775 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18776 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18777
18778 if (SafeToContinue)
18779 Kind = PrevTagDecl->getTagKind();
18780 else {
18781 // Recover by making this an anonymous redefinition.
18782 Name = nullptr;
18783 Previous.clear();
18784 Invalid = true;
18785 }
18786 }
18787
18788 if (Kind == TagTypeKind::Enum &&
18789 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18790 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18791 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18792 return PrevTagDecl;
18793
18794 QualType EnumUnderlyingTy;
18795 if (TypeSourceInfo *TI =
18796 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18797 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18798 else if (const Type *T =
18799 dyn_cast_if_present<const Type *>(EnumUnderlying))
18800 EnumUnderlyingTy = QualType(T, 0);
18801
18802 // All conflicts with previous declarations are recovered by
18803 // returning the previous declaration, unless this is a definition,
18804 // in which case we want the caller to bail out.
18805 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18806 ScopedEnum, EnumUnderlyingTy,
18807 IsFixed, PrevEnum))
18808 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18809 }
18810
18811 // C++11 [class.mem]p1:
18812 // A member shall not be declared twice in the member-specification,
18813 // except that a nested class or member class template can be declared
18814 // and then later defined.
18815 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18816 S->isDeclScope(PrevDecl)) {
18817 Diag(NameLoc, diag::ext_member_redeclared);
18818 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18819 }
18820
18821 // C++ [class.local]p3:
18822 // A class nested within a local class is a local class. A member of
18823 // a local class X shall be declared only in the definition of X or,
18824 // if the member is a nested class, in the nearest enclosing block
18825 // scope of X.
18826 if (TUK == TagUseKind::Definition && SS.isValid()) {
18827 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(PrevDecl)) {
18828 while (const auto *ParentClass =
18829 dyn_cast<CXXRecordDecl>(OutermostClass->getParent()))
18830 OutermostClass = ParentClass;
18831
18832 if (OutermostClass->isLocalClass() &&
18833 !S->isDeclScope(OutermostClass)) {
18834 Diag(NameLoc, diag::err_local_nested_class_invalid_scope)
18835 << Name << OutermostClass;
18836 Diag(OutermostClass->getLocation(), diag::note_defined_here)
18837 << OutermostClass;
18838 }
18839 }
18840 }
18841
18842 if (!Invalid) {
18843 // If this is a use, just return the declaration we found, unless
18844 // we have attributes.
18845 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18846 if (!Attrs.empty()) {
18847 // FIXME: Diagnose these attributes. For now, we create a new
18848 // declaration to hold them.
18849 } else if (TUK == TagUseKind::Reference &&
18850 (PrevTagDecl->getFriendObjectKind() ==
18852 PrevDecl->getOwningModule() != getCurrentModule()) &&
18853 SS.isEmpty()) {
18854 // This declaration is a reference to an existing entity, but
18855 // has different visibility from that entity: it either makes
18856 // a friend visible or it makes a type visible in a new module.
18857 // In either case, create a new declaration. We only do this if
18858 // the declaration would have meant the same thing if no prior
18859 // declaration were found, that is, if it was found in the same
18860 // scope where we would have injected a declaration.
18861 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18862 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18863 return PrevTagDecl;
18864 // This is in the injected scope, create a new declaration in
18865 // that scope.
18867 } else {
18868 return PrevTagDecl;
18869 }
18870 }
18871
18872 // Diagnose attempts to redefine a tag.
18873 if (TUK == TagUseKind::Definition) {
18874 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18875 // If the type is currently being defined, complain
18876 // about a nested redefinition.
18877 if (Def->isBeingDefined()) {
18878 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18879 Diag(PrevTagDecl->getLocation(),
18880 diag::note_previous_definition);
18881 Name = nullptr;
18882 Previous.clear();
18883 Invalid = true;
18884 } else {
18885 // If we're defining a specialization and the previous
18886 // definition is from an implicit instantiation, don't emit an
18887 // error here; we'll catch this in the general case below.
18888 bool IsExplicitSpecializationAfterInstantiation = false;
18889 if (isMemberSpecialization) {
18890 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18891 IsExplicitSpecializationAfterInstantiation =
18892 RD->getTemplateSpecializationKind() !=
18894 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18895 IsExplicitSpecializationAfterInstantiation =
18896 ED->getTemplateSpecializationKind() !=
18898 }
18899
18900 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18901 // do not keep more that one definition around (merge them).
18902 // However, ensure the decl passes the structural compatibility
18903 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18904 NamedDecl *Hidden = nullptr;
18905 bool HiddenDefVisible = false;
18906 if (SkipBody && (isRedefinitionAllowedFor(Def, NameLoc, &Hidden,
18907 HiddenDefVisible) ||
18908 getLangOpts().C23)) {
18909 // There is a definition of this tag, but it is not visible.
18910 // We explicitly make use of C++'s one definition rule here,
18911 // and assume that this definition is identical to the hidden
18912 // one we already have. Make the existing definition visible
18913 // and use it in place of this one.
18914 if (!getLangOpts().CPlusPlus) {
18915 // Postpone making the old definition visible until after we
18916 // complete parsing the new one and do the structural
18917 // comparison.
18918 SkipBody->CheckSameAsPrevious = true;
18919 SkipBody->New = createTagFromNewDecl();
18920 SkipBody->Previous = Def;
18921
18922 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18923 return Def;
18924 }
18925
18926 SkipBody->ShouldSkip = true;
18927 SkipBody->Previous = Def;
18928 if (!HiddenDefVisible && Hidden)
18930 // Carry on and handle it like a normal definition. We'll
18931 // skip starting the definition later.
18932
18933 } else if (!IsExplicitSpecializationAfterInstantiation) {
18934 // A redeclaration in function prototype scope in C isn't
18935 // visible elsewhere, so merely issue a warning.
18936 if (!getLangOpts().CPlusPlus &&
18938 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18939 << Name;
18940 else
18941 Diag(NameLoc, diag::err_redefinition) << Name;
18943 NameLoc.isValid() ? NameLoc : KWLoc);
18944 // If this is a redefinition, recover by making this
18945 // struct be anonymous, which will make any later
18946 // references get the previous definition.
18947 Name = nullptr;
18948 Previous.clear();
18949 Invalid = true;
18950 }
18951 }
18952 }
18953
18954 // Okay, this is definition of a previously declared or referenced
18955 // tag. We're going to create a new Decl for it.
18956 }
18957
18958 // Qualified lookup can find a tag in an inline namespace. Its
18959 // redeclaration belongs to that namespace, which need not be the
18960 // context named by the qualifier.
18961 if (SS.isNotEmpty())
18962 SearchDC = PrevTagDecl->getDeclContext();
18963
18964 // Okay, we're going to make a redeclaration. If this is some kind
18965 // of reference, make sure we build the redeclaration in the same DC
18966 // as the original, and ignore the current access specifier.
18967 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18968 IsInjectedClassName) {
18969 SearchDC = PrevTagDecl->getDeclContext();
18970 AS = AS_none;
18971 }
18972 }
18973 // If we get here we have (another) forward declaration or we
18974 // have a definition. Just create a new decl.
18975
18976 } else {
18977 // If we get here, this is a definition of a new tag type in a nested
18978 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18979 // new decl/type. We set PrevDecl to NULL so that the entities
18980 // have distinct types.
18981 Previous.clear();
18982 }
18983 // If we get here, we're going to create a new Decl. If PrevDecl
18984 // is non-NULL, it's a definition of the tag declared by
18985 // PrevDecl. If it's NULL, we have a new definition.
18986
18987 // Otherwise, PrevDecl is not a tag, but was found with tag
18988 // lookup. This is only actually possible in C++, where a few
18989 // things like templates still live in the tag namespace.
18990 } else {
18991 // Use a better diagnostic if an elaborated-type-specifier
18992 // found the wrong kind of type on the first
18993 // (non-redeclaration) lookup.
18994 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18995 !Previous.isForRedeclaration()) {
18996 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18997 Diag(NameLoc, diag::err_tag_reference_non_tag)
18998 << PrevDecl << NTK << Kind;
18999 Diag(PrevDecl->getLocation(), diag::note_declared_at);
19000 Invalid = true;
19001
19002 // Otherwise, only diagnose if the declaration is in scope.
19003 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
19004 SS.isNotEmpty() || isMemberSpecialization)) {
19005 // do nothing
19006
19007 // Diagnose implicit declarations introduced by elaborated types.
19008 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
19009 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
19010 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
19011 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
19012 Invalid = true;
19013
19014 // Otherwise it's a declaration. Call out a particularly common
19015 // case here.
19016 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
19017 unsigned Kind = 0;
19018 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
19019 Diag(NameLoc, diag::err_tag_definition_of_typedef)
19020 << Name << Kind << TND->getUnderlyingType();
19021 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
19022 Invalid = true;
19023
19024 // Otherwise, diagnose.
19025 } else {
19026 // The tag name clashes with something else in the target scope,
19027 // issue an error and recover by making this tag be anonymous.
19028 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
19029 notePreviousDefinition(PrevDecl, NameLoc);
19030 Name = nullptr;
19031 Invalid = true;
19032 }
19033
19034 // The existing declaration isn't relevant to us; we're in a
19035 // new scope, so clear out the previous declaration.
19036 Previous.clear();
19037 }
19038 }
19039
19040CreateNewDecl:
19041
19042 TagDecl *PrevDecl = nullptr;
19043 if (Previous.isSingleResult())
19044 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
19045
19046 // If there is an identifier, use the location of the identifier as the
19047 // location of the decl, otherwise use the location of the struct/union
19048 // keyword.
19049 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
19050
19051 // Otherwise, create a new declaration. If there is a previous
19052 // declaration of the same entity, the two will be linked via
19053 // PrevDecl.
19054 TagDecl *New;
19055
19056 if (Kind == TagTypeKind::Enum) {
19057 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19058 // enum X { A, B, C } D; D should chain to X.
19059 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
19060 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
19061 ScopedEnumUsesClassTag, IsFixed);
19062
19065 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19066
19067 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19069
19070 // If this is an undefined enum, warn.
19071 if (TUK != TagUseKind::Definition && !Invalid) {
19072 TagDecl *Def;
19073 if (IsFixed && ED->isFixed()) {
19074 // C++0x: 7.2p2: opaque-enum-declaration.
19075 // Conflicts are diagnosed above. Do nothing.
19076 } else if (PrevDecl &&
19077 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
19078 Diag(Loc, diag::ext_forward_ref_enum_def)
19079 << New;
19080 Diag(Def->getLocation(), diag::note_previous_definition);
19081 } else {
19082 unsigned DiagID = diag::ext_forward_ref_enum;
19083 if (getLangOpts().MSVCCompat)
19084 DiagID = diag::ext_ms_forward_ref_enum;
19085 else if (getLangOpts().CPlusPlus)
19086 DiagID = diag::err_forward_ref_enum;
19087 Diag(Loc, DiagID);
19088 }
19089 }
19090
19091 if (EnumUnderlying) {
19093 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
19095 else
19096 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
19097 QualType EnumTy = ED->getIntegerType();
19098 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
19099 ? Context.getPromotedIntegerType(EnumTy)
19100 : EnumTy);
19101 assert(ED->isComplete() && "enum with type should be complete");
19102 }
19103 } else {
19104 // struct/union/class
19105
19106 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19107 // struct X { int A; } D; D should chain to X.
19108 if (getLangOpts().CPlusPlus) {
19109 // FIXME: Look for a way to use RecordDecl for simple structs.
19110 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
19111 cast_or_null<CXXRecordDecl>(PrevDecl));
19112
19113 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19115 } else
19116 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
19117 cast_or_null<RecordDecl>(PrevDecl));
19118 }
19119
19120 // Only C23 and later allow defining new types in 'offsetof()'.
19121 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19123 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
19124 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19125
19126 // C++11 [dcl.type]p3:
19127 // A type-specifier-seq shall not define a class or enumeration [...].
19128 if (!Invalid && getLangOpts().CPlusPlus &&
19129 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19130 TUK == TagUseKind::Definition) {
19131 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
19132 << Context.getCanonicalTagType(New);
19133 Invalid = true;
19134 }
19135
19137 DC->getDeclKind() == Decl::Enum) {
19138 Diag(New->getLocation(), diag::err_type_defined_in_enum)
19139 << Context.getCanonicalTagType(New);
19140 Invalid = true;
19141 }
19142
19143 // Maybe add qualifier info.
19144 if (SS.isNotEmpty()) {
19145 if (SS.isSet()) {
19146 // If this is either a declaration or a definition, check the
19147 // nested-name-specifier against the current context.
19148 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19149 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
19150 /*TemplateId=*/nullptr,
19151 isMemberSpecialization))
19152 Invalid = true;
19153
19154 New->setQualifierInfo(SS.getWithLocInContext(Context));
19155 if (TemplateParameterLists.size() > 0) {
19156 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
19157 }
19158 }
19159 else
19160 Invalid = true;
19161 }
19162
19163 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
19164 // Add alignment attributes if necessary; these attributes are checked when
19165 // the ASTContext lays out the structure.
19166 //
19167 // It is important for implementing the correct semantics that this
19168 // happen here (in ActOnTag). The #pragma pack stack is
19169 // maintained as a result of parser callbacks which can occur at
19170 // many points during the parsing of a struct declaration (because
19171 // the #pragma tokens are effectively skipped over during the
19172 // parsing of the struct).
19173 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19174 if (LangOpts.HLSL)
19175 RD->addAttr(PackedAttr::CreateImplicit(Context));
19178 }
19179
19180 // The __interface tag implies __declspec(novtable) according to MSDN:
19181 // https://learn.microsoft.com/en-us/cpp/cpp/interface?view=msvc-170
19182 // so add the implicit attribute now.
19183 if (Kind == TagTypeKind::Interface)
19184 RD->addAttr(MSNoVTableAttr::CreateImplicit(Context));
19185 }
19186
19187 if (ModulePrivateLoc.isValid()) {
19188 if (isMemberSpecialization)
19189 Diag(New->getLocation(), diag::err_module_private_specialization)
19190 << 2
19191 << FixItHint::CreateRemoval(ModulePrivateLoc);
19192 // __module_private__ does not apply to local classes. However, we only
19193 // diagnose this as an error when the declaration specifiers are
19194 // freestanding. Here, we just ignore the __module_private__.
19195 else if (!SearchDC->isFunctionOrMethod())
19196 New->setModulePrivate();
19197 }
19198
19199 // If this is a specialization of a member class (of a class template),
19200 // check the specialization.
19201 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
19202 Invalid = true;
19203
19204 // If we're declaring or defining a tag in function prototype scope in C,
19205 // note that this type can only be used within the function and add it to
19206 // the list of decls to inject into the function definition scope. However,
19207 // in C23 and later, while the type is only visible within the function, the
19208 // function can be called with a compatible type defined in the same TU, so
19209 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19210 if ((Name || Kind == TagTypeKind::Enum) &&
19211 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19212 if (getLangOpts().CPlusPlus) {
19213 // C++ [dcl.fct]p6:
19214 // Types shall not be defined in return or parameter types.
19215 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19216 Diag(Loc, diag::err_type_defined_in_param_type)
19217 << Name;
19218 Invalid = true;
19219 }
19220 if (TUK == TagUseKind::Declaration)
19221 Invalid = true;
19222 } else if (!PrevDecl) {
19223 // In C23 mode, if the declaration is complete, we do not want to
19224 // diagnose.
19225 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19226 Diag(Loc, diag::warn_decl_in_param_list)
19227 << Context.getCanonicalTagType(New);
19228 }
19229 }
19230
19231 if (Invalid)
19232 New->setInvalidDecl();
19233
19234 // Set the lexical context. If the tag has a C++ scope specifier, the
19235 // lexical context will be different from the semantic context.
19236 New->setLexicalDeclContext(CurContext);
19237
19238 // Mark this as a friend decl if applicable.
19239 // In Microsoft mode, a friend declaration also acts as a forward
19240 // declaration so we always pass true to setObjectOfFriendDecl to make
19241 // the tag name visible.
19242 if (TUK == TagUseKind::Friend)
19243 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19244
19245 // Set the access specifier.
19246 if (!Invalid && SearchDC->isRecord())
19247 SetMemberAccessSpecifier(New, PrevDecl, AS);
19248
19249 // FIXME: An elaborated-type-specifier referring to an existing tag should
19250 // ideally not introduce a redeclaration. ActOnTag currently creates one, so
19251 // avoid diagnosing it as a redeclaration across module boundaries.
19252 //
19253 // See https://github.com/llvm/llvm-project/pull/194546 for full background.
19254 if (PrevDecl && TUK != TagUseKind::Reference)
19256
19257 if (TUK == TagUseKind::Definition) {
19258 if (!SkipBody || !SkipBody->ShouldSkip) {
19259 New->startDefinition();
19260 } else {
19261 New->setCompleteDefinition();
19262 New->demoteThisDefinitionToDeclaration();
19263 }
19264 }
19265
19266 ProcessDeclAttributeList(S, New, Attrs);
19268
19269 // If this has an identifier, add it to the scope stack.
19270 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19271 // We might be replacing an existing declaration in the lookup tables;
19272 // if so, borrow its access specifier.
19273 if (PrevDecl)
19274 New->setAccess(PrevDecl->getAccess());
19275
19276 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19278 if (Name) // can be null along some error paths
19279 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19280 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
19281 } else if (Name) {
19282 S = getNonFieldDeclScope(S);
19283 PushOnScopeChains(New, S, true);
19284 } else {
19285 CurContext->addDecl(New);
19286 }
19287
19288 // If this is the C FILE type, notify the AST context.
19289 if (IdentifierInfo *II = New->getIdentifier())
19290 if (!New->isInvalidDecl() &&
19291 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19292 II->isStr("FILE"))
19293 Context.setFILEDecl(New);
19294
19295 if (PrevDecl)
19296 mergeDeclAttributes(New, PrevDecl);
19297
19298 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
19301 }
19302
19303 // If there's a #pragma GCC visibility in scope, set the visibility of this
19304 // record.
19306
19307 // If this is not a definition, process API notes for it now.
19308 if (TUK != TagUseKind::Definition)
19310
19311 if (isMemberSpecialization && !New->isInvalidDecl())
19313
19314 OwnedDecl = true;
19315 // In C++, don't return an invalid declaration. We can't recover well from
19316 // the cases where we make the type anonymous.
19317 if (Invalid && getLangOpts().CPlusPlus) {
19318 if (New->isBeingDefined())
19319 if (auto RD = dyn_cast<RecordDecl>(New))
19320 RD->completeDefinition();
19321 return true;
19322 } else if (SkipBody && SkipBody->ShouldSkip) {
19323 return SkipBody->Previous;
19324 } else {
19325 return New;
19326 }
19327}
19328
19331 TagDecl *Tag = cast<TagDecl>(TagD);
19332
19333 // Enter the tag context.
19334 PushDeclContext(S, Tag);
19335
19337
19338 // If there's a #pragma GCC visibility in scope, set the visibility of this
19339 // record.
19341}
19342
19344 SkipBodyInfo &SkipBody) {
19345 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19346 return false;
19347
19348 // Make the previous decl visible.
19350 CleanupMergedEnum(S, SkipBody.New);
19351 return true;
19352}
19353
19355 SourceLocation FinalLoc,
19356 bool IsFinalSpelledSealed,
19357 bool IsAbstract,
19358 SourceLocation LBraceLoc) {
19361
19362 FieldCollector->StartClass();
19363
19364 if (!Record->getIdentifier())
19365 return;
19366
19367 if (IsAbstract)
19368 Record->markAbstract();
19369
19370 if (FinalLoc.isValid()) {
19371 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19372 IsFinalSpelledSealed
19373 ? FinalAttr::Keyword_sealed
19374 : FinalAttr::Keyword_final));
19375 }
19376
19377 // C++ [class]p2:
19378 // [...] The class-name is also inserted into the scope of the
19379 // class itself; this is known as the injected-class-name. For
19380 // purposes of access checking, the injected-class-name is treated
19381 // as if it were a public member name.
19382 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19383 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19384 Record->getLocation(), Record->getIdentifier());
19385 InjectedClassName->setImplicit();
19386 InjectedClassName->setAccess(AS_public);
19387 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19388 InjectedClassName->setDescribedClassTemplate(Template);
19389
19390 PushOnScopeChains(InjectedClassName, S);
19391 assert(InjectedClassName->isInjectedClassName() &&
19392 "Broken injected-class-name");
19393}
19394
19396 SourceRange BraceRange) {
19398 TagDecl *Tag = cast<TagDecl>(TagD);
19399 Tag->setBraceRange(BraceRange);
19400
19401 // Make sure we "complete" the definition even it is invalid.
19402 if (Tag->isBeingDefined()) {
19403 assert(Tag->isInvalidDecl() && "We should already have completed it");
19404 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19405 RD->completeDefinition();
19406 }
19407
19408 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19409 FieldCollector->FinishClass();
19410 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19411 auto *Def = RD->getDefinition();
19412 assert(Def && "The record is expected to have a completed definition");
19413 unsigned NumInitMethods = 0;
19414 for (auto *Method : Def->methods()) {
19415 if (!Method->getIdentifier())
19416 continue;
19417 if (Method->getName() == "__init")
19418 NumInitMethods++;
19419 }
19420 if (NumInitMethods > 1 || !Def->hasInitMethod())
19421 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19422 }
19423
19424 // If we're defining a dynamic class in a module interface unit, we always
19425 // need to produce the vtable for it, even if the vtable is not used in the
19426 // current TU.
19427 //
19428 // The case where the current class is not dynamic is handled in
19429 // MarkVTableUsed.
19430 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19431 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19432 }
19433
19434 // Exit this scope of this tag's definition.
19436
19437 if (getCurLexicalContext()->isObjCContainer() &&
19438 Tag->getDeclContext()->isFileContext())
19439 Tag->setTopLevelDeclInObjCContainer();
19440
19441 // Notify the consumer that we've defined a tag.
19442 if (!Tag->isInvalidDecl())
19443 Consumer.HandleTagDeclDefinition(Tag);
19444
19445 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19446 // from XLs and instead matches the XL #pragma pack(1) behavior.
19447 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19448 AlignPackStack.hasValue()) {
19449 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19450 // Only diagnose #pragma align(packed).
19451 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19452 return;
19453 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19454 if (!RD)
19455 return;
19456 // Only warn if there is at least 1 bitfield member.
19457 if (llvm::any_of(RD->fields(),
19458 [](const FieldDecl *FD) { return FD->isBitField(); }))
19459 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19460 }
19461}
19462
19465 TagDecl *Tag = cast<TagDecl>(TagD);
19466 Tag->setInvalidDecl();
19467
19468 // Make sure we "complete" the definition even it is invalid.
19469 if (Tag->isBeingDefined()) {
19470 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19471 RD->completeDefinition();
19472 }
19473
19474 // We're undoing ActOnTagStartDefinition here, not
19475 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19476 // the FieldCollector.
19477
19479}
19480
19481// Note that FieldName may be null for anonymous bitfields.
19483 const IdentifierInfo *FieldName,
19484 QualType FieldTy, bool IsMsStruct,
19485 Expr *BitWidth) {
19486 assert(BitWidth);
19487 if (BitWidth->containsErrors())
19488 return ExprError();
19489
19490 // C99 6.7.2.1p4 - verify the field type.
19491 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19492 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19493 // Handle incomplete and sizeless types with a specific error.
19494 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19495 diag::err_field_incomplete_or_sizeless))
19496 return ExprError();
19497 if (FieldName)
19498 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19499 << FieldName << FieldTy << BitWidth->getSourceRange();
19500 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19501 << FieldTy << BitWidth->getSourceRange();
19503 return ExprError();
19504
19505 // If the bit-width is type- or value-dependent, don't try to check
19506 // it now.
19507 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19508 return BitWidth;
19509
19510 llvm::APSInt Value;
19511 ExprResult ICE =
19513 if (ICE.isInvalid())
19514 return ICE;
19515 BitWidth = ICE.get();
19516
19517 // Zero-width bitfield is ok for anonymous field.
19518 if (Value == 0 && FieldName)
19519 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19520 << FieldName << BitWidth->getSourceRange();
19521
19522 if (Value.isSigned() && Value.isNegative()) {
19523 if (FieldName)
19524 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19525 << FieldName << toString(Value, 10);
19526 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19527 << toString(Value, 10);
19528 }
19529
19530 // The size of the bit-field must not exceed our maximum permitted object
19531 // size.
19532 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19533 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19534 << !FieldName << FieldName << toString(Value, 10);
19535 }
19536
19537 if (!FieldTy->isDependentType()) {
19538 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19539 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19540 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19541
19542 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19543 // ABI.
19544 bool CStdConstraintViolation =
19545 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19546 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19547 if (CStdConstraintViolation || MSBitfieldViolation) {
19548 unsigned DiagWidth =
19549 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19550 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19551 << (bool)FieldName << FieldName << toString(Value, 10)
19552 << !CStdConstraintViolation << DiagWidth;
19553 }
19554
19555 // Warn on types where the user might conceivably expect to get all
19556 // specified bits as value bits: that's all integral types other than
19557 // 'bool'.
19558 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19559 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19560 << FieldName << Value << (unsigned)TypeWidth;
19561 }
19562 }
19563
19564 if (isa<ConstantExpr>(BitWidth))
19565 return BitWidth;
19566 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19567}
19568
19570 Declarator &D, Expr *BitfieldWidth) {
19571 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19572 D, BitfieldWidth,
19573 /*InitStyle=*/ICIS_NoInit, AS_public);
19574 return Res;
19575}
19576
19578 SourceLocation DeclStart,
19579 Declarator &D, Expr *BitWidth,
19580 InClassInitStyle InitStyle,
19581 AccessSpecifier AS) {
19582 if (D.isDecompositionDeclarator()) {
19584 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19585 << Decomp.getSourceRange();
19586 return nullptr;
19587 }
19588
19589 const IdentifierInfo *II = D.getIdentifier();
19590 SourceLocation Loc = DeclStart;
19591 if (II) Loc = D.getIdentifierLoc();
19592
19594 QualType T = TInfo->getType();
19595 if (getLangOpts().CPlusPlus) {
19597
19600 D.setInvalidType();
19601 T = Context.IntTy;
19602 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19603 }
19604 }
19605
19607
19609 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19610 << getLangOpts().CPlusPlus17;
19613 diag::err_invalid_thread)
19615
19616 // Check to see if this name was declared as a member previously
19617 NamedDecl *PrevDecl = nullptr;
19618 LookupResult Previous(*this, II, Loc, LookupMemberName,
19620 LookupName(Previous, S);
19621 switch (Previous.getResultKind()) {
19624 PrevDecl = Previous.getAsSingle<NamedDecl>();
19625 break;
19626
19628 PrevDecl = Previous.getRepresentativeDecl();
19629 break;
19630
19634 break;
19635 }
19636 Previous.suppressDiagnostics();
19637
19638 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19639 // Maybe we will complain about the shadowed template parameter.
19641 // Just pretend that we didn't see the previous declaration.
19642 PrevDecl = nullptr;
19643 }
19644
19645 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19646 PrevDecl = nullptr;
19647
19648 bool Mutable
19649 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19650 SourceLocation TSSL = D.getBeginLoc();
19651 FieldDecl *NewFD
19652 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19653 TSSL, AS, PrevDecl, &D);
19654
19655 if (NewFD->isInvalidDecl())
19656 Record->setInvalidDecl();
19657
19659 NewFD->setModulePrivate();
19660
19661 if (NewFD->isInvalidDecl() && PrevDecl) {
19662 // Don't introduce NewFD into scope; there's already something
19663 // with the same name in the same scope.
19664 } else if (II) {
19665 PushOnScopeChains(NewFD, S);
19666 } else
19667 Record->addDecl(NewFD);
19668
19669 return NewFD;
19670}
19671
19673 TypeSourceInfo *TInfo,
19675 bool Mutable, Expr *BitWidth,
19676 InClassInitStyle InitStyle,
19677 SourceLocation TSSL,
19678 AccessSpecifier AS, NamedDecl *PrevDecl,
19679 Declarator *D) {
19680 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19681 bool InvalidDecl = false;
19682 if (D) InvalidDecl = D->isInvalidType();
19683
19684 // If we receive a broken type, recover by assuming 'int' and
19685 // marking this declaration as invalid.
19686 if (T.isNull() || T->containsErrors()) {
19687 InvalidDecl = true;
19688 T = Context.IntTy;
19689 }
19690
19691 QualType EltTy = Context.getBaseElementType(T);
19692 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19693 bool isIncomplete =
19694 LangOpts.HLSL // HLSL allows sizeless builtin types
19695 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19696 : RequireCompleteSizedType(Loc, EltTy,
19697 diag::err_field_incomplete_or_sizeless);
19698 if (isIncomplete) {
19699 // Fields of incomplete type force their record to be invalid.
19700 Record->setInvalidDecl();
19701 InvalidDecl = true;
19702 } else {
19703 NamedDecl *Def;
19704 EltTy->isIncompleteType(&Def);
19705 if (Def && Def->isInvalidDecl()) {
19706 Record->setInvalidDecl();
19707 InvalidDecl = true;
19708 }
19709 }
19710 }
19711
19712 // TR 18037 does not allow fields to be declared with address space
19713 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19714 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19715 Diag(Loc, diag::err_field_with_address_space);
19716 Record->setInvalidDecl();
19717 InvalidDecl = true;
19718 }
19719
19720 if (LangOpts.OpenCL) {
19721 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19722 // used as structure or union field: image, sampler, event or block types.
19723 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19724 T->isBlockPointerType()) {
19725 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19726 Record->setInvalidDecl();
19727 InvalidDecl = true;
19728 }
19729 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19730 // is enabled.
19731 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19732 "__cl_clang_bitfields", LangOpts)) {
19733 Diag(Loc, diag::err_opencl_bitfields);
19734 InvalidDecl = true;
19735 }
19736 }
19737
19738 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19739 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19740 T.hasQualifiers()) {
19741 InvalidDecl = true;
19742 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19743 }
19744
19745 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19746 // than a variably modified type.
19747 if (!InvalidDecl && T->isVariablyModifiedType()) {
19749 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19750 InvalidDecl = true;
19751 }
19752
19753 // Fields can not have abstract class types
19754 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19755 diag::err_abstract_type_in_decl,
19757 InvalidDecl = true;
19758
19759 if (InvalidDecl)
19760 BitWidth = nullptr;
19761 // If this is declared as a bit-field, check the bit-field.
19762 if (BitWidth) {
19763 BitWidth =
19764 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19765 if (!BitWidth) {
19766 InvalidDecl = true;
19767 BitWidth = nullptr;
19768 }
19769 }
19770
19771 // Check that 'mutable' is consistent with the type of the declaration.
19772 if (!InvalidDecl && Mutable) {
19773 unsigned DiagID = 0;
19774 if (T->isReferenceType())
19775 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19776 : diag::err_mutable_reference;
19777 else if (T.isConstQualified())
19778 DiagID = diag::err_mutable_const;
19779
19780 if (DiagID) {
19781 SourceLocation ErrLoc = Loc;
19782 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19783 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19784 Diag(ErrLoc, DiagID);
19785 if (DiagID != diag::ext_mutable_reference) {
19786 Mutable = false;
19787 InvalidDecl = true;
19788 }
19789 }
19790 }
19791
19792 // C++11 [class.union]p8 (DR1460):
19793 // At most one variant member of a union may have a
19794 // brace-or-equal-initializer.
19795 if (InitStyle != ICIS_NoInit)
19797
19798 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19799 BitWidth, Mutable, InitStyle);
19800 if (InvalidDecl)
19801 NewFD->setInvalidDecl();
19802
19803 if (!InvalidDecl)
19805
19806 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19807 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19808 Diag(Loc, diag::err_duplicate_member) << II;
19809 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19810 NewFD->setInvalidDecl();
19811 }
19812
19813 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19814 if (Record->isUnion()) {
19815 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19816 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19817
19818 // C++ [class.union]p1: An object of a class with a non-trivial
19819 // constructor, a non-trivial copy constructor, a non-trivial
19820 // destructor, or a non-trivial copy assignment operator
19821 // cannot be a member of a union, nor can an array of such
19822 // objects.
19823 if (CheckNontrivialField(NewFD))
19824 NewFD->setInvalidDecl();
19825 }
19826
19827 // C++ [class.union]p1: If a union contains a member of reference type,
19828 // the program is ill-formed, except when compiling with MSVC extensions
19829 // enabled.
19830 if (EltTy->isReferenceType()) {
19831 const bool HaveMSExt =
19832 getLangOpts().MicrosoftExt &&
19834
19835 Diag(NewFD->getLocation(),
19836 HaveMSExt ? diag::ext_union_member_of_reference_type
19837 : diag::err_union_member_of_reference_type)
19838 << NewFD->getDeclName() << EltTy;
19839 if (!HaveMSExt)
19840 NewFD->setInvalidDecl();
19841 }
19842 }
19843 }
19844
19845 // FIXME: We need to pass in the attributes given an AST
19846 // representation, not a parser representation.
19847 if (D) {
19848 // FIXME: The current scope is almost... but not entirely... correct here.
19849 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19850
19851 if (NewFD->hasAttrs())
19853 }
19854
19855 // In auto-retain/release, infer strong retension for fields of
19856 // retainable type.
19857 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19858 NewFD->setInvalidDecl();
19859
19860 if (T.isObjCGCWeak())
19861 Diag(Loc, diag::warn_attribute_weak_on_field);
19862
19863 // PPC MMA non-pointer types are not allowed as field types.
19864 if (Context.getTargetInfo().getTriple().isPPC64() &&
19865 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19866 NewFD->setInvalidDecl();
19867
19868 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19869 if (!AMDGPU().checkAMDGPUTypeSupport(T, NewFD->getLocation()))
19870 NewFD->setInvalidDecl();
19871 }
19872
19873 NewFD->setAccess(AS);
19874 return NewFD;
19875}
19876
19878 assert(FD);
19879 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19880
19881 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19882 return false;
19883
19884 QualType EltTy = Context.getBaseElementType(FD->getType());
19885 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19886 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19887 // We check for copy constructors before constructors
19888 // because otherwise we'll never get complaints about
19889 // copy constructors.
19890
19892 // We're required to check for any non-trivial constructors. Since the
19893 // implicit default constructor is suppressed if there are any
19894 // user-declared constructors, we just need to check that there is a
19895 // trivial default constructor and a trivial copy constructor. (We don't
19896 // worry about move constructors here, since this is a C++98 check.)
19897 if (RDecl->hasNonTrivialCopyConstructor())
19899 else if (!RDecl->hasTrivialDefaultConstructor())
19901 else if (RDecl->hasNonTrivialCopyAssignment())
19903 else if (RDecl->hasNonTrivialDestructor())
19905
19906 if (member != CXXSpecialMemberKind::Invalid) {
19907 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19908 RDecl->hasObjectMember()) {
19909 // Objective-C++ ARC: it is an error to have a non-trivial field of
19910 // a union. However, system headers in Objective-C programs
19911 // occasionally have Objective-C lifetime objects within unions,
19912 // and rather than cause the program to fail, we make those
19913 // members unavailable.
19914 SourceLocation Loc = FD->getLocation();
19915 if (getSourceManager().isInSystemHeader(Loc)) {
19916 if (!FD->hasAttr<UnavailableAttr>())
19917 FD->addAttr(UnavailableAttr::CreateImplicit(
19918 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19919 return false;
19920 }
19921 }
19922
19923 Diag(FD->getLocation(),
19925 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19926 : diag::err_illegal_union_or_anon_struct_member)
19927 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19928 DiagnoseNontrivial(RDecl, member);
19929 return !getLangOpts().CPlusPlus11;
19930 }
19931 }
19932
19933 return false;
19934}
19935
19937 SmallVectorImpl<Decl *> &AllIvarDecls) {
19938 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19939 return;
19940
19941 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19942 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19943
19944 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19945 return;
19946 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19947 if (!ID) {
19948 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19949 if (!CD->IsClassExtension())
19950 return;
19951 }
19952 // No need to add this to end of @implementation.
19953 else
19954 return;
19955 }
19956 // All conditions are met. Add a new bitfield to the tail end of ivars.
19957 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19958 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19959 Expr *BitWidth =
19960 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19961
19962 Ivar = ObjCIvarDecl::Create(
19963 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19964 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19965 ObjCIvarDecl::Private, BitWidth, true);
19966 AllIvarDecls.push_back(Ivar);
19967}
19968
19969/// [class.dtor]p4:
19970/// At the end of the definition of a class, overload resolution is
19971/// performed among the prospective destructors declared in that class with
19972/// an empty argument list to select the destructor for the class, also
19973/// known as the selected destructor.
19974///
19975/// We do the overload resolution here, then mark the selected constructor in the AST.
19976/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19978 if (!Record->hasUserDeclaredDestructor()) {
19979 return;
19980 }
19981
19982 SourceLocation Loc = Record->getLocation();
19984
19985 for (auto *Decl : Record->decls()) {
19986 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19987 if (DD->isInvalidDecl())
19988 continue;
19989 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19990 OCS);
19991 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19992 }
19993 }
19994
19995 if (OCS.empty()) {
19996 return;
19997 }
19999 unsigned Msg = 0;
20000 OverloadCandidateDisplayKind DisplayKind;
20001
20002 switch (OCS.BestViableFunction(S, Loc, Best)) {
20003 case OR_Success:
20004 case OR_Deleted:
20005 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
20006 break;
20007
20008 case OR_Ambiguous:
20009 Msg = diag::err_ambiguous_destructor;
20010 DisplayKind = OCD_AmbiguousCandidates;
20011 break;
20012
20014 Msg = diag::err_no_viable_destructor;
20015 DisplayKind = OCD_AllCandidates;
20016 break;
20017 }
20018
20019 if (Msg) {
20020 // OpenCL have got their own thing going with destructors. It's slightly broken,
20021 // but we allow it.
20022 if (!S.LangOpts.OpenCL) {
20023 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
20024 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
20025 Record->setInvalidDecl();
20026 }
20027 // It's a bit hacky: At this point we've raised an error but we want the
20028 // rest of the compiler to continue somehow working. However almost
20029 // everything we'll try to do with the class will depend on there being a
20030 // destructor. So let's pretend the first one is selected and hope for the
20031 // best.
20032 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
20033 }
20034}
20035
20036/// [class.mem.special]p5
20037/// Two special member functions are of the same kind if:
20038/// - they are both default constructors,
20039/// - they are both copy or move constructors with the same first parameter
20040/// type, or
20041/// - they are both copy or move assignment operators with the same first
20042/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
20044 CXXMethodDecl *M1,
20045 CXXMethodDecl *M2,
20047 // We don't want to compare templates to non-templates: See
20048 // https://github.com/llvm/llvm-project/issues/59206
20050 return bool(M1->getDescribedFunctionTemplate()) ==
20052 // FIXME: better resolve CWG
20053 // https://cplusplus.github.io/CWG/issues/2787.html
20054 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
20055 M2->getNonObjectParameter(0)->getType()))
20056 return false;
20057 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
20059 return false;
20060
20061 return true;
20062}
20063
20064/// [class.mem.special]p6:
20065/// An eligible special member function is a special member function for which:
20066/// - the function is not deleted,
20067/// - the associated constraints, if any, are satisfied, and
20068/// - no special member function of the same kind whose associated constraints
20069/// [CWG2595], if any, are satisfied is more constrained.
20073 SmallVector<bool, 4> SatisfactionStatus;
20074
20075 for (CXXMethodDecl *Method : Methods) {
20076 if (!Method->getTrailingRequiresClause())
20077 SatisfactionStatus.push_back(true);
20078 else {
20079 ConstraintSatisfaction Satisfaction;
20080 if (S.CheckFunctionConstraints(Method, Satisfaction))
20081 SatisfactionStatus.push_back(false);
20082 else
20083 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
20084 }
20085 }
20086
20087 for (size_t i = 0; i < Methods.size(); i++) {
20088 if (!SatisfactionStatus[i])
20089 continue;
20090 CXXMethodDecl *Method = Methods[i];
20091 CXXMethodDecl *OrigMethod = Method;
20092 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20093 OrigMethod = cast<CXXMethodDecl>(MF);
20094
20096 bool AnotherMethodIsMoreConstrained = false;
20097 for (size_t j = 0; j < Methods.size(); j++) {
20098 if (i == j || !SatisfactionStatus[j])
20099 continue;
20100 CXXMethodDecl *OtherMethod = Methods[j];
20101 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20102 OtherMethod = cast<CXXMethodDecl>(MF);
20103
20104 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
20105 CSM))
20106 continue;
20107
20109 if (!Other)
20110 continue;
20111 if (!Orig) {
20112 AnotherMethodIsMoreConstrained = true;
20113 break;
20114 }
20115 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
20116 AnotherMethodIsMoreConstrained)) {
20117 // There was an error with the constraints comparison. Exit the loop
20118 // and don't consider this function eligible.
20119 AnotherMethodIsMoreConstrained = true;
20120 }
20121 if (AnotherMethodIsMoreConstrained)
20122 break;
20123 }
20124 // FIXME: Do not consider deleted methods as eligible after implementing
20125 // DR1734 and DR1496.
20126 if (!AnotherMethodIsMoreConstrained) {
20127 Method->setIneligibleOrNotSelected(false);
20128 Record->addedEligibleSpecialMemberFunction(Method,
20129 1 << llvm::to_underlying(CSM));
20130 }
20131 }
20132}
20133
20136 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20137 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20138 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20139 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20140 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20141
20142 for (auto *Decl : Record->decls()) {
20143 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
20144 if (!MD) {
20145 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
20146 if (FTD)
20147 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
20148 }
20149 if (!MD)
20150 continue;
20151 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
20152 if (CD->isInvalidDecl())
20153 continue;
20154 if (CD->isDefaultConstructor())
20155 DefaultConstructors.push_back(MD);
20156 else if (CD->isCopyConstructor())
20157 CopyConstructors.push_back(MD);
20158 else if (CD->isMoveConstructor())
20159 MoveConstructors.push_back(MD);
20160 } else if (MD->isCopyAssignmentOperator()) {
20161 CopyAssignmentOperators.push_back(MD);
20162 } else if (MD->isMoveAssignmentOperator()) {
20163 MoveAssignmentOperators.push_back(MD);
20164 }
20165 }
20166
20167 SetEligibleMethods(S, Record, DefaultConstructors,
20169 SetEligibleMethods(S, Record, CopyConstructors,
20171 SetEligibleMethods(S, Record, MoveConstructors,
20173 SetEligibleMethods(S, Record, CopyAssignmentOperators,
20175 SetEligibleMethods(S, Record, MoveAssignmentOperators,
20177}
20178
20179bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20180 // Check to see if a FieldDecl is a pointer to a function.
20181 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20182 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
20183 if (!FD) {
20184 // Check whether this is a forward declaration that was inserted by
20185 // Clang. This happens when a non-forward declared / defined type is
20186 // used, e.g.:
20187 //
20188 // struct foo {
20189 // struct bar *(*f)();
20190 // struct bar *(*g)();
20191 // };
20192 //
20193 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20194 // incomplete definition.
20195 if (const auto *TD = dyn_cast<TagDecl>(D))
20196 return !TD->isCompleteDefinition();
20197 return false;
20198 }
20199 QualType FieldType = FD->getType().getDesugaredType(Context);
20200 if (isa<PointerType>(FieldType)) {
20201 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
20202 return PointeeType.getDesugaredType(Context)->isFunctionType();
20203 }
20204 // If a member is a struct entirely of function pointers, that counts too.
20205 if (const auto *Record = FieldType->getAsRecordDecl();
20206 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20207 return true;
20208 return false;
20209 };
20210
20211 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
20212}
20213
20214void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20215 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20216 SourceLocation RBrac,
20217 const ParsedAttributesView &Attrs) {
20218 assert(EnclosingDecl && "missing record or interface decl");
20219
20220 // If this is an Objective-C @implementation or category and we have
20221 // new fields here we should reset the layout of the interface since
20222 // it will now change.
20223 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
20224 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
20225 switch (DC->getKind()) {
20226 default: break;
20227 case Decl::ObjCCategory:
20228 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
20229 break;
20230 case Decl::ObjCImplementation:
20231 Context.
20232 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
20233 break;
20234 }
20235 }
20236
20237 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
20238 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
20239
20240 // Start counting up the number of named members; make sure to include
20241 // members of anonymous structs and unions in the total.
20242 unsigned NumNamedMembers = 0;
20243 if (Record) {
20244 for (const auto *I : Record->decls()) {
20245 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
20246 if (IFD->getDeclName())
20247 ++NumNamedMembers;
20248 }
20249 }
20250
20251 // Verify that all the fields are okay.
20253 const FieldDecl *PreviousField = nullptr;
20254 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20255 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
20256 FieldDecl *FD = cast<FieldDecl>(*i);
20257
20258 // Get the type for the field.
20259 const Type *FDTy = FD->getType().getTypePtr();
20260
20261 if (!FD->isAnonymousStructOrUnion()) {
20262 // Remember all fields written by the user.
20263 RecFields.push_back(FD);
20264 }
20265
20266 // If the field is already invalid for some reason, don't emit more
20267 // diagnostics about it.
20268 if (FD->isInvalidDecl()) {
20269 EnclosingDecl->setInvalidDecl();
20270 continue;
20271 }
20272
20273 // C99 6.7.2.1p2:
20274 // A structure or union shall not contain a member with
20275 // incomplete or function type (hence, a structure shall not
20276 // contain an instance of itself, but may contain a pointer to
20277 // an instance of itself), except that the last member of a
20278 // structure with more than one named member may have incomplete
20279 // array type; such a structure (and any union containing,
20280 // possibly recursively, a member that is such a structure)
20281 // shall not be a member of a structure or an element of an
20282 // array.
20283 bool IsLastField = (i + 1 == Fields.end());
20284 if (FDTy->isFunctionType()) {
20285 // Field declared as a function.
20286 Diag(FD->getLocation(), diag::err_field_declared_as_function)
20287 << FD->getDeclName();
20288 FD->setInvalidDecl();
20289 EnclosingDecl->setInvalidDecl();
20290 continue;
20291 } else if (FDTy->isIncompleteArrayType() &&
20292 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
20293 if (Record) {
20294 // Flexible array member.
20295 // Microsoft and g++ is more permissive regarding flexible array.
20296 // It will accept flexible array in union and also
20297 // as the sole element of a struct/class.
20298 unsigned DiagID = 0;
20299 if (!Record->isUnion() && !IsLastField) {
20300 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
20301 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20302 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
20303 FD->setInvalidDecl();
20304 EnclosingDecl->setInvalidDecl();
20305 continue;
20306 } else if (Record->isUnion())
20307 DiagID = getLangOpts().MicrosoftExt
20308 ? diag::ext_flexible_array_union_ms
20309 : diag::ext_flexible_array_union_gnu;
20310 else if (NumNamedMembers < 1)
20311 DiagID = getLangOpts().MicrosoftExt
20312 ? diag::ext_flexible_array_empty_aggregate_ms
20313 : diag::ext_flexible_array_empty_aggregate_gnu;
20314
20315 if (DiagID)
20316 Diag(FD->getLocation(), DiagID)
20317 << FD->getDeclName() << Record->getTagKind();
20318 // While the layout of types that contain virtual bases is not specified
20319 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20320 // virtual bases after the derived members. This would make a flexible
20321 // array member declared at the end of an object not adjacent to the end
20322 // of the type.
20323 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20324 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
20325 << FD->getDeclName() << Record->getTagKind();
20326 if (!getLangOpts().C99)
20327 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
20328 << FD->getDeclName() << Record->getTagKind();
20329
20330 // If the element type has a non-trivial destructor, we would not
20331 // implicitly destroy the elements, so disallow it for now.
20332 //
20333 // FIXME: GCC allows this. We should probably either implicitly delete
20334 // the destructor of the containing class, or just allow this.
20335 QualType BaseElem = Context.getBaseElementType(FD->getType());
20336 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20337 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
20338 << FD->getDeclName() << FD->getType();
20339 FD->setInvalidDecl();
20340 EnclosingDecl->setInvalidDecl();
20341 continue;
20342 }
20343 // Okay, we have a legal flexible array member at the end of the struct.
20344 Record->setHasFlexibleArrayMember(true);
20345 } else {
20346 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20347 // unless they are followed by another ivar. That check is done
20348 // elsewhere, after synthesized ivars are known.
20349 }
20350 } else if (!FDTy->isDependentType() &&
20351 (LangOpts.HLSL // HLSL allows sizeless builtin types
20353 diag::err_incomplete_type)
20355 FD->getLocation(), FD->getType(),
20356 diag::err_field_incomplete_or_sizeless))) {
20357 // Incomplete type
20358 FD->setInvalidDecl();
20359 EnclosingDecl->setInvalidDecl();
20360 continue;
20361 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20362 if (Record && RD->hasFlexibleArrayMember()) {
20363 // A type which contains a flexible array member is considered to be a
20364 // flexible array member.
20365 Record->setHasFlexibleArrayMember(true);
20366 if (!Record->isUnion()) {
20367 // If this is a struct/class and this is not the last element, reject
20368 // it. Note that GCC supports variable sized arrays in the middle of
20369 // structures.
20370 if (!IsLastField)
20371 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20372 << FD->getDeclName() << FD->getType();
20373 else {
20374 // We support flexible arrays at the end of structs in
20375 // other structs as an extension.
20376 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20377 << FD->getDeclName();
20378 }
20379 }
20380 }
20381 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20383 diag::err_abstract_type_in_decl,
20385 // Ivars can not have abstract class types
20386 FD->setInvalidDecl();
20387 }
20388 if (Record && RD->hasObjectMember())
20389 Record->setHasObjectMember(true);
20390 if (Record && RD->hasVolatileMember())
20391 Record->setHasVolatileMember(true);
20392 } else if (FDTy->isObjCObjectType()) {
20393 /// A field cannot be an Objective-c object
20394 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20396 QualType T = Context.getObjCObjectPointerType(FD->getType());
20397 FD->setType(T);
20398 } else if (Record && Record->isUnion() &&
20400 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20401 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20403 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20404 // For backward compatibility, fields of C unions declared in system
20405 // headers that have non-trivial ObjC ownership qualifications are marked
20406 // as unavailable unless the qualifier is explicit and __strong. This can
20407 // break ABI compatibility between programs compiled with ARC and MRR, but
20408 // is a better option than rejecting programs using those unions under
20409 // ARC.
20410 FD->addAttr(UnavailableAttr::CreateImplicit(
20411 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20412 FD->getLocation()));
20413 } else if (getLangOpts().ObjC &&
20414 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20415 !Record->hasObjectMember()) {
20416 if (FD->getType()->isObjCObjectPointerType() ||
20417 FD->getType().isObjCGCStrong())
20418 Record->setHasObjectMember(true);
20419 else if (Context.getAsArrayType(FD->getType())) {
20420 QualType BaseType = Context.getBaseElementType(FD->getType());
20421 if (const auto *RD = BaseType->getAsRecordDecl();
20422 RD && RD->hasObjectMember())
20423 Record->setHasObjectMember(true);
20424 else if (BaseType->isObjCObjectPointerType() ||
20425 BaseType.isObjCGCStrong())
20426 Record->setHasObjectMember(true);
20427 }
20428 }
20429
20430 if (Record && !getLangOpts().CPlusPlus &&
20431 !shouldIgnoreForRecordTriviality(FD)) {
20432 QualType FT = FD->getType();
20434 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20436 Record->isUnion())
20437 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20438 }
20441 Record->setNonTrivialToPrimitiveCopy(true);
20442 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20443 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20444 }
20445 if (FD->hasAttr<ExplicitInitAttr>())
20446 Record->setHasUninitializedExplicitInitFields(true);
20447 if (FT.isDestructedType()) {
20448 Record->setNonTrivialToPrimitiveDestroy(true);
20449 Record->setParamDestroyedInCallee(true);
20450 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20451 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20452 }
20453
20454 if (const auto *RD = FT->getAsRecordDecl()) {
20455 if (RD->getArgPassingRestrictions() ==
20457 Record->setArgPassingRestrictions(
20459 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20460 Record->setArgPassingRestrictions(
20462 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20463 Q && Q.isAddressDiscriminated()) {
20464 Record->setArgPassingRestrictions(
20466 Record->setNonTrivialToPrimitiveCopy(true);
20467 }
20468 }
20469
20470 if (Record && FD->getType().isVolatileQualified())
20471 Record->setHasVolatileMember(true);
20472 bool ReportMSBitfieldStoragePacking =
20473 Record && PreviousField &&
20474 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20475 Record->getLocation());
20476 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20477 return FD->isBitField() && !FD->getType()->isDependentType();
20478 };
20479
20480 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20481 IsNonDependentBitField(PreviousField)) {
20482 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20483 CharUnits PreviousFieldStorageSize =
20484 Context.getTypeSizeInChars(PreviousField->getType());
20485 if (FDStorageSize != PreviousFieldStorageSize) {
20486 Diag(FD->getLocation(),
20487 diag::warn_ms_bitfield_mismatched_storage_packing)
20488 << FD << FD->getType() << FDStorageSize.getQuantity()
20489 << PreviousFieldStorageSize.getQuantity();
20490 Diag(PreviousField->getLocation(),
20491 diag::note_ms_bitfield_mismatched_storage_size_previous)
20492 << PreviousField << PreviousField->getType();
20493 }
20494 }
20495 // Keep track of the number of named members.
20496 if (FD->getIdentifier())
20497 ++NumNamedMembers;
20498 }
20499
20500 // Okay, we successfully defined 'Record'.
20501 if (Record) {
20502 bool Completed = false;
20503 if (S) {
20504 Scope *Parent = S->getParent();
20505 if (Parent && Parent->isTypeAliasScope() &&
20506 Parent->isTemplateParamScope())
20507 Record->setInvalidDecl();
20508 }
20509
20510 if (CXXRecord) {
20511 if (!CXXRecord->isInvalidDecl()) {
20512 // Set access bits correctly on the directly-declared conversions.
20514 I = CXXRecord->conversion_begin(),
20515 E = CXXRecord->conversion_end(); I != E; ++I)
20516 I.setAccess((*I)->getAccess());
20517 }
20518
20519 // Add any implicitly-declared members to this class.
20521
20522 if (!CXXRecord->isDependentType()) {
20523 if (!CXXRecord->isInvalidDecl()) {
20524 // If we have virtual base classes, we may end up finding multiple
20525 // final overriders for a given virtual function. Check for this
20526 // problem now.
20527 if (CXXRecord->getNumVBases()) {
20528 CXXFinalOverriderMap FinalOverriders;
20529 CXXRecord->getFinalOverriders(FinalOverriders);
20530
20531 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20532 MEnd = FinalOverriders.end();
20533 M != MEnd; ++M) {
20534 for (OverridingMethods::iterator SO = M->second.begin(),
20535 SOEnd = M->second.end();
20536 SO != SOEnd; ++SO) {
20537 assert(SO->second.size() > 0 &&
20538 "Virtual function without overriding functions?");
20539 if (SO->second.size() == 1)
20540 continue;
20541
20542 // C++ [class.virtual]p2:
20543 // In a derived class, if a virtual member function of a base
20544 // class subobject has more than one final overrider the
20545 // program is ill-formed.
20546 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20547 << (const NamedDecl *)M->first << Record;
20548 Diag(M->first->getLocation(),
20549 diag::note_overridden_virtual_function);
20551 OM = SO->second.begin(),
20552 OMEnd = SO->second.end();
20553 OM != OMEnd; ++OM)
20554 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20555 << (const NamedDecl *)M->first << OM->Method->getParent();
20556
20557 Record->setInvalidDecl();
20558 }
20559 }
20560 CXXRecord->completeDefinition(&FinalOverriders);
20561 Completed = true;
20562 }
20563 }
20564 ComputeSelectedDestructor(*this, CXXRecord);
20566 }
20567 }
20568
20569 if (!Completed)
20570 Record->completeDefinition();
20571
20572 // Handle attributes before checking the layout.
20574
20575 // Maybe randomize the record's decls. We automatically randomize a record
20576 // of function pointers, unless it has the "no_randomize_layout" attribute.
20577 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20578 !Record->isRandomized() && !Record->isUnion() &&
20579 (Record->hasAttr<RandomizeLayoutAttr>() ||
20580 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20581 EntirelyFunctionPointers(Record)))) {
20582 SmallVector<Decl *, 32> NewDeclOrdering;
20584 NewDeclOrdering))
20585 Record->reorderDecls(NewDeclOrdering);
20586 }
20587
20588 // We may have deferred checking for a deleted destructor. Check now.
20589 if (CXXRecord) {
20590 auto *Dtor = CXXRecord->getDestructor();
20591 if (Dtor && Dtor->isImplicit() &&
20593 CXXRecord->setImplicitDestructorIsDeleted();
20594 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20595 }
20596 }
20597
20598 if (Record->hasAttrs()) {
20600
20601 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20603 IA->getRange(), IA->getBestCase(),
20604 IA->getInheritanceModel());
20605 }
20606
20607 // Check if the structure/union declaration is a type that can have zero
20608 // size in C. For C this is a language extension, for C++ it may cause
20609 // compatibility problems.
20610 bool CheckForZeroSize;
20611 if (!getLangOpts().CPlusPlus) {
20612 CheckForZeroSize = true;
20613 } else {
20614 // For C++ filter out types that cannot be referenced in C code.
20616 CheckForZeroSize =
20617 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20618 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20619 CXXRecord->isCLike();
20620 }
20621 if (CheckForZeroSize) {
20622 bool ZeroSize = true;
20623 bool IsEmpty = true;
20624 unsigned NonBitFields = 0;
20625 for (RecordDecl::field_iterator I = Record->field_begin(),
20626 E = Record->field_end();
20627 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20628 IsEmpty = false;
20629 if (I->isUnnamedBitField()) {
20630 if (!I->isZeroLengthBitField())
20631 ZeroSize = false;
20632 } else {
20633 ++NonBitFields;
20634 QualType FieldType = I->getType();
20635 if (FieldType->isIncompleteType() ||
20636 !Context.getTypeSizeInChars(FieldType).isZero())
20637 ZeroSize = false;
20638 }
20639 }
20640
20641 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20642 // allowed in C++, but warn if its declaration is inside
20643 // extern "C" block.
20644 if (ZeroSize) {
20645 Diag(RecLoc, getLangOpts().CPlusPlus ?
20646 diag::warn_zero_size_struct_union_in_extern_c :
20647 diag::warn_zero_size_struct_union_compat)
20648 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20649 }
20650
20651 // Structs without named members are extension in C (C99 6.7.2.1p7),
20652 // but are accepted by GCC. In C2y, this became implementation-defined
20653 // (C2y 6.7.3.2p10).
20654 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20655 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20656 : diag::ext_no_named_members_in_struct_union)
20657 << Record->isUnion();
20658 }
20659 }
20660 } else {
20661 ObjCIvarDecl **ClsFields =
20662 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20663 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20664 ID->setEndOfDefinitionLoc(RBrac);
20665 // Add ivar's to class's DeclContext.
20666 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20667 ClsFields[i]->setLexicalDeclContext(ID);
20668 ID->addDecl(ClsFields[i]);
20669 }
20670 // Must enforce the rule that ivars in the base classes may not be
20671 // duplicates.
20672 if (ID->getSuperClass())
20673 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20674 } else if (ObjCImplementationDecl *IMPDecl =
20675 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20676 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20677 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20678 // Ivar declared in @implementation never belongs to the implementation.
20679 // Only it is in implementation's lexical context.
20680 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20681 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20682 RBrac);
20683 IMPDecl->setIvarLBraceLoc(LBrac);
20684 IMPDecl->setIvarRBraceLoc(RBrac);
20685 } else if (ObjCCategoryDecl *CDecl =
20686 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20687 // case of ivars in class extension; all other cases have been
20688 // reported as errors elsewhere.
20689 // FIXME. Class extension does not have a LocEnd field.
20690 // CDecl->setLocEnd(RBrac);
20691 // Add ivar's to class extension's DeclContext.
20692 // Diagnose redeclaration of private ivars.
20693 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20694 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20695 if (IDecl) {
20696 if (const ObjCIvarDecl *ClsIvar =
20697 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20698 Diag(ClsFields[i]->getLocation(),
20699 diag::err_duplicate_ivar_declaration);
20700 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20701 continue;
20702 }
20703 for (const auto *Ext : IDecl->known_extensions()) {
20704 if (const ObjCIvarDecl *ClsExtIvar
20705 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20706 Diag(ClsFields[i]->getLocation(),
20707 diag::err_duplicate_ivar_declaration);
20708 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20709 continue;
20710 }
20711 }
20712 }
20713 ClsFields[i]->setLexicalDeclContext(CDecl);
20714 CDecl->addDecl(ClsFields[i]);
20715 }
20716 CDecl->setIvarLBraceLoc(LBrac);
20717 CDecl->setIvarRBraceLoc(RBrac);
20718 }
20719 }
20720
20721 if (Record)
20723
20726}
20727
20728// Given an integral type, return the next larger integral type
20729// (or a NULL type of no such type exists).
20731 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20732 // enum checking below.
20733 assert((T->isIntegralType(Context) ||
20734 T->isEnumeralType()) && "Integral type required!");
20735 const unsigned NumTypes = 4;
20736 QualType SignedIntegralTypes[NumTypes] = {
20737 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20738 };
20739 QualType UnsignedIntegralTypes[NumTypes] = {
20740 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20741 Context.UnsignedLongLongTy
20742 };
20743
20744 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20745 // bits but a 64-bit standard type can still represent its incremented
20746 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20747 // bit-precise type either.
20748 unsigned BitWidth = Context.getIntWidth(T);
20749 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20750 : UnsignedIntegralTypes;
20751 for (unsigned I = 0; I != NumTypes; ++I)
20752 if (Context.getTypeSize(Types[I]) > BitWidth)
20753 return Types[I];
20754
20755 return QualType();
20756}
20757
20759 EnumConstantDecl *LastEnumConst,
20760 SourceLocation IdLoc,
20761 IdentifierInfo *Id,
20762 Expr *Val) {
20763 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20764 llvm::APSInt EnumVal(IntWidth);
20765 QualType EltTy;
20766
20768 Val = nullptr;
20769
20770 if (Val)
20771 Val = DefaultLvalueConversion(Val).get();
20772
20773 if (Val) {
20774 if (Enum->isDependentType() || Val->isTypeDependent() ||
20775 Val->containsErrors())
20776 EltTy = Context.DependentTy;
20777 else {
20778 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20779 // underlying type, but do allow it in all other contexts.
20780 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20781 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20782 // constant-expression in the enumerator-definition shall be a converted
20783 // constant expression of the underlying type.
20784 EltTy = Enum->getIntegerType();
20786 Val, EltTy, EnumVal, CCEKind::Enumerator);
20787 if (Converted.isInvalid())
20788 Val = nullptr;
20789 else
20790 Val = Converted.get();
20791 } else if (!Val->isValueDependent() &&
20792 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20794 .get())) {
20795 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20796 } else {
20797 if (Enum->isComplete()) {
20798 EltTy = Enum->getIntegerType();
20799
20800 // In Obj-C and Microsoft mode, require the enumeration value to be
20801 // representable in the underlying type of the enumeration. In C++11,
20802 // we perform a non-narrowing conversion as part of converted constant
20803 // expression checking.
20804 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20805 if (Context.getTargetInfo()
20806 .getTriple()
20807 .isWindowsMSVCEnvironment()) {
20808 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20809 } else {
20810 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20811 }
20812 }
20813
20814 // Cast to the underlying type.
20815 Val = ImpCastExprToType(Val, EltTy,
20816 EltTy->isBooleanType() ? CK_IntegralToBoolean
20817 : CK_IntegralCast)
20818 .get();
20819 } else if (getLangOpts().CPlusPlus) {
20820 // C++11 [dcl.enum]p5:
20821 // If the underlying type is not fixed, the type of each enumerator
20822 // is the type of its initializing value:
20823 // - If an initializer is specified for an enumerator, the
20824 // initializing value has the same type as the expression.
20825 EltTy = Val->getType();
20826 } else {
20827 // C99 6.7.2.2p2:
20828 // The expression that defines the value of an enumeration constant
20829 // shall be an integer constant expression that has a value
20830 // representable as an int.
20831
20832 // Complain if the value is not representable in an int.
20833 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20834 Diag(IdLoc, getLangOpts().C23
20835 ? diag::warn_c17_compat_enum_value_not_int
20836 : diag::ext_c23_enum_value_not_int)
20837 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20838 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20839 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20840 // Force the type of the expression to 'int'.
20841 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20842 }
20843 EltTy = Val->getType();
20844 }
20845 }
20846 }
20847 }
20848
20849 if (!Val) {
20850 if (Enum->isDependentType())
20851 EltTy = Context.DependentTy;
20852 else if (!LastEnumConst) {
20853 // C++0x [dcl.enum]p5:
20854 // If the underlying type is not fixed, the type of each enumerator
20855 // is the type of its initializing value:
20856 // - If no initializer is specified for the first enumerator, the
20857 // initializing value has an unspecified integral type.
20858 //
20859 // GCC uses 'int' for its unspecified integral type, as does
20860 // C99 6.7.2.2p3.
20861 if (Enum->isFixed()) {
20862 EltTy = Enum->getIntegerType();
20863 }
20864 else {
20865 EltTy = Context.IntTy;
20866 }
20867 } else {
20868 // Assign the last value + 1.
20869 EnumVal = LastEnumConst->getInitVal();
20870 ++EnumVal;
20871 EltTy = LastEnumConst->getType();
20872
20873 // Check for overflow on increment.
20874 if (EnumVal < LastEnumConst->getInitVal()) {
20875 // C++0x [dcl.enum]p5:
20876 // If the underlying type is not fixed, the type of each enumerator
20877 // is the type of its initializing value:
20878 //
20879 // - Otherwise the type of the initializing value is the same as
20880 // the type of the initializing value of the preceding enumerator
20881 // unless the incremented value is not representable in that type,
20882 // in which case the type is an unspecified integral type
20883 // sufficient to contain the incremented value. If no such type
20884 // exists, the program is ill-formed.
20886 if (T.isNull() || Enum->isFixed()) {
20887 // There is no integral type larger enough to represent this
20888 // value. Complain, then allow the value to wrap around.
20889 EnumVal = LastEnumConst->getInitVal();
20890 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20891 ++EnumVal;
20892 if (Enum->isFixed())
20893 // When the underlying type is fixed, this is ill-formed.
20894 Diag(IdLoc, diag::err_enumerator_wrapped)
20895 << toString(EnumVal, 10)
20896 << EltTy;
20897 else
20898 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20899 << toString(EnumVal, 10);
20900 } else {
20901 EltTy = T;
20902 }
20903
20904 // Retrieve the last enumerator's value, extent that type to the
20905 // type that is supposed to be large enough to represent the incremented
20906 // value, then increment.
20907 EnumVal = LastEnumConst->getInitVal();
20908 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20909 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20910 ++EnumVal;
20911
20912 // If we're not in C++, diagnose the overflow of enumerator values,
20913 // which in C99 means that the enumerator value is not representable in
20914 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20915 // are representable in some larger integral type and we allow it in
20916 // older language modes as an extension.
20917 // Exclude fixed enumerators since they are diagnosed with an error for
20918 // this case.
20919 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20920 Diag(IdLoc, getLangOpts().C23
20921 ? diag::warn_c17_compat_enum_value_not_int
20922 : diag::ext_c23_enum_value_not_int)
20923 << 1 << toString(EnumVal, 10) << 1;
20924 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20925 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20926 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20927 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20928 : diag::ext_c23_enum_value_not_int)
20929 << 1 << toString(EnumVal, 10) << 1;
20930 }
20931 }
20932 }
20933
20934 if (!EltTy->isDependentType()) {
20935 // Make the enumerator value match the signedness and size of the
20936 // enumerator's type.
20937 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20938 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20939 }
20940
20941 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20942 Val, EnumVal);
20943}
20944
20946 SourceLocation IILoc) {
20947 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20949 return SkipBodyInfo();
20950
20951 // We have an anonymous enum definition. Look up the first enumerator to
20952 // determine if we should merge the definition with an existing one and
20953 // skip the body.
20954 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20956 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20957 if (!PrevECD)
20958 return SkipBodyInfo();
20959
20960 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20961 NamedDecl *Hidden;
20962 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20964 Skip.Previous = Hidden;
20965 return Skip;
20966 }
20967
20968 return SkipBodyInfo();
20969}
20970
20971Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20972 SourceLocation IdLoc, IdentifierInfo *Id,
20973 const ParsedAttributesView &Attrs,
20974 SourceLocation EqualLoc, Expr *Val,
20975 SkipBodyInfo *SkipBody) {
20976 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20977 EnumConstantDecl *LastEnumConst =
20978 cast_or_null<EnumConstantDecl>(lastEnumConst);
20979
20980 // The scope passed in may not be a decl scope. Zip up the scope tree until
20981 // we find one that is.
20982 S = getNonFieldDeclScope(S);
20983
20984 // Verify that there isn't already something declared with this name in this
20985 // scope.
20986 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20988 LookupName(R, S);
20989 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20990
20991 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20992 // Maybe we will complain about the shadowed template parameter.
20993 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20994 // Just pretend that we didn't see the previous declaration.
20995 PrevDecl = nullptr;
20996 }
20997
20998 // C++ [class.mem]p15:
20999 // If T is the name of a class, then each of the following shall have a name
21000 // different from T:
21001 // - every enumerator of every member of class T that is an unscoped
21002 // enumerated type
21003 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
21005 DeclarationNameInfo(Id, IdLoc)))
21006 return nullptr;
21007
21009 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
21010 if (!New)
21011 return nullptr;
21012
21013 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
21014 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
21015 // Check for other kinds of shadowing not already handled.
21016 CheckShadow(New, PrevDecl, R);
21017 }
21018
21019 // When in C++, we may get a TagDecl with the same name; in this case the
21020 // enum constant will 'hide' the tag.
21021 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
21022 "Received TagDecl when not in C++!");
21023 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
21024 if (isa<EnumConstantDecl>(PrevDecl))
21025 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
21026 else
21027 Diag(IdLoc, diag::err_redefinition) << Id;
21028 notePreviousDefinition(PrevDecl, IdLoc);
21029 return nullptr;
21030 }
21031 }
21032
21033 // Process attributes.
21034 ProcessDeclAttributeList(S, New, Attrs);
21037
21038 // Register this decl in the current scope stack.
21039 New->setAccess(TheEnumDecl->getAccess());
21041
21043
21044 return New;
21045}
21046
21047// Returns true when the enum initial expression does not trigger the
21048// duplicate enum warning. A few common cases are exempted as follows:
21049// Element2 = Element1
21050// Element2 = Element1 + 1
21051// Element2 = Element1 - 1
21052// Where Element2 and Element1 are from the same enum.
21054 Expr *InitExpr = ECD->getInitExpr();
21055 if (!InitExpr)
21056 return true;
21057 InitExpr = InitExpr->IgnoreImpCasts();
21058
21059 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
21060 if (!BO->isAdditiveOp())
21061 return true;
21062 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
21063 if (!IL)
21064 return true;
21065 if (IL->getValue() != 1)
21066 return true;
21067
21068 InitExpr = BO->getLHS();
21069 }
21070
21071 // This checks if the elements are from the same enum.
21072 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
21073 if (!DRE)
21074 return true;
21075
21076 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
21077 if (!EnumConstant)
21078 return true;
21079
21081 Enum)
21082 return true;
21083
21084 return false;
21085}
21086
21087// Emits a warning when an element is implicitly set a value that
21088// a previous element has already been set to.
21090 EnumDecl *Enum, QualType EnumType) {
21091 // Avoid anonymous enums
21092 if (!Enum->getIdentifier())
21093 return;
21094
21095 // Only check for small enums.
21096 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21097 return;
21098
21099 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
21100 return;
21101
21102 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21103 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21104
21105 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21106
21107 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21108 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21109
21110 // Use int64_t as a key to avoid needing special handling for map keys.
21111 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21112 llvm::APSInt Val = D->getInitVal();
21113 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21114 };
21115
21116 DuplicatesVector DupVector;
21117 ValueToVectorMap EnumMap;
21118
21119 // Populate the EnumMap with all values represented by enum constants without
21120 // an initializer.
21121 for (auto *Element : Elements) {
21122 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
21123
21124 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21125 // this constant. Skip this enum since it may be ill-formed.
21126 if (!ECD) {
21127 return;
21128 }
21129
21130 // Constants with initializers are handled in the next loop.
21131 if (ECD->getInitExpr())
21132 continue;
21133
21134 // Duplicate values are handled in the next loop.
21135 EnumMap.insert({EnumConstantToKey(ECD), ECD});
21136 }
21137
21138 if (EnumMap.size() == 0)
21139 return;
21140
21141 // Create vectors for any values that has duplicates.
21142 for (auto *Element : Elements) {
21143 // The last loop returned if any constant was null.
21145 if (!ValidDuplicateEnum(ECD, Enum))
21146 continue;
21147
21148 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
21149 if (Iter == EnumMap.end())
21150 continue;
21151
21152 DeclOrVector& Entry = Iter->second;
21153 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
21154 // Ensure constants are different.
21155 if (D == ECD)
21156 continue;
21157
21158 // Create new vector and push values onto it.
21159 auto Vec = std::make_unique<ECDVector>();
21160 Vec->push_back(D);
21161 Vec->push_back(ECD);
21162
21163 // Update entry to point to the duplicates vector.
21164 Entry = Vec.get();
21165
21166 // Store the vector somewhere we can consult later for quick emission of
21167 // diagnostics.
21168 DupVector.emplace_back(std::move(Vec));
21169 continue;
21170 }
21171
21172 ECDVector *Vec = cast<ECDVector *>(Entry);
21173 // Make sure constants are not added more than once.
21174 if (*Vec->begin() == ECD)
21175 continue;
21176
21177 Vec->push_back(ECD);
21178 }
21179
21180 // Emit diagnostics.
21181 for (const auto &Vec : DupVector) {
21182 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21183
21184 // Emit warning for one enum constant.
21185 auto *FirstECD = Vec->front();
21186 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
21187 << FirstECD << toString(FirstECD->getInitVal(), 10)
21188 << FirstECD->getSourceRange();
21189
21190 // Emit one note for each of the remaining enum constants with
21191 // the same value.
21192 for (auto *ECD : llvm::drop_begin(*Vec))
21193 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
21194 << ECD << toString(ECD->getInitVal(), 10)
21195 << ECD->getSourceRange();
21196 }
21197}
21198
21199bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21200 bool AllowMask) const {
21201 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21202 assert(ED->isCompleteDefinition() && "expected enum definition");
21203
21204 auto R = FlagBitsCache.try_emplace(ED);
21205 llvm::APInt &FlagBits = R.first->second;
21206
21207 if (R.second) {
21208 for (auto *E : ED->enumerators()) {
21209 const auto &EVal = E->getInitVal();
21210 // Only single-bit enumerators introduce new flag values.
21211 if (EVal.isPowerOf2())
21212 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
21213 }
21214 }
21215
21216 // A value is in a flag enum if either its bits are a subset of the enum's
21217 // flag bits (the first condition) or we are allowing masks and the same is
21218 // true of its complement (the second condition). When masks are allowed, we
21219 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21220 //
21221 // While it's true that any value could be used as a mask, the assumption is
21222 // that a mask will have all of the insignificant bits set. Anything else is
21223 // likely a logic error.
21224 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
21225 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21226}
21227
21228// Emits a warning when a suspicious comparison operator is used along side
21229// binary operators in enum initializers.
21231 const EnumDecl *Enum) {
21232 bool HasBitwiseOp = false;
21233 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21234
21235 // Iterate over all the enum values, gather suspisious comparison ops and
21236 // whether any enum initialisers contain a binary operator.
21237 for (const auto *ECD : Enum->enumerators()) {
21238 const Expr *InitExpr = ECD->getInitExpr();
21239 if (!InitExpr)
21240 continue;
21241
21242 const Expr *E = InitExpr->IgnoreParenImpCasts();
21243
21244 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
21245 BinaryOperatorKind Op = BinOp->getOpcode();
21246
21247 // Check for bitwise ops (<<, >>, &, |)
21248 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21249 HasBitwiseOp = true;
21250 } else if (Op == BO_LT || Op == BO_GT) {
21251 // Check for the typo pattern (Comparison < or >)
21252 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21253 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
21254 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21255 if (IntLiteral->getValue() == 1)
21256 SuspiciousCompares.push_back(BinOp);
21257 }
21258 }
21259 }
21260 }
21261
21262 // If we found a bitwise op and some sus compares, iterate over the compares
21263 // and warn.
21264 if (HasBitwiseOp) {
21265 for (const auto *BinOp : SuspiciousCompares) {
21266 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21269 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21270
21271 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
21272 << BinOp->getOpcodeStr() << SuggestedOp;
21273
21274 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
21275 << SuggestedOp
21276 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
21277 }
21278 }
21279}
21280
21282 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21283 const ParsedAttributesView &Attrs) {
21284 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
21285 CanQualType EnumType = Context.getCanonicalTagType(Enum);
21286
21287 ProcessDeclAttributeList(S, Enum, Attrs);
21289
21290 if (Enum->isDependentType()) {
21291 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21292 EnumConstantDecl *ECD =
21293 cast_or_null<EnumConstantDecl>(Elements[i]);
21294 if (!ECD) continue;
21295
21296 ECD->setType(EnumType);
21297 }
21298
21299 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
21300 return;
21301 }
21302
21303 // Verify that all the values are okay, compute the size of the values, and
21304 // reverse the list.
21305 unsigned NumNegativeBits = 0;
21306 unsigned NumPositiveBits = 0;
21307 bool MembersRepresentableByInt =
21308 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
21309
21310 // Figure out the type that should be used for this enum.
21311 QualType BestType;
21312 unsigned BestWidth;
21313
21314 // C++0x N3000 [conv.prom]p3:
21315 // An rvalue of an unscoped enumeration type whose underlying
21316 // type is not fixed can be converted to an rvalue of the first
21317 // of the following types that can represent all the values of
21318 // the enumeration: int, unsigned int, long int, unsigned long
21319 // int, long long int, or unsigned long long int.
21320 // C99 6.4.4.3p2:
21321 // An identifier declared as an enumeration constant has type int.
21322 // The C99 rule is modified by C23.
21323 QualType BestPromotionType;
21324
21325 bool Packed = Enum->hasAttr<PackedAttr>();
21326 // -fshort-enums is the equivalent to specifying the packed attribute on all
21327 // enum definitions.
21328 if (LangOpts.ShortEnums)
21329 Packed = true;
21330
21331 // If the enum already has a type because it is fixed or dictated by the
21332 // target, promote that type instead of analyzing the enumerators.
21333 if (Enum->isComplete()) {
21334 BestType = Enum->getIntegerType();
21335 if (Context.isPromotableIntegerType(BestType))
21336 BestPromotionType = Context.getPromotedIntegerType(BestType);
21337 else
21338 BestPromotionType = BestType;
21339
21340 BestWidth = Context.getIntWidth(BestType);
21341 } else {
21342 bool EnumTooLarge = Context.computeBestEnumTypes(
21343 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21344 BestWidth = Context.getIntWidth(BestType);
21345 if (EnumTooLarge)
21346 Diag(Enum->getLocation(), diag::ext_enum_too_large);
21347 }
21348
21349 // Loop over all of the enumerator constants, changing their types to match
21350 // the type of the enum if needed.
21351 for (auto *D : Elements) {
21352 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21353 if (!ECD) continue; // Already issued a diagnostic.
21354
21355 // C99 says the enumerators have int type, but we allow, as an
21356 // extension, the enumerators to be larger than int size. If each
21357 // enumerator value fits in an int, type it as an int, otherwise type it the
21358 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21359 // that X has type 'int', not 'unsigned'.
21360
21361 // Determine whether the value fits into an int.
21362 llvm::APSInt InitVal = ECD->getInitVal();
21363
21364 // If it fits into an integer type, force it. Otherwise force it to match
21365 // the enum decl type.
21366 QualType NewTy;
21367 unsigned NewWidth;
21368 bool NewSign;
21369 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21370 MembersRepresentableByInt) {
21371 // C23 6.7.3.3.3p15:
21372 // The enumeration member type for an enumerated type without fixed
21373 // underlying type upon completion is:
21374 // - int if all the values of the enumeration are representable as an
21375 // int; or,
21376 // - the enumerated type
21377 NewTy = Context.IntTy;
21378 NewWidth = Context.getTargetInfo().getIntWidth();
21379 NewSign = true;
21380 } else if (ECD->getType() == BestType) {
21381 // Already the right type!
21382 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21383 // C++ [dcl.enum]p4: Following the closing brace of an
21384 // enum-specifier, each enumerator has the type of its
21385 // enumeration.
21386 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21387 // with fixed underlying type is the enumerated type.
21388 ECD->setType(EnumType);
21389 continue;
21390 } else {
21391 NewTy = BestType;
21392 NewWidth = BestWidth;
21393 NewSign = BestType->isSignedIntegerOrEnumerationType();
21394 }
21395
21396 // Adjust the APSInt value.
21397 InitVal = InitVal.extOrTrunc(NewWidth);
21398 InitVal.setIsSigned(NewSign);
21399 ECD->setInitVal(Context, InitVal);
21400
21401 // Adjust the Expr initializer and type.
21402 if (ECD->getInitExpr() &&
21403 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21404 ECD->setInitExpr(ImplicitCastExpr::Create(
21405 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21406 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21407 if (getLangOpts().CPlusPlus ||
21408 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21409 // C++ [dcl.enum]p4: Following the closing brace of an
21410 // enum-specifier, each enumerator has the type of its
21411 // enumeration.
21412 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21413 // with fixed underlying type is the enumerated type.
21414 ECD->setType(EnumType);
21415 else
21416 ECD->setType(NewTy);
21417 }
21418
21419 Enum->completeDefinition(BestType, BestPromotionType,
21420 NumPositiveBits, NumNegativeBits);
21421
21422 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21424
21425 if (Enum->isClosedFlag()) {
21426 for (Decl *D : Elements) {
21427 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21428 if (!ECD) continue; // Already issued a diagnostic.
21429
21430 llvm::APSInt InitVal = ECD->getInitVal();
21431 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21432 !IsValueInFlagEnum(Enum, InitVal, true))
21433 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21434 << ECD << Enum;
21435 }
21436 }
21437
21438 // Now that the enum type is defined, ensure it's not been underaligned.
21439 if (Enum->hasAttrs())
21441}
21442
21444 SourceLocation EndLoc) {
21445
21447 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21448 CurContext->addDecl(New);
21449 return New;
21450}
21451
21453 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21454 CurContext->addDecl(New);
21455 PushDeclContext(S, New);
21457 PushCompoundScope(false);
21458 return New;
21459}
21460
21462 if (Statement)
21463 D->setStmt(Statement);
21467}
21468
21470 IdentifierInfo* AliasName,
21471 SourceLocation PragmaLoc,
21472 SourceLocation NameLoc,
21473 SourceLocation AliasNameLoc) {
21474 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21476 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21478 AsmLabelAttr *Attr =
21479 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21480
21481 // If a declaration that:
21482 // 1) declares a function or a variable
21483 // 2) has external linkage
21484 // already exists, add a label attribute to it.
21485 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21486 if (isDeclExternC(PrevDecl))
21487 PrevDecl->addAttr(Attr);
21488 else
21489 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21490 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21491 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21492 } else
21493 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21494}
21495
21497 SourceLocation PragmaLoc,
21498 SourceLocation NameLoc) {
21499 NamedDecl *PrevDecl =
21501
21502 if (PrevDecl) {
21503 auto *Attr = WeakAttr::CreateImplicit(Context, PragmaLoc);
21504 if (checkWeakAttrCompatibility(*this, *PrevDecl, *Attr))
21505 PrevDecl->addAttr(Attr);
21506 } else {
21507 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21508 }
21509}
21510
21512 IdentifierInfo* AliasName,
21513 SourceLocation PragmaLoc,
21514 SourceLocation NameLoc,
21515 SourceLocation AliasNameLoc) {
21516 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21518 WeakInfo W = WeakInfo(Name, NameLoc);
21519
21520 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21521 if (!PrevDecl->hasAttr<AliasAttr>())
21522 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21524 } else {
21525 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21526 }
21527}
21528
21529/// Whether the definition \p FD is only handed to the ASTConsumer, and thus to
21530/// CodeGen, once it is used, so that it is never emitted unless it is used.
21531static bool isEmittedOnlyIfUsed(const FunctionDecl *FD) {
21532 // Lambda call operators are defined by their lambda expressions, which are
21533 // not top-level declarations. Implicit functions and functions defaulted on
21534 // their first declaration are defined when they are used.
21535 return isLambdaMethod(FD) || FD->isImplicit() ||
21537}
21538
21539/// Whether CodeGen emits \p FD regardless of whether it is used.
21540static bool isEmittedRegardlessOfUses(const Sema &S, const FunctionDecl *FD,
21541 bool Final) {
21542 const FunctionDecl *Def = FD->getDefinition();
21543 if (!Def || Def->hasSkippedBody())
21544 return false;
21545 // Immediate functions are never emitted. Whether an immediate-escalating
21546 // function is immediate is only known once its body is complete, so leave
21547 // that to the check at the end of the translation unit.
21548 const LangOptions &LangOpts = S.getLangOpts();
21549 if (Def->isImmediateFunction() ||
21550 (!Final && LangOpts.CPlusPlus20 && Def->isImmediateEscalating()))
21551 return false;
21552 if (isEmittedOnlyIfUsed(Def))
21553 return false;
21554 // An available externally definition is only emitted to be inlined into its
21555 // callers.
21556 ASTContext &Ctx = S.getASTContext();
21558 return false;
21559 return Ctx.shouldEmitCUDADecl(Def) &&
21560 (LangOpts.EmitAllDecls || Ctx.DeclMustBeEmitted(Def));
21561}
21562
21564 bool Final) {
21565 assert(FD && "Expected non-null FunctionDecl");
21566
21567 // Templates are emitted when they're instantiated.
21568 if (FD->isDependentContext())
21570
21571 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21572 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21573 FD->hasAttr<SYCLExternalAttr>()))
21575
21576 // Check whether this function is an externally visible definition.
21577 auto IsEmittedForExternalSymbol = [this, FD]() {
21578 // We have to check the GVA linkage of the function's *definition* -- if we
21579 // only have a declaration, we don't know whether or not the function will
21580 // be emitted, because (say) the definition could include "inline".
21581 const FunctionDecl *Def = FD->getDefinition();
21582
21583 // We can't compute linkage when we skip function bodies.
21584 return Def && !Def->hasSkippedBody() &&
21586 getASTContext().GetGVALinkageForFunction(Def));
21587 };
21588
21589 if (LangOpts.OpenMPIsTargetDevice) {
21590 // In OpenMP device mode we will not emit host only functions, or functions
21591 // we don't need due to their linkage.
21592 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21593 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21594 // DevTy may be changed later by
21595 // #pragma omp declare target to(*) device_type(*).
21596 // Therefore DevTy having no value does not imply host. The emission status
21597 // will be checked again at the end of compilation unit with Final = true.
21598 if (DevTy)
21599 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21601 // If we have an explicit value for the device type, or we are in a target
21602 // declare context, we need to emit all extern and used symbols.
21603 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21604 if (IsEmittedForExternalSymbol())
21606 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21607 // we'll omit it.
21608 if (Final)
21610 } else if (LangOpts.OpenMP > 45) {
21611 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21612 // function. In 5.0, no_host was introduced which might cause a function to
21613 // be omitted.
21614 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21615 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21616 if (DevTy)
21617 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21619 }
21620
21621 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21623
21624 if (LangOpts.CUDA) {
21625 // When compiling for device, host functions are never emitted. Similarly,
21626 // when compiling for host, device and global functions are never emitted.
21627 // (Technically, we do emit a host-side stub for global functions, but this
21628 // doesn't count for our purposes here.)
21630 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21632 if (!LangOpts.CUDAIsDevice &&
21635
21636 if (IsEmittedForExternalSymbol() ||
21637 isEmittedRegardlessOfUses(*this, FD, Final))
21639 }
21640
21641 // Otherwise, the function is known-emitted if it's in our set of
21642 // known-emitted functions.
21644}
21645
21647 // Host-side references to a __global__ function refer to the stub, so the
21648 // function itself is never emitted and therefore should not be marked.
21649 // If we have host fn calls kernel fn calls host+device, the HD function
21650 // does not get instantiated on the host. We model this by omitting at the
21651 // call to the kernel from the callgraph. This ensures that, when compiling
21652 // for host, only HD functions actually called from the host get marked as
21653 // known-emitted.
21654 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21656}
21657
21659 SourceLocation NewDefinitionLoc,
21660 NamedDecl **Suggested, bool &Visible) {
21661 Visible = hasVisibleDefinition(D, Suggested);
21662 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21663 // for declaratins which is attached to named modules.
21664 // We only did this if the current module is named module as we have better
21665 // diagnostics for declarations in global module and named modules.
21666 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21667 D->isInNamedModule())
21668 return false;
21669 // The redefinition of D in the **current** TU is allowed if D is invisible or
21670 // D is defined in the global module of other module units or D is defined in
21671 // the same header in a different module.
21672 return D->isInAnotherModuleUnit() || !Visible ||
21673 isFromSameSingleIncludeHeader(D, NewDefinitionLoc);
21674}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2210
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
#define CC_VLS_CASE(ABI_VLEN)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:82
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:181
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:236
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isEmittedOnlyIfUsed(const FunctionDecl *FD)
Whether the definition FD is only handed to the ASTConsumer, and thus to CodeGen, once it is used,...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:848
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool isEmittedRegardlessOfUses(const Sema &S, const FunctionDecl *FD, bool Final)
Whether CodeGen emits FD regardless of whether it is used.
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:612
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static bool checkWeakAttrCompatibility(Sema &S, const NamedDecl &ND, const WeakAttr &Attr)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const ValueDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:631
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:863
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void CheckForComparisonInEnumInitializer(SemaBase &Sema, const EnumDecl *Enum)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkModularFormatAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static bool isSYCLAddressSpace(LangAS AS)
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:913
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
IdentifierTable & Idents
Definition ASTContext.h:852
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
bool shouldEmitCUDADecl(const ValueDecl *D) const
Determines if the global variable or function D is emitted on the side of the CUDA/HIP compilation,...
CanQualType getCanonicalTagType(const TagDecl *TD) const
@ GE_Missing_type
Missing a type.
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3605
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1810
Expr * getSizeExpr() const
Definition TypeLoc.h:1830
TypeLoc getElementLoc() const
Definition TypeLoc.h:1838
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1818
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
bool isInherited() const
Definition Attr.h:102
bool isImplicit() const
Returns true if the attribute has been implicitly created instead of explicitly written by the user.
Definition Attr.h:106
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:107
SourceLocation getLocation() const
Definition Attr.h:100
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:643
AttributeFactory & getFactory() const
Definition ParsedAttr.h:739
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4576
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4564
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
StringRef getOpcodeStr() const
Definition Expr.h:4173
Expr * getRHS() const
Definition Expr.h:4159
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
A binding in a decomposition declaration.
Definition DeclCXX.h:4223
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
bool doesNotEscape() const
Definition Decl.h:5007
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:238
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:385
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:195
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3018
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2985
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3283
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2383
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3158
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2805
bool isVirtual() const
Definition DeclCXX.h:2208
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2232
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2331
bool isConst() const
Definition DeclCXX.h:2205
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
base_class_iterator bases_end()
Definition DeclCXX.h:618
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1578
base_class_range bases()
Definition DeclCXX.h:609
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:616
capture_const_range captures() const
Definition DeclCXX.h:1107
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1158
bool hasDefinition() const
Definition DeclCXX.h:562
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1069
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1129
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:187
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
static CharSourceRange getCharRange(SourceRange R)
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:336
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:376
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1410
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2261
bool isFileContext() const
Definition DeclBase.h:2199
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2609
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2141
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2124
bool isNamespace() const
Definition DeclBase.h:2221
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2204
bool isRecord() const
Definition DeclBase.h:2208
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2405
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2163
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2101
DeclContext * getNonTransparentContext()
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
SourceLocation getBeginLoc() const
Definition Expr.h:1394
Captures information about "declaration specifiers".
Definition DeclSpec.h:279
bool isVirtualSpecified() const
Definition DeclSpec.h:721
bool isModulePrivateSpecified() const
Definition DeclSpec.h:902
static const TST TST_typeof_unqualType
Definition DeclSpec.h:341
bool hasAutoTypeSpec() const
Definition DeclSpec.h:646
static const TST TST_typename
Definition DeclSpec.h:338
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:637
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:296
void ClearStorageClassSpecs()
Definition DeclSpec.h:566
bool isNoreturnSpecified() const
Definition DeclSpec.h:734
TST getTypeSpecType() const
Definition DeclSpec.h:588
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:561
SCS getStorageClassSpec() const
Definition DeclSpec.h:552
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:843
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:626
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:625
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:782
static const TST TST_interface
Definition DeclSpec.h:336
static const TST TST_typeofExpr
Definition DeclSpec.h:340
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:668
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:781
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:735
bool isExternInLinkageSpec() const
Definition DeclSpec.h:556
static const TST TST_union
Definition DeclSpec.h:334
SCS
storage-class-specifier
Definition DeclSpec.h:283
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:727
static const TST TST_int
Definition DeclSpec.h:317
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:903
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:598
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:861
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:553
ParsedAttributes & getAttributes()
Definition DeclSpec.h:946
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:697
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:669
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:728
Expr * getRepAsExpr() const
Definition DeclSpec.h:606
static const TST TST_enum
Definition DeclSpec.h:333
static const TST TST_decltype
Definition DeclSpec.h:343
static bool isDeclRep(TST T)
Definition DeclSpec.h:518
bool isInlineSpecified() const
Definition DeclSpec.h:710
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:670
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:342
static const TST TST_class
Definition DeclSpec.h:337
TypeSpecifierType TST
Definition DeclSpec.h:309
static const TST TST_void
Definition DeclSpec.h:311
void ClearConstexprSpec()
Definition DeclSpec.h:914
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:534
static const TST TST_atomic
Definition DeclSpec.h:353
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:562
Decl * getRepAsDecl() const
Definition DeclSpec.h:602
static const TST TST_unspecified
Definition DeclSpec.h:310
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:672
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:722
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:909
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:633
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:865
static const TSCS TSCS_thread_local
Definition DeclSpec.h:299
static const TST TST_error
Definition DeclSpec.h:363
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:717
bool isTypeSpecOwned() const
Definition DeclSpec.h:592
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:713
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:673
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:671
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:894
bool hasExplicitSpecifier() const
Definition DeclSpec.h:724
bool hasConstexprSpecifier() const
Definition DeclSpec.h:910
static const TST TST_typeofType
Definition DeclSpec.h:339
static const TST TST_auto
Definition DeclSpec.h:350
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:905
static const TST TST_struct
Definition DeclSpec.h:335
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1079
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1094
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:344
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:444
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:582
bool hasAttrs() const
Definition DeclBase.h:527
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:529
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:784
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1169
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:101
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:647
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:911
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1237
@ FOK_None
Not a friend object.
Definition DeclBase.h:1235
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1236
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:604
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1198
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2807
bool isInvalidDecl() const
Definition DeclBase.h:597
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1187
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:603
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:457
attr_range attrs() const
Definition DeclBase.h:544
AccessSpecifier getAccess() const
Definition DeclBase.h:516
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
void dropAttr()
Definition DeclBase.h:565
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1639
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1253
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
Kind getKind() const
Definition DeclBase.h:451
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:824
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2067
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2071
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:857
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:816
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2017
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:839
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2051
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2559
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2501
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
Expr * getAsmLabel() const
Definition DeclSpec.h:2810
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2849
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2786
void setRedeclaration(bool Val)
Definition DeclSpec.h:2872
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2436
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2439
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2183
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2736
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2779
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2821
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc, const LateParsedAttrList &LateAttrs={})
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2453
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2766
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2497
bool isRedeclaration() const
Definition DeclSpec.h:2873
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2789
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2167
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:412
bool isFunctionDefinition() const
Definition DeclSpec.h:2845
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2165
bool hasInitializer() const
Definition DeclSpec.h:2854
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2841
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2161
bool isInvalidType() const
Definition DeclSpec.h:2822
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:400
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2181
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2426
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2857
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:391
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2153
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2590
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
A decomposition declaration.
Definition DeclCXX.h:4287
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, SourceLocation RSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3742
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1884
SourceRange getSourceRange() const
Definition DeclSpec.h:1932
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1930
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2544
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3604
llvm::APSInt getInitVal() const
Definition Decl.h:3624
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5824
const Expr * getInitExpr() const
Definition Decl.h:3622
Represents an enum.
Definition Decl.h:4192
enumerator_range enumerators() const
Definition Decl.h:4338
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4410
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4374
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4377
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4424
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5182
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5221
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4419
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5196
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4360
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4272
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4365
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3386
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4817
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4802
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4863
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5957
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2082
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2862
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2345
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2645
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4280
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3806
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4273
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4268
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3371
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2470
bool isImmediateFunction() const
Definition Decl.cpp:3413
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2874
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2853
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4102
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3835
param_iterator param_end()
Definition Decl.h:2960
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3098
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2868
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3779
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2558
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2546
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3687
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4388
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2617
void setWillHaveBody(bool V=true)
Definition Decl.h:2859
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2765
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2612
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4398
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3820
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition Decl.cpp:4079
param_iterator param_begin()
Definition Decl.h:2959
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:3000
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2482
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3315
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3448
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4332
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3065
bool isStatic() const
Definition Decl.h:3106
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4622
void setTrivial(bool IT)
Definition Decl.h:2547
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4219
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
bool isDeletedAsWritten() const
Definition Decl.h:2713
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2522
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3691
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2526
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2597
bool isImmediateEscalating() const
Definition Decl.cpp:3384
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2518
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2852
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3441
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:3093
bool param_empty() const
Definition Decl.h:2958
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3228
void setRangeEnd(SourceLocation E)
Definition Decl.h:2374
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3775
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2554
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2590
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4645
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3110
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4213
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2642
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4492
void setDefaulted(bool D=true)
Definition Decl.h:2555
bool isConsteval() const
Definition Decl.h:2651
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:3039
void setBody(Stmt *B)
Definition Decl.cpp:3296
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3705
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3174
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2628
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4240
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3899
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2367
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3204
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2604
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3251
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:3076
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3761
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2858
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5484
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6093
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
unsigned getNumParams() const
Definition TypeBase.h:5826
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:6045
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5861
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Wrapper for source info for functions.
Definition TypeLoc.h:1675
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4855
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4967
CallingConv getCC() const
Definition TypeBase.h:4914
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4933
unsigned getRegParm() const
Definition TypeBase.h:4907
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4903
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4926
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4947
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4961
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
ExtInfo getExtInfo() const
Definition TypeBase.h:5100
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3847
unsigned getRegParmType() const
Definition TypeBase.h:5087
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
bool getCmseNSCallAttr() const
Definition TypeBase.h:5098
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3648
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5851
void setInherited(bool I)
Definition Attr.h:164
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2616
child_range children()
Definition Expr.h:5584
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
Represents the declaration of a label.
Definition Decl.h:526
bool isResolvedMSAsmLabel() const
Definition Decl.h:561
LabelStmt * getStmt() const
Definition Decl.h:550
bool isMSAsmLabel() const
Definition Decl.h:560
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2088
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool isCompatibleWithMSVC() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1437
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1381
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3053
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Describes a module or submodule.
Definition Module.h:340
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
Module * Parent
The parent of this module.
Definition Module.h:389
bool isPrivateModule() const
Definition Module.h:451
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:869
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:885
bool isModulePartition() const
Is this a module partition.
Definition Module.h:874
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:441
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:242
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1087
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1097
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:446
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:481
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:431
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1873
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:719
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
bool isExternallyVisible() const
Definition Decl.h:435
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1134
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:399
Represent a C++ namespace.
Definition Decl.h:594
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:645
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2781
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1303
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
bool isOptional() const
Definition DeclObjC.h:508
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:353
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:895
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:280
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1459
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3383
Represents a parameter to a function.
Definition Decl.h:1832
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1896
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1865
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1924
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2963
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2986
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:838
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:918
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:958
AttributePool & getPool() const
Definition ParsedAttr.h:965
Pointer-authentication qualifiers.
Definition TypeBase.h:153
bool isAddressDiscriminated() const
Definition TypeBase.h:266
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1525
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8656
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3149
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:194
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:3215
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3199
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1449
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8699
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8635
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1325
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2914
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1509
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1514
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8518
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8525
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4982
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasConst() const
Definition TypeBase.h:458
bool hasVolatile() const
Definition TypeBase.h:468
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
bool empty() const
Definition TypeBase.h:648
static std::string getAddrSpaceAsString(LangAS AS)
Represents a struct/union/class.
Definition Decl.h:4506
field_range fields() const
Definition Decl.h:4709
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5340
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
field_iterator field_begin() const
Definition Decl.cpp:5383
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7589
void setMemberSpecialization()
Note that this member template is a specialization.
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5514
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3216
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:395
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:414
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:325
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:335
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:614
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
void setLookupEntity(DeclContext *E)
Definition Scope.h:400
unsigned getMSLastManglingNumber() const
Definition Scope.h:372
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
unsigned getMSCurManglingNumber() const
Definition Scope.h:378
bool decl_empty() const
Definition Scope.h:346
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:329
Scope * getDeclParent()
Definition Scope.h:321
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:605
decl_range decls() const
Definition Scope.h:342
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition Scope.cpp:106
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:473
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:406
void applyNRVO()
Definition Scope.cpp:171
Scope * getTemplateParamParent()
Definition Scope.h:318
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void DiagnoseUnguardedBuiltinUsage(FunctionDecl *FD)
void checkNamedBarrierWrapper(RecordDecl *R)
Called in ActOnFields - whenever a C/C++ Record is being finalized.
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1640
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:745
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:874
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:939
void CheckEntryPoint(FunctionDecl *FD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:762
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:728
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:940
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:798
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:742
void ActOnVariableDeclarator(VarDecl *VD)
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
StmtResult BuildUnresolvedSYCLKernelCallStmt(CompoundStmt *Body, Expr *LaunchIdExpr)
Builds an UnresolvedSYCLKernelCallStmt to wrap 'Body'.
Definition SemaSYCL.cpp:831
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body, Expr *LaunchIdExpr)
Builds a SYCLKernelCallStmt to wrap 'Body' and to be used as the body of 'FD'.
Definition SemaSYCL.cpp:786
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:293
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:310
ExprResult BuildSYCLKernelLaunchIdExpr(FunctionDecl *FD, QualType KernelName)
Builds an expression for the lookup of a 'sycl_kernel_launch' template with 'KernelName' as an explic...
Definition SemaSYCL.cpp:440
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
SwiftAttrAttr * mergeAttrAttr(Decl *D, const SwiftAttrAttr &SAA)
Definition SemaSwift.cpp:42
WebAssemblyExportNameAttr * mergeExportNameAttr(Decl *D, const WebAssemblyExportNameAttr &AL)
Definition SemaWasm.cpp:386
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:353
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:319
bool IsAlignAttr() const
Definition Sema.h:1948
Mode getAlignMode() const
Definition Sema.h:1950
A RAII object to temporarily push a declaration context.
Definition Sema.h:3639
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1411
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1423
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3865
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3875
static NameClassification Unknown()
Definition Sema.h:3845
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3849
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3893
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3881
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3855
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3887
static NameClassification UndeclaredNonType()
Definition Sema.h:3861
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3869
static NameClassification Error()
Definition Sema.h:3841
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12708
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12742
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1473
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3743
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13322
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2721
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1164
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8428
bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc)
Determine if a definition at NewLoc coincides with PrevD.
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9525
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9529
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9548
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9564
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9561
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9537
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9532
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
void ActOnPopScope(SourceLocation Loc, Scope *S)
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
void deduceOpenCLAddressSpace(VarDecl *decl)
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1558
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4933
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1874
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6673
bool areDocumentationDiagsEnabled(SourceLocation Loc)
Returns true if any of the documentation warnings is enabled at Loc.
Definition Sema.cpp:2808
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1498
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:933
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2105
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2099
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
@ Default
= default ;
Definition Sema.h:4322
@ Delete
deleted-function-body
Definition Sema.h:4328
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1583
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1779
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:689
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1331
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:229
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2393
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void ActOnReenterFunctionPrototypeParams(Scope *S, ArrayRef< ParmVarDecl * > Params)
Add Params to scope, so a late-parsed attribute can name them.
void * SkippedDefinitionContext
Definition Sema.h:4546
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1543
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1398
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2102
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3733
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:934
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void CheckCoroutineWrapper(FunctionDecl *FD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2098
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:774
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
InitSegPragmaState CurInitSeg
Definition Sema.h:2145
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1235
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1784
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12406
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8546
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2512
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4772
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
void addImplicitCallingConvAbiTag(FunctionDecl *FD)
Attach the ABI tag a standard calling convention variant requires, as an implicit abi_tag attribute.
FPOptions & getCurFPFeatures()
Definition Sema.h:929
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2530
void PopCompoundScope()
Definition Sema.cpp:2663
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14707
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14710
@ UPPC_Initializer
An initializer.
Definition Sema.h:14722
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14716
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14695
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14734
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14719
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14698
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14701
const LangOptions & getLangOpts() const
Definition Sema.h:927
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2624
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3750
SemaOpenACC & OpenACC()
Definition Sema.h:1548
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1330
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2299
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1329
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2739
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15838
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1508
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1875
SemaRISCV & RISCV()
Definition Sema.h:1573
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:16024
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:218
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition Sema.h:1588
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2087
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7140
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2097
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1168
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:912
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4948
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1366
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2658
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
bool CheckNontrivialField(FieldDecl *FD)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7137
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:649
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15832
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3716
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:10057
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
void ActOnExitFunctionPrototypeParams(Scope *S, ArrayRef< ParmVarDecl * > Params)
Undo the above, for when S outlives the attribute so no scope pop removes them.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1553
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1758
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3747
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14241
SourceManager & getSourceManager() const
Definition Sema.h:932
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_enum attribute.
Definition Sema.h:3690
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1876
@ NTCUK_Destruct
Definition Sema.h:4261
@ NTCUK_Init
Definition Sema.h:4260
@ NTCUK_Copy
Definition Sema.h:4262
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1873
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6934
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15787
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2679
RedeclarationKind forRedeclarationInCurContext() const
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6695
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:641
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:276
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1332
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4835
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7144
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1371
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1905
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:10086
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
SemaPPC & PPC()
Definition Sema.h:1563
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:76
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1290
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3740
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3720
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8501
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
DiagnosticsEngine & Diags
Definition Sema.h:1333
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:928
FPOptions CurFPFeatures
Definition Sema.h:1327
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1109
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2096
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
@ TPC_FriendFunctionTemplate
Definition Sema.h:11839
@ TPC_ClassTemplateMember
Definition Sema.h:11837
@ TPC_FunctionTemplate
Definition Sema.h:11836
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11840
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
friend class InitializationSequence
Definition Sema.h:1613
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
Definition Sema.cpp:976
void DiagnoseUnusedDecl(const NamedDecl *ND)
void PopDeclContext()
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6711
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3709
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2280
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1872
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6451
@ AbstractReturnType
Definition Sema.h:6449
@ AbstractFieldType
Definition Sema.h:6452
@ AbstractIvarType
Definition Sema.h:6453
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8550
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6585
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1323
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition Sema.h:3686
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
SemaWasm & Wasm()
Definition Sema.h:1598
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
IdentifierResolver IdResolver
Definition Sema.h:3632
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2670
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:732
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:149
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8509
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1322
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition Sema.h:3988
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SemaARM & ARM()
Definition Sema.h:1478
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8845
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:2015
StringRef getString() const
Definition Expr.h:1912
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:4184
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:5037
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3994
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3980
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
bool isStruct() const
Definition Decl.h:4106
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:5009
bool isUnion() const
Definition Decl.h:4109
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:4131
TagKind getTagKind() const
Definition Decl.h:4098
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:4044
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
Definition TargetInfo.h:228
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
bool isOneOf(Ts... Ks) const
Definition Token.h:105
bool isNot(tok::TokenKind K) const
Definition Token.h:111
A declaration that models statements at global scope.
Definition Decl.h:4816
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5975
void setStmt(Stmt *S)
Definition Decl.cpp:5997
Represents a declaration of a type.
Definition Decl.h:3694
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1468
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:892
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isStructureType() const
Definition Type.cpp:811
bool isDependentSizedArrayType() const
Definition TypeBase.h:8934
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isFunctionReferenceType() const
Definition TypeBase.h:8889
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9391
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3239
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9507
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8918
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9371
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8914
bool isFunctionPointerType() const
Definition TypeBase.h:8882
bool isPointerType() const
Definition TypeBase.h:8815
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isHLSLIntangibleType() const
Definition Type.cpp:5726
bool isScalarType() const
Definition TypeBase.h:9310
bool isVariableArrayType() const
Definition TypeBase.h:8926
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isImageType() const
Definition TypeBase.h:9079
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isOpenCLSpecificType() const
Definition TypeBase.h:9115
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2631
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:9208
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2235
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2779
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2857
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9384
bool isAtomicType() const
Definition TypeBase.h:9007
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isObjCIdType() const
Definition TypeBase.h:9027
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isObjCObjectType() const
Definition TypeBase.h:8998
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
bool isEventT() const
Definition TypeBase.h:9063
bool isPointerOrReferenceType() const
Definition TypeBase.h:8819
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8900
bool isFloatingType() const
Definition Type.cpp:2517
bool isAnyPointerType() const
Definition TypeBase.h:8823
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2240
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5717
bool isUnionType() const
Definition Type.cpp:851
bool isReserveIDT() const
Definition TypeBase.h:9075
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3848
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5874
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3793
QualType getUnderlyingType() const
Definition Decl.h:3798
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3804
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6392
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2409
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1110
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1142
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1146
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1198
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1150
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1171
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1319
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1154
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1168
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1157
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1138
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1192
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1162
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:464
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3437
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3501
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:785
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5701
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5695
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2802
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2132
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1562
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
TLSKind getTLSKind() const
Definition Decl.cpp:2149
bool hasInit() const
Definition Decl.cpp:2400
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1489
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2256
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2463
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2238
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
bool isCXXCondDecl() const
Definition Decl.h:1648
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:945
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:948
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:942
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2144
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1630
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
void assignAddressSpace(const ASTContext &Ctxt, LangAS AS)
Apply a deduced address space, if one isn't already set.
Definition Decl.cpp:2932
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2368
void setInlineSpecified()
Definition Decl.h:1595
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2764
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1367
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1181
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1588
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1185
const Expr * getInit() const
Definition Decl.h:1393
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1240
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2431
void setConstexpr(bool IC)
Definition Decl.h:1609
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:957
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:960
@ TLS_None
Not a TLS variable.
Definition Decl.h:954
void setInit(Expr *I)
Definition Decl.cpp:2470
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2347
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1323
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1320
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1326
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2807
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2226
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1176
void setImplicitlyInline()
Definition Decl.h:1600
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1513
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1625
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2711
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1287
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2771
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:676
bool isVariableCapture() const
Definition ScopeInfo.h:651
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:746
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:733
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:722
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1099
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:738
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:499
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
Expr * SYCLKernelLaunchIdExpr
An unresolved identifier lookup expression for an implicit call to a SYCL kernel launch function in a...
Definition ScopeInfo.h:255
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:887
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:918
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:884
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:951
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:899
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
constexpr bool isInitializedByPipeline(LangAS AS)
Definition HLSLRuntime.h:34
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:82
@ TST_class
Definition Specifiers.h:83
@ TST_union
Definition Specifiers.h:81
@ TST_enum
Definition Specifiers.h:80
@ TST_interface
Definition Specifiers.h:84
ImplicitTypenameContext
Definition DeclSpec.h:1979
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:827
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:823
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:819
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:216
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_Internal
Definition Linkage.h:73
CUDAFunctionTarget
Definition Cuda.h:65
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:275
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:597
@ TemplateTemplateArgument
Definition Sema.h:606
NonTrivialCUnionContext
Definition Sema.h:525
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:621
@ None
Don't merge availability attributes at all.
Definition Sema.h:623
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:629
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:635
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:626
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:632
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1106
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1104
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1102
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1098
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1096
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1094
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1088
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1100
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1090
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1092
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_public
Definition Specifiers.h:128
@ AS_protected
Definition Specifiers.h:129
@ AS_none
Definition Specifiers.h:131
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:252
@ SC_Auto
Definition Specifiers.h:260
@ SC_PrivateExtern
Definition Specifiers.h:257
@ SC_Extern
Definition Specifiers.h:255
@ SC_Register
Definition Specifiers.h:261
@ SC_Static
Definition Specifiers.h:256
@ SC_None
Definition Specifiers.h:254
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:245
@ TSCS_unspecified
Definition Specifiers.h:240
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:248
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:242
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:344
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:609
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:322
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:444
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6171
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6176
@ Struct
The "struct" keyword.
Definition TypeBase.h:6173
@ Class
The "class" keyword.
Definition TypeBase.h:6182
@ Union
The "union" keyword.
Definition TypeBase.h:6179
@ Enum
The "enum" keyword.
Definition TypeBase.h:6185
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4499
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2031
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
MultiVersionKind
Definition Decl.h:2021
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:375
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:427
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_X86StdCall
Definition Specifiers.h:284
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:833
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6164
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1787
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:90
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1516
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1667
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1491
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1450
const IdentifierInfo * Ident
Definition DeclSpec.h:1422
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1330
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1751
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1732
FunctionTypeInfo Fun
Definition DeclSpec.h:1730
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1779
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
Extra information about a function prototype.
Definition TypeBase.h:5633
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5660
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6210
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3500
An element in an Objective-C dictionary literal.
Definition ExprObjC.h:294
Expr * Value
The value of the dictionary element.
Definition ExprObjC.h:299
Expr * Key
The key for the dictionary element.
Definition ExprObjC.h:296
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:59
std::vector< std::string > Features
Definition TargetInfo.h:60
Describes how types, statements, expressions, and declarations should be printed.
ValueType CurrentValue
Definition Sema.h:2072
SourceLocation CurrentPragmaLocation
Definition Sema.h:2073
bool CheckSameAsPrevious
Definition Sema.h:359
NamedDecl * Previous
Definition Sema.h:360
NamedDecl * New
Definition Sema.h:361
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105
SourceLocation SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new",...
Definition DeclSpec.h:1130
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1121