clang 20.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"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.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"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaWasm.h"
58#include "clang/Sema/Template.h"
59#include "llvm/ADT/STLForwardCompat.h"
60#include "llvm/ADT/SmallString.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/TargetParser/Triple.h"
63#include <algorithm>
64#include <cstring>
65#include <functional>
66#include <optional>
67#include <unordered_map>
68
69using namespace clang;
70using namespace sema;
71
73 if (OwnedType) {
74 Decl *Group[2] = { OwnedType, Ptr };
76 }
77
79}
80
81namespace {
82
83class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
84 public:
85 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
86 bool AllowTemplates = false,
87 bool AllowNonTemplates = true)
88 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
89 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
90 WantExpressionKeywords = false;
91 WantCXXNamedCasts = false;
92 WantRemainingKeywords = false;
93 }
94
95 bool ValidateCandidate(const TypoCorrection &candidate) override {
96 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
97 if (!AllowInvalidDecl && ND->isInvalidDecl())
98 return false;
99
100 if (getAsTypeTemplateDecl(ND))
101 return AllowTemplates;
102
103 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
104 if (!IsType)
105 return false;
106
107 if (AllowNonTemplates)
108 return true;
109
110 // An injected-class-name of a class template (specialization) is valid
111 // as a template or as a non-template.
112 if (AllowTemplates) {
113 auto *RD = dyn_cast<CXXRecordDecl>(ND);
114 if (!RD || !RD->isInjectedClassName())
115 return false;
116 RD = cast<CXXRecordDecl>(RD->getDeclContext());
117 return RD->getDescribedClassTemplate() ||
118 isa<ClassTemplateSpecializationDecl>(RD);
119 }
120
121 return false;
122 }
123
124 return !WantClassName && candidate.isKeyword();
125 }
126
127 std::unique_ptr<CorrectionCandidateCallback> clone() override {
128 return std::make_unique<TypeNameValidatorCCC>(*this);
129 }
130
131 private:
132 bool AllowInvalidDecl;
133 bool WantClassName;
134 bool AllowTemplates;
135 bool AllowNonTemplates;
136};
137
138} // end anonymous namespace
139
140namespace {
141enum class UnqualifiedTypeNameLookupResult {
142 NotFound,
143 FoundNonType,
144 FoundType
145};
146} // end anonymous namespace
147
148/// Tries to perform unqualified lookup of the type decls in bases for
149/// dependent class.
150/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
151/// type decl, \a FoundType if only type decls are found.
152static UnqualifiedTypeNameLookupResult
154 SourceLocation NameLoc,
155 const CXXRecordDecl *RD) {
156 if (!RD->hasDefinition())
157 return UnqualifiedTypeNameLookupResult::NotFound;
158 // Look for type decls in base classes.
159 UnqualifiedTypeNameLookupResult FoundTypeDecl =
160 UnqualifiedTypeNameLookupResult::NotFound;
161 for (const auto &Base : RD->bases()) {
162 const CXXRecordDecl *BaseRD = nullptr;
163 if (auto *BaseTT = Base.getType()->getAs<TagType>())
164 BaseRD = BaseTT->getAsCXXRecordDecl();
165 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
166 // Look for type decls in dependent base classes that have known primary
167 // templates.
168 if (!TST || !TST->isDependentType())
169 continue;
170 auto *TD = TST->getTemplateName().getAsTemplateDecl();
171 if (!TD)
172 continue;
173 if (auto *BasePrimaryTemplate =
174 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
175 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
176 BaseRD = BasePrimaryTemplate;
177 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
179 CTD->findPartialSpecialization(Base.getType()))
180 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
181 BaseRD = PS;
182 }
183 }
184 }
185 if (BaseRD) {
186 for (NamedDecl *ND : BaseRD->lookup(&II)) {
187 if (!isa<TypeDecl>(ND))
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190 }
191 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
192 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
193 case UnqualifiedTypeNameLookupResult::FoundNonType:
194 return UnqualifiedTypeNameLookupResult::FoundNonType;
195 case UnqualifiedTypeNameLookupResult::FoundType:
196 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
197 break;
198 case UnqualifiedTypeNameLookupResult::NotFound:
199 break;
200 }
201 }
202 }
203 }
204
205 return FoundTypeDecl;
206}
207
209 const IdentifierInfo &II,
210 SourceLocation NameLoc) {
211 // Lookup in the parent class template context, if any.
212 const CXXRecordDecl *RD = nullptr;
213 UnqualifiedTypeNameLookupResult FoundTypeDecl =
214 UnqualifiedTypeNameLookupResult::NotFound;
215 for (DeclContext *DC = S.CurContext;
216 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
217 DC = DC->getParent()) {
218 // Look for type decls in dependent base classes that have known primary
219 // templates.
220 RD = dyn_cast<CXXRecordDecl>(DC);
221 if (RD && RD->getDescribedClassTemplate())
222 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
223 }
224 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
225 return nullptr;
226
227 // We found some types in dependent base classes. Recover as if the user
228 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
229 // lookup during template instantiation.
230 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
231
232 ASTContext &Context = S.Context;
233 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
234 cast<Type>(Context.getRecordType(RD)));
235 QualType T =
237
238 CXXScopeSpec SS;
239 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
240
241 TypeLocBuilder Builder;
242 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
243 DepTL.setNameLoc(NameLoc);
245 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
246 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
247}
248
249/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
251 SourceLocation NameLoc,
252 bool WantNontrivialTypeSourceInfo = true) {
253 switch (T->getTypeClass()) {
254 case Type::DeducedTemplateSpecialization:
255 case Type::Enum:
256 case Type::InjectedClassName:
257 case Type::Record:
258 case Type::Typedef:
259 case Type::UnresolvedUsing:
260 case Type::Using:
261 break;
262 // These can never be qualified so an ElaboratedType node
263 // would carry no additional meaning.
264 case Type::ObjCInterface:
265 case Type::ObjCTypeParam:
266 case Type::TemplateTypeParm:
267 return ParsedType::make(T);
268 default:
269 llvm_unreachable("Unexpected Type Class");
270 }
271
272 if (!SS || SS->isEmpty())
274 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
275
277 if (!WantNontrivialTypeSourceInfo)
278 return ParsedType::make(ElTy);
279
280 TypeLocBuilder Builder;
281 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
282 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
285 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
286}
287
289 Scope *S, CXXScopeSpec *SS, bool isClassName,
290 bool HasTrailingDot, ParsedType ObjectTypePtr,
291 bool IsCtorOrDtorName,
292 bool WantNontrivialTypeSourceInfo,
293 bool IsClassTemplateDeductionContext,
294 ImplicitTypenameContext AllowImplicitTypename,
295 IdentifierInfo **CorrectedII) {
296 // FIXME: Consider allowing this outside C++1z mode as an extension.
297 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
298 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
299 !isClassName && !HasTrailingDot;
300
301 // Determine where we will perform name lookup.
302 DeclContext *LookupCtx = nullptr;
303 if (ObjectTypePtr) {
304 QualType ObjectType = ObjectTypePtr.get();
305 if (ObjectType->isRecordType())
306 LookupCtx = computeDeclContext(ObjectType);
307 } else if (SS && SS->isNotEmpty()) {
308 LookupCtx = computeDeclContext(*SS, false);
309
310 if (!LookupCtx) {
311 if (isDependentScopeSpecifier(*SS)) {
312 // C++ [temp.res]p3:
313 // A qualified-id that refers to a type and in which the
314 // nested-name-specifier depends on a template-parameter (14.6.2)
315 // shall be prefixed by the keyword typename to indicate that the
316 // qualified-id denotes a type, forming an
317 // elaborated-type-specifier (7.1.5.3).
318 //
319 // We therefore do not perform any name lookup if the result would
320 // refer to a member of an unknown specialization.
321 // In C++2a, in several contexts a 'typename' is not required. Also
322 // allow this as an extension.
323 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
324 !isClassName && !IsCtorOrDtorName)
325 return nullptr;
326 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
327 if (IsImplicitTypename) {
328 SourceLocation QualifiedLoc = SS->getRange().getBegin();
330 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
331 else
332 Diag(QualifiedLoc, diag::ext_implicit_typename)
333 << SS->getScopeRep() << II.getName()
334 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
335 }
336
337 // We know from the grammar that this name refers to a type,
338 // so build a dependent node to describe the type.
339 if (WantNontrivialTypeSourceInfo)
340 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
341 (ImplicitTypenameContext)IsImplicitTypename)
342 .get();
343
346 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
348 SourceLocation(), QualifierLoc, II, NameLoc);
349 return ParsedType::make(T);
350 }
351
352 return nullptr;
353 }
354
355 if (!LookupCtx->isDependentContext() &&
356 RequireCompleteDeclContext(*SS, LookupCtx))
357 return nullptr;
358 }
359
360 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
361 // lookup for class-names.
362 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
364 LookupResult Result(*this, &II, NameLoc, Kind);
365 if (LookupCtx) {
366 // Perform "qualified" name lookup into the declaration context we
367 // computed, which is either the type of the base of a member access
368 // expression or the declaration context associated with a prior
369 // nested-name-specifier.
370 LookupQualifiedName(Result, LookupCtx);
371
372 if (ObjectTypePtr && Result.empty()) {
373 // C++ [basic.lookup.classref]p3:
374 // If the unqualified-id is ~type-name, the type-name is looked up
375 // in the context of the entire postfix-expression. If the type T of
376 // the object expression is of a class type C, the type-name is also
377 // looked up in the scope of class C. At least one of the lookups shall
378 // find a name that refers to (possibly cv-qualified) T.
379 LookupName(Result, S);
380 }
381 } else {
382 // Perform unqualified name lookup.
383 LookupName(Result, S);
384
385 // For unqualified lookup in a class template in MSVC mode, look into
386 // dependent base classes where the primary class template is known.
387 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
388 if (ParsedType TypeInBase =
389 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
390 return TypeInBase;
391 }
392 }
393
394 NamedDecl *IIDecl = nullptr;
395 UsingShadowDecl *FoundUsingShadow = nullptr;
396 switch (Result.getResultKind()) {
398 if (CorrectedII) {
399 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
400 AllowDeducedTemplate);
401 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
402 S, SS, CCC, CTK_ErrorRecovery);
403 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
404 TemplateTy Template;
405 bool MemberOfUnknownSpecialization;
407 TemplateName.setIdentifier(NewII, NameLoc);
409 CXXScopeSpec NewSS, *NewSSPtr = SS;
410 if (SS && NNS) {
411 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
412 NewSSPtr = &NewSS;
413 }
414 if (Correction && (NNS || NewII != &II) &&
415 // Ignore a correction to a template type as the to-be-corrected
416 // identifier is not a template (typo correction for template names
417 // is handled elsewhere).
418 !(getLangOpts().CPlusPlus && NewSSPtr &&
419 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
420 Template, MemberOfUnknownSpecialization))) {
421 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
422 isClassName, HasTrailingDot, ObjectTypePtr,
423 IsCtorOrDtorName,
424 WantNontrivialTypeSourceInfo,
425 IsClassTemplateDeductionContext);
426 if (Ty) {
427 diagnoseTypo(Correction,
428 PDiag(diag::err_unknown_type_or_class_name_suggest)
429 << Result.getLookupName() << isClassName);
430 if (SS && NNS)
431 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
432 *CorrectedII = NewII;
433 return Ty;
434 }
435 }
436 }
437 Result.suppressDiagnostics();
438 return nullptr;
440 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
442 SS->getScopeRep(), &II);
443 TypeLocBuilder TLB;
447 TL.setNameLoc(NameLoc);
449 }
450 [[fallthrough]];
453 Result.suppressDiagnostics();
454 return nullptr;
455
457 // Recover from type-hiding ambiguities by hiding the type. We'll
458 // do the lookup again when looking for an object, and we can
459 // diagnose the error then. If we don't do this, then the error
460 // about hiding the type will be immediately followed by an error
461 // that only makes sense if the identifier was treated like a type.
462 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
463 Result.suppressDiagnostics();
464 return nullptr;
465 }
466
467 // Look to see if we have a type anywhere in the list of results.
468 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
469 Res != ResEnd; ++Res) {
470 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
471 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
472 RealRes) ||
473 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
474 if (!IIDecl ||
475 // Make the selection of the recovery decl deterministic.
476 RealRes->getLocation() < IIDecl->getLocation()) {
477 IIDecl = RealRes;
478 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
479 }
480 }
481 }
482
483 if (!IIDecl) {
484 // None of the entities we found is a type, so there is no way
485 // to even assume that the result is a type. In this case, don't
486 // complain about the ambiguity. The parser will either try to
487 // perform this lookup again (e.g., as an object name), which
488 // will produce the ambiguity, or will complain that it expected
489 // a type name.
490 Result.suppressDiagnostics();
491 return nullptr;
492 }
493
494 // We found a type within the ambiguous lookup; diagnose the
495 // ambiguity and then return that type. This might be the right
496 // answer, or it might not be, but it suppresses any attempt to
497 // perform the name lookup again.
498 break;
499
501 IIDecl = Result.getFoundDecl();
502 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
503 break;
504 }
505
506 assert(IIDecl && "Didn't find decl");
507
508 QualType T;
509 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
510 // C++ [class.qual]p2: A lookup that would find the injected-class-name
511 // instead names the constructors of the class, except when naming a class.
512 // This is ill-formed when we're not actually forming a ctor or dtor name.
513 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
514 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
515 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
516 FoundRD->isInjectedClassName() &&
517 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
518 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
519 << &II << /*Type*/1;
520
521 DiagnoseUseOfDecl(IIDecl, NameLoc);
522
524 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
525 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
526 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
527 if (!HasTrailingDot)
529 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
530 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
531 (void)DiagnoseUseOfDecl(UD, NameLoc);
532 // Recover with 'int'
534 } else if (AllowDeducedTemplate) {
535 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
536 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
538 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
539 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
541 false);
542 // Don't wrap in a further UsingType.
543 FoundUsingShadow = nullptr;
544 }
545 }
546
547 if (T.isNull()) {
548 // If it's not plausibly a type, suppress diagnostics.
549 Result.suppressDiagnostics();
550 return nullptr;
551 }
552
553 if (FoundUsingShadow)
554 T = Context.getUsingType(FoundUsingShadow, T);
555
556 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
557}
558
559// Builds a fake NNS for the given decl context.
560static NestedNameSpecifier *
562 for (;; DC = DC->getLookupParent()) {
563 DC = DC->getPrimaryContext();
564 auto *ND = dyn_cast<NamespaceDecl>(DC);
565 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
566 return NestedNameSpecifier::Create(Context, nullptr, ND);
567 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
568 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569 RD->getTypeForDecl());
570 else if (isa<TranslationUnitDecl>(DC))
572 }
573 llvm_unreachable("something isn't in TU scope?");
574}
575
576/// Find the parent class with dependent bases of the innermost enclosing method
577/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
578/// up allowing unqualified dependent type names at class-level, which MSVC
579/// correctly rejects.
580static const CXXRecordDecl *
582 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
583 DC = DC->getPrimaryContext();
584 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
585 if (MD->getParent()->hasAnyDependentBases())
586 return MD->getParent();
587 }
588 return nullptr;
589}
590
592 SourceLocation NameLoc,
593 bool IsTemplateTypeArg) {
594 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
595
596 NestedNameSpecifier *NNS = nullptr;
597 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
598 // If we weren't able to parse a default template argument, delay lookup
599 // until instantiation time by making a non-dependent DependentTypeName. We
600 // pretend we saw a NestedNameSpecifier referring to the current scope, and
601 // lookup is retried.
602 // FIXME: This hurts our diagnostic quality, since we get errors like "no
603 // type named 'Foo' in 'current_namespace'" when the user didn't write any
604 // name specifiers.
606 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
607 } else if (const CXXRecordDecl *RD =
609 // Build a DependentNameType that will perform lookup into RD at
610 // instantiation time.
611 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
612 RD->getTypeForDecl());
613
614 // Diagnose that this identifier was undeclared, and retry the lookup during
615 // template instantiation.
616 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
617 << RD;
618 } else {
619 // This is not a situation that we should recover from.
620 return ParsedType();
621 }
622
623 QualType T =
625
626 // Build type location information. We synthesized the qualifier, so we have
627 // to build a fake NestedNameSpecifierLoc.
628 NestedNameSpecifierLocBuilder NNSLocBuilder;
629 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
630 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
631
632 TypeLocBuilder Builder;
633 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
634 DepTL.setNameLoc(NameLoc);
636 DepTL.setQualifierLoc(QualifierLoc);
637 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
638}
639
641 // Do a tag name lookup in this scope.
642 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
643 LookupName(R, S, false);
646 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
647 switch (TD->getTagKind()) {
653 return DeclSpec::TST_union;
655 return DeclSpec::TST_class;
657 return DeclSpec::TST_enum;
658 }
659 }
660
662}
663
665 if (CurContext->isRecord()) {
667 return true;
668
669 const Type *Ty = SS->getScopeRep()->getAsType();
670
671 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672 for (const auto &Base : RD->bases())
673 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674 return true;
675 return S->isFunctionPrototypeScope();
676 }
677 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678}
679
681 SourceLocation IILoc,
682 Scope *S,
683 CXXScopeSpec *SS,
684 ParsedType &SuggestedType,
685 bool IsTemplateName) {
686 // Don't report typename errors for editor placeholders.
687 if (II->isEditorPlaceholder())
688 return;
689 // We don't have anything to suggest (yet).
690 SuggestedType = nullptr;
691
692 // There may have been a typo in the name of the type. Look up typo
693 // results, in case we have something that we can suggest.
694 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695 /*AllowTemplates=*/IsTemplateName,
696 /*AllowNonTemplates=*/!IsTemplateName);
697 if (TypoCorrection Corrected =
699 CCC, CTK_ErrorRecovery)) {
700 // FIXME: Support error recovery for the template-name case.
701 bool CanRecover = !IsTemplateName;
702 if (Corrected.isKeyword()) {
703 // We corrected to a keyword.
704 diagnoseTypo(Corrected,
705 PDiag(IsTemplateName ? diag::err_no_template_suggest
706 : diag::err_unknown_typename_suggest)
707 << II);
708 II = Corrected.getCorrectionAsIdentifierInfo();
709 } else {
710 // We found a similarly-named type or interface; suggest that.
711 if (!SS || !SS->isSet()) {
712 diagnoseTypo(Corrected,
713 PDiag(IsTemplateName ? diag::err_no_template_suggest
714 : diag::err_unknown_typename_suggest)
715 << II, CanRecover);
716 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718 bool DroppedSpecifier =
719 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
720 diagnoseTypo(Corrected,
721 PDiag(IsTemplateName
722 ? diag::err_no_member_template_suggest
723 : diag::err_unknown_nested_typename_suggest)
724 << II << DC << DroppedSpecifier << SS->getRange(),
725 CanRecover);
726 } else {
727 llvm_unreachable("could not have corrected a typo here");
728 }
729
730 if (!CanRecover)
731 return;
732
733 CXXScopeSpec tmpSS;
734 if (Corrected.getCorrectionSpecifier())
735 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736 SourceRange(IILoc));
737 // FIXME: Support class template argument deduction here.
738 SuggestedType =
739 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741 /*IsCtorOrDtorName=*/false,
742 /*WantNontrivialTypeSourceInfo=*/true);
743 }
744 return;
745 }
746
747 if (getLangOpts().CPlusPlus && !IsTemplateName) {
748 // See if II is a class template that the user forgot to pass arguments to.
749 UnqualifiedId Name;
750 Name.setIdentifier(II, IILoc);
751 CXXScopeSpec EmptySS;
752 TemplateTy TemplateResult;
753 bool MemberOfUnknownSpecialization;
754 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755 Name, nullptr, true, TemplateResult,
756 MemberOfUnknownSpecialization) == TNK_Type_template) {
757 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758 return;
759 }
760 }
761
762 // FIXME: Should we move the logic that tries to recover from a missing tag
763 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764
765 if (!SS || (!SS->isSet() && !SS->isInvalid()))
766 Diag(IILoc, IsTemplateName ? diag::err_no_template
767 : diag::err_unknown_typename)
768 << II;
769 else if (DeclContext *DC = computeDeclContext(*SS, false))
770 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771 : diag::err_typename_nested_not_found)
772 << II << DC << SS->getRange();
773 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774 SuggestedType =
775 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776 } else if (isDependentScopeSpecifier(*SS)) {
777 unsigned DiagID = diag::err_typename_missing;
778 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779 DiagID = diag::ext_typename_missing;
780
781 Diag(SS->getRange().getBegin(), DiagID)
782 << SS->getScopeRep() << II->getName()
783 << SourceRange(SS->getRange().getBegin(), IILoc)
784 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785 SuggestedType = ActOnTypenameType(S, SourceLocation(),
786 *SS, *II, IILoc).get();
787 } else {
788 assert(SS && SS->isInvalid() &&
789 "Invalid scope specifier has already been diagnosed");
790 }
791}
792
793/// Determine whether the given result set contains either a type name
794/// or
795static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797 NextToken.is(tok::less);
798
799 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801 return true;
802
803 if (CheckTemplate && isa<TemplateDecl>(*I))
804 return true;
805 }
806
807 return false;
808}
809
811 Scope *S, CXXScopeSpec &SS,
812 IdentifierInfo *&Name,
813 SourceLocation NameLoc) {
814 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
816 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817 StringRef FixItTagName;
818 switch (Tag->getTagKind()) {
820 FixItTagName = "class ";
821 break;
822
824 FixItTagName = "enum ";
825 break;
826
828 FixItTagName = "struct ";
829 break;
830
832 FixItTagName = "__interface ";
833 break;
834
836 FixItTagName = "union ";
837 break;
838 }
839
840 StringRef TagName = FixItTagName.drop_back();
841 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844
845 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846 I != IEnd; ++I)
847 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848 << Name << TagName;
849
850 // Replace lookup results with just the tag decl.
852 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
853 return true;
854 }
855
856 return false;
857}
858
860 IdentifierInfo *&Name,
861 SourceLocation NameLoc,
862 const Token &NextToken,
864 DeclarationNameInfo NameInfo(Name, NameLoc);
865 ObjCMethodDecl *CurMethod = getCurMethodDecl();
866
867 assert(NextToken.isNot(tok::coloncolon) &&
868 "parse nested name specifiers before calling ClassifyName");
869 if (getLangOpts().CPlusPlus && SS.isSet() &&
870 isCurrentClassName(*Name, S, &SS)) {
871 // Per [class.qual]p2, this names the constructors of SS, not the
872 // injected-class-name. We don't have a classification for that.
873 // There's not much point caching this result, since the parser
874 // will reject it later.
876 }
877
878 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
880 /*AllowBuiltinCreation=*/!CurMethod);
881
882 if (SS.isInvalid())
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension. However, this is not
935 // allowed in all language modes as functions without prototypes may not
936 // be supported.
937 if (getLangOpts().implicitFunctionsAllowed()) {
938 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
940 }
941 }
942
943 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
944 // In C++20 onwards, this could be an ADL-only call to a function
945 // template, and we're required to assume that this is a template name.
946 //
947 // FIXME: Find a way to still do typo correction in this case.
948 TemplateName Template =
951 }
952
953 // In C, we first see whether there is a tag type by the same name, in
954 // which case it's likely that the user just forgot to write "enum",
955 // "struct", or "union".
956 if (!getLangOpts().CPlusPlus && !SecondTry &&
957 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
958 break;
959 }
960
961 // Perform typo correction to determine if there is another name that is
962 // close to this name.
963 if (!SecondTry && CCC) {
964 SecondTry = true;
965 if (TypoCorrection Corrected =
966 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
967 &SS, *CCC, CTK_ErrorRecovery)) {
968 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
969 unsigned QualifiedDiag = diag::err_no_member_suggest;
970
971 NamedDecl *FirstDecl = Corrected.getFoundDecl();
972 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
973 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
974 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
975 UnqualifiedDiag = diag::err_no_template_suggest;
976 QualifiedDiag = diag::err_no_member_template_suggest;
977 } else if (UnderlyingFirstDecl &&
978 (isa<TypeDecl>(UnderlyingFirstDecl) ||
979 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
980 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
981 UnqualifiedDiag = diag::err_unknown_typename_suggest;
982 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
983 }
984
985 if (SS.isEmpty()) {
986 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
987 } else {// FIXME: is this even reachable? Test it.
988 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
989 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
990 Name->getName() == CorrectedStr;
991 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
992 << Name << computeDeclContext(SS, false)
993 << DroppedSpecifier << SS.getRange());
994 }
995
996 // Update the name, so that the caller has the new name.
997 Name = Corrected.getCorrectionAsIdentifierInfo();
998
999 // Typo correction corrected to a keyword.
1000 if (Corrected.isKeyword())
1001 return Name;
1002
1003 // Also update the LookupResult...
1004 // FIXME: This should probably go away at some point
1005 Result.clear();
1006 Result.setLookupName(Corrected.getCorrection());
1007 if (FirstDecl)
1008 Result.addDecl(FirstDecl);
1009
1010 // If we found an Objective-C instance variable, let
1011 // LookupInObjCMethod build the appropriate expression to
1012 // reference the ivar.
1013 // FIXME: This is a gross hack.
1014 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1015 DeclResult R =
1016 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1017 if (R.isInvalid())
1019 if (R.isUsable())
1020 return NameClassification::NonType(Ivar);
1021 }
1022
1023 goto Corrected;
1024 }
1025 }
1026
1027 // We failed to correct; just fall through and let the parser deal with it.
1028 Result.suppressDiagnostics();
1030
1032 // We performed name lookup into the current instantiation, and there were
1033 // dependent bases, so we treat this result the same way as any other
1034 // dependent nested-name-specifier.
1035
1036 // C++ [temp.res]p2:
1037 // A name used in a template declaration or definition and that is
1038 // dependent on a template-parameter is assumed not to name a type
1039 // unless the applicable name lookup finds a type name or the name is
1040 // qualified by the keyword typename.
1041 //
1042 // FIXME: If the next token is '<', we might want to ask the parser to
1043 // perform some heroics to see if we actually have a
1044 // template-argument-list, which would indicate a missing 'template'
1045 // keyword here.
1047 }
1048
1052 break;
1053
1055 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1056 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1057 /*AllowDependent=*/false)) {
1058 // C++ [temp.local]p3:
1059 // A lookup that finds an injected-class-name (10.2) can result in an
1060 // ambiguity in certain cases (for example, if it is found in more than
1061 // one base class). If all of the injected-class-names that are found
1062 // refer to specializations of the same class template, and if the name
1063 // is followed by a template-argument-list, the reference refers to the
1064 // class template itself and not a specialization thereof, and is not
1065 // ambiguous.
1066 //
1067 // This filtering can make an ambiguous result into an unambiguous one,
1068 // so try again after filtering out template names.
1070 if (!Result.isAmbiguous()) {
1071 IsFilteredTemplateName = true;
1072 break;
1073 }
1074 }
1075
1076 // Diagnose the ambiguity and return an error.
1078 }
1079
1080 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1081 (IsFilteredTemplateName ||
1083 Result, /*AllowFunctionTemplates=*/true,
1084 /*AllowDependent=*/false,
1085 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1087 // C++ [temp.names]p3:
1088 // After name lookup (3.4) finds that a name is a template-name or that
1089 // an operator-function-id or a literal- operator-id refers to a set of
1090 // overloaded functions any member of which is a function template if
1091 // this is followed by a <, the < is always taken as the delimiter of a
1092 // template-argument-list and never as the less-than operator.
1093 // C++2a [temp.names]p2:
1094 // A name is also considered to refer to a template if it is an
1095 // unqualified-id followed by a < and name lookup finds either one
1096 // or more functions or finds nothing.
1097 if (!IsFilteredTemplateName)
1099
1100 bool IsFunctionTemplate;
1101 bool IsVarTemplate;
1102 TemplateName Template;
1103 if (Result.end() - Result.begin() > 1) {
1104 IsFunctionTemplate = true;
1105 Template = Context.getOverloadedTemplateName(Result.begin(),
1106 Result.end());
1107 } else if (!Result.empty()) {
1108 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1109 *Result.begin(), /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false));
1111 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1112 IsVarTemplate = isa<VarTemplateDecl>(TD);
1113
1114 UsingShadowDecl *FoundUsingShadow =
1115 dyn_cast<UsingShadowDecl>(*Result.begin());
1116 assert(!FoundUsingShadow ||
1117 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1119 SS.getScopeRep(),
1120 /*TemplateKeyword=*/false,
1121 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1122 } else {
1123 // All results were non-template functions. This is a function template
1124 // name.
1125 IsFunctionTemplate = true;
1126 Template = Context.getAssumedTemplateName(NameInfo.getName());
1127 }
1128
1129 if (IsFunctionTemplate) {
1130 // Function templates always go through overload resolution, at which
1131 // point we'll perform the various checks (e.g., accessibility) we need
1132 // to based on which function we selected.
1133 Result.suppressDiagnostics();
1134
1135 return NameClassification::FunctionTemplate(Template);
1136 }
1137
1138 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1140 }
1141
1142 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1144 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1145 T = Context.getUsingType(USD, T);
1146 return buildNamedType(*this, &SS, T, NameLoc);
1147 };
1148
1149 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1150 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1151 DiagnoseUseOfDecl(Type, NameLoc);
1152 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1153 return BuildTypeFor(Type, *Result.begin());
1154 }
1155
1156 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1157 if (!Class) {
1158 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1159 if (ObjCCompatibleAliasDecl *Alias =
1160 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1161 Class = Alias->getClassInterface();
1162 }
1163
1164 if (Class) {
1165 DiagnoseUseOfDecl(Class, NameLoc);
1166
1167 if (NextToken.is(tok::period)) {
1168 // Interface. <something> is parsed as a property reference expression.
1169 // Just return "unknown" as a fall-through for now.
1170 Result.suppressDiagnostics();
1172 }
1173
1175 return ParsedType::make(T);
1176 }
1177
1178 if (isa<ConceptDecl>(FirstDecl)) {
1179 // We want to preserve the UsingShadowDecl for concepts.
1180 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1183 TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 }
1185
1186 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1187 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1189 }
1190
1191 // We can have a type template here if we're classifying a template argument.
1192 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1193 !isa<VarTemplateDecl>(FirstDecl))
1195 TemplateName(cast<TemplateDecl>(FirstDecl)));
1196
1197 // Check for a tag type hidden by a non-type decl in a few cases where it
1198 // seems likely a type is wanted instead of the non-type that was found.
1199 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1200 if ((NextToken.is(tok::identifier) ||
1201 (NextIsOp &&
1202 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1203 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1204 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1205 DiagnoseUseOfDecl(Type, NameLoc);
1206 return BuildTypeFor(Type, *Result.begin());
1207 }
1208
1209 // If we already know which single declaration is referenced, just annotate
1210 // that declaration directly. Defer resolving even non-overloaded class
1211 // member accesses, as we need to defer certain access checks until we know
1212 // the context.
1213 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1214 if (Result.isSingleResult() && !ADL &&
1215 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1216 return NameClassification::NonType(Result.getRepresentativeDecl());
1217
1218 // Otherwise, this is an overload set that we will need to resolve later.
1219 Result.suppressDiagnostics();
1221 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1222 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1223 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1224}
1225
1228 SourceLocation NameLoc) {
1229 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1230 CXXScopeSpec SS;
1231 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1232 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1233}
1234
1237 IdentifierInfo *Name,
1238 SourceLocation NameLoc,
1239 bool IsAddressOfOperand) {
1240 DeclarationNameInfo NameInfo(Name, NameLoc);
1241 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1242 NameInfo, IsAddressOfOperand,
1243 /*TemplateArgs=*/nullptr);
1244}
1245
1248 SourceLocation NameLoc,
1249 const Token &NextToken) {
1250 if (getCurMethodDecl() && SS.isEmpty())
1251 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1252 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1253
1254 // Reconstruct the lookup result.
1255 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1256 Result.addDecl(Found);
1257 Result.resolveKind();
1258
1259 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1260 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1261}
1262
1264 // For an implicit class member access, transform the result into a member
1265 // access expression if necessary.
1266 auto *ULE = cast<UnresolvedLookupExpr>(E);
1267 if ((*ULE->decls_begin())->isCXXClassMember()) {
1268 CXXScopeSpec SS;
1269 SS.Adopt(ULE->getQualifierLoc());
1270
1271 // Reconstruct the lookup result.
1272 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1274 Result.setNamingClass(ULE->getNamingClass());
1275 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1276 Result.addDecl(*I, I.getAccess());
1277 Result.resolveKind();
1279 nullptr, S);
1280 }
1281
1282 // Otherwise, this is already in the form we needed, and no further checks
1283 // are necessary.
1284 return ULE;
1285}
1286
1289 auto *TD = Name.getAsTemplateDecl();
1290 if (!TD)
1292 if (isa<ClassTemplateDecl>(TD))
1294 if (isa<FunctionTemplateDecl>(TD))
1296 if (isa<VarTemplateDecl>(TD))
1298 if (isa<TypeAliasTemplateDecl>(TD))
1300 if (isa<TemplateTemplateParmDecl>(TD))
1302 if (isa<ConceptDecl>(TD))
1305}
1306
1308 assert(DC->getLexicalParent() == CurContext &&
1309 "The next DeclContext should be lexically contained in the current one.");
1310 CurContext = DC;
1311 S->setEntity(DC);
1312}
1313
1315 assert(CurContext && "DeclContext imbalance!");
1316
1318 assert(CurContext && "Popped translation unit!");
1319}
1320
1322 Decl *D) {
1323 // Unlike PushDeclContext, the context to which we return is not necessarily
1324 // the containing DC of TD, because the new context will be some pre-existing
1325 // TagDecl definition instead of a fresh one.
1326 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1327 CurContext = cast<TagDecl>(D)->getDefinition();
1328 assert(CurContext && "skipping definition of undefined tag");
1329 // Start lookups from the parent of the current context; we don't want to look
1330 // into the pre-existing complete definition.
1331 S->setEntity(CurContext->getLookupParent());
1332 return Result;
1333}
1334
1336 CurContext = static_cast<decltype(CurContext)>(Context);
1337}
1338
1340 // C++0x [basic.lookup.unqual]p13:
1341 // A name used in the definition of a static data member of class
1342 // X (after the qualified-id of the static member) is looked up as
1343 // if the name was used in a member function of X.
1344 // C++0x [basic.lookup.unqual]p14:
1345 // If a variable member of a namespace is defined outside of the
1346 // scope of its namespace then any name used in the definition of
1347 // the variable member (after the declarator-id) is looked up as
1348 // if the definition of the variable member occurred in its
1349 // namespace.
1350 // Both of these imply that we should push a scope whose context
1351 // is the semantic context of the declaration. We can't use
1352 // PushDeclContext here because that context is not necessarily
1353 // lexically contained in the current context. Fortunately,
1354 // the containing scope should have the appropriate information.
1355
1356 assert(!S->getEntity() && "scope already has entity");
1357
1358#ifndef NDEBUG
1359 Scope *Ancestor = S->getParent();
1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1362#endif
1363
1364 CurContext = DC;
1365 S->setEntity(DC);
1366
1367 if (S->getParent()->isTemplateParamScope()) {
1368 // Also set the corresponding entities for all immediately-enclosing
1369 // template parameter scopes.
1370 EnterTemplatedContext(S->getParent(), DC);
1371 }
1372}
1373
1375 assert(S->getEntity() == CurContext && "Context imbalance!");
1376
1377 // Switch back to the lexical context. The safety of this is
1378 // enforced by an assert in EnterDeclaratorContext.
1379 Scope *Ancestor = S->getParent();
1380 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1381 CurContext = Ancestor->getEntity();
1382
1383 // We don't need to do anything with the scope, which is going to
1384 // disappear.
1385}
1386
1388 assert(S->isTemplateParamScope() &&
1389 "expected to be initializing a template parameter scope");
1390
1391 // C++20 [temp.local]p7:
1392 // In the definition of a member of a class template that appears outside
1393 // of the class template definition, the name of a member of the class
1394 // template hides the name of a template-parameter of any enclosing class
1395 // templates (but not a template-parameter of the member if the member is a
1396 // class or function template).
1397 // C++20 [temp.local]p9:
1398 // In the definition of a class template or in the definition of a member
1399 // of such a template that appears outside of the template definition, for
1400 // each non-dependent base class (13.8.2.1), if the name of the base class
1401 // or the name of a member of the base class is the same as the name of a
1402 // template-parameter, the base class name or member name hides the
1403 // template-parameter name (6.4.10).
1404 //
1405 // This means that a template parameter scope should be searched immediately
1406 // after searching the DeclContext for which it is a template parameter
1407 // scope. For example, for
1408 // template<typename T> template<typename U> template<typename V>
1409 // void N::A<T>::B<U>::f(...)
1410 // we search V then B<U> (and base classes) then U then A<T> (and base
1411 // classes) then T then N then ::.
1412 unsigned ScopeDepth = getTemplateDepth(S);
1413 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1414 DeclContext *SearchDCAfterScope = DC;
1415 for (; DC; DC = DC->getLookupParent()) {
1416 if (const TemplateParameterList *TPL =
1417 cast<Decl>(DC)->getDescribedTemplateParams()) {
1418 unsigned DCDepth = TPL->getDepth() + 1;
1419 if (DCDepth > ScopeDepth)
1420 continue;
1421 if (ScopeDepth == DCDepth)
1422 SearchDCAfterScope = DC = DC->getLookupParent();
1423 break;
1424 }
1425 }
1426 S->setLookupEntity(SearchDCAfterScope);
1427 }
1428}
1429
1431 // We assume that the caller has already called
1432 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1433 FunctionDecl *FD = D->getAsFunction();
1434 if (!FD)
1435 return;
1436
1437 // Same implementation as PushDeclContext, but enters the context
1438 // from the lexical parent, rather than the top-level class.
1439 assert(CurContext == FD->getLexicalParent() &&
1440 "The next DeclContext should be lexically contained in the current one.");
1441 CurContext = FD;
1442 S->setEntity(CurContext);
1443
1444 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1445 ParmVarDecl *Param = FD->getParamDecl(P);
1446 // If the parameter has an identifier, then add it to the scope
1447 if (Param->getIdentifier()) {
1448 S->AddDecl(Param);
1449 IdResolver.AddDecl(Param);
1450 }
1451 }
1452}
1453
1455 // Same implementation as PopDeclContext, but returns to the lexical parent,
1456 // rather than the top-level class.
1457 assert(CurContext && "DeclContext imbalance!");
1459 assert(CurContext && "Popped translation unit!");
1460}
1461
1462/// Determine whether overloading is allowed for a new function
1463/// declaration considering prior declarations of the same name.
1464///
1465/// This routine determines whether overloading is possible, not
1466/// whether a new declaration actually overloads a previous one.
1467/// It will return true in C++ (where overloads are always permitted)
1468/// or, as a C extension, when either the new declaration or a
1469/// previous one is declared with the 'overloadable' attribute.
1471 ASTContext &Context,
1472 const FunctionDecl *New) {
1473 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1474 return true;
1475
1476 // Multiversion function declarations are not overloads in the
1477 // usual sense of that term, but lookup will report that an
1478 // overload set was found if more than one multiversion function
1479 // declaration is present for the same name. It is therefore
1480 // inadequate to assume that some prior declaration(s) had
1481 // the overloadable attribute; checking is required. Since one
1482 // declaration is permitted to omit the attribute, it is necessary
1483 // to check at least two; hence the 'any_of' check below. Note that
1484 // the overloadable attribute is implicitly added to declarations
1485 // that were required to have it but did not.
1486 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1487 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1488 return ND->hasAttr<OverloadableAttr>();
1489 });
1490 } else if (Previous.getResultKind() == LookupResult::Found)
1491 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1492
1493 return false;
1494}
1495
1496void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1497 // Move up the scope chain until we find the nearest enclosing
1498 // non-transparent context. The declaration will be introduced into this
1499 // scope.
1500 while (S->getEntity() && S->getEntity()->isTransparentContext())
1501 S = S->getParent();
1502
1503 // Add scoped declarations into their context, so that they can be
1504 // found later. Declarations without a context won't be inserted
1505 // into any context.
1506 if (AddToContext)
1508
1509 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1510 // are function-local declarations.
1511 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1512 return;
1513
1514 // Template instantiations should also not be pushed into scope.
1515 if (isa<FunctionDecl>(D) &&
1516 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1517 return;
1518
1519 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1520 S->AddDecl(D);
1521 return;
1522 }
1523 // If this replaces anything in the current scope,
1524 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1525 IEnd = IdResolver.end();
1526 for (; I != IEnd; ++I) {
1527 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1528 S->RemoveDecl(*I);
1530
1531 // Should only need to replace one decl.
1532 break;
1533 }
1534 }
1535
1536 S->AddDecl(D);
1537
1538 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1539 // Implicitly-generated labels may end up getting generated in an order that
1540 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1541 // the label at the appropriate place in the identifier chain.
1542 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1543 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1544 if (IDC == CurContext) {
1545 if (!S->isDeclScope(*I))
1546 continue;
1547 } else if (IDC->Encloses(CurContext))
1548 break;
1549 }
1550
1552 } else {
1554 }
1556}
1557
1559 bool AllowInlineNamespace) const {
1560 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1561}
1562
1564 DeclContext *TargetDC = DC->getPrimaryContext();
1565 do {
1566 if (DeclContext *ScopeDC = S->getEntity())
1567 if (ScopeDC->getPrimaryContext() == TargetDC)
1568 return S;
1569 } while ((S = S->getParent()));
1570
1571 return nullptr;
1572}
1573
1575 DeclContext*,
1576 ASTContext&);
1577
1579 bool ConsiderLinkage,
1580 bool AllowInlineNamespace) {
1582 while (F.hasNext()) {
1583 NamedDecl *D = F.next();
1584
1585 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586 continue;
1587
1588 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589 continue;
1590
1591 F.erase();
1592 }
1593
1594 F.done();
1595}
1596
1598 // [module.interface]p7:
1599 // A declaration is attached to a module as follows:
1600 // - If the declaration is a non-dependent friend declaration that nominates a
1601 // function with a declarator-id that is a qualified-id or template-id or that
1602 // nominates a class other than with an elaborated-type-specifier with neither
1603 // a nested-name-specifier nor a simple-template-id, it is attached to the
1604 // module to which the friend is attached ([basic.link]).
1605 if (New->getFriendObjectKind() &&
1609 return false;
1610 }
1611
1612 Module *NewM = New->getOwningModule();
1613 Module *OldM = Old->getOwningModule();
1614
1615 if (NewM && NewM->isPrivateModule())
1616 NewM = NewM->Parent;
1617 if (OldM && OldM->isPrivateModule())
1618 OldM = OldM->Parent;
1619
1620 if (NewM == OldM)
1621 return false;
1622
1623 if (NewM && OldM) {
1624 // A module implementation unit has visibility of the decls in its
1625 // implicitly imported interface.
1626 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1627 return false;
1628
1629 // Partitions are part of the module, but a partition could import another
1630 // module, so verify that the PMIs agree.
1631 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1632 getASTContext().isInSameModule(NewM, OldM))
1633 return false;
1634 }
1635
1636 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1637 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1638 if (NewIsModuleInterface || OldIsModuleInterface) {
1639 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1640 // if a declaration of D [...] appears in the purview of a module, all
1641 // other such declarations shall appear in the purview of the same module
1642 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1643 << New
1644 << NewIsModuleInterface
1645 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1646 << OldIsModuleInterface
1647 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1648 Diag(Old->getLocation(), diag::note_previous_declaration);
1649 New->setInvalidDecl();
1650 return true;
1651 }
1652
1653 return false;
1654}
1655
1657 // [module.interface]p1:
1658 // An export-declaration shall inhabit a namespace scope.
1659 //
1660 // So it is meaningless to talk about redeclaration which is not at namespace
1661 // scope.
1662 if (!New->getLexicalDeclContext()
1664 ->isFileContext() ||
1665 !Old->getLexicalDeclContext()
1667 ->isFileContext())
1668 return false;
1669
1670 bool IsNewExported = New->isInExportDeclContext();
1671 bool IsOldExported = Old->isInExportDeclContext();
1672
1673 // It should be irrevelant if both of them are not exported.
1674 if (!IsNewExported && !IsOldExported)
1675 return false;
1676
1677 if (IsOldExported)
1678 return false;
1679
1680 // If the Old declaration are not attached to named modules
1681 // and the New declaration are attached to global module.
1682 // It should be fine to allow the export since it doesn't change
1683 // the linkage of declarations. See
1684 // https://github.com/llvm/llvm-project/issues/98583 for details.
1685 if (!Old->isInNamedModule() && New->getOwningModule() &&
1687 return false;
1688
1689 assert(IsNewExported);
1690
1691 auto Lk = Old->getFormalLinkage();
1692 int S = 0;
1693 if (Lk == Linkage::Internal)
1694 S = 1;
1695 else if (Lk == Linkage::Module)
1696 S = 2;
1697 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1698 Diag(Old->getLocation(), diag::note_previous_declaration);
1699 return true;
1700}
1701
1704 return true;
1705
1706 if (CheckRedeclarationExported(New, Old))
1707 return true;
1708
1709 return false;
1710}
1711
1713 const NamedDecl *Old) const {
1714 assert(getASTContext().isSameEntity(New, Old) &&
1715 "New and Old are not the same definition, we should diagnostic it "
1716 "immediately instead of checking it.");
1717 assert(const_cast<Sema *>(this)->isReachable(New) &&
1718 const_cast<Sema *>(this)->isReachable(Old) &&
1719 "We shouldn't see unreachable definitions here.");
1720
1721 Module *NewM = New->getOwningModule();
1722 Module *OldM = Old->getOwningModule();
1723
1724 // We only checks for named modules here. The header like modules is skipped.
1725 // FIXME: This is not right if we import the header like modules in the module
1726 // purview.
1727 //
1728 // For example, assuming "header.h" provides definition for `D`.
1729 // ```C++
1730 // //--- M.cppm
1731 // export module M;
1732 // import "header.h"; // or #include "header.h" but import it by clang modules
1733 // actually.
1734 //
1735 // //--- Use.cpp
1736 // import M;
1737 // import "header.h"; // or uses clang modules.
1738 // ```
1739 //
1740 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1741 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1742 // reject it. But the current implementation couldn't detect the case since we
1743 // don't record the information about the importee modules.
1744 //
1745 // But this might not be painful in practice. Since the design of C++20 Named
1746 // Modules suggests us to use headers in global module fragment instead of
1747 // module purview.
1748 if (NewM && NewM->isHeaderLikeModule())
1749 NewM = nullptr;
1750 if (OldM && OldM->isHeaderLikeModule())
1751 OldM = nullptr;
1752
1753 if (!NewM && !OldM)
1754 return true;
1755
1756 // [basic.def.odr]p14.3
1757 // Each such definition shall not be attached to a named module
1758 // ([module.unit]).
1759 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1760 return true;
1761
1762 // Then New and Old lives in the same TU if their share one same module unit.
1763 if (NewM)
1764 NewM = NewM->getTopLevelModule();
1765 if (OldM)
1766 OldM = OldM->getTopLevelModule();
1767 return OldM == NewM;
1768}
1769
1771 if (D->getDeclContext()->isFileContext())
1772 return false;
1773
1774 return isa<UsingShadowDecl>(D) ||
1775 isa<UnresolvedUsingTypenameDecl>(D) ||
1776 isa<UnresolvedUsingValueDecl>(D);
1777}
1778
1779/// Removes using shadow declarations not at class scope from the lookup
1780/// results.
1783 while (F.hasNext())
1785 F.erase();
1786
1787 F.done();
1788}
1789
1790/// Check for this common pattern:
1791/// @code
1792/// class S {
1793/// S(const S&); // DO NOT IMPLEMENT
1794/// void operator=(const S&); // DO NOT IMPLEMENT
1795/// };
1796/// @endcode
1798 // FIXME: Should check for private access too but access is set after we get
1799 // the decl here.
1800 if (D->doesThisDeclarationHaveABody())
1801 return false;
1802
1803 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1804 return CD->isCopyConstructor();
1805 return D->isCopyAssignmentOperator();
1806}
1807
1808bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1809 const DeclContext *DC = D->getDeclContext();
1810 while (!DC->isTranslationUnit()) {
1811 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1812 if (!RD->hasNameForLinkage())
1813 return true;
1814 }
1815 DC = DC->getParent();
1816 }
1817
1818 return !D->isExternallyVisible();
1819}
1820
1821// FIXME: This needs to be refactored; some other isInMainFile users want
1822// these semantics.
1823static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1825 return false;
1826 return S.SourceMgr.isInMainFile(Loc);
1827}
1828
1830 assert(D);
1831
1832 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1833 return false;
1834
1835 // Ignore all entities declared within templates, and out-of-line definitions
1836 // of members of class templates.
1839 return false;
1840
1841 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1842 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1843 return false;
1844 // A non-out-of-line declaration of a member specialization was implicitly
1845 // instantiated; it's the out-of-line declaration that we're interested in.
1846 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1847 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1848 return false;
1849
1850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1851 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1852 return false;
1853 } else {
1854 // 'static inline' functions are defined in headers; don't warn.
1855 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1856 return false;
1857 }
1858
1859 if (FD->doesThisDeclarationHaveABody() &&
1861 return false;
1862 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1863 // Constants and utility variables are defined in headers with internal
1864 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1865 // like "inline".)
1866 if (!isMainFileLoc(*this, VD->getLocation()))
1867 return false;
1868
1869 if (Context.DeclMustBeEmitted(VD))
1870 return false;
1871
1872 if (VD->isStaticDataMember() &&
1873 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1874 return false;
1875 if (VD->isStaticDataMember() &&
1876 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1877 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1878 return false;
1879
1880 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1881 return false;
1882 } else {
1883 return false;
1884 }
1885
1886 // Only warn for unused decls internal to the translation unit.
1887 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1888 // for inline functions defined in the main source file, for instance.
1889 return mightHaveNonExternalLinkage(D);
1890}
1891
1893 if (!D)
1894 return;
1895
1896 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1897 const FunctionDecl *First = FD->getFirstDecl();
1899 return; // First should already be in the vector.
1900 }
1901
1902 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1903 const VarDecl *First = VD->getFirstDecl();
1905 return; // First should already be in the vector.
1906 }
1907
1910}
1911
1912static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1913 const NamedDecl *D) {
1914 if (D->isInvalidDecl())
1915 return false;
1916
1917 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1918 // For a decomposition declaration, warn if none of the bindings are
1919 // referenced, instead of if the variable itself is referenced (which
1920 // it is, by the bindings' expressions).
1921 bool IsAllPlaceholders = true;
1922 for (const auto *BD : DD->bindings()) {
1923 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1924 return false;
1925 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1926 }
1927 if (IsAllPlaceholders)
1928 return false;
1929 } else if (!D->getDeclName()) {
1930 return false;
1931 } else if (D->isReferenced() || D->isUsed()) {
1932 return false;
1933 }
1934
1935 if (D->isPlaceholderVar(LangOpts))
1936 return false;
1937
1938 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1939 D->hasAttr<CleanupAttr>())
1940 return false;
1941
1942 if (isa<LabelDecl>(D))
1943 return true;
1944
1945 // Except for labels, we only care about unused decls that are local to
1946 // functions.
1947 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1948 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1949 // For dependent types, the diagnostic is deferred.
1950 WithinFunction =
1951 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1952 if (!WithinFunction)
1953 return false;
1954
1955 if (isa<TypedefNameDecl>(D))
1956 return true;
1957
1958 // White-list anything that isn't a local variable.
1959 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1960 return false;
1961
1962 // Types of valid local variables should be complete, so this should succeed.
1963 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1964
1965 const Expr *Init = VD->getInit();
1966 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1967 Init = Cleanups->getSubExpr();
1968
1969 const auto *Ty = VD->getType().getTypePtr();
1970
1971 // Only look at the outermost level of typedef.
1972 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1973 // Allow anything marked with __attribute__((unused)).
1974 if (TT->getDecl()->hasAttr<UnusedAttr>())
1975 return false;
1976 }
1977
1978 // Warn for reference variables whose initializtion performs lifetime
1979 // extension.
1980 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1981 MTE && MTE->getExtendingDecl()) {
1982 Ty = VD->getType().getNonReferenceType().getTypePtr();
1983 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1984 }
1985
1986 // If we failed to complete the type for some reason, or if the type is
1987 // dependent, don't diagnose the variable.
1988 if (Ty->isIncompleteType() || Ty->isDependentType())
1989 return false;
1990
1991 // Look at the element type to ensure that the warning behaviour is
1992 // consistent for both scalars and arrays.
1993 Ty = Ty->getBaseElementTypeUnsafe();
1994
1995 if (const TagType *TT = Ty->getAs<TagType>()) {
1996 const TagDecl *Tag = TT->getDecl();
1997 if (Tag->hasAttr<UnusedAttr>())
1998 return false;
1999
2000 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2001 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2002 return false;
2003
2004 if (Init) {
2005 const auto *Construct =
2006 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2007 if (Construct && !Construct->isElidable()) {
2008 const CXXConstructorDecl *CD = Construct->getConstructor();
2009 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2010 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2011 return false;
2012 }
2013
2014 // Suppress the warning if we don't know how this is constructed, and
2015 // it could possibly be non-trivial constructor.
2016 if (Init->isTypeDependent()) {
2017 for (const CXXConstructorDecl *Ctor : RD->ctors())
2018 if (!Ctor->isTrivial())
2019 return false;
2020 }
2021
2022 // Suppress the warning if the constructor is unresolved because
2023 // its arguments are dependent.
2024 if (isa<CXXUnresolvedConstructExpr>(Init))
2025 return false;
2026 }
2027 }
2028 }
2029
2030 // TODO: __attribute__((unused)) templates?
2031 }
2032
2033 return true;
2034}
2035
2037 FixItHint &Hint) {
2038 if (isa<LabelDecl>(D)) {
2040 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2041 /*SkipTrailingWhitespaceAndNewline=*/false);
2042 if (AfterColon.isInvalid())
2043 return;
2046 }
2047}
2048
2051 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2052}
2053
2055 DiagReceiverTy DiagReceiver) {
2056 if (D->getTypeForDecl()->isDependentType())
2057 return;
2058
2059 for (auto *TmpD : D->decls()) {
2060 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2061 DiagnoseUnusedDecl(T, DiagReceiver);
2062 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2063 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2064 }
2065}
2066
2069 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2070}
2071
2074 return;
2075
2076 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2077 // typedefs can be referenced later on, so the diagnostics are emitted
2078 // at end-of-translation-unit.
2080 return;
2081 }
2082
2083 FixItHint Hint;
2085
2086 unsigned DiagID;
2087 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2088 DiagID = diag::warn_unused_exception_param;
2089 else if (isa<LabelDecl>(D))
2090 DiagID = diag::warn_unused_label;
2091 else
2092 DiagID = diag::warn_unused_variable;
2093
2094 SourceLocation DiagLoc = D->getLocation();
2095 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2096}
2097
2099 DiagReceiverTy DiagReceiver) {
2100 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2101 // it's not really unused.
2102 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2103 return;
2104
2105 // In C++, `_` variables behave as if they were maybe_unused
2106 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2107 return;
2108
2109 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2110
2111 if (Ty->isReferenceType() || Ty->isDependentType())
2112 return;
2113
2114 if (const TagType *TT = Ty->getAs<TagType>()) {
2115 const TagDecl *Tag = TT->getDecl();
2116 if (Tag->hasAttr<UnusedAttr>())
2117 return;
2118 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2119 // mimic gcc's behavior.
2120 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2121 RD && !RD->hasAttr<WarnUnusedAttr>())
2122 return;
2123 }
2124
2125 // Don't warn about __block Objective-C pointer variables, as they might
2126 // be assigned in the block but not used elsewhere for the purpose of lifetime
2127 // extension.
2128 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2129 return;
2130
2131 // Don't warn about Objective-C pointer variables with precise lifetime
2132 // semantics; they can be used to ensure ARC releases the object at a known
2133 // time, which may mean assignment but no other references.
2134 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2135 return;
2136
2137 auto iter = RefsMinusAssignments.find(VD);
2138 if (iter == RefsMinusAssignments.end())
2139 return;
2140
2141 assert(iter->getSecond() >= 0 &&
2142 "Found a negative number of references to a VarDecl");
2143 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2144 // Assume the given VarDecl is "used" if its ref count stored in
2145 // `RefMinusAssignments` is positive, with one exception.
2146 //
2147 // For a C++ variable whose decl (with initializer) entirely consist the
2148 // condition expression of a if/while/for construct,
2149 // Clang creates a DeclRefExpr for the condition expression rather than a
2150 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2151 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2152 // used in the body of the if/while/for construct.
2153 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2154 if (!UnusedCXXCondDecl)
2155 return;
2156 }
2157
2158 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2159 : diag::warn_unused_but_set_variable;
2160 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2161}
2162
2164 Sema::DiagReceiverTy DiagReceiver) {
2165 // Verify that we have no forward references left. If so, there was a goto
2166 // or address of a label taken, but no definition of it. Label fwd
2167 // definitions are indicated with a null substmt which is also not a resolved
2168 // MS inline assembly label name.
2169 bool Diagnose = false;
2170 if (L->isMSAsmLabel())
2171 Diagnose = !L->isResolvedMSAsmLabel();
2172 else
2173 Diagnose = L->getStmt() == nullptr;
2174 if (Diagnose)
2175 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2176 << L);
2177}
2178
2180 S->applyNRVO();
2181
2182 if (S->decl_empty()) return;
2183 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2184 "Scope shouldn't contain decls!");
2185
2186 /// We visit the decls in non-deterministic order, but we want diagnostics
2187 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2188 /// and sort the diagnostics before emitting them, after we visited all decls.
2189 struct LocAndDiag {
2191 std::optional<SourceLocation> PreviousDeclLoc;
2193 };
2195 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2196 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2197 };
2198 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2199 SourceLocation PreviousDeclLoc,
2200 PartialDiagnostic PD) {
2201 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2202 };
2203
2204 for (auto *TmpD : S->decls()) {
2205 assert(TmpD && "This decl didn't get pushed??");
2206
2207 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2208 NamedDecl *D = cast<NamedDecl>(TmpD);
2209
2210 // Diagnose unused variables in this scope.
2211 if (!S->hasUnrecoverableErrorOccurred()) {
2212 DiagnoseUnusedDecl(D, addDiag);
2213 if (const auto *RD = dyn_cast<RecordDecl>(D))
2214 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2215 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2216 DiagnoseUnusedButSetDecl(VD, addDiag);
2217 RefsMinusAssignments.erase(VD);
2218 }
2219 }
2220
2221 if (!D->getDeclName()) continue;
2222
2223 // If this was a forward reference to a label, verify it was defined.
2224 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2225 CheckPoppedLabel(LD, *this, addDiag);
2226
2227 // Partial translation units that are created in incremental processing must
2228 // not clean up the IdResolver because PTUs should take into account the
2229 // declarations that came from previous PTUs.
2233
2234 // Warn on it if we are shadowing a declaration.
2235 auto ShadowI = ShadowingDecls.find(D);
2236 if (ShadowI != ShadowingDecls.end()) {
2237 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2238 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2239 PDiag(diag::warn_ctor_parm_shadows_field)
2240 << D << FD << FD->getParent());
2241 }
2242 ShadowingDecls.erase(ShadowI);
2243 }
2244 }
2245
2246 llvm::sort(DeclDiags,
2247 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2248 // The particular order for diagnostics is not important, as long
2249 // as the order is deterministic. Using the raw location is going
2250 // to generally be in source order unless there are macro
2251 // expansions involved.
2252 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2253 });
2254 for (const LocAndDiag &D : DeclDiags) {
2255 Diag(D.Loc, D.PD);
2256 if (D.PreviousDeclLoc)
2257 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2258 }
2259}
2260
2262 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2263 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2264 (S->isClassScope() && !getLangOpts().CPlusPlus))
2265 S = S->getParent();
2266 return S;
2267}
2268
2269static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2271 switch (Error) {
2273 return "";
2275 return BuiltinInfo.getHeaderName(ID);
2277 return "stdio.h";
2279 return "setjmp.h";
2281 return "ucontext.h";
2282 }
2283 llvm_unreachable("unhandled error kind");
2284}
2285
2287 unsigned ID, SourceLocation Loc) {
2289
2290 if (getLangOpts().CPlusPlus) {
2293 CLinkageDecl->setImplicit();
2294 Parent->addDecl(CLinkageDecl);
2295 Parent = CLinkageDecl;
2296 }
2297
2300 assert(getLangOpts().CPlusPlus20 &&
2301 "consteval builtins should only be available in C++20 mode");
2302 ConstexprKind = ConstexprSpecKind::Consteval;
2303 }
2304
2306 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2307 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2308 Type->isFunctionProtoType(), ConstexprKind);
2309 New->setImplicit();
2310 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2311
2312 // Create Decl objects for each parameter, adding them to the
2313 // FunctionDecl.
2314 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2316 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2318 Context, New, SourceLocation(), SourceLocation(), nullptr,
2319 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2320 parm->setScopeInfo(0, i);
2321 Params.push_back(parm);
2322 }
2323 New->setParams(Params);
2324 }
2325
2327 return New;
2328}
2329
2331 Scope *S, bool ForRedeclaration,
2334
2336 QualType R = Context.GetBuiltinType(ID, Error);
2337 if (Error) {
2338 if (!ForRedeclaration)
2339 return nullptr;
2340
2341 // If we have a builtin without an associated type we should not emit a
2342 // warning when we were not able to find a type for it.
2343 if (Error == ASTContext::GE_Missing_type ||
2345 return nullptr;
2346
2347 // If we could not find a type for setjmp it is because the jmp_buf type was
2348 // not defined prior to the setjmp declaration.
2349 if (Error == ASTContext::GE_Missing_setjmp) {
2350 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2352 return nullptr;
2353 }
2354
2355 // Generally, we emit a warning that the declaration requires the
2356 // appropriate header.
2357 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2358 << getHeaderName(Context.BuiltinInfo, ID, Error)
2360 return nullptr;
2361 }
2362
2363 if (!ForRedeclaration &&
2366 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2367 : diag::ext_implicit_lib_function_decl)
2368 << Context.BuiltinInfo.getName(ID) << R;
2369 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2370 Diag(Loc, diag::note_include_header_or_declare)
2371 << Header << Context.BuiltinInfo.getName(ID);
2372 }
2373
2374 if (R.isNull())
2375 return nullptr;
2376
2377 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2379
2380 // TUScope is the translation-unit scope to insert this function into.
2381 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2382 // relate Scopes to DeclContexts, and probably eliminate CurContext
2383 // entirely, but we're not there yet.
2384 DeclContext *SavedContext = CurContext;
2385 CurContext = New->getDeclContext();
2387 CurContext = SavedContext;
2388 return New;
2389}
2390
2391/// Typedef declarations don't have linkage, but they still denote the same
2392/// entity if their types are the same.
2393/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2394/// isSameEntity.
2395static void
2398 // This is only interesting when modules are enabled.
2399 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2400 return;
2401
2402 // Empty sets are uninteresting.
2403 if (Previous.empty())
2404 return;
2405
2406 LookupResult::Filter Filter = Previous.makeFilter();
2407 while (Filter.hasNext()) {
2408 NamedDecl *Old = Filter.next();
2409
2410 // Non-hidden declarations are never ignored.
2411 if (S.isVisible(Old))
2412 continue;
2413
2414 // Declarations of the same entity are not ignored, even if they have
2415 // different linkages.
2416 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2417 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2418 Decl->getUnderlyingType()))
2419 continue;
2420
2421 // If both declarations give a tag declaration a typedef name for linkage
2422 // purposes, then they declare the same entity.
2423 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2424 Decl->getAnonDeclWithTypedefName())
2425 continue;
2426 }
2427
2428 Filter.erase();
2429 }
2430
2431 Filter.done();
2432}
2433
2435 QualType OldType;
2436 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2437 OldType = OldTypedef->getUnderlyingType();
2438 else
2439 OldType = Context.getTypeDeclType(Old);
2440 QualType NewType = New->getUnderlyingType();
2441
2442 if (NewType->isVariablyModifiedType()) {
2443 // Must not redefine a typedef with a variably-modified type.
2444 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2445 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2446 << Kind << NewType;
2447 if (Old->getLocation().isValid())
2449 New->setInvalidDecl();
2450 return true;
2451 }
2452
2453 if (OldType != NewType &&
2454 !OldType->isDependentType() &&
2455 !NewType->isDependentType() &&
2456 !Context.hasSameType(OldType, NewType)) {
2457 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2458 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2459 << Kind << NewType << OldType;
2460 if (Old->getLocation().isValid())
2462 New->setInvalidDecl();
2463 return true;
2464 }
2465 return false;
2466}
2467
2469 LookupResult &OldDecls) {
2470 // If the new decl is known invalid already, don't bother doing any
2471 // merging checks.
2472 if (New->isInvalidDecl()) return;
2473
2474 // Allow multiple definitions for ObjC built-in typedefs.
2475 // FIXME: Verify the underlying types are equivalent!
2476 if (getLangOpts().ObjC) {
2477 const IdentifierInfo *TypeID = New->getIdentifier();
2478 switch (TypeID->getLength()) {
2479 default: break;
2480 case 2:
2481 {
2482 if (!TypeID->isStr("id"))
2483 break;
2484 QualType T = New->getUnderlyingType();
2485 if (!T->isPointerType())
2486 break;
2487 if (!T->isVoidPointerType()) {
2489 if (!PT->isStructureType())
2490 break;
2491 }
2493 // Install the built-in type for 'id', ignoring the current definition.
2495 return;
2496 }
2497 case 5:
2498 if (!TypeID->isStr("Class"))
2499 break;
2501 // Install the built-in type for 'Class', ignoring the current definition.
2503 return;
2504 case 3:
2505 if (!TypeID->isStr("SEL"))
2506 break;
2508 // Install the built-in type for 'SEL', ignoring the current definition.
2510 return;
2511 }
2512 // Fall through - the typedef name was not a builtin type.
2513 }
2514
2515 // Verify the old decl was also a type.
2516 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2517 if (!Old) {
2518 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2519 << New->getDeclName();
2520
2521 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2522 if (OldD->getLocation().isValid())
2523 notePreviousDefinition(OldD, New->getLocation());
2524
2525 return New->setInvalidDecl();
2526 }
2527
2528 // If the old declaration is invalid, just give up here.
2529 if (Old->isInvalidDecl())
2530 return New->setInvalidDecl();
2531
2532 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2533 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2534 auto *NewTag = New->getAnonDeclWithTypedefName();
2535 NamedDecl *Hidden = nullptr;
2536 if (OldTag && NewTag &&
2537 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2538 !hasVisibleDefinition(OldTag, &Hidden)) {
2539 // There is a definition of this tag, but it is not visible. Use it
2540 // instead of our tag.
2541 New->setTypeForDecl(OldTD->getTypeForDecl());
2542 if (OldTD->isModed())
2543 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2544 OldTD->getUnderlyingType());
2545 else
2546 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2547
2548 // Make the old tag definition visible.
2550
2551 // If this was an unscoped enumeration, yank all of its enumerators
2552 // out of the scope.
2553 if (isa<EnumDecl>(NewTag)) {
2554 Scope *EnumScope = getNonFieldDeclScope(S);
2555 for (auto *D : NewTag->decls()) {
2556 auto *ED = cast<EnumConstantDecl>(D);
2557 assert(EnumScope->isDeclScope(ED));
2558 EnumScope->RemoveDecl(ED);
2560 ED->getLexicalDeclContext()->removeDecl(ED);
2561 }
2562 }
2563 }
2564 }
2565
2566 // If the typedef types are not identical, reject them in all languages and
2567 // with any extensions enabled.
2568 if (isIncompatibleTypedef(Old, New))
2569 return;
2570
2571 // The types match. Link up the redeclaration chain and merge attributes if
2572 // the old declaration was a typedef.
2573 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2574 New->setPreviousDecl(Typedef);
2575 mergeDeclAttributes(New, Old);
2576 }
2577
2578 if (getLangOpts().MicrosoftExt)
2579 return;
2580
2581 if (getLangOpts().CPlusPlus) {
2582 // C++ [dcl.typedef]p2:
2583 // In a given non-class scope, a typedef specifier can be used to
2584 // redefine the name of any type declared in that scope to refer
2585 // to the type to which it already refers.
2586 if (!isa<CXXRecordDecl>(CurContext))
2587 return;
2588
2589 // C++0x [dcl.typedef]p4:
2590 // In a given class scope, a typedef specifier can be used to redefine
2591 // any class-name declared in that scope that is not also a typedef-name
2592 // to refer to the type to which it already refers.
2593 //
2594 // This wording came in via DR424, which was a correction to the
2595 // wording in DR56, which accidentally banned code like:
2596 //
2597 // struct S {
2598 // typedef struct A { } A;
2599 // };
2600 //
2601 // in the C++03 standard. We implement the C++0x semantics, which
2602 // allow the above but disallow
2603 //
2604 // struct S {
2605 // typedef int I;
2606 // typedef int I;
2607 // };
2608 //
2609 // since that was the intent of DR56.
2610 if (!isa<TypedefNameDecl>(Old))
2611 return;
2612
2613 Diag(New->getLocation(), diag::err_redefinition)
2614 << New->getDeclName();
2616 return New->setInvalidDecl();
2617 }
2618
2619 // Modules always permit redefinition of typedefs, as does C11.
2620 if (getLangOpts().Modules || getLangOpts().C11)
2621 return;
2622
2623 // If we have a redefinition of a typedef in C, emit a warning. This warning
2624 // is normally mapped to an error, but can be controlled with
2625 // -Wtypedef-redefinition. If either the original or the redefinition is
2626 // in a system header, don't emit this for compatibility with GCC.
2627 if (getDiagnostics().getSuppressSystemWarnings() &&
2628 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2629 (Old->isImplicit() ||
2632 return;
2633
2634 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2635 << New->getDeclName();
2637}
2638
2639/// DeclhasAttr - returns true if decl Declaration already has the target
2640/// attribute.
2641static bool DeclHasAttr(const Decl *D, const Attr *A) {
2642 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2643 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2644 for (const auto *i : D->attrs())
2645 if (i->getKind() == A->getKind()) {
2646 if (Ann) {
2647 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2648 return true;
2649 continue;
2650 }
2651 // FIXME: Don't hardcode this check
2652 if (OA && isa<OwnershipAttr>(i))
2653 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2654 return true;
2655 }
2656
2657 return false;
2658}
2659
2661 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2662 return VD->isThisDeclarationADefinition();
2663 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2664 return TD->isCompleteDefinition() || TD->isBeingDefined();
2665 return true;
2666}
2667
2668/// Merge alignment attributes from \p Old to \p New, taking into account the
2669/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2670///
2671/// \return \c true if any attributes were added to \p New.
2672static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2673 // Look for alignas attributes on Old, and pick out whichever attribute
2674 // specifies the strictest alignment requirement.
2675 AlignedAttr *OldAlignasAttr = nullptr;
2676 AlignedAttr *OldStrictestAlignAttr = nullptr;
2677 unsigned OldAlign = 0;
2678 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2679 // FIXME: We have no way of representing inherited dependent alignments
2680 // in a case like:
2681 // template<int A, int B> struct alignas(A) X;
2682 // template<int A, int B> struct alignas(B) X {};
2683 // For now, we just ignore any alignas attributes which are not on the
2684 // definition in such a case.
2685 if (I->isAlignmentDependent())
2686 return false;
2687
2688 if (I->isAlignas())
2689 OldAlignasAttr = I;
2690
2691 unsigned Align = I->getAlignment(S.Context);
2692 if (Align > OldAlign) {
2693 OldAlign = Align;
2694 OldStrictestAlignAttr = I;
2695 }
2696 }
2697
2698 // Look for alignas attributes on New.
2699 AlignedAttr *NewAlignasAttr = nullptr;
2700 unsigned NewAlign = 0;
2701 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2702 if (I->isAlignmentDependent())
2703 return false;
2704
2705 if (I->isAlignas())
2706 NewAlignasAttr = I;
2707
2708 unsigned Align = I->getAlignment(S.Context);
2709 if (Align > NewAlign)
2710 NewAlign = Align;
2711 }
2712
2713 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2714 // Both declarations have 'alignas' attributes. We require them to match.
2715 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2716 // fall short. (If two declarations both have alignas, they must both match
2717 // every definition, and so must match each other if there is a definition.)
2718
2719 // If either declaration only contains 'alignas(0)' specifiers, then it
2720 // specifies the natural alignment for the type.
2721 if (OldAlign == 0 || NewAlign == 0) {
2722 QualType Ty;
2723 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2724 Ty = VD->getType();
2725 else
2726 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2727
2728 if (OldAlign == 0)
2729 OldAlign = S.Context.getTypeAlign(Ty);
2730 if (NewAlign == 0)
2731 NewAlign = S.Context.getTypeAlign(Ty);
2732 }
2733
2734 if (OldAlign != NewAlign) {
2735 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2738 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2739 }
2740 }
2741
2742 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2743 // C++11 [dcl.align]p6:
2744 // if any declaration of an entity has an alignment-specifier,
2745 // every defining declaration of that entity shall specify an
2746 // equivalent alignment.
2747 // C11 6.7.5/7:
2748 // If the definition of an object does not have an alignment
2749 // specifier, any other declaration of that object shall also
2750 // have no alignment specifier.
2751 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2752 << OldAlignasAttr;
2753 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2754 << OldAlignasAttr;
2755 }
2756
2757 bool AnyAdded = false;
2758
2759 // Ensure we have an attribute representing the strictest alignment.
2760 if (OldAlign > NewAlign) {
2761 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2762 Clone->setInherited(true);
2763 New->addAttr(Clone);
2764 AnyAdded = true;
2765 }
2766
2767 // Ensure we have an alignas attribute if the old declaration had one.
2768 if (OldAlignasAttr && !NewAlignasAttr &&
2769 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2770 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2771 Clone->setInherited(true);
2772 New->addAttr(Clone);
2773 AnyAdded = true;
2774 }
2775
2776 return AnyAdded;
2777}
2778
2779#define WANT_DECL_MERGE_LOGIC
2780#include "clang/Sema/AttrParsedAttrImpl.inc"
2781#undef WANT_DECL_MERGE_LOGIC
2782
2784 const InheritableAttr *Attr,
2786 // Diagnose any mutual exclusions between the attribute that we want to add
2787 // and attributes that already exist on the declaration.
2788 if (!DiagnoseMutualExclusions(S, D, Attr))
2789 return false;
2790
2791 // This function copies an attribute Attr from a previous declaration to the
2792 // new declaration D if the new declaration doesn't itself have that attribute
2793 // yet or if that attribute allows duplicates.
2794 // If you're adding a new attribute that requires logic different from
2795 // "use explicit attribute on decl if present, else use attribute from
2796 // previous decl", for example if the attribute needs to be consistent
2797 // between redeclarations, you need to call a custom merge function here.
2798 InheritableAttr *NewAttr = nullptr;
2799 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2800 NewAttr = S.mergeAvailabilityAttr(
2801 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2802 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2803 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2804 AA->getPriority(), AA->getEnvironment());
2805 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2806 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2807 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2808 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2809 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2810 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2811 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2812 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2813 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2814 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2815 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2816 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2817 FA->getFirstArg());
2818 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2819 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2820 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2821 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2822 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2823 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2824 IA->getInheritanceModel());
2825 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2826 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2827 &S.Context.Idents.get(AA->getSpelling()));
2828 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2829 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2830 isa<CUDAGlobalAttr>(Attr))) {
2831 // CUDA target attributes are part of function signature for
2832 // overloading purposes and must not be merged.
2833 return false;
2834 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2835 NewAttr = S.mergeMinSizeAttr(D, *MA);
2836 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2837 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2838 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2839 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2840 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2841 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2842 else if (isa<AlignedAttr>(Attr))
2843 // AlignedAttrs are handled separately, because we need to handle all
2844 // such attributes on a declaration at the same time.
2845 NewAttr = nullptr;
2846 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2847 (AMK == Sema::AMK_Override ||
2850 NewAttr = nullptr;
2851 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2852 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2853 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2854 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2855 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2856 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2857 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2858 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2859 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2860 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2861 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2862 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2863 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2864 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2865 NT->getZ());
2866 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2867 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2868 else if (isa<SuppressAttr>(Attr))
2869 // Do nothing. Each redeclaration should be suppressed separately.
2870 NewAttr = nullptr;
2871 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2872 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2873
2874 if (NewAttr) {
2875 NewAttr->setInherited(true);
2876 D->addAttr(NewAttr);
2877 if (isa<MSInheritanceAttr>(NewAttr))
2878 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2879 return true;
2880 }
2881
2882 return false;
2883}
2884
2885static const NamedDecl *getDefinition(const Decl *D) {
2886 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2887 return TD->getDefinition();
2888 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2889 const VarDecl *Def = VD->getDefinition();
2890 if (Def)
2891 return Def;
2892 return VD->getActingDefinition();
2893 }
2894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2895 const FunctionDecl *Def = nullptr;
2896 if (FD->isDefined(Def, true))
2897 return Def;
2898 }
2899 return nullptr;
2900}
2901
2902static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2903 for (const auto *Attribute : D->attrs())
2904 if (Attribute->getKind() == Kind)
2905 return true;
2906 return false;
2907}
2908
2909/// checkNewAttributesAfterDef - If we already have a definition, check that
2910/// there are no new attributes in this declaration.
2911static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2912 if (!New->hasAttrs())
2913 return;
2914
2915 const NamedDecl *Def = getDefinition(Old);
2916 if (!Def || Def == New)
2917 return;
2918
2919 AttrVec &NewAttributes = New->getAttrs();
2920 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2921 const Attr *NewAttribute = NewAttributes[I];
2922
2923 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2924 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2925 SkipBodyInfo SkipBody;
2926 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2927
2928 // If we're skipping this definition, drop the "alias" attribute.
2929 if (SkipBody.ShouldSkip) {
2930 NewAttributes.erase(NewAttributes.begin() + I);
2931 --E;
2932 continue;
2933 }
2934 } else {
2935 VarDecl *VD = cast<VarDecl>(New);
2936 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2938 ? diag::err_alias_after_tentative
2939 : diag::err_redefinition;
2940 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2941 if (Diag == diag::err_redefinition)
2942 S.notePreviousDefinition(Def, VD->getLocation());
2943 else
2944 S.Diag(Def->getLocation(), diag::note_previous_definition);
2945 VD->setInvalidDecl();
2946 }
2947 ++I;
2948 continue;
2949 }
2950
2951 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2952 // Tentative definitions are only interesting for the alias check above.
2953 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2954 ++I;
2955 continue;
2956 }
2957 }
2958
2959 if (hasAttribute(Def, NewAttribute->getKind())) {
2960 ++I;
2961 continue; // regular attr merging will take care of validating this.
2962 }
2963
2964 if (isa<C11NoReturnAttr>(NewAttribute)) {
2965 // C's _Noreturn is allowed to be added to a function after it is defined.
2966 ++I;
2967 continue;
2968 } else if (isa<UuidAttr>(NewAttribute)) {
2969 // msvc will allow a subsequent definition to add an uuid to a class
2970 ++I;
2971 continue;
2972 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2973 if (AA->isAlignas()) {
2974 // C++11 [dcl.align]p6:
2975 // if any declaration of an entity has an alignment-specifier,
2976 // every defining declaration of that entity shall specify an
2977 // equivalent alignment.
2978 // C11 6.7.5/7:
2979 // If the definition of an object does not have an alignment
2980 // specifier, any other declaration of that object shall also
2981 // have no alignment specifier.
2982 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2983 << AA;
2984 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2985 << AA;
2986 NewAttributes.erase(NewAttributes.begin() + I);
2987 --E;
2988 continue;
2989 }
2990 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2991 // If there is a C definition followed by a redeclaration with this
2992 // attribute then there are two different definitions. In C++, prefer the
2993 // standard diagnostics.
2994 if (!S.getLangOpts().CPlusPlus) {
2995 S.Diag(NewAttribute->getLocation(),
2996 diag::err_loader_uninitialized_redeclaration);
2997 S.Diag(Def->getLocation(), diag::note_previous_definition);
2998 NewAttributes.erase(NewAttributes.begin() + I);
2999 --E;
3000 continue;
3001 }
3002 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3003 cast<VarDecl>(New)->isInline() &&
3004 !cast<VarDecl>(New)->isInlineSpecified()) {
3005 // Don't warn about applying selectany to implicitly inline variables.
3006 // Older compilers and language modes would require the use of selectany
3007 // to make such variables inline, and it would have no effect if we
3008 // honored it.
3009 ++I;
3010 continue;
3011 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3012 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3013 // declarations after definitions.
3014 ++I;
3015 continue;
3016 }
3017
3018 S.Diag(NewAttribute->getLocation(),
3019 diag::warn_attribute_precede_definition);
3020 S.Diag(Def->getLocation(), diag::note_previous_definition);
3021 NewAttributes.erase(NewAttributes.begin() + I);
3022 --E;
3023 }
3024}
3025
3026static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3027 const ConstInitAttr *CIAttr,
3028 bool AttrBeforeInit) {
3029 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3030
3031 // Figure out a good way to write this specifier on the old declaration.
3032 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3033 // enough of the attribute list spelling information to extract that without
3034 // heroics.
3035 std::string SuitableSpelling;
3036 if (S.getLangOpts().CPlusPlus20)
3037 SuitableSpelling = std::string(
3038 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3039 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3040 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3041 InsertLoc, {tok::l_square, tok::l_square,
3042 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3043 S.PP.getIdentifierInfo("require_constant_initialization"),
3044 tok::r_square, tok::r_square}));
3045 if (SuitableSpelling.empty())
3046 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3047 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3048 S.PP.getIdentifierInfo("require_constant_initialization"),
3049 tok::r_paren, tok::r_paren}));
3050 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3051 SuitableSpelling = "constinit";
3052 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3053 SuitableSpelling = "[[clang::require_constant_initialization]]";
3054 if (SuitableSpelling.empty())
3055 SuitableSpelling = "__attribute__((require_constant_initialization))";
3056 SuitableSpelling += " ";
3057
3058 if (AttrBeforeInit) {
3059 // extern constinit int a;
3060 // int a = 0; // error (missing 'constinit'), accepted as extension
3061 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3062 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3063 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3064 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3065 } else {
3066 // int a = 0;
3067 // constinit extern int a; // error (missing 'constinit')
3068 S.Diag(CIAttr->getLocation(),
3069 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3070 : diag::warn_require_const_init_added_too_late)
3071 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3072 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3073 << CIAttr->isConstinit()
3074 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3075 }
3076}
3077
3080 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3081 UsedAttr *NewAttr = OldAttr->clone(Context);
3082 NewAttr->setInherited(true);
3083 New->addAttr(NewAttr);
3084 }
3085 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3086 RetainAttr *NewAttr = OldAttr->clone(Context);
3087 NewAttr->setInherited(true);
3088 New->addAttr(NewAttr);
3089 }
3090
3091 if (!Old->hasAttrs() && !New->hasAttrs())
3092 return;
3093
3094 // [dcl.constinit]p1:
3095 // If the [constinit] specifier is applied to any declaration of a
3096 // variable, it shall be applied to the initializing declaration.
3097 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3098 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3099 if (bool(OldConstInit) != bool(NewConstInit)) {
3100 const auto *OldVD = cast<VarDecl>(Old);
3101 auto *NewVD = cast<VarDecl>(New);
3102
3103 // Find the initializing declaration. Note that we might not have linked
3104 // the new declaration into the redeclaration chain yet.
3105 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3106 if (!InitDecl &&
3107 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3108 InitDecl = NewVD;
3109
3110 if (InitDecl == NewVD) {
3111 // This is the initializing declaration. If it would inherit 'constinit',
3112 // that's ill-formed. (Note that we do not apply this to the attribute
3113 // form).
3114 if (OldConstInit && OldConstInit->isConstinit())
3115 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3116 /*AttrBeforeInit=*/true);
3117 } else if (NewConstInit) {
3118 // This is the first time we've been told that this declaration should
3119 // have a constant initializer. If we already saw the initializing
3120 // declaration, this is too late.
3121 if (InitDecl && InitDecl != NewVD) {
3122 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3123 /*AttrBeforeInit=*/false);
3124 NewVD->dropAttr<ConstInitAttr>();
3125 }
3126 }
3127 }
3128
3129 // Attributes declared post-definition are currently ignored.
3130 checkNewAttributesAfterDef(*this, New, Old);
3131
3132 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3133 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3134 if (!OldA->isEquivalent(NewA)) {
3135 // This redeclaration changes __asm__ label.
3136 Diag(New->getLocation(), diag::err_different_asm_label);
3137 Diag(OldA->getLocation(), diag::note_previous_declaration);
3138 }
3139 } else if (Old->isUsed()) {
3140 // This redeclaration adds an __asm__ label to a declaration that has
3141 // already been ODR-used.
3142 Diag(New->getLocation(), diag::err_late_asm_label_name)
3143 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3144 }
3145 }
3146
3147 // Re-declaration cannot add abi_tag's.
3148 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3149 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3150 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3151 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3152 Diag(NewAbiTagAttr->getLocation(),
3153 diag::err_new_abi_tag_on_redeclaration)
3154 << NewTag;
3155 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3156 }
3157 }
3158 } else {
3159 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3160 Diag(Old->getLocation(), diag::note_previous_declaration);
3161 }
3162 }
3163
3164 // This redeclaration adds a section attribute.
3165 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3166 if (auto *VD = dyn_cast<VarDecl>(New)) {
3167 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3168 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3169 Diag(Old->getLocation(), diag::note_previous_declaration);
3170 }
3171 }
3172 }
3173
3174 // Redeclaration adds code-seg attribute.
3175 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3176 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3177 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3178 Diag(New->getLocation(), diag::warn_mismatched_section)
3179 << 0 /*codeseg*/;
3180 Diag(Old->getLocation(), diag::note_previous_declaration);
3181 }
3182
3183 if (!Old->hasAttrs())
3184 return;
3185
3186 bool foundAny = New->hasAttrs();
3187
3188 // Ensure that any moving of objects within the allocated map is done before
3189 // we process them.
3190 if (!foundAny) New->setAttrs(AttrVec());
3191
3192 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3193 // Ignore deprecated/unavailable/availability attributes if requested.
3195 if (isa<DeprecatedAttr>(I) ||
3196 isa<UnavailableAttr>(I) ||
3197 isa<AvailabilityAttr>(I)) {
3198 switch (AMK) {
3199 case AMK_None:
3200 continue;
3201
3202 case AMK_Redeclaration:
3203 case AMK_Override:
3206 LocalAMK = AMK;
3207 break;
3208 }
3209 }
3210
3211 // Already handled.
3212 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3213 continue;
3214
3215 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3216 foundAny = true;
3217 }
3218
3219 if (mergeAlignedAttrs(*this, New, Old))
3220 foundAny = true;
3221
3222 if (!foundAny) New->dropAttrs();
3223}
3224
3225/// mergeParamDeclAttributes - Copy attributes from the old parameter
3226/// to the new one.
3228 const ParmVarDecl *oldDecl,
3229 Sema &S) {
3230 // C++11 [dcl.attr.depend]p2:
3231 // The first declaration of a function shall specify the
3232 // carries_dependency attribute for its declarator-id if any declaration
3233 // of the function specifies the carries_dependency attribute.
3234 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3235 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3236 S.Diag(CDA->getLocation(),
3237 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3238 // Find the first declaration of the parameter.
3239 // FIXME: Should we build redeclaration chains for function parameters?
3240 const FunctionDecl *FirstFD =
3241 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3242 const ParmVarDecl *FirstVD =
3243 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3244 S.Diag(FirstVD->getLocation(),
3245 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3246 }
3247
3248 // HLSL parameter declarations for inout and out must match between
3249 // declarations. In HLSL inout and out are ambiguous at the call site, but
3250 // have different calling behavior, so you cannot overload a method based on a
3251 // difference between inout and out annotations.
3252 if (S.getLangOpts().HLSL) {
3253 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3254 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3255 // We don't need to cover the case where one declaration doesn't have an
3256 // attribute. The only possible case there is if one declaration has an `in`
3257 // attribute and the other declaration has no attribute. This case is
3258 // allowed since parameters are `in` by default.
3259 if (NDAttr && ODAttr &&
3260 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3261 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3262 << NDAttr << newDecl;
3263 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3264 << ODAttr;
3265 }
3266 }
3267
3268 if (!oldDecl->hasAttrs())
3269 return;
3270
3271 bool foundAny = newDecl->hasAttrs();
3272
3273 // Ensure that any moving of objects within the allocated map is
3274 // done before we process them.
3275 if (!foundAny) newDecl->setAttrs(AttrVec());
3276
3277 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3278 if (!DeclHasAttr(newDecl, I)) {
3279 InheritableAttr *newAttr =
3280 cast<InheritableParamAttr>(I->clone(S.Context));
3281 newAttr->setInherited(true);
3282 newDecl->addAttr(newAttr);
3283 foundAny = true;
3284 }
3285 }
3286
3287 if (!foundAny) newDecl->dropAttrs();
3288}
3289
3291 const ASTContext &Ctx) {
3292
3293 auto NoSizeInfo = [&Ctx](QualType Ty) {
3294 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3295 return true;
3296 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3297 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3298 return false;
3299 };
3300
3301 // `type[]` is equivalent to `type *` and `type[*]`.
3302 if (NoSizeInfo(Old) && NoSizeInfo(New))
3303 return true;
3304
3305 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3306 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3307 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3308 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3309 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3310 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3311 return false;
3312 return true;
3313 }
3314
3315 // Only compare size, ignore Size modifiers and CVR.
3316 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3317 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3318 Ctx.getAsConstantArrayType(New)->getSize();
3319 }
3320
3321 // Don't try to compare dependent sized array
3323 return true;
3324 }
3325
3326 return Old == New;
3327}
3328
3329static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3330 const ParmVarDecl *OldParam,
3331 Sema &S) {
3332 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3333 if (auto Newnullability = NewParam->getType()->getNullability()) {
3334 if (*Oldnullability != *Newnullability) {
3335 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3337 *Newnullability,
3339 != 0))
3341 *Oldnullability,
3343 != 0));
3344 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3345 }
3346 } else {
3347 QualType NewT = NewParam->getType();
3348 NewT = S.Context.getAttributedType(
3350 NewT, NewT);
3351 NewParam->setType(NewT);
3352 }
3353 }
3354 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3355 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3356 if (OldParamDT && NewParamDT &&
3357 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3358 QualType OldParamOT = OldParamDT->getOriginalType();
3359 QualType NewParamOT = NewParamDT->getOriginalType();
3360 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3361 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3362 << NewParam << NewParamOT;
3363 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3364 << OldParamOT;
3365 }
3366 }
3367}
3368
3369namespace {
3370
3371/// Used in MergeFunctionDecl to keep track of function parameters in
3372/// C.
3373struct GNUCompatibleParamWarning {
3374 ParmVarDecl *OldParm;
3375 ParmVarDecl *NewParm;
3376 QualType PromotedType;
3377};
3378
3379} // end anonymous namespace
3380
3381// Determine whether the previous declaration was a definition, implicit
3382// declaration, or a declaration.
3383template <typename T>
3384static std::pair<diag::kind, SourceLocation>
3385getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3386 diag::kind PrevDiag;
3387 SourceLocation OldLocation = Old->getLocation();
3388 if (Old->isThisDeclarationADefinition())
3389 PrevDiag = diag::note_previous_definition;
3390 else if (Old->isImplicit()) {
3391 PrevDiag = diag::note_previous_implicit_declaration;
3392 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3393 if (FD->getBuiltinID())
3394 PrevDiag = diag::note_previous_builtin_declaration;
3395 }
3396 if (OldLocation.isInvalid())
3397 OldLocation = New->getLocation();
3398 } else
3399 PrevDiag = diag::note_previous_declaration;
3400 return std::make_pair(PrevDiag, OldLocation);
3401}
3402
3403/// canRedefineFunction - checks if a function can be redefined. Currently,
3404/// only extern inline functions can be redefined, and even then only in
3405/// GNU89 mode.
3406static bool canRedefineFunction(const FunctionDecl *FD,
3407 const LangOptions& LangOpts) {
3408 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3409 !LangOpts.CPlusPlus &&
3410 FD->isInlineSpecified() &&
3411 FD->getStorageClass() == SC_Extern);
3412}
3413
3415 const AttributedType *AT = T->getAs<AttributedType>();
3416 while (AT && !AT->isCallingConv())
3417 AT = AT->getModifiedType()->getAs<AttributedType>();
3418 return AT;
3419}
3420
3421template <typename T>
3422static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3423 const DeclContext *DC = Old->getDeclContext();
3424 if (DC->isRecord())
3425 return false;
3426
3427 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3428 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3429 return true;
3430 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3431 return true;
3432 return false;
3433}
3434
3435template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3436static bool isExternC(VarTemplateDecl *) { return false; }
3437static bool isExternC(FunctionTemplateDecl *) { return false; }
3438
3439/// Check whether a redeclaration of an entity introduced by a
3440/// using-declaration is valid, given that we know it's not an overload
3441/// (nor a hidden tag declaration).
3442template<typename ExpectedDecl>
3444 ExpectedDecl *New) {
3445 // C++11 [basic.scope.declarative]p4:
3446 // Given a set of declarations in a single declarative region, each of
3447 // which specifies the same unqualified name,
3448 // -- they shall all refer to the same entity, or all refer to functions
3449 // and function templates; or
3450 // -- exactly one declaration shall declare a class name or enumeration
3451 // name that is not a typedef name and the other declarations shall all
3452 // refer to the same variable or enumerator, or all refer to functions
3453 // and function templates; in this case the class name or enumeration
3454 // name is hidden (3.3.10).
3455
3456 // C++11 [namespace.udecl]p14:
3457 // If a function declaration in namespace scope or block scope has the
3458 // same name and the same parameter-type-list as a function introduced
3459 // by a using-declaration, and the declarations do not declare the same
3460 // function, the program is ill-formed.
3461
3462 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3463 if (Old &&
3464 !Old->getDeclContext()->getRedeclContext()->Equals(
3465 New->getDeclContext()->getRedeclContext()) &&
3466 !(isExternC(Old) && isExternC(New)))
3467 Old = nullptr;
3468
3469 if (!Old) {
3470 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3471 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3472 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3473 return true;
3474 }
3475 return false;
3476}
3477
3479 const FunctionDecl *B) {
3480 assert(A->getNumParams() == B->getNumParams());
3481
3482 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3483 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3484 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3485 if (AttrA == AttrB)
3486 return true;
3487 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3488 AttrA->isDynamic() == AttrB->isDynamic();
3489 };
3490
3491 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3492}
3493
3494/// If necessary, adjust the semantic declaration context for a qualified
3495/// declaration to name the correct inline namespace within the qualifier.
3497 DeclaratorDecl *OldD) {
3498 // The only case where we need to update the DeclContext is when
3499 // redeclaration lookup for a qualified name finds a declaration
3500 // in an inline namespace within the context named by the qualifier:
3501 //
3502 // inline namespace N { int f(); }
3503 // int ::f(); // Sema DC needs adjusting from :: to N::.
3504 //
3505 // For unqualified declarations, the semantic context *can* change
3506 // along the redeclaration chain (for local extern declarations,
3507 // extern "C" declarations, and friend declarations in particular).
3508 if (!NewD->getQualifier())
3509 return;
3510
3511 // NewD is probably already in the right context.
3512 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3513 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3514 if (NamedDC->Equals(SemaDC))
3515 return;
3516
3517 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3518 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3519 "unexpected context for redeclaration");
3520
3521 auto *LexDC = NewD->getLexicalDeclContext();
3522 auto FixSemaDC = [=](NamedDecl *D) {
3523 if (!D)
3524 return;
3525 D->setDeclContext(SemaDC);
3526 D->setLexicalDeclContext(LexDC);
3527 };
3528
3529 FixSemaDC(NewD);
3530 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3531 FixSemaDC(FD->getDescribedFunctionTemplate());
3532 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3533 FixSemaDC(VD->getDescribedVarTemplate());
3534}
3535
3537 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3538 // Verify the old decl was also a function.
3539 FunctionDecl *Old = OldD->getAsFunction();
3540 if (!Old) {
3541 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3542 if (New->getFriendObjectKind()) {
3543 Diag(New->getLocation(), diag::err_using_decl_friend);
3544 Diag(Shadow->getTargetDecl()->getLocation(),
3545 diag::note_using_decl_target);
3546 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3547 << 0;
3548 return true;
3549 }
3550
3551 // Check whether the two declarations might declare the same function or
3552 // function template.
3553 if (FunctionTemplateDecl *NewTemplate =
3555 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3556 NewTemplate))
3557 return true;
3558 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3559 ->getAsFunction();
3560 } else {
3561 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3562 return true;
3563 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3564 }
3565 } else {
3566 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3567 << New->getDeclName();
3568 notePreviousDefinition(OldD, New->getLocation());
3569 return true;
3570 }
3571 }
3572
3573 // If the old declaration was found in an inline namespace and the new
3574 // declaration was qualified, update the DeclContext to match.
3576
3577 // If the old declaration is invalid, just give up here.
3578 if (Old->isInvalidDecl())
3579 return true;
3580
3581 // Disallow redeclaration of some builtins.
3582 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3583 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3584 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3585 << Old << Old->getType();
3586 return true;
3587 }
3588
3589 diag::kind PrevDiag;
3590 SourceLocation OldLocation;
3591 std::tie(PrevDiag, OldLocation) =
3593
3594 // Don't complain about this if we're in GNU89 mode and the old function
3595 // is an extern inline function.
3596 // Don't complain about specializations. They are not supposed to have
3597 // storage classes.
3598 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3599 New->getStorageClass() == SC_Static &&
3600 Old->hasExternalFormalLinkage() &&
3603 if (getLangOpts().MicrosoftExt) {
3604 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3605 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3606 } else {
3607 Diag(New->getLocation(), diag::err_static_non_static) << New;
3608 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3609 return true;
3610 }
3611 }
3612
3613 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3614 if (!Old->hasAttr<InternalLinkageAttr>()) {
3615 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3616 << ILA;
3617 Diag(Old->getLocation(), diag::note_previous_declaration);
3618 New->dropAttr<InternalLinkageAttr>();
3619 }
3620
3621 if (auto *EA = New->getAttr<ErrorAttr>()) {
3622 if (!Old->hasAttr<ErrorAttr>()) {
3623 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3624 Diag(Old->getLocation(), diag::note_previous_declaration);
3625 New->dropAttr<ErrorAttr>();
3626 }
3627 }
3628
3629 if (CheckRedeclarationInModule(New, Old))
3630 return true;
3631
3632 if (!getLangOpts().CPlusPlus) {
3633 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3634 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3635 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3636 << New << OldOvl;
3637
3638 // Try our best to find a decl that actually has the overloadable
3639 // attribute for the note. In most cases (e.g. programs with only one
3640 // broken declaration/definition), this won't matter.
3641 //
3642 // FIXME: We could do this if we juggled some extra state in
3643 // OverloadableAttr, rather than just removing it.
3644 const Decl *DiagOld = Old;
3645 if (OldOvl) {
3646 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3647 const auto *A = D->getAttr<OverloadableAttr>();
3648 return A && !A->isImplicit();
3649 });
3650 // If we've implicitly added *all* of the overloadable attrs to this
3651 // chain, emitting a "previous redecl" note is pointless.
3652 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3653 }
3654
3655 if (DiagOld)
3656 Diag(DiagOld->getLocation(),
3657 diag::note_attribute_overloadable_prev_overload)
3658 << OldOvl;
3659
3660 if (OldOvl)
3661 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3662 else
3663 New->dropAttr<OverloadableAttr>();
3664 }
3665 }
3666
3667 // It is not permitted to redeclare an SME function with different SME
3668 // attributes.
3669 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3670 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3671 << New->getType() << Old->getType();
3672 Diag(OldLocation, diag::note_previous_declaration);
3673 return true;
3674 }
3675
3676 // If a function is first declared with a calling convention, but is later
3677 // declared or defined without one, all following decls assume the calling
3678 // convention of the first.
3679 //
3680 // It's OK if a function is first declared without a calling convention,
3681 // but is later declared or defined with the default calling convention.
3682 //
3683 // To test if either decl has an explicit calling convention, we look for
3684 // AttributedType sugar nodes on the type as written. If they are missing or
3685 // were canonicalized away, we assume the calling convention was implicit.
3686 //
3687 // Note also that we DO NOT return at this point, because we still have
3688 // other tests to run.
3689 QualType OldQType = Context.getCanonicalType(Old->getType());
3690 QualType NewQType = Context.getCanonicalType(New->getType());
3691 const FunctionType *OldType = cast<FunctionType>(OldQType);
3692 const FunctionType *NewType = cast<FunctionType>(NewQType);
3693 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3694 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3695 bool RequiresAdjustment = false;
3696
3697 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3699 const FunctionType *FT =
3700 First->getType().getCanonicalType()->castAs<FunctionType>();
3702 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3703 if (!NewCCExplicit) {
3704 // Inherit the CC from the previous declaration if it was specified
3705 // there but not here.
3706 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3707 RequiresAdjustment = true;
3708 } else if (Old->getBuiltinID()) {
3709 // Builtin attribute isn't propagated to the new one yet at this point,
3710 // so we check if the old one is a builtin.
3711
3712 // Calling Conventions on a Builtin aren't really useful and setting a
3713 // default calling convention and cdecl'ing some builtin redeclarations is
3714 // common, so warn and ignore the calling convention on the redeclaration.
3715 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3716 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3718 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3719 RequiresAdjustment = true;
3720 } else {
3721 // Calling conventions aren't compatible, so complain.
3722 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3723 Diag(New->getLocation(), diag::err_cconv_change)
3724 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3725 << !FirstCCExplicit
3726 << (!FirstCCExplicit ? "" :
3728
3729 // Put the note on the first decl, since it is the one that matters.
3730 Diag(First->getLocation(), diag::note_previous_declaration);
3731 return true;
3732 }
3733 }
3734
3735 // FIXME: diagnose the other way around?
3736 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3737 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3738 RequiresAdjustment = true;
3739 }
3740
3741 // Merge regparm attribute.
3742 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3743 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3744 if (NewTypeInfo.getHasRegParm()) {
3745 Diag(New->getLocation(), diag::err_regparm_mismatch)
3746 << NewType->getRegParmType()
3747 << OldType->getRegParmType();
3748 Diag(OldLocation, diag::note_previous_declaration);
3749 return true;
3750 }
3751
3752 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3753 RequiresAdjustment = true;
3754 }
3755
3756 // Merge ns_returns_retained attribute.
3757 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3758 if (NewTypeInfo.getProducesResult()) {
3759 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3760 << "'ns_returns_retained'";
3761 Diag(OldLocation, diag::note_previous_declaration);
3762 return true;
3763 }
3764
3765 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3766 RequiresAdjustment = true;
3767 }
3768
3769 if (OldTypeInfo.getNoCallerSavedRegs() !=
3770 NewTypeInfo.getNoCallerSavedRegs()) {
3771 if (NewTypeInfo.getNoCallerSavedRegs()) {
3772 AnyX86NoCallerSavedRegistersAttr *Attr =
3773 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3774 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3775 Diag(OldLocation, diag::note_previous_declaration);
3776 return true;
3777 }
3778
3779 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3780 RequiresAdjustment = true;
3781 }
3782
3783 if (RequiresAdjustment) {
3786 New->setType(QualType(AdjustedType, 0));
3787 NewQType = Context.getCanonicalType(New->getType());
3788 }
3789
3790 // If this redeclaration makes the function inline, we may need to add it to
3791 // UndefinedButUsed.
3792 if (!Old->isInlined() && New->isInlined() &&
3793 !New->hasAttr<GNUInlineAttr>() &&
3794 !getLangOpts().GNUInline &&
3795 Old->isUsed(false) &&
3796 !Old->isDefined() && !New->isThisDeclarationADefinition())
3797 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3798 SourceLocation()));
3799
3800 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3801 // about it.
3802 if (New->hasAttr<GNUInlineAttr>() &&
3803 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3804 UndefinedButUsed.erase(Old->getCanonicalDecl());
3805 }
3806
3807 // If pass_object_size params don't match up perfectly, this isn't a valid
3808 // redeclaration.
3809 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3811 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3812 << New->getDeclName();
3813 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3814 return true;
3815 }
3816
3817 QualType OldQTypeForComparison = OldQType;
3819 const auto OldFX = Old->getFunctionEffects();
3820 const auto NewFX = New->getFunctionEffects();
3821 if (OldFX != NewFX) {
3822 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
3823 for (const auto &Diff : Diffs) {
3824 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3825 Diag(New->getLocation(),
3826 diag::warn_mismatched_func_effect_redeclaration)
3827 << Diff.effectName();
3828 Diag(Old->getLocation(), diag::note_previous_declaration);
3829 }
3830 }
3831 // Following a warning, we could skip merging effects from the previous
3832 // declaration, but that would trigger an additional "conflicting types"
3833 // error.
3834 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3836 FunctionEffectSet MergedFX =
3837 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3838 if (!MergeErrs.empty())
3840 Old->getLocation());
3841
3842 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3843 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3844 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3845 NewFPT->getParamTypes(), EPI);
3846
3847 New->setType(ModQT);
3848 NewQType = New->getType();
3849
3850 // Revise OldQTForComparison to include the merged effects,
3851 // so as not to fail due to differences later.
3852 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3853 EPI = OldFPT->getExtProtoInfo();
3854 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3855 OldQTypeForComparison = Context.getFunctionType(
3856 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3857 }
3858 }
3859 }
3860 }
3861
3862 if (getLangOpts().CPlusPlus) {
3863 OldQType = Context.getCanonicalType(Old->getType());
3864 NewQType = Context.getCanonicalType(New->getType());
3865
3866 // Go back to the type source info to compare the declared return types,
3867 // per C++1y [dcl.type.auto]p13:
3868 // Redeclarations or specializations of a function or function template
3869 // with a declared return type that uses a placeholder type shall also
3870 // use that placeholder, not a deduced type.
3871 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3872 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3873 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3874 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3875 OldDeclaredReturnType)) {
3876 QualType ResQT;
3877 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3878 OldDeclaredReturnType->isObjCObjectPointerType())
3879 // FIXME: This does the wrong thing for a deduced return type.
3880 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3881 if (ResQT.isNull()) {
3882 if (New->isCXXClassMember() && New->isOutOfLine())
3883 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3884 << New << New->getReturnTypeSourceRange();
3885 else
3886 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3887 << New->getReturnTypeSourceRange();
3888 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3889 << Old->getReturnTypeSourceRange();
3890 return true;
3891 }
3892 else
3893 NewQType = ResQT;
3894 }
3895
3896 QualType OldReturnType = OldType->getReturnType();
3897 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3898 if (OldReturnType != NewReturnType) {
3899 // If this function has a deduced return type and has already been
3900 // defined, copy the deduced value from the old declaration.
3901 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3902 if (OldAT && OldAT->isDeduced()) {
3903 QualType DT = OldAT->getDeducedType();
3904 if (DT.isNull()) {
3906 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3907 } else {
3908 New->setType(SubstAutoType(New->getType(), DT));
3909 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3910 }
3911 }
3912 }
3913
3914 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3915 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3916 if (OldMethod && NewMethod) {
3917 // Preserve triviality.
3918 NewMethod->setTrivial(OldMethod->isTrivial());
3919
3920 // MSVC allows explicit template specialization at class scope:
3921 // 2 CXXMethodDecls referring to the same function will be injected.
3922 // We don't want a redeclaration error.
3923 bool IsClassScopeExplicitSpecialization =
3924 OldMethod->isFunctionTemplateSpecialization() &&
3926 bool isFriend = NewMethod->getFriendObjectKind();
3927
3928 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3929 !IsClassScopeExplicitSpecialization) {
3930 // -- Member function declarations with the same name and the
3931 // same parameter types cannot be overloaded if any of them
3932 // is a static member function declaration.
3933 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3934 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3935 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3936 return true;
3937 }
3938
3939 // C++ [class.mem]p1:
3940 // [...] A member shall not be declared twice in the
3941 // member-specification, except that a nested class or member
3942 // class template can be declared and then later defined.
3943 if (!inTemplateInstantiation()) {
3944 unsigned NewDiag;
3945 if (isa<CXXConstructorDecl>(OldMethod))
3946 NewDiag = diag::err_constructor_redeclared;
3947 else if (isa<CXXDestructorDecl>(NewMethod))
3948 NewDiag = diag::err_destructor_redeclared;
3949 else if (isa<CXXConversionDecl>(NewMethod))
3950 NewDiag = diag::err_conv_function_redeclared;
3951 else
3952 NewDiag = diag::err_member_redeclared;
3953
3954 Diag(New->getLocation(), NewDiag);
3955 } else {
3956 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3957 << New << New->getType();
3958 }
3959 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3960 return true;
3961
3962 // Complain if this is an explicit declaration of a special
3963 // member that was initially declared implicitly.
3964 //
3965 // As an exception, it's okay to befriend such methods in order
3966 // to permit the implicit constructor/destructor/operator calls.
3967 } else if (OldMethod->isImplicit()) {
3968 if (isFriend) {
3969 NewMethod->setImplicit();
3970 } else {
3971 Diag(NewMethod->getLocation(),
3972 diag::err_definition_of_implicitly_declared_member)
3973 << New << llvm::to_underlying(getSpecialMember(OldMethod));
3974 return true;
3975 }
3976 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3977 Diag(NewMethod->getLocation(),
3978 diag::err_definition_of_explicitly_defaulted_member)
3979 << llvm::to_underlying(getSpecialMember(OldMethod));
3980 return true;
3981 }
3982 }
3983
3984 // C++1z [over.load]p2
3985 // Certain function declarations cannot be overloaded:
3986 // -- Function declarations that differ only in the return type,
3987 // the exception specification, or both cannot be overloaded.
3988
3989 // Check the exception specifications match. This may recompute the type of
3990 // both Old and New if it resolved exception specifications, so grab the
3991 // types again after this. Because this updates the type, we do this before
3992 // any of the other checks below, which may update the "de facto" NewQType
3993 // but do not necessarily update the type of New.
3994 if (CheckEquivalentExceptionSpec(Old, New))
3995 return true;
3996
3997 // C++11 [dcl.attr.noreturn]p1:
3998 // The first declaration of a function shall specify the noreturn
3999 // attribute if any declaration of that function specifies the noreturn
4000 // attribute.
4001 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4002 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4003 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4004 << NRA;
4005 Diag(Old->getLocation(), diag::note_previous_declaration);
4006 }
4007
4008 // C++11 [dcl.attr.depend]p2:
4009 // The first declaration of a function shall specify the
4010 // carries_dependency attribute for its declarator-id if any declaration
4011 // of the function specifies the carries_dependency attribute.
4012 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4013 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4014 Diag(CDA->getLocation(),
4015 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4016 Diag(Old->getFirstDecl()->getLocation(),
4017 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4018 }
4019
4020 // (C++98 8.3.5p3):
4021 // All declarations for a function shall agree exactly in both the
4022 // return type and the parameter-type-list.
4023 // We also want to respect all the extended bits except noreturn.
4024
4025 // noreturn should now match unless the old type info didn't have it.
4026 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4027 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4028 const FunctionType *OldTypeForComparison
4029 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4030 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4031 assert(OldQTypeForComparison.isCanonical());
4032 }
4033
4034 if (haveIncompatibleLanguageLinkages(Old, New)) {
4035 // As a special case, retain the language linkage from previous
4036 // declarations of a friend function as an extension.
4037 //
4038 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4039 // and is useful because there's otherwise no way to specify language
4040 // linkage within class scope.
4041 //
4042 // Check cautiously as the friend object kind isn't yet complete.
4043 if (New->getFriendObjectKind() != Decl::FOK_None) {
4044 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4045 Diag(OldLocation, PrevDiag);
4046 } else {
4047 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4048 Diag(OldLocation, PrevDiag);
4049 return true;
4050 }
4051 }
4052
4053 // If the function types are compatible, merge the declarations. Ignore the
4054 // exception specifier because it was already checked above in
4055 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4056 // about incompatible types under -fms-compatibility.
4057 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4058 NewQType))
4059 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4060
4061 // If the types are imprecise (due to dependent constructs in friends or
4062 // local extern declarations), it's OK if they differ. We'll check again
4063 // during instantiation.
4064 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4065 return false;
4066
4067 // Fall through for conflicting redeclarations and redefinitions.
4068 }
4069
4070 // C: Function types need to be compatible, not identical. This handles
4071 // duplicate function decls like "void f(int); void f(enum X);" properly.
4072 if (!getLangOpts().CPlusPlus) {
4073 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4074 // type is specified by a function definition that contains a (possibly
4075 // empty) identifier list, both shall agree in the number of parameters
4076 // and the type of each parameter shall be compatible with the type that
4077 // results from the application of default argument promotions to the
4078 // type of the corresponding identifier. ...
4079 // This cannot be handled by ASTContext::typesAreCompatible() because that
4080 // doesn't know whether the function type is for a definition or not when
4081 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4082 // we need to cover here is that the number of arguments agree as the
4083 // default argument promotion rules were already checked by
4084 // ASTContext::typesAreCompatible().
4085 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4086 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4087 if (Old->hasInheritedPrototype())
4088 Old = Old->getCanonicalDecl();
4089 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4090 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4091 return true;
4092 }
4093
4094 // If we are merging two functions where only one of them has a prototype,
4095 // we may have enough information to decide to issue a diagnostic that the
4096 // function without a prototype will change behavior in C23. This handles
4097 // cases like:
4098 // void i(); void i(int j);
4099 // void i(int j); void i();
4100 // void i(); void i(int j) {}
4101 // See ActOnFinishFunctionBody() for other cases of the behavior change
4102 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4103 // type without a prototype.
4104 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4105 !New->isImplicit() && !Old->isImplicit()) {
4106 const FunctionDecl *WithProto, *WithoutProto;
4107 if (New->hasWrittenPrototype()) {
4108 WithProto = New;
4109 WithoutProto = Old;
4110 } else {
4111 WithProto = Old;
4112 WithoutProto = New;
4113 }
4114
4115 if (WithProto->getNumParams() != 0) {
4116 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4117 // The one without the prototype will be changing behavior in C23, so
4118 // warn about that one so long as it's a user-visible declaration.
4119 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4120 if (WithoutProto == New)
4121 IsWithoutProtoADef = NewDeclIsDefn;
4122 else
4123 IsWithProtoADef = NewDeclIsDefn;
4124 Diag(WithoutProto->getLocation(),
4125 diag::warn_non_prototype_changes_behavior)
4126 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4127 << (WithoutProto == Old) << IsWithProtoADef;
4128
4129 // The reason the one without the prototype will be changing behavior
4130 // is because of the one with the prototype, so note that so long as
4131 // it's a user-visible declaration. There is one exception to this:
4132 // when the new declaration is a definition without a prototype, the
4133 // old declaration with a prototype is not the cause of the issue,
4134 // and that does not need to be noted because the one with a
4135 // prototype will not change behavior in C23.
4136 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4137 !IsWithoutProtoADef)
4138 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4139 }
4140 }
4141 }
4142
4143 if (Context.typesAreCompatible(OldQType, NewQType)) {
4144 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4145 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4146 const FunctionProtoType *OldProto = nullptr;
4147 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4148 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4149 // The old declaration provided a function prototype, but the
4150 // new declaration does not. Merge in the prototype.
4151 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4152 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4153 OldProto->getParamTypes(),
4154 OldProto->getExtProtoInfo());
4155 New->setType(NewQType);
4157
4158 // Synthesize parameters with the same types.
4160 for (const auto &ParamType : OldProto->param_types()) {
4162 Context, New, SourceLocation(), SourceLocation(), nullptr,
4163 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4164 Param->setScopeInfo(0, Params.size());
4165 Param->setImplicit();
4166 Params.push_back(Param);
4167 }
4168
4169 New->setParams(Params);
4170 }
4171
4172 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4173 }
4174 }
4175
4176 // Check if the function types are compatible when pointer size address
4177 // spaces are ignored.
4178 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4179 return false;
4180
4181 // GNU C permits a K&R definition to follow a prototype declaration
4182 // if the declared types of the parameters in the K&R definition
4183 // match the types in the prototype declaration, even when the
4184 // promoted types of the parameters from the K&R definition differ
4185 // from the types in the prototype. GCC then keeps the types from
4186 // the prototype.
4187 //
4188 // If a variadic prototype is followed by a non-variadic K&R definition,
4189 // the K&R definition becomes variadic. This is sort of an edge case, but
4190 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4191 // C99 6.9.1p8.
4192 if (!getLangOpts().CPlusPlus &&
4193 Old->hasPrototype() && !New->hasPrototype() &&
4194 New->getType()->getAs<FunctionProtoType>() &&
4195 Old->getNumParams() == New->getNumParams()) {
4198 const FunctionProtoType *OldProto
4199 = Old->getType()->getAs<FunctionProtoType>();
4200 const FunctionProtoType *NewProto
4201 = New->getType()->getAs<FunctionProtoType>();
4202
4203 // Determine whether this is the GNU C extension.
4204 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4205 NewProto->getReturnType());
4206 bool LooseCompatible = !MergedReturn.isNull();
4207 for (unsigned Idx = 0, End = Old->getNumParams();
4208 LooseCompatible && Idx != End; ++Idx) {
4209 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4210 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4211 if (Context.typesAreCompatible(OldParm->getType(),
4212 NewProto->getParamType(Idx))) {
4213 ArgTypes.push_back(NewParm->getType());
4214 } else if (Context.typesAreCompatible(OldParm->getType(),
4215 NewParm->getType(),
4216 /*CompareUnqualified=*/true)) {
4217 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4218 NewProto->getParamType(Idx) };
4219 Warnings.push_back(Warn);
4220 ArgTypes.push_back(NewParm->getType());
4221 } else
4222 LooseCompatible = false;
4223 }
4224
4225 if (LooseCompatible) {
4226 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4227 Diag(Warnings[Warn].NewParm->getLocation(),
4228 diag::ext_param_promoted_not_compatible_with_prototype)
4229 << Warnings[Warn].PromotedType
4230 << Warnings[Warn].OldParm->getType();
4231 if (Warnings[Warn].OldParm->getLocation().isValid())
4232 Diag(Warnings[Warn].OldParm->getLocation(),
4233 diag::note_previous_declaration);
4234 }
4235
4236 if (MergeTypeWithOld)
4237 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4238 OldProto->getExtProtoInfo()));
4239 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4240 }
4241
4242 // Fall through to diagnose conflicting types.
4243 }
4244
4245 // A function that has already been declared has been redeclared or
4246 // defined with a different type; show an appropriate diagnostic.
4247
4248 // If the previous declaration was an implicitly-generated builtin
4249 // declaration, then at the very least we should use a specialized note.
4250 unsigned BuiltinID;
4251 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4252 // If it's actually a library-defined builtin function like 'malloc'
4253 // or 'printf', just warn about the incompatible redeclaration.
4255 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4256 Diag(OldLocation, diag::note_previous_builtin_declaration)
4257 << Old << Old->getType();
4258 return false;
4259 }
4260
4261 PrevDiag = diag::note_previous_builtin_declaration;
4262 }
4263
4264 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4265 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4266 return true;
4267}
4268
4270 Scope *S, bool MergeTypeWithOld) {
4271 // Merge the attributes
4272 mergeDeclAttributes(New, Old);
4273
4274 // Merge "pure" flag.
4275 if (Old->isPureVirtual())
4276 New->setIsPureVirtual();
4277
4278 // Merge "used" flag.
4279 if (Old->getMostRecentDecl()->isUsed(false))
4280 New->setIsUsed();
4281
4282 // Merge attributes from the parameters. These can mismatch with K&R
4283 // declarations.
4284 if (New->getNumParams() == Old->getNumParams())
4285 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4286 ParmVarDecl *NewParam = New->getParamDecl(i);
4287 ParmVarDecl *OldParam = Old->getParamDecl(i);
4288 mergeParamDeclAttributes(NewParam, OldParam, *this);
4289 mergeParamDeclTypes(NewParam, OldParam, *this);
4290 }
4291
4292 if (getLangOpts().CPlusPlus)
4293 return MergeCXXFunctionDecl(New, Old, S);
4294
4295 // Merge the function types so the we get the composite types for the return
4296 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4297 // was visible.
4298 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4299 if (!Merged.isNull() && MergeTypeWithOld)
4300 New->setType(Merged);
4301
4302 return false;
4303}
4304
4306 ObjCMethodDecl *oldMethod) {
4307 // Merge the attributes, including deprecated/unavailable
4308 AvailabilityMergeKind MergeKind =
4309 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4312 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4313 : AMK_Override;
4314
4315 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4316
4317 // Merge attributes from the parameters.
4319 oe = oldMethod->param_end();
4321 ni = newMethod->param_begin(), ne = newMethod->param_end();
4322 ni != ne && oi != oe; ++ni, ++oi)
4323 mergeParamDeclAttributes(*ni, *oi, *this);
4324
4325 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4326}
4327
4329 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4330
4332 ? diag::err_redefinition_different_type
4333 : diag::err_redeclaration_different_type)
4334 << New->getDeclName() << New->getType() << Old->getType();
4335
4336 diag::kind PrevDiag;
4337 SourceLocation OldLocation;
4338 std::tie(PrevDiag, OldLocation)
4340 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4341 New->setInvalidDecl();
4342}
4343
4345 bool MergeTypeWithOld) {
4346 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4347 return;
4348
4349 QualType MergedT;
4350 if (getLangOpts().CPlusPlus) {
4351 if (New->getType()->isUndeducedType()) {
4352 // We don't know what the new type is until the initializer is attached.
4353 return;
4354 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4355 // These could still be something that needs exception specs checked.
4356 return MergeVarDeclExceptionSpecs(New, Old);
4357 }
4358 // C++ [basic.link]p10:
4359 // [...] the types specified by all declarations referring to a given
4360 // object or function shall be identical, except that declarations for an
4361 // array object can specify array types that differ by the presence or
4362 // absence of a major array bound (8.3.4).
4363 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4364 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4365 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4366
4367 // We are merging a variable declaration New into Old. If it has an array
4368 // bound, and that bound differs from Old's bound, we should diagnose the
4369 // mismatch.
4370 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4371 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4372 PrevVD = PrevVD->getPreviousDecl()) {
4373 QualType PrevVDTy = PrevVD->getType();
4374 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4375 continue;
4376
4377 if (!Context.hasSameType(New->getType(), PrevVDTy))
4378 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4379 }
4380 }
4381
4382 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4383 if (Context.hasSameType(OldArray->getElementType(),
4384 NewArray->getElementType()))
4385 MergedT = New->getType();
4386 }
4387 // FIXME: Check visibility. New is hidden but has a complete type. If New
4388 // has no array bound, it should not inherit one from Old, if Old is not
4389 // visible.
4390 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4391 if (Context.hasSameType(OldArray->getElementType(),
4392 NewArray->getElementType()))
4393 MergedT = Old->getType();
4394 }
4395 }
4396 else if (New->getType()->isObjCObjectPointerType() &&
4397 Old->getType()->isObjCObjectPointerType()) {
4398 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4399 Old->getType());
4400 }
4401 } else {
4402 // C 6.2.7p2:
4403 // All declarations that refer to the same object or function shall have
4404 // compatible type.
4405 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4406 }
4407 if (MergedT.isNull()) {
4408 // It's OK if we couldn't merge types if either type is dependent, for a
4409 // block-scope variable. In other cases (static data members of class
4410 // templates, variable templates, ...), we require the types to be
4411 // equivalent.
4412 // FIXME: The C++ standard doesn't say anything about this.
4413 if ((New->getType()->isDependentType() ||
4414 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4415 // If the old type was dependent, we can't merge with it, so the new type
4416 // becomes dependent for now. We'll reproduce the original type when we
4417 // instantiate the TypeSourceInfo for the variable.
4418 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4420 return;
4421 }
4422 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4423 }
4424
4425 // Don't actually update the type on the new declaration if the old
4426 // declaration was an extern declaration in a different scope.
4427 if (MergeTypeWithOld)
4428 New->setType(MergedT);
4429}
4430
4431static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4433 // C11 6.2.7p4:
4434 // For an identifier with internal or external linkage declared
4435 // in a scope in which a prior declaration of that identifier is
4436 // visible, if the prior declaration specifies internal or
4437 // external linkage, the type of the identifier at the later
4438 // declaration becomes the composite type.
4439 //
4440 // If the variable isn't visible, we do not merge with its type.
4441 if (Previous.isShadowed())
4442 return false;
4443
4444 if (S.getLangOpts().CPlusPlus) {
4445 // C++11 [dcl.array]p3:
4446 // If there is a preceding declaration of the entity in the same
4447 // scope in which the bound was specified, an omitted array bound
4448 // is taken to be the same as in that earlier declaration.
4449 return NewVD->isPreviousDeclInSameBlockScope() ||
4452 } else {
4453 // If the old declaration was function-local, don't merge with its
4454 // type unless we're in the same function.
4455 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4456 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4457 }
4458}
4459
4461 // If the new decl is already invalid, don't do any other checking.
4462 if (New->isInvalidDecl())
4463 return;
4464
4465 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4466 return;
4467
4468 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4469
4470 // Verify the old decl was also a variable or variable template.
4471 VarDecl *Old = nullptr;
4472 VarTemplateDecl *OldTemplate = nullptr;
4473 if (Previous.isSingleResult()) {
4474 if (NewTemplate) {
4475 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4476 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4477
4478 if (auto *Shadow =
4479 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4480 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4481 return New->setInvalidDecl();
4482 } else {
4483 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4484
4485 if (auto *Shadow =
4486 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4487 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4488 return New->setInvalidDecl();
4489 }
4490 }
4491 if (!Old) {
4492 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4493 << New->getDeclName();
4494 notePreviousDefinition(Previous.getRepresentativeDecl(),
4495 New->getLocation());
4496 return New->setInvalidDecl();
4497 }
4498
4499 // If the old declaration was found in an inline namespace and the new
4500 // declaration was qualified, update the DeclContext to match.
4502
4503 // Ensure the template parameters are compatible.
4504 if (NewTemplate &&
4506 OldTemplate->getTemplateParameters(),
4507 /*Complain=*/true, TPL_TemplateMatch))
4508 return New->setInvalidDecl();
4509
4510 // C++ [class.mem]p1:
4511 // A member shall not be declared twice in the member-specification [...]
4512 //
4513 // Here, we need only consider static data members.
4514 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4515 Diag(New->getLocation(), diag::err_duplicate_member)
4516 << New->getIdentifier();
4517 Diag(Old->getLocation(), diag::note_previous_declaration);
4518 New->setInvalidDecl();
4519 }
4520
4521 mergeDeclAttributes(New, Old);
4522 // Warn if an already-defined variable is made a weak_import in a subsequent
4523 // declaration
4524 if (New->hasAttr<WeakImportAttr>())
4525 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4526 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4527 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4528 Diag(D->getLocation(), diag::note_previous_definition);
4529 // Remove weak_import attribute on new declaration.
4530 New->dropAttr<WeakImportAttr>();
4531 break;
4532 }
4533 }
4534
4535 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4536 if (!Old->hasAttr<InternalLinkageAttr>()) {
4537 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4538 << ILA;
4539 Diag(Old->getLocation(), diag::note_previous_declaration);
4540 New->dropAttr<InternalLinkageAttr>();
4541 }
4542
4543 // Merge the types.
4544 VarDecl *MostRecent = Old->getMostRecentDecl();
4545 if (MostRecent != Old) {
4546 MergeVarDeclTypes(New, MostRecent,
4547 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4548 if (New->isInvalidDecl())
4549 return;
4550 }
4551
4552 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4553 if (New->isInvalidDecl())
4554 return;
4555
4556 diag::kind PrevDiag;
4557 SourceLocation OldLocation;
4558 std::tie(PrevDiag, OldLocation) =
4560
4561 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4562 if (New->getStorageClass() == SC_Static &&
4563 !New->isStaticDataMember() &&
4564 Old->hasExternalFormalLinkage()) {
4565 if (getLangOpts().MicrosoftExt) {
4566 Diag(New->getLocation(), diag::ext_static_non_static)
4567 << New->getDeclName();
4568 Diag(OldLocation, PrevDiag);
4569 } else {
4570 Diag(New->getLocation(), diag::err_static_non_static)
4571 << New->getDeclName();
4572 Diag(OldLocation, PrevDiag);
4573 return New->setInvalidDecl();
4574 }
4575 }
4576 // C99 6.2.2p4:
4577 // For an identifier declared with the storage-class specifier
4578 // extern in a scope in which a prior declaration of that
4579 // identifier is visible,23) if the prior declaration specifies
4580 // internal or external linkage, the linkage of the identifier at
4581 // the later declaration is the same as the linkage specified at
4582 // the prior declaration. If no prior declaration is visible, or
4583 // if the prior declaration specifies no linkage, then the
4584 // identifier has external linkage.
4585 if (New->hasExternalStorage() && Old->hasLinkage())
4586 /* Okay */;
4587 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4588 !New->isStaticDataMember() &&
4590 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4591 Diag(OldLocation, PrevDiag);
4592 return New->setInvalidDecl();
4593 }
4594
4595 // Check if extern is followed by non-extern and vice-versa.
4596 if (New->hasExternalStorage() &&
4597 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4598 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4599 Diag(OldLocation, PrevDiag);
4600 return New->setInvalidDecl();
4601 }
4602 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4603 !New->hasExternalStorage()) {
4604 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4605 Diag(OldLocation, PrevDiag);
4606 return New->setInvalidDecl();
4607 }
4608
4609 if (CheckRedeclarationInModule(New, Old))
4610 return;
4611
4612 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4613
4614 // FIXME: The test for external storage here seems wrong? We still
4615 // need to check for mismatches.
4616 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4617 // Don't complain about out-of-line definitions of static members.
4618 !(Old->getLexicalDeclContext()->isRecord() &&
4619 !New->getLexicalDeclContext()->isRecord())) {
4620 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4621 Diag(OldLocation, PrevDiag);
4622 return New->setInvalidDecl();
4623 }
4624
4625 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4626 if (VarDecl *Def = Old->getDefinition()) {
4627 // C++1z [dcl.fcn.spec]p4:
4628 // If the definition of a variable appears in a translation unit before
4629 // its first declaration as inline, the program is ill-formed.
4630 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4631 Diag(Def->getLocation(), diag::note_previous_definition);
4632 }
4633 }
4634
4635 // If this redeclaration makes the variable inline, we may need to add it to
4636 // UndefinedButUsed.
4637 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4639 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4640 SourceLocation()));
4641
4642 if (New->getTLSKind() != Old->getTLSKind()) {
4643 if (!Old->getTLSKind()) {
4644 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4645 Diag(OldLocation, PrevDiag);
4646 } else if (!New->getTLSKind()) {
4647 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4648 Diag(OldLocation, PrevDiag);
4649 } else {
4650 // Do not allow redeclaration to change the variable between requiring
4651 // static and dynamic initialization.
4652 // FIXME: GCC allows this, but uses the TLS keyword on the first
4653 // declaration to determine the kind. Do we need to be compatible here?
4654 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4655 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4656 Diag(OldLocation, PrevDiag);
4657 }
4658 }
4659
4660 // C++ doesn't have tentative definitions, so go right ahead and check here.
4661 if (getLangOpts().CPlusPlus) {
4662 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4663 Old->getCanonicalDecl()->isConstexpr()) {
4664 // This definition won't be a definition any more once it's been merged.
4665 Diag(New->getLocation(),
4666 diag::warn_deprecated_redundant_constexpr_static_def);
4668 VarDecl *Def = Old->getDefinition();
4669 if (Def && checkVarDeclRedefinition(Def, New))
4670 return;
4671 }
4672 }
4673
4674 if (haveIncompatibleLanguageLinkages(Old, New)) {
4675 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4676 Diag(OldLocation, PrevDiag);
4677 New->setInvalidDecl();
4678 return;
4679 }
4680
4681 // Merge "used" flag.
4682 if (Old->getMostRecentDecl()->isUsed(false))
4683 New->setIsUsed();
4684
4685 // Keep a chain of previous declarations.
4686 New->setPreviousDecl(Old);
4687 if (NewTemplate)
4688 NewTemplate->setPreviousDecl(OldTemplate);
4689
4690 // Inherit access appropriately.
4691 New->setAccess(Old->getAccess());
4692 if (NewTemplate)
4693 NewTemplate->setAccess(New->getAccess());
4694
4695 if (Old->isInline())
4696 New->setImplicitlyInline();
4697}
4698
4700 SourceManager &SrcMgr = getSourceManager();
4701 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4702 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4703 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4704 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4705 auto &HSI = PP.getHeaderSearchInfo();
4706 StringRef HdrFilename =
4707 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4708
4709 auto noteFromModuleOrInclude = [&](Module *Mod,
4710 SourceLocation IncLoc) -> bool {
4711 // Redefinition errors with modules are common with non modular mapped
4712 // headers, example: a non-modular header H in module A that also gets
4713 // included directly in a TU. Pointing twice to the same header/definition
4714 // is confusing, try to get better diagnostics when modules is on.
4715 if (IncLoc.isValid()) {
4716 if (Mod) {
4717 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4718 << HdrFilename.str() << Mod->getFullModuleName();
4719 if (!Mod->DefinitionLoc.isInvalid())
4720 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4721 << Mod->getFullModuleName();
4722 } else {
4723 Diag(IncLoc, diag::note_redefinition_include_same_file)
4724 << HdrFilename.str();
4725 }
4726 return true;
4727 }
4728
4729 return false;
4730 };
4731
4732 // Is it the same file and same offset? Provide more information on why
4733 // this leads to a redefinition error.
4734 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4735 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4736 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4737 bool EmittedDiag =
4738 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4739 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4740
4741 // If the header has no guards, emit a note suggesting one.
4742 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4743 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4744
4745 if (EmittedDiag)
4746 return;
4747 }
4748
4749 // Redefinition coming from different files or couldn't do better above.
4750 if (Old->getLocation().isValid())
4751 Diag(Old->getLocation(), diag::note_previous_definition);
4752}
4753
4755 if (!hasVisibleDefinition(Old) &&
4756 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4757 isa<VarTemplateSpecializationDecl>(New) ||
4760 // The previous definition is hidden, and multiple definitions are
4761 // permitted (in separate TUs). Demote this to a declaration.
4763
4764 // Make the canonical definition visible.
4765 if (auto *OldTD = Old->getDescribedVarTemplate())
4768 return false;
4769 } else {
4770 Diag(New->getLocation(), diag::err_redefinition) << New;
4772 New->setInvalidDecl();
4773 return true;
4774 }
4775}
4776
4778 DeclSpec &DS,
4779 const ParsedAttributesView &DeclAttrs,
4780 RecordDecl *&AnonRecord) {
4782 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4783}
4784
4785// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4786// disambiguate entities defined in different scopes.
4787// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4788// compatibility.
4789// We will pick our mangling number depending on which version of MSVC is being
4790// targeted.
4791static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4793 ? S->getMSCurManglingNumber()
4794 : S->getMSLastManglingNumber();
4795}
4796
4797void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4798 if (!Context.getLangOpts().CPlusPlus)
4799 return;
4800
4801 if (isa<CXXRecordDecl>(Tag->getParent())) {
4802 // If this tag is the direct child of a class, number it if
4803 // it is anonymous.
4804 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4805 return;
4807 Context.getManglingNumberContext(Tag->getParent());
4809 Tag, MCtx.getManglingNumber(
4810 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4811 return;
4812 }
4813
4814 // If this tag isn't a direct child of a class, number it if it is local.
4816 Decl *ManglingContextDecl;
4817 std::tie(MCtx, ManglingContextDecl) =
4818 getCurrentMangleNumberContext(Tag->getDeclContext());
4819 if (MCtx) {
4821 Tag, MCtx->getManglingNumber(
4822 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4823 }
4824}
4825
4826namespace {
4827struct NonCLikeKind {
4828 enum {
4829 None,
4830 BaseClass,
4831 DefaultMemberInit,
4832 Lambda,
4833 Friend,
4834 OtherMember,
4835 Invalid,
4836 } Kind = None;
4838
4839 explicit operator bool() { return Kind != None; }
4840};
4841}
4842
4843/// Determine whether a class is C-like, according to the rules of C++
4844/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4845static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4846 if (RD->isInvalidDecl())
4847 return {NonCLikeKind::Invalid, {}};
4848
4849 // C++ [dcl.typedef]p9: [P1766R1]
4850 // An unnamed class with a typedef name for linkage purposes shall not
4851 //
4852 // -- have any base classes
4853 if (RD->getNumBases())
4854 return {NonCLikeKind::BaseClass,
4856 RD->bases_end()[-1].getEndLoc())};
4857 bool Invalid = false;
4858 for (Decl *D : RD->decls()) {
4859 // Don't complain about things we already diagnosed.
4860 if (D->isInvalidDecl()) {
4861 Invalid = true;
4862 continue;
4863 }
4864
4865 // -- have any [...] default member initializers
4866 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4867 if (FD->hasInClassInitializer()) {
4868 auto *Init = FD->getInClassInitializer();
4869 return {NonCLikeKind::DefaultMemberInit,
4870 Init ? Init->getSourceRange() : D->getSourceRange()};
4871 }
4872 continue;
4873 }
4874
4875 // FIXME: We don't allow friend declarations. This violates the wording of
4876 // P1766, but not the intent.
4877 if (isa<FriendDecl>(D))
4878 return {NonCLikeKind::Friend, D->getSourceRange()};
4879
4880 // -- declare any members other than non-static data members, member
4881 // enumerations, or member classes,
4882 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4883 isa<EnumDecl>(D))
4884 continue;
4885 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4886 if (!MemberRD) {
4887 if (D->isImplicit())
4888 continue;
4889 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4890 }
4891
4892 // -- contain a lambda-expression,
4893 if (MemberRD->isLambda())
4894 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4895
4896 // and all member classes shall also satisfy these requirements
4897 // (recursively).
4898 if (MemberRD->isThisDeclarationADefinition()) {
4899 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4900 return Kind;
4901 }
4902 }
4903
4904 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4905}
4906
4908 TypedefNameDecl *NewTD) {
4909 if (TagFromDeclSpec->isInvalidDecl())
4910 return;
4911
4912 // Do nothing if the tag already has a name for linkage purposes.
4913 if (TagFromDeclSpec->hasNameForLinkage())
4914 return;
4915
4916 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4917 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4918
4919 // The type must match the tag exactly; no qualifiers allowed.
4921 Context.getTagDeclType(TagFromDeclSpec))) {
4922 if (getLangOpts().CPlusPlus)
4923 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4924 return;
4925 }
4926
4927 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4928 // An unnamed class with a typedef name for linkage purposes shall [be
4929 // C-like].
4930 //
4931 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4932 // shouldn't happen, but there are constructs that the language rule doesn't
4933 // disallow for which we can't reasonably avoid computing linkage early.
4934 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4935 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4936 : NonCLikeKind();
4937 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4938 if (NonCLike || ChangesLinkage) {
4939 if (NonCLike.Kind == NonCLikeKind::Invalid)
4940 return;
4941
4942 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4943 if (ChangesLinkage) {
4944 // If the linkage changes, we can't accept this as an extension.
4945 if (NonCLike.Kind == NonCLikeKind::None)
4946 DiagID = diag::err_typedef_changes_linkage;
4947 else
4948 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4949 }
4950
4951 SourceLocation FixitLoc =
4952 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4953 llvm::SmallString<40> TextToInsert;
4954 TextToInsert += ' ';
4955 TextToInsert += NewTD->getIdentifier()->getName();
4956
4957 Diag(FixitLoc, DiagID)
4958 << isa<TypeAliasDecl>(NewTD)
4959 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4960 if (NonCLike.Kind != NonCLikeKind::None) {
4961 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4962 << NonCLike.Kind - 1 << NonCLike.Range;
4963 }
4964 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4965 << NewTD << isa<TypeAliasDecl>(NewTD);
4966
4967 if (ChangesLinkage)
4968 return;
4969 }
4970
4971 // Otherwise, set this as the anon-decl typedef for the tag.
4972 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4973}
4974
4975static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
4977 switch (T) {
4979 return 0;
4981 return 1;
4983 return 2;
4985 return 3;
4986 case DeclSpec::TST_enum:
4987 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
4988 if (ED->isScopedUsingClassTag())
4989 return 5;
4990 if (ED->isScoped())
4991 return 6;
4992 }
4993 return 4;
4994 default:
4995 llvm_unreachable("unexpected type specifier");
4996 }
4997}
4998
5000 DeclSpec &DS,
5001 const ParsedAttributesView &DeclAttrs,
5002 MultiTemplateParamsArg TemplateParams,
5003 bool IsExplicitInstantiation,
5004 RecordDecl *&AnonRecord,
5005 SourceLocation EllipsisLoc) {
5006 Decl *TagD = nullptr;
5007 TagDecl *Tag = nullptr;
5013 TagD = DS.getRepAsDecl();
5014
5015 if (!TagD) // We probably had an error
5016 return nullptr;
5017
5018 // Note that the above type specs guarantee that the
5019 // type rep is a Decl, whereas in many of the others
5020 // it's a Type.
5021 if (isa<TagDecl>(TagD))
5022 Tag = cast<TagDecl>(TagD);
5023 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5024 Tag = CTD->getTemplatedDecl();
5025 }
5026
5027 if (Tag) {
5028 handleTagNumbering(Tag, S);
5029 Tag->setFreeStanding();
5030 if (Tag->isInvalidDecl())
5031 return Tag;
5032 }
5033
5034 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5035 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5036 // or incomplete types shall not be restrict-qualified."
5037 if (TypeQuals & DeclSpec::TQ_restrict)
5039 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5040 << DS.getSourceRange();
5041 }
5042
5043 if (DS.isInlineSpecified())
5044 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5045 << getLangOpts().CPlusPlus17;
5046
5047 if (DS.hasConstexprSpecifier()) {
5048 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5049 // and definitions of functions and variables.
5050 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5051 // the declaration of a function or function template
5052 if (Tag)
5053 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5055 << static_cast<int>(DS.getConstexprSpecifier());
5056 else if (getLangOpts().C23)
5057 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5058 else
5059 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5060 << static_cast<int>(DS.getConstexprSpecifier());
5061 // Don't emit warnings after this error.
5062 return TagD;
5063 }
5064
5066
5067 if (DS.isFriendSpecified()) {
5068 // If we're dealing with a decl but not a TagDecl, assume that
5069 // whatever routines created it handled the friendship aspect.
5070 if (TagD && !Tag)
5071 return nullptr;
5072 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5073 }
5074
5075 assert(EllipsisLoc.isInvalid() &&
5076 "Friend ellipsis but not friend-specified?");
5077
5078 // Track whether this decl-specifier declares anything.
5079 bool DeclaresAnything = true;
5080
5081 // Handle anonymous struct definitions.
5082 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5083 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5085 if (getLangOpts().CPlusPlus ||
5086 Record->getDeclContext()->isRecord()) {
5087 // If CurContext is a DeclContext that can contain statements,
5088 // RecursiveASTVisitor won't visit the decls that
5089 // BuildAnonymousStructOrUnion() will put into CurContext.
5090 // Also store them here so that they can be part of the
5091 // DeclStmt that gets created in this case.
5092 // FIXME: Also return the IndirectFieldDecls created by
5093 // BuildAnonymousStructOr union, for the same reason?
5095 AnonRecord = Record;
5096 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5098 }
5099
5100 DeclaresAnything = false;
5101 }
5102 }
5103
5104 // C11 6.7.2.1p2:
5105 // A struct-declaration that does not declare an anonymous structure or
5106 // anonymous union shall contain a struct-declarator-list.
5107 //
5108 // This rule also existed in C89 and C99; the grammar for struct-declaration
5109 // did not permit a struct-declaration without a struct-declarator-list.
5112 // Check for Microsoft C extension: anonymous struct/union member.
5113 // Handle 2 kinds of anonymous struct/union:
5114 // struct STRUCT;
5115 // union UNION;
5116 // and
5117 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5118 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5119 if ((Tag && Tag->getDeclName()) ||
5121 RecordDecl *Record = nullptr;
5122 if (Tag)
5123 Record = dyn_cast<RecordDecl>(Tag);
5124 else if (const RecordType *RT =
5126 Record = RT->getDecl();
5127 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5128 Record = UT->getDecl();
5129
5130 if (Record && getLangOpts().MicrosoftExt) {
5131 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5132 << Record->isUnion() << DS.getSourceRange();
5134 }
5135
5136 DeclaresAnything = false;
5137 }
5138 }
5139
5140 // Skip all the checks below if we have a type error.
5142 (TagD && TagD->isInvalidDecl()))
5143 return TagD;
5144
5145 if (getLangOpts().CPlusPlus &&
5147 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5148 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5149 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5150 DeclaresAnything = false;
5151
5152 if (!DS.isMissingDeclaratorOk()) {
5153 // Customize diagnostic for a typedef missing a name.
5155 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5156 << DS.getSourceRange();
5157 else
5158 DeclaresAnything = false;
5159 }
5160
5161 if (DS.isModulePrivateSpecified() &&
5162 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5163 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5164 << llvm::to_underlying(Tag->getTagKind())
5166
5168
5169 // C 6.7/2:
5170 // A declaration [...] shall declare at least a declarator [...], a tag,
5171 // or the members of an enumeration.
5172 // C++ [dcl.dcl]p3:
5173 // [If there are no declarators], and except for the declaration of an
5174 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5175 // names into the program, or shall redeclare a name introduced by a
5176 // previous declaration.
5177 if (!DeclaresAnything) {
5178 // In C, we allow this as a (popular) extension / bug. Don't bother
5179 // producing further diagnostics for redundant qualifiers after this.
5180 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5181 ? diag::err_no_declarators
5182 : diag::ext_no_declarators)
5183 << DS.getSourceRange();
5184 return TagD;
5185 }
5186
5187 // C++ [dcl.stc]p1:
5188 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5189 // init-declarator-list of the declaration shall not be empty.
5190 // C++ [dcl.fct.spec]p1:
5191 // If a cv-qualifier appears in a decl-specifier-seq, the
5192 // init-declarator-list of the declaration shall not be empty.
5193 //
5194 // Spurious qualifiers here appear to be valid in C.
5195 unsigned DiagID = diag::warn_standalone_specifier;
5196 if (getLangOpts().CPlusPlus)
5197 DiagID = diag::ext_standalone_specifier;
5198
5199 // Note that a linkage-specification sets a storage class, but
5200 // 'extern "C" struct foo;' is actually valid and not theoretically
5201 // useless.
5202 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5203 if (SCS == DeclSpec::SCS_mutable)
5204 // Since mutable is not a viable storage class specifier in C, there is
5205 // no reason to treat it as an extension. Instead, diagnose as an error.
5206 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5207 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5208 Diag(DS.getStorageClassSpecLoc(), DiagID)
5210 }
5211
5215 if (DS.getTypeQualifiers()) {
5217 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5219 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5220 // Restrict is covered above.
5222 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5224 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5225 }
5226
5227 // Warn about ignored type attributes, for example:
5228 // __attribute__((aligned)) struct A;
5229 // Attributes should be placed after tag to apply to type declaration.
5230 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5231 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5232 if (TypeSpecType == DeclSpec::TST_class ||
5233 TypeSpecType == DeclSpec::TST_struct ||
5234 TypeSpecType == DeclSpec::TST_interface ||
5235 TypeSpecType == DeclSpec::TST_union ||
5236 TypeSpecType == DeclSpec::TST_enum) {
5237
5238 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5239 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5240 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5241 DiagnosticId = diag::warn_attribute_ignored;
5242 else if (AL.isRegularKeywordAttribute())
5243 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5244 else
5245 DiagnosticId = diag::warn_declspec_attribute_ignored;
5246 Diag(AL.getLoc(), DiagnosticId)
5247 << AL << GetDiagnosticTypeSpecifierID(DS);
5248 };
5249
5250 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5251 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5252 }
5253 }
5254
5255 return TagD;
5256}
5257
5258/// We are trying to inject an anonymous member into the given scope;
5259/// check if there's an existing declaration that can't be overloaded.
5260///
5261/// \return true if this is a forbidden redeclaration
5262static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5263 DeclContext *Owner,
5264 DeclarationName Name,
5265 SourceLocation NameLoc, bool IsUnion,
5266 StorageClass SC) {
5267 LookupResult R(SemaRef, Name, NameLoc,
5270 RedeclarationKind::ForVisibleRedeclaration);
5271 if (!SemaRef.LookupName(R, S)) return false;
5272
5273 // Pick a representative declaration.
5275 assert(PrevDecl && "Expected a non-null Decl");
5276
5277 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5278 return false;
5279
5280 if (SC == StorageClass::SC_None &&
5281 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5282 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5283 if (!Owner->isRecord())
5284 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5285 return false;
5286 }
5287
5288 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5289 << IsUnion << Name;
5290 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5291
5292 return true;
5293}
5294
5296 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5298}
5299
5301 if (!getLangOpts().CPlusPlus)
5302 return;
5303
5304 // This function can be parsed before we have validated the
5305 // structure as an anonymous struct
5306 if (Record->isAnonymousStructOrUnion())
5307 return;
5308
5309 const NamedDecl *First = 0;
5310 for (const Decl *D : Record->decls()) {
5311 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5312 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5313 continue;
5314 if (!First)
5315 First = ND;
5316 else
5318 }
5319}
5320
5321/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5322/// anonymous struct or union AnonRecord into the owning context Owner
5323/// and scope S. This routine will be invoked just after we realize
5324/// that an unnamed union or struct is actually an anonymous union or
5325/// struct, e.g.,
5326///
5327/// @code
5328/// union {
5329/// int i;
5330/// float f;
5331/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5332/// // f into the surrounding scope.x
5333/// @endcode
5334///
5335/// This routine is recursive, injecting the names of nested anonymous
5336/// structs/unions into the owning context and scope as well.
5337static bool
5339 RecordDecl *AnonRecord, AccessSpecifier AS,
5340 StorageClass SC,
5341 SmallVectorImpl<NamedDecl *> &Chaining) {
5342 bool Invalid = false;
5343
5344 // Look every FieldDecl and IndirectFieldDecl with a name.
5345 for (auto *D : AnonRecord->decls()) {
5346 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5347 cast<NamedDecl>(D)->getDeclName()) {
5348 ValueDecl *VD = cast<ValueDecl>(D);
5349 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5350 VD->getLocation(), AnonRecord->isUnion(),
5351 SC)) {
5352 // C++ [class.union]p2:
5353 // The names of the members of an anonymous union shall be
5354 // distinct from the names of any other entity in the
5355 // scope in which the anonymous union is declared.
5356 Invalid = true;
5357 } else {
5358 // C++ [class.union]p2:
5359 // For the purpose of name lookup, after the anonymous union
5360 // definition, the members of the anonymous union are
5361 // considered to have been defined in the scope in which the
5362 // anonymous union is declared.
5363 unsigned OldChainingSize = Chaining.size();
5364 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5365 Chaining.append(IF->chain_begin(), IF->chain_end());
5366 else
5367 Chaining.push_back(VD);
5368
5369 assert(Chaining.size() >= 2);
5370 NamedDecl **NamedChain =
5371 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5372 for (unsigned i = 0; i < Chaining.size(); i++)
5373 NamedChain[i] = Chaining[i];
5374
5376 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5377 VD->getType(), {NamedChain, Chaining.size()});
5378
5379 for (const auto *Attr : VD->attrs())
5380 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5381
5382 IndirectField->setAccess(AS);
5383 IndirectField->setImplicit();
5384 SemaRef.PushOnScopeChains(IndirectField, S);
5385
5386 // That includes picking up the appropriate access specifier.
5387 if (AS != AS_none) IndirectField->setAccess(AS);
5388
5389 Chaining.resize(OldChainingSize);
5390 }
5391 }
5392 }
5393
5394 return Invalid;
5395}
5396
5397/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5398/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5399/// illegal input values are mapped to SC_None.
5400static StorageClass
5402 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5403 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5404 "Parser allowed 'typedef' as storage class VarDecl.");
5405 switch (StorageClassSpec) {
5408 if (DS.isExternInLinkageSpec())
5409 return SC_None;
5410 return SC_Extern;
5411 case DeclSpec::SCS_static: return SC_Static;
5412 case DeclSpec::SCS_auto: return SC_Auto;
5415 // Illegal SCSs map to None: error reporting is up to the caller.
5416 case DeclSpec::SCS_mutable: // Fall through.
5417 case DeclSpec::SCS_typedef: return SC_None;
5418 }
5419 llvm_unreachable("unknown storage class specifier");
5420}
5421
5423 assert(Record->hasInClassInitializer());
5424
5425 for (const auto *I : Record->decls()) {
5426 const auto *FD = dyn_cast<FieldDecl>(I);
5427 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5428 FD = IFD->getAnonField();
5429 if (FD && FD->hasInClassInitializer())
5430 return FD->getLocation();
5431 }
5432
5433 llvm_unreachable("couldn't find in-class initializer");
5434}
5435
5437 SourceLocation DefaultInitLoc) {
5438 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5439 return;
5440
5441 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5442 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5443}
5444
5446 CXXRecordDecl *AnonUnion) {
5447 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5448 return;
5449
5451}
5452
5454 AccessSpecifier AS,
5456 const PrintingPolicy &Policy) {
5457 DeclContext *Owner = Record->getDeclContext();
5458
5459 // Diagnose whether this anonymous struct/union is an extension.
5460 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5461 Diag(Record->getLocation(), diag::ext_anonymous_union);
5462 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5463 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5464 else if (!Record->isUnion() && !getLangOpts().C11)
5465 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5466
5467 // C and C++ require different kinds of checks for anonymous
5468 // structs/unions.
5469 bool Invalid = false;
5470 if (getLangOpts().CPlusPlus) {
5471 const char *PrevSpec = nullptr;
5472 if (Record->isUnion()) {
5473 // C++ [class.union]p6:
5474 // C++17 [class.union.anon]p2:
5475 // Anonymous unions declared in a named namespace or in the
5476 // global namespace shall be declared static.
5477 unsigned DiagID;
5478 DeclContext *OwnerScope = Owner->getRedeclContext();
5480 (OwnerScope->isTranslationUnit() ||
5481 (OwnerScope->isNamespace() &&
5482 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5483 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5484 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5485
5486 // Recover by adding 'static'.
5488 PrevSpec, DiagID, Policy);
5489 }
5490 // C++ [class.union]p6:
5491 // A storage class is not allowed in a declaration of an
5492 // anonymous union in a class scope.
5494 isa<RecordDecl>(Owner)) {
5496 diag::err_anonymous_union_with_storage_spec)
5498
5499 // Recover by removing the storage specifier.
5502 PrevSpec, DiagID, Context.getPrintingPolicy());
5503 }
5504 }
5505
5506 // Ignore const/volatile/restrict qualifiers.
5507 if (DS.getTypeQualifiers()) {
5509 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5510 << Record->isUnion() << "const"
5514 diag::ext_anonymous_struct_union_qualified)
5515 << Record->isUnion() << "volatile"
5519 diag::ext_anonymous_struct_union_qualified)
5520 << Record->isUnion() << "restrict"
5524 diag::ext_anonymous_struct_union_qualified)
5525 << Record->isUnion() << "_Atomic"
5529 diag::ext_anonymous_struct_union_qualified)
5530 << Record->isUnion() << "__unaligned"
5532
5534 }
5535
5536 // C++ [class.union]p2:
5537 // The member-specification of an anonymous union shall only
5538 // define non-static data members. [Note: nested types and
5539 // functions cannot be declared within an anonymous union. ]
5540 for (auto *Mem : Record->decls()) {
5541 // Ignore invalid declarations; we already diagnosed them.
5542 if (Mem->isInvalidDecl())
5543 continue;
5544
5545 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5546 // C++ [class.union]p3:
5547 // An anonymous union shall not have private or protected
5548 // members (clause 11).
5549 assert(FD->getAccess() != AS_none);
5550 if (FD->getAccess() != AS_public) {
5551 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5552 << Record->isUnion() << (FD->getAccess() == AS_protected);
5553 Invalid = true;
5554 }
5555
5556 // C++ [class.union]p1
5557 // An object of a class with a non-trivial constructor, a non-trivial
5558 // copy constructor, a non-trivial destructor, or a non-trivial copy
5559 // assignment operator cannot be a member of a union, nor can an
5560 // array of such objects.
5561 if (CheckNontrivialField(FD))
5562 Invalid = true;
5563 } else if (Mem->isImplicit()) {
5564 // Any implicit members are fine.
5565 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5566 // This is a type that showed up in an
5567 // elaborated-type-specifier inside the anonymous struct or
5568 // union, but which actually declares a type outside of the
5569 // anonymous struct or union. It's okay.
5570 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5571 if (!MemRecord->isAnonymousStructOrUnion() &&
5572 MemRecord->getDeclName()) {
5573 // Visual C++ allows type definition in anonymous struct or union.
5574 if (getLangOpts().MicrosoftExt)
5575 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5576 << Record->isUnion();
5577 else {
5578 // This is a nested type declaration.
5579 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5580 << Record->isUnion();
5581 Invalid = true;
5582 }
5583 } else {
5584 // This is an anonymous type definition within another anonymous type.
5585 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5586 // not part of standard C++.
5587 Diag(MemRecord->getLocation(),
5588 diag::ext_anonymous_record_with_anonymous_type)
5589 << Record->isUnion();
5590 }
5591 } else if (isa<AccessSpecDecl>(Mem)) {
5592 // Any access specifier is fine.
5593 } else if (isa<StaticAssertDecl>(Mem)) {
5594 // In C++1z, static_assert declarations are also fine.
5595 } else {
5596 // We have something that isn't a non-static data
5597 // member. Complain about it.
5598 unsigned DK = diag::err_anonymous_record_bad_member;
5599 if (isa<TypeDecl>(Mem))
5600 DK = diag::err_anonymous_record_with_type;
5601 else if (isa<FunctionDecl>(Mem))
5602 DK = diag::err_anonymous_record_with_function;
5603 else if (isa<VarDecl>(Mem))
5604 DK = diag::err_anonymous_record_with_static;
5605
5606 // Visual C++ allows type definition in anonymous struct or union.
5607 if (getLangOpts().MicrosoftExt &&
5608 DK == diag::err_anonymous_record_with_type)
5609 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5610 << Record->isUnion();
5611 else {
5612 Diag(Mem->getLocation(), DK) << Record->isUnion();
5613 Invalid = true;
5614 }
5615 }
5616 }
5617
5618 // C++11 [class.union]p8 (DR1460):
5619 // At most one variant member of a union may have a
5620 // brace-or-equal-initializer.
5621 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5622 Owner->isRecord())
5623 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5624 cast<CXXRecordDecl>(Record));
5625 }
5626
5627 if (!Record->isUnion() && !Owner->isRecord()) {
5628 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5629 << getLangOpts().CPlusPlus;
5630 Invalid = true;
5631 }
5632
5633 // C++ [dcl.dcl]p3:
5634 // [If there are no declarators], and except for the declaration of an
5635 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5636 // names into the program
5637 // C++ [class.mem]p2:
5638 // each such member-declaration shall either declare at least one member
5639 // name of the class or declare at least one unnamed bit-field
5640 //
5641 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5642 if (getLangOpts().CPlusPlus && Record->field_empty())
5643 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5644
5645 // Mock up a declarator.
5649 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5650
5651 // Create a declaration for this anonymous struct/union.
5652 NamedDecl *Anon = nullptr;
5653 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5654 Anon = FieldDecl::Create(
5655 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5656 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5657 /*BitWidth=*/nullptr, /*Mutable=*/false,
5658 /*InitStyle=*/ICIS_NoInit);
5659 Anon->setAccess(AS);
5660 ProcessDeclAttributes(S, Anon, Dc);
5661
5662 if (getLangOpts().CPlusPlus)
5663 FieldCollector->Add(cast<FieldDecl>(Anon));
5664 } else {
5665 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5666 if (SCSpec == DeclSpec::SCS_mutable) {
5667 // mutable can only appear on non-static class members, so it's always
5668 // an error here
5669 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5670 Invalid = true;
5671 SC = SC_None;
5672 }
5673
5674 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5675 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5676 Context.getTypeDeclType(Record), TInfo, SC);
5677 if (Invalid)
5678 Anon->setInvalidDecl();
5679
5680 ProcessDeclAttributes(S, Anon, Dc);
5681
5682 // Default-initialize the implicit variable. This initialization will be
5683 // trivial in almost all cases, except if a union member has an in-class
5684 // initializer:
5685 // union { int n = 0; };
5687 }
5688 Anon->setImplicit();
5689
5690 // Mark this as an anonymous struct/union type.
5691 Record->setAnonymousStructOrUnion(true);
5692
5693 // Add the anonymous struct/union object to the current
5694 // context. We'll be referencing this object when we refer to one of
5695 // its members.
5696 Owner->addDecl(Anon);
5697
5698 // Inject the members of the anonymous struct/union into the owning
5699 // context and into the identifier resolver chain for name lookup
5700 // purposes.
5702 Chain.push_back(Anon);
5703
5704 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5705 Chain))
5706 Invalid = true;
5707
5708 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5709 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5711 Decl *ManglingContextDecl;
5712 std::tie(MCtx, ManglingContextDecl) =
5713 getCurrentMangleNumberContext(NewVD->getDeclContext());
5714 if (MCtx) {
5716 NewVD, MCtx->getManglingNumber(
5717 NewVD, getMSManglingNumber(getLangOpts(), S)));
5719 }
5720 }
5721 }
5722
5723 if (Invalid)
5724 Anon->setInvalidDecl();
5725
5726 return Anon;
5727}
5728
5730 RecordDecl *Record) {
5731 assert(Record && "expected a record!");
5732
5733 // Mock up a declarator.
5736 assert(TInfo && "couldn't build declarator info for anonymous struct");
5737
5738 auto *ParentDecl = cast<RecordDecl>(CurContext);
5740
5741 // Create a declaration for this anonymous struct.
5742 NamedDecl *Anon =
5743 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5744 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5745 /*BitWidth=*/nullptr, /*Mutable=*/false,
5746 /*InitStyle=*/ICIS_NoInit);
5747 Anon->setImplicit();
5748
5749 // Add the anonymous struct object to the current context.
5750 CurContext->addDecl(Anon);
5751
5752 // Inject the members of the anonymous struct into the current
5753 // context and into the identifier resolver chain for name lookup
5754 // purposes.
5756 Chain.push_back(Anon);
5757
5758 RecordDecl *RecordDef = Record->getDefinition();
5759 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5760 diag::err_field_incomplete_or_sizeless) ||
5762 *this, S, CurContext, RecordDef, AS_none,
5764 Anon->setInvalidDecl();
5765 ParentDecl->setInvalidDecl();
5766 }
5767
5768 return Anon;
5769}
5770
5772 return GetNameFromUnqualifiedId(D.getName());
5773}
5774
5777 DeclarationNameInfo NameInfo;
5778 NameInfo.setLoc(Name.StartLocation);
5779
5780 switch (Name.getKind()) {
5781
5784 NameInfo.setName(Name.Identifier);
5785 return NameInfo;
5786
5788 // C++ [temp.deduct.guide]p3:
5789 // The simple-template-id shall name a class template specialization.
5790 // The template-name shall be the same identifier as the template-name
5791 // of the simple-template-id.
5792 // These together intend to imply that the template-name shall name a
5793 // class template.
5794 // FIXME: template<typename T> struct X {};
5795 // template<typename T> using Y = X<T>;
5796 // Y(int) -> Y<int>;
5797 // satisfies these rules but does not name a class template.
5798 TemplateName TN = Name.TemplateName.get().get();
5799 auto *Template = TN.getAsTemplateDecl();
5800 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5801 Diag(Name.StartLocation,
5802 diag::err_deduction_guide_name_not_class_template)
5804 if (Template)
5805 NoteTemplateLocation(*Template);
5806 return DeclarationNameInfo();
5807 }
5808
5809 NameInfo.setName(
5811 return NameInfo;
5812 }
5813
5816 Name.OperatorFunctionId.Operator));
5818 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5819 return NameInfo;
5820
5823 Name.Identifier));
5824 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5825 return NameInfo;
5826
5828 TypeSourceInfo *TInfo;
5829 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5830 if (Ty.isNull())
5831 return DeclarationNameInfo();
5834 NameInfo.setNamedTypeInfo(TInfo);
5835 return NameInfo;
5836 }
5837
5839 TypeSourceInfo *TInfo;
5840 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5841 if (Ty.isNull())
5842 return DeclarationNameInfo();
5845 NameInfo.setNamedTypeInfo(TInfo);
5846 return NameInfo;
5847 }
5848
5850 // In well-formed code, we can only have a constructor
5851 // template-id that refers to the current context, so go there
5852 // to find the actual type being constructed.
5853 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5854 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5855 return DeclarationNameInfo();
5856
5857 // Determine the type of the class being constructed.
5858 QualType CurClassType = Context.getTypeDeclType(CurClass);
5859
5860 // FIXME: Check two things: that the template-id names the same type as
5861 // CurClassType, and that the template-id does not occur when the name
5862 // was qualified.
5863
5865 Context.getCanonicalType(CurClassType)));
5866 // FIXME: should we retrieve TypeSourceInfo?
5867 NameInfo.setNamedTypeInfo(nullptr);
5868 return NameInfo;
5869 }
5870
5872 TypeSourceInfo *TInfo;
5873 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5874 if (Ty.isNull())
5875 return DeclarationNameInfo();
5878 NameInfo.setNamedTypeInfo(TInfo);
5879 return NameInfo;
5880 }
5881
5883 TemplateName TName = Name.TemplateId->Template.get();
5884 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5885 return Context.getNameForTemplate(TName, TNameLoc);
5886 }
5887
5888 } // switch (Name.getKind())
5889
5890 llvm_unreachable("Unknown name kind");
5891}
5892
5894 do {
5895 if (Ty->isPointerOrReferenceType())
5896 Ty = Ty->getPointeeType();
5897 else if (Ty->isArrayType())
5899 else
5900 return Ty.withoutLocalFastQualifiers();
5901 } while (true);
5902}
5903
5904/// hasSimilarParameters - Determine whether the C++ functions Declaration
5905/// and Definition have "nearly" matching parameters. This heuristic is
5906/// used to improve diagnostics in the case where an out-of-line function
5907/// definition doesn't match any declaration within the class or namespace.
5908/// Also sets Params to the list of indices to the parameters that differ
5909/// between the declaration and the definition. If hasSimilarParameters
5910/// returns true and Params is empty, then all of the parameters match.
5914 SmallVectorImpl<unsigned> &Params) {
5915 Params.clear();
5916 if (Declaration->param_size() != Definition->param_size())
5917 return false;
5918 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5919 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5920 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5921
5922 // The parameter types are identical
5923 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5924 continue;
5925
5926 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5927 QualType DefParamBaseTy = getCoreType(DefParamTy);
5928 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5929 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5930
5931 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5932 (DeclTyName && DeclTyName == DefTyName))
5933 Params.push_back(Idx);
5934 else // The two parameters aren't even close
5935 return false;
5936 }
5937
5938 return true;
5939}
5940
5941/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5942/// declarator needs to be rebuilt in the current instantiation.
5943/// Any bits of declarator which appear before the name are valid for
5944/// consideration here. That's specifically the type in the decl spec
5945/// and the base type in any member-pointer chunks.
5947 DeclarationName Name) {
5948 // The types we specifically need to rebuild are:
5949 // - typenames, typeofs, and decltypes
5950 // - types which will become injected class names
5951 // Of course, we also need to rebuild any type referencing such a
5952 // type. It's safest to just say "dependent", but we call out a
5953 // few cases here.
5954
5955 DeclSpec &DS = D.getMutableDeclSpec();
5956 switch (DS.getTypeSpecType()) {
5960#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5961#include "clang/Basic/TransformTypeTraits.def"
5962 case DeclSpec::TST_atomic: {
5963 // Grab the type from the parser.
5964 TypeSourceInfo *TSI = nullptr;
5965 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5966 if (T.isNull() || !T->isInstantiationDependentType()) break;
5967
5968 // Make sure there's a type source info. This isn't really much
5969 // of a waste; most dependent types should have type source info
5970 // attached already.
5971 if (!TSI)
5973
5974 // Rebuild the type in the current instantiation.
5975 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5976 if (!TSI) return true;
5977
5978 // Store the new type back in the decl spec.
5979 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5980 DS.UpdateTypeRep(LocType);
5981 break;
5982 }
5983
5987 Expr *E = DS.getRepAsExpr();
5989 if (Result.isInvalid()) return true;
5990 DS.UpdateExprRep(Result.get());
5991 break;
5992 }
5993
5994 default:
5995 // Nothing to do for these decl specs.
5996 break;
5997 }
5998
5999 // It doesn't matter what order we do this in.
6000 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6001 DeclaratorChunk &Chunk = D.getTypeObject(I);
6002
6003 // The only type information in the declarator which can come
6004 // before the declaration name is the base type of a member
6005 // pointer.
6007 continue;
6008
6009 // Rebuild the scope specifier in-place.
6010 CXXScopeSpec &SS = Chunk.Mem.Scope();
6012 return true;
6013 }
6014
6015 return false;
6016}
6017
6018/// Returns true if the declaration is declared in a system header or from a
6019/// system macro.
6021 return SM.isInSystemHeader(D->getLocation()) ||
6022 SM.isInSystemMacro(D->getLocation());
6023}
6024
6026 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6027 // of system decl.
6028 if (D->getPreviousDecl() || D->isImplicit())
6029 return;
6030 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6033 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6034 << D << static_cast<int>(Status);
6035 }
6036}
6037
6039 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6040
6041 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6042 // declaration only if the `bind_to_declaration` extension is set.
6044 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6045 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6046 llvm::omp::TraitProperty::
6047 implementation_extension_bind_to_declaration))
6049 S, D, MultiTemplateParamsArg(), Bases);
6050
6052
6054 Dcl && Dcl->getDeclContext()->isFileContext())
6056
6057 if (!Bases.empty())
6059 Bases);
6060
6061 return Dcl;
6062}
6063
6065 DeclarationNameInfo NameInfo) {
6066 DeclarationName Name = NameInfo.getName();
6067
6068 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6069 while (Record && Record->isAnonymousStructOrUnion())
6070 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6071 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6072 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6073 return true;
6074 }
6075
6076 return false;
6077}
6078
6080 DeclarationName Name,
6082 TemplateIdAnnotation *TemplateId,
6083 bool IsMemberSpecialization) {
6084 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6085 "without nested-name-specifier");
6086 DeclContext *Cur = CurContext;
6087 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6088 Cur = Cur->getParent();
6089
6090 // If the user provided a superfluous scope specifier that refers back to the
6091 // class in which the entity is already declared, diagnose and ignore it.
6092 //
6093 // class X {
6094 // void X::f();
6095 // };
6096 //
6097 // Note, it was once ill-formed to give redundant qualification in all
6098 // contexts, but that rule was removed by DR482.
6099 if (Cur->Equals(DC)) {
6100 if (Cur->isRecord()) {
6101 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6102 : diag::err_member_extra_qualification)
6103 << Name << FixItHint::CreateRemoval(SS.getRange());
6104 SS.clear();
6105 } else {
6106 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6107 }
6108 return false;
6109 }
6110
6111 // Check whether the qualifying scope encloses the scope of the original
6112 // declaration. For a template-id, we perform the checks in
6113 // CheckTemplateSpecializationScope.
6114 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6115 if (Cur->isRecord())
6116 Diag(Loc, diag::err_member_qualification)
6117 << Name << SS.getRange();
6118 else if (isa<TranslationUnitDecl>(DC))
6119 Diag(Loc, diag::err_invalid_declarator_global_scope)
6120 << Name << SS.getRange();
6121 else if (isa<FunctionDecl>(Cur))
6122 Diag(Loc, diag::err_invalid_declarator_in_function)
6123 << Name << SS.getRange();
6124 else if (isa<BlockDecl>(Cur))
6125 Diag(Loc, diag::err_invalid_declarator_in_block)
6126 << Name << SS.getRange();
6127 else if (isa<ExportDecl>(Cur)) {
6128 if (!isa<NamespaceDecl>(DC))
6129 Diag(Loc, diag::err_export_non_namespace_scope_name)
6130 << Name << SS.getRange();
6131 else
6132 // The cases that DC is not NamespaceDecl should be handled in
6133 // CheckRedeclarationExported.
6134 return false;
6135 } else
6136 Diag(Loc, diag::err_invalid_declarator_scope)
6137 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6138
6139 return true;
6140 }
6141
6142 if (Cur->isRecord()) {
6143 // Cannot qualify members within a class.
6144 Diag(Loc, diag::err_member_qualification)
6145 << Name << SS.getRange();
6146 SS.clear();
6147
6148 // C++ constructors and destructors with incorrect scopes can break
6149 // our AST invariants by having the wrong underlying types. If
6150 // that's the case, then drop this declaration entirely.
6151 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6152 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6153 !Context.hasSameType(Name.getCXXNameType(),
6154 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6155 return true;
6156
6157 return false;
6158 }
6159
6160 // C++23 [temp.names]p5:
6161 // The keyword template shall not appear immediately after a declarative
6162 // nested-name-specifier.
6163 //
6164 // First check the template-id (if any), and then check each component of the
6165 // nested-name-specifier in reverse order.
6166 //
6167 // FIXME: nested-name-specifiers in friend declarations are declarative,
6168 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6169 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6170 Diag(Loc, diag::ext_template_after_declarative_nns)
6172
6174 do {
6175 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6177 Diag(Loc, diag::ext_template_after_declarative_nns)
6179 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6180
6181 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6182 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6183 // C++23 [expr.prim.id.qual]p3:
6184 // [...] If a nested-name-specifier N is declarative and has a
6185 // simple-template-id with a template argument list A that involves a
6186 // template parameter, let T be the template nominated by N without A.
6187 // T shall be a class template.
6188 if (TST->isDependentType() && TST->isTypeAlias())
6189 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6190 << SpecLoc.getLocalSourceRange();
6191 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6192 // C++23 [expr.prim.id.qual]p2:
6193 // [...] A declarative nested-name-specifier shall not have a
6194 // computed-type-specifier.
6195 //
6196 // CWG2858 changed this from 'decltype-specifier' to
6197 // 'computed-type-specifier'.
6198 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6199 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6200 }
6201 }
6202 } while ((SpecLoc = SpecLoc.getPrefix()));
6203
6204 return false;
6205}
6206
6208 MultiTemplateParamsArg TemplateParamLists) {
6209 // TODO: consider using NameInfo for diagnostic.
6211 DeclarationName Name = NameInfo.getName();
6212
6213 // All of these full declarators require an identifier. If it doesn't have
6214 // one, the ParsedFreeStandingDeclSpec action should be used.
6215 if (D.isDecompositionDeclarator()) {
6216 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6217 } else if (!Name) {
6218 if (!D.isInvalidType()) // Reject this if we think it is valid.
6219 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6220 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6221 return nullptr;
6223 return nullptr;
6224
6225 DeclContext *DC = CurContext;
6226 if (D.getCXXScopeSpec().isInvalid())
6227 D.setInvalidType();
6228 else if (D.getCXXScopeSpec().isSet()) {
6229 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6231 return nullptr;
6232
6233 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6234 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6235 if (!DC || isa<EnumDecl>(DC)) {
6236 // If we could not compute the declaration context, it's because the
6237 // declaration context is dependent but does not refer to a class,
6238 // class template, or class template partial specialization. Complain
6239 // and return early, to avoid the coming semantic disaster.
6240 Diag(D.getIdentifierLoc(),
6241 diag::err_template_qualified_declarator_no_match)
6242 << D.getCXXScopeSpec().getScopeRep()
6243 << D.getCXXScopeSpec().getRange();
6244 return nullptr;
6245 }
6246 bool IsDependentContext = DC->isDependentContext();
6247
6248 if (!IsDependentContext &&
6249 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6250 return nullptr;
6251
6252 // If a class is incomplete, do not parse entities inside it.
6253 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6254 Diag(D.getIdentifierLoc(),
6255 diag::err_member_def_undefined_record)
6256 << Name << DC << D.getCXXScopeSpec().getRange();
6257 return nullptr;
6258 }
6259 if (!D.getDeclSpec().isFriendSpecified()) {
6260 TemplateIdAnnotation *TemplateId =
6262 ? D.getName().TemplateId
6263 : nullptr;
6264 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6265 D.getIdentifierLoc(), TemplateId,
6266 /*IsMemberSpecialization=*/false)) {
6267 if (DC->isRecord())
6268 return nullptr;
6269
6270 D.setInvalidType();
6271 }
6272 }
6273
6274 // Check whether we need to rebuild the type of the given
6275 // declaration in the current instantiation.
6276 if (EnteringContext && IsDependentContext &&
6277 TemplateParamLists.size() != 0) {
6278 ContextRAII SavedContext(*this, DC);
6280 D.setInvalidType();
6281 }
6282 }
6283
6285 QualType R = TInfo->getType();
6286
6287 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6289 D.setInvalidType();
6290
6291 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6293
6294 // See if this is a redefinition of a variable in the same scope.
6295 if (!D.getCXXScopeSpec().isSet()) {
6296 bool IsLinkageLookup = false;
6297 bool CreateBuiltins = false;
6298
6299 // If the declaration we're planning to build will be a function
6300 // or object with linkage, then look for another declaration with
6301 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6302 //
6303 // If the declaration we're planning to build will be declared with
6304 // external linkage in the translation unit, create any builtin with
6305 // the same name.
6306 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6307 /* Do nothing*/;
6308 else if (CurContext->isFunctionOrMethod() &&
6309 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6310 R->isFunctionType())) {
6311 IsLinkageLookup = true;
6312 CreateBuiltins =
6315 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6316 CreateBuiltins = true;
6317
6318 if (IsLinkageLookup) {
6320 Previous.setRedeclarationKind(
6321 RedeclarationKind::ForExternalRedeclaration);
6322 }
6323
6324 LookupName(Previous, S, CreateBuiltins);
6325 } else { // Something like "int foo::x;"
6327
6328 // C++ [dcl.meaning]p1:
6329 // When the declarator-id is qualified, the declaration shall refer to a
6330 // previously declared member of the class or namespace to which the
6331 // qualifier refers (or, in the case of a namespace, of an element of the
6332 // inline namespace set of that namespace (7.3.1)) or to a specialization
6333 // thereof; [...]
6334 //
6335 // Note that we already checked the context above, and that we do not have
6336 // enough information to make sure that Previous contains the declaration
6337 // we want to match. For example, given:
6338 //
6339 // class X {
6340 // void f();
6341 // void f(float);
6342 // };
6343 //
6344 // void X::f(int) { } // ill-formed
6345 //
6346 // In this case, Previous will point to the overload set
6347 // containing the two f's declared in X, but neither of them
6348 // matches.
6349
6351 }
6352
6353 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6354 TPD && TPD->isTemplateParameter()) {
6355 // Older versions of clang allowed the names of function/variable templates
6356 // to shadow the names of their template parameters. For the compatibility
6357 // purposes we detect such cases and issue a default-to-error warning that
6358 // can be disabled with -Wno-strict-primary-template-shadow.
6359 if (!D.isInvalidType()) {
6360 bool AllowForCompatibility = false;
6361 if (Scope *DeclParent = S->getDeclParent();
6362 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6363 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6364 TemplateParamParent->isDeclScope(TPD);
6365 }
6366 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6367 AllowForCompatibility);
6368 }
6369
6370 // Just pretend that we didn't see the previous declaration.
6371 Previous.clear();
6372 }
6373
6374 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6375 // Forget that the previous declaration is the injected-class-name.
6376 Previous.clear();
6377
6378 // In C++, the previous declaration we find might be a tag type
6379 // (class or enum). In this case, the new declaration will hide the
6380 // tag type. Note that this applies to functions, function templates, and
6381 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6382 if (Previous.isSingleTagDecl() &&
6383 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6384 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6385 Previous.clear();
6386
6387 // Check that there are no default arguments other than in the parameters
6388 // of a function declaration (C++ only).
6389 if (getLangOpts().CPlusPlus)
6391
6392 /// Get the innermost enclosing declaration scope.
6393 S = S->getDeclParent();
6394
6395 NamedDecl *New;
6396
6397 bool AddToScope = true;
6398 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6399 if (TemplateParamLists.size()) {
6400 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6401 return nullptr;
6402 }
6403
6404 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6405 } else if (R->isFunctionType()) {
6406 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6407 TemplateParamLists,
6408 AddToScope);
6409 } else {
6410 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6411 AddToScope);
6412 }
6413
6414 if (!New)
6415 return nullptr;
6416
6417 // If this has an identifier and is not a function template specialization,
6418 // add it to the scope stack.
6419 if (New->getDeclName() && AddToScope)
6420 PushOnScopeChains(New, S);
6421
6422 if (OpenMP().isInOpenMPDeclareTargetContext())
6424
6425 return New;
6426}
6427
6428/// Helper method to turn variable array types into constant array
6429/// types in certain situations which would otherwise be errors (for
6430/// GCC compatibility).
6432 ASTContext &Context,
6433 bool &SizeIsNegative,
6434 llvm::APSInt &Oversized) {
6435 // This method tries to turn a variable array into a constant
6436 // array even when the size isn't an ICE. This is necessary
6437 // for compatibility with code that depends on gcc's buggy
6438 // constant expression folding, like struct {char x[(int)(char*)2];}
6439 SizeIsNegative = false;
6440 Oversized = 0;
6441
6442 if (T->isDependentType())
6443 return QualType();
6444
6446 const Type *Ty = Qs.strip(T);
6447
6448 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6449 QualType Pointee = PTy->getPointeeType();
6450 QualType FixedType =
6451 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6452 Oversized);
6453 if (FixedType.isNull()) return FixedType;
6454 FixedType = Context.getPointerType(FixedType);
6455 return Qs.apply(Context, FixedType);
6456 }
6457 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6458 QualType Inner = PTy->getInnerType();
6459 QualType FixedType =
6460 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6461 Oversized);
6462 if (FixedType.isNull()) return FixedType;
6463 FixedType = Context.getParenType(FixedType);
6464 return Qs.apply(Context, FixedType);
6465 }
6466
6467 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6468 if (!VLATy)
6469 return QualType();
6470
6471 QualType ElemTy = VLATy->getElementType();
6472 if (ElemTy->isVariablyModifiedType()) {
6473 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6474 SizeIsNegative, Oversized);
6475 if (ElemTy.isNull())
6476 return QualType();
6477 }
6478
6480 if (!VLATy->getSizeExpr() ||
6481 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6482 return QualType();
6483
6484 llvm::APSInt Res = Result.Val.getInt();
6485
6486 // Check whether the array size is negative.
6487 if (Res.isSigned() && Res.isNegative()) {
6488 SizeIsNegative = true;
6489 return QualType();
6490 }
6491
6492 // Check whether the array is too large to be addressed.
6493 unsigned ActiveSizeBits =
6494 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6495 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6496 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6497 : Res.getActiveBits();
6498 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6499 Oversized = Res;
6500 return QualType();
6501 }
6502
6503 QualType FoldedArrayType = Context.getConstantArrayType(
6504 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6505 return Qs.apply(Context, FoldedArrayType);
6506}
6507
6508static void
6510 SrcTL = SrcTL.getUnqualifiedLoc();
6511 DstTL = DstTL.getUnqualifiedLoc();
6512 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6513 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6514 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6515 DstPTL.getPointeeLoc());
6516 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6517 return;
6518 }
6519 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6520 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6521 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6522 DstPTL.getInnerLoc());
6523 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6524 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6525 return;
6526 }
6527 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6528 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6529 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6530 TypeLoc DstElemTL = DstATL.getElementLoc();
6531 if (VariableArrayTypeLoc SrcElemATL =
6532 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6533 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6534 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6535 } else {
6536 DstElemTL.initializeFullCopy(SrcElemTL);
6537 }
6538 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6539 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6540 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6541}
6542
6543/// Helper method to turn variable array types into constant array
6544/// types in certain situations which would otherwise be errors (for
6545/// GCC compatibility).
6546static TypeSourceInfo*
6548 ASTContext &Context,
6549 bool &SizeIsNegative,
6550 llvm::APSInt &Oversized) {
6551 QualType FixedTy
6552 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6553 SizeIsNegative, Oversized);
6554 if (FixedTy.isNull())
6555 return nullptr;
6556 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6558 FixedTInfo->getTypeLoc());
6559 return FixedTInfo;
6560}
6561
6564 unsigned FailedFoldDiagID) {
6565 bool SizeIsNegative;
6566 llvm::APSInt Oversized;
6568 TInfo, Context, SizeIsNegative, Oversized);
6569 if (FixedTInfo) {
6570 Diag(Loc, diag::ext_vla_folded_to_constant);
6571 TInfo = FixedTInfo;
6572 T = FixedTInfo->getType();
6573 return true;
6574 }
6575
6576 if (SizeIsNegative)
6577 Diag(Loc, diag::err_typecheck_negative_array_size);
6578 else if (Oversized.getBoolValue())
6579 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6580 else if (FailedFoldDiagID)
6581 Diag(Loc, FailedFoldDiagID);
6582 return false;
6583}
6584
6585void
6587 if (!getLangOpts().CPlusPlus &&
6589 // Don't need to track declarations in the TU in C.
6590 return;
6591
6592 // Note that we have a locally-scoped external with this name.
6594}
6595
6597 // FIXME: We can have multiple results via __attribute__((overloadable)).
6599 return Result.empty() ? nullptr : *Result.begin();
6600}
6601
6603 // FIXME: We should probably indicate the identifier in question to avoid
6604 // confusion for constructs like "virtual int a(), b;"
6605 if (DS.isVirtualSpecified())
6607 diag::err_virtual_non_function);
6608
6609 if (DS.hasExplicitSpecifier())
6611 diag::err_explicit_non_function);
6612
6613 if (DS.isNoreturnSpecified())
6615 diag::err_noreturn_non_function);
6616}
6617
6618NamedDecl*
6621 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6622 if (D.getCXXScopeSpec().isSet()) {
6623 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6624 << D.getCXXScopeSpec().getRange();
6625 D.setInvalidType();
6626 // Pretend we didn't see the scope specifier.
6627 DC = CurContext;
6628 Previous.clear();
6629 }
6630
6631 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6632
6633 if (D.getDeclSpec().isInlineSpecified())
6634 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6635 << getLangOpts().CPlusPlus17;
6636 if (D.getDeclSpec().hasConstexprSpecifier())
6637 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6638 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6639
6640 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6642 Diag(D.getName().StartLocation,
6643 diag::err_deduction_guide_invalid_specifier)
6644 << "typedef";
6645 else
6646 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6647 << D.getName().getSourceRange();
6648 return nullptr;
6649 }
6650
6651 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6652 if (!NewTD) return nullptr;
6653
6654 // Handle attributes prior to checking for duplicates in MergeVarDecl
6655 ProcessDeclAttributes(S, NewTD, D);
6656
6658
6659 bool Redeclaration = D.isRedeclaration();
6660 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6661 D.setRedeclaration(Redeclaration);
6662 return ND;
6663}
6664
6665void
6667 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6668 // then it shall have block scope.
6669 // Note that variably modified types must be fixed before merging the decl so
6670 // that redeclarations will match.
6671 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6672 QualType T = TInfo->getType();
6673 if (T->isVariablyModifiedType()) {
6675
6676 if (S->getFnParent() == nullptr) {
6677 bool SizeIsNegative;
6678 llvm::APSInt Oversized;
6679 TypeSourceInfo *FixedTInfo =
6681 SizeIsNegative,
6682 Oversized);
6683 if (FixedTInfo) {
6684 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6685 NewTD->setTypeSourceInfo(FixedTInfo);
6686 } else {
6687 if (SizeIsNegative)
6688 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6689 else if (T->isVariableArrayType())
6690 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6691 else if (Oversized.getBoolValue())
6692 Diag(NewTD->getLocation(), diag::err_array_too_large)
6693 << toString(Oversized, 10);
6694 else
6695 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6696 NewTD->setInvalidDecl();
6697 }
6698 }
6699 }
6700}
6701
6702NamedDecl*
6704 LookupResult &Previous, bool &Redeclaration) {
6705
6706 // Find the shadowed declaration before filtering for scope.
6707 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6708
6709 // Merge the decl with the existing one if appropriate. If the decl is
6710 // in an outer scope, it isn't the same thing.
6711 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6712 /*AllowInlineNamespace*/false);
6714 if (!Previous.empty()) {
6715 Redeclaration = true;
6716 MergeTypedefNameDecl(S, NewTD, Previous);
6717 } else {
6719 }
6720
6721 if (ShadowedDecl && !Redeclaration)
6722 CheckShadow(NewTD, ShadowedDecl, Previous);
6723
6724 // If this is the C FILE type, notify the AST context.
6725 if (IdentifierInfo *II = NewTD->getIdentifier())
6726 if (!NewTD->isInvalidDecl() &&
6728 switch (II->getNotableIdentifierID()) {
6729 case tok::NotableIdentifierKind::FILE:
6730 Context.setFILEDecl(NewTD);
6731 break;
6732 case tok::NotableIdentifierKind::jmp_buf:
6733 Context.setjmp_bufDecl(NewTD);
6734 break;
6735 case tok::NotableIdentifierKind::sigjmp_buf:
6737 break;
6738 case tok::NotableIdentifierKind::ucontext_t:
6740 break;
6741 case tok::NotableIdentifierKind::float_t:
6742 case tok::NotableIdentifierKind::double_t:
6743 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6744 break;
6745 default:
6746 break;
6747 }
6748 }
6749
6750 return NewTD;
6751}
6752
6753/// Determines whether the given declaration is an out-of-scope
6754/// previous declaration.
6755///
6756/// This routine should be invoked when name lookup has found a
6757/// previous declaration (PrevDecl) that is not in the scope where a
6758/// new declaration by the same name is being introduced. If the new
6759/// declaration occurs in a local scope, previous declarations with
6760/// linkage may still be considered previous declarations (C99
6761/// 6.2.2p4-5, C++ [basic.link]p6).
6762///
6763/// \param PrevDecl the previous declaration found by name
6764/// lookup
6765///
6766/// \param DC the context in which the new declaration is being
6767/// declared.
6768///
6769/// \returns true if PrevDecl is an out-of-scope previous declaration
6770/// for a new delcaration with the same name.
6771static bool
6773 ASTContext &Context) {
6774 if (!PrevDecl)
6775 return false;
6776
6777 if (!PrevDecl->hasLinkage())
6778 return false;
6779
6780 if (Context.getLangOpts().CPlusPlus) {
6781 // C++ [basic.link]p6:
6782 // If there is a visible declaration of an entity with linkage
6783 // having the same name and type, ignoring entities declared
6784 // outside the innermost enclosing namespace scope, the block
6785 // scope declaration declares that same entity and receives the
6786 // linkage of the previous declaration.
6787 DeclContext *OuterContext = DC->getRedeclContext();
6788 if (!OuterContext->isFunctionOrMethod())
6789 // This rule only applies to block-scope declarations.
6790 return false;
6791
6792 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6793 if (PrevOuterContext->isRecord())
6794 // We found a member function: ignore it.
6795 return false;
6796
6797 // Find the innermost enclosing namespace for the new and
6798 // previous declarations.
6799 OuterContext = OuterContext->getEnclosingNamespaceContext();
6800 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6801
6802 // The previous declaration is in a different namespace, so it
6803 // isn't the same function.
6804 if (!OuterContext->Equals(PrevOuterContext))
6805 return false;
6806 }
6807
6808 return true;
6809}
6810
6812 CXXScopeSpec &SS = D.getCXXScopeSpec();
6813 if (!SS.isSet()) return;
6815}
6816
6818 if (Decl->getType().hasAddressSpace())
6819 return;
6820 if (Decl->getType()->isDependentType())
6821 return;
6822 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6823 QualType Type = Var->getType();
6824 if (Type->isSamplerT() || Type->isVoidType())
6825 return;
6827 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6828 // __opencl_c_program_scope_global_variables feature, the address space
6829 // for a variable at program scope or a static or extern variable inside
6830 // a function are inferred to be __global.
6831 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6832 Var->hasGlobalStorage())
6833 ImplAS = LangAS::opencl_global;
6834 // If the original type from a decayed type is an array type and that array
6835 // type has no address space yet, deduce it now.
6836 if (auto DT = dyn_cast<DecayedType>(Type)) {
6837 auto OrigTy = DT->getOriginalType();
6838 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6839 // Add the address space to the original array type and then propagate
6840 // that to the element type through `getAsArrayType`.
6841 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6842 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6843 // Re-generate the decayed type.
6844 Type = Context.getDecayedType(OrigTy);
6845 }
6846 }
6848 // Apply any qualifiers (including address space) from the array type to
6849 // the element type. This implements C99 6.7.3p8: "If the specification of
6850 // an array type includes any type qualifiers, the element type is so
6851 // qualified, not the array type."
6852 if (Type->isArrayType())
6854 Decl->setType(Type);
6855 }
6856}
6857
6859 // Ensure that an auto decl is deduced otherwise the checks below might cache
6860 // the wrong linkage.
6861 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6862
6863 // 'weak' only applies to declarations with external linkage.
6864 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6865 if (!ND.isExternallyVisible()) {
6866 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6867 ND.dropAttr<WeakAttr>();
6868 }
6869 }
6870 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6871 if (ND.isExternallyVisible()) {
6872 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6873 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6874 }
6875 }
6876
6877 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6878 if (VD->hasInit()) {
6879 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6880 assert(VD->isThisDeclarationADefinition() &&
6881 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6882 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6883 VD->dropAttr<AliasAttr>();
6884 }
6885 }
6886 }
6887
6888 // 'selectany' only applies to externally visible variable declarations.
6889 // It does not apply to functions.
6890 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6891 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6892 S.Diag(Attr->getLocation(),
6893 diag::err_attribute_selectany_non_extern_data);
6894 ND.dropAttr<SelectAnyAttr>();
6895 }
6896 }
6897
6898 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6899 if (!ND.isExternallyVisible())
6900 S.Diag(Attr->getLocation(),
6901 diag::warn_attribute_hybrid_patchable_non_extern);
6902 }
6903 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6904 auto *VD = dyn_cast<VarDecl>(&ND);
6905 bool IsAnonymousNS = false;
6906 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6907 if (VD) {
6908 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6909 while (NS && !IsAnonymousNS) {
6910 IsAnonymousNS = NS->isAnonymousNamespace();
6911 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6912 }
6913 }
6914 // dll attributes require external linkage. Static locals may have external
6915 // linkage but still cannot be explicitly imported or exported.
6916 // In Microsoft mode, a variable defined in anonymous namespace must have
6917 // external linkage in order to be exported.
6918 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6919 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6920 (!AnonNSInMicrosoftMode &&
6921 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6922 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6923 << &ND << Attr;
6924 ND.setInvalidDecl();
6925 }
6926 }
6927
6928 // Check the attributes on the function type, if any.
6929 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6930 // Don't declare this variable in the second operand of the for-statement;
6931 // GCC miscompiles that by ending its lifetime before evaluating the
6932 // third operand. See gcc.gnu.org/PR86769.
6934 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6935 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6936 TL = ATL.getModifiedLoc()) {
6937 // The [[lifetimebound]] attribute can be applied to the implicit object
6938 // parameter of a non-static member function (other than a ctor or dtor)
6939 // by applying it to the function type.
6940 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6941 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6942 int NoImplicitObjectError = -1;
6943 if (!MD)
6944 NoImplicitObjectError = 0;
6945 else if (MD->isStatic())
6946 NoImplicitObjectError = 1;
6947 else if (MD->isExplicitObjectMemberFunction())
6948 NoImplicitObjectError = 2;
6949 if (NoImplicitObjectError != -1) {
6950 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6951 << NoImplicitObjectError << A->getRange();
6952 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6953 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6954 << isa<CXXDestructorDecl>(MD) << A->getRange();
6955 }
6956 }
6957 }
6958 }
6959}
6960
6962 NamedDecl *NewDecl,
6963 bool IsSpecialization,
6964 bool IsDefinition) {
6965 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6966 return;
6967
6968 bool IsTemplate = false;
6969 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6970 OldDecl = OldTD->getTemplatedDecl();
6971 IsTemplate = true;
6972 if (!IsSpecialization)
6973 IsDefinition = false;
6974 }
6975 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6976 NewDecl = NewTD->getTemplatedDecl();
6977 IsTemplate = true;
6978 }
6979
6980 if (!OldDecl || !NewDecl)
6981 return;
6982
6983 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6984 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6985 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6986 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6987
6988 // dllimport and dllexport are inheritable attributes so we have to exclude
6989 // inherited attribute instances.
6990 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6991 (NewExportAttr && !NewExportAttr->isInherited());
6992
6993 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6994 // the only exception being explicit specializations.
6995 // Implicitly generated declarations are also excluded for now because there
6996 // is no other way to switch these to use dllimport or dllexport.
6997 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6998
6999 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7000 // Allow with a warning for free functions and global variables.
7001 bool JustWarn = false;
7002 if (!OldDecl->isCXXClassMember()) {
7003 auto *VD = dyn_cast<VarDecl>(OldDecl);
7004 if (VD && !VD->getDescribedVarTemplate())
7005 JustWarn = true;
7006 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7007 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7008 JustWarn = true;
7009 }
7010
7011 // We cannot change a declaration that's been used because IR has already
7012 // been emitted. Dllimported functions will still work though (modulo
7013 // address equality) as they can use the thunk.
7014 if (OldDecl->isUsed())
7015 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7016 JustWarn = false;
7017
7018 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7019 : diag::err_attribute_dll_redeclaration;
7020 S.Diag(NewDecl->getLocation(), DiagID)
7021 << NewDecl
7022 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7023 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7024 if (!JustWarn) {
7025 NewDecl->setInvalidDecl();
7026 return;
7027 }
7028 }
7029
7030 // A redeclaration is not allowed to drop a dllimport attribute, the only
7031 // exceptions being inline function definitions (except for function
7032 // templates), local extern declarations, qualified friend declarations or
7033 // special MSVC extension: in the last case, the declaration is treated as if
7034 // it were marked dllexport.
7035 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7036 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7037 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7038 // Ignore static data because out-of-line definitions are diagnosed
7039 // separately.
7040 IsStaticDataMember = VD->isStaticDataMember();
7041 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7043 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7044 IsInline = FD->isInlined();
7045 IsQualifiedFriend = FD->getQualifier() &&
7046 FD->getFriendObjectKind() == Decl::FOK_Declared;
7047 }
7048
7049 if (OldImportAttr && !HasNewAttr &&
7050 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7051 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7052 if (IsMicrosoftABI && IsDefinition) {
7053 if (IsSpecialization) {
7054 S.Diag(
7055 NewDecl->getLocation(),
7056 diag::err_attribute_dllimport_function_specialization_definition);
7057 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7058 NewDecl->dropAttr<DLLImportAttr>();
7059 } else {
7060 S.Diag(NewDecl->getLocation(),
7061 diag::warn_redeclaration_without_import_attribute)
7062 << NewDecl;
7063 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7064 NewDecl->dropAttr<DLLImportAttr>();
7065 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7066 S.Context, NewImportAttr->getRange()));
7067 }
7068 } else if (IsMicrosoftABI && IsSpecialization) {
7069 assert(!IsDefinition);
7070 // MSVC allows this. Keep the inherited attribute.
7071 } else {
7072 S.Diag(NewDecl->getLocation(),
7073 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7074 << NewDecl << OldImportAttr;
7075 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7076 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7077 OldDecl->dropAttr<DLLImportAttr>();
7078 NewDecl->dropAttr<DLLImportAttr>();
7079 }
7080 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7081 // In MinGW, seeing a function declared inline drops the dllimport
7082 // attribute.
7083 OldDecl->dropAttr<DLLImportAttr>();
7084 NewDecl->dropAttr<DLLImportAttr>();
7085 S.Diag(NewDecl->getLocation(),
7086 diag::warn_dllimport_dropped_from_inline_function)
7087 << NewDecl << OldImportAttr;
7088 }
7089
7090 // A specialization of a class template member function is processed here
7091 // since it's a redeclaration. If the parent class is dllexport, the
7092 // specialization inherits that attribute. This doesn't happen automatically
7093 // since the parent class isn't instantiated until later.
7094 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7095 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7096 !NewImportAttr && !NewExportAttr) {
7097 if (const DLLExportAttr *ParentExportAttr =
7098 MD->getParent()->getAttr<DLLExportAttr>()) {
7099 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7100 NewAttr->setInherited(true);
7101 NewDecl->addAttr(NewAttr);
7102 }
7103 }
7104 }
7105}
7106
7107/// Given that we are within the definition of the given function,
7108/// will that definition behave like C99's 'inline', where the
7109/// definition is discarded except for optimization purposes?
7111 // Try to avoid calling GetGVALinkageForFunction.
7112
7113 // All cases of this require the 'inline' keyword.
7114 if (!FD->isInlined()) return false;
7115
7116 // This is only possible in C++ with the gnu_inline attribute.
7117 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7118 return false;
7119
7120 // Okay, go ahead and call the relatively-more-expensive function.
7122}
7123
7124/// Determine whether a variable is extern "C" prior to attaching
7125/// an initializer. We can't just call isExternC() here, because that
7126/// will also compute and cache whether the declaration is externally
7127/// visible, which might change when we attach the initializer.
7128///
7129/// This can only be used if the declaration is known to not be a
7130/// redeclaration of an internal linkage declaration.
7131///
7132/// For instance:
7133///
7134/// auto x = []{};
7135///
7136/// Attaching the initializer here makes this declaration not externally
7137/// visible, because its type has internal linkage.
7138///
7139/// FIXME: This is a hack.
7140template<typename T>
7141static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7142 if (S.getLangOpts().CPlusPlus) {
7143 // In C++, the overloadable attribute negates the effects of extern "C".
7144 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7145 return false;
7146
7147 // So do CUDA's host/device attributes.
7148 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7149 D->template hasAttr<CUDAHostAttr>()))
7150 return false;
7151 }
7152 return D->isExternC();
7153}
7154
7155static bool shouldConsiderLinkage(const VarDecl *VD) {
7156 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7157 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7158 isa<OMPDeclareMapperDecl>(DC))
7159 return VD->hasExternalStorage();
7160 if (DC->isFileContext())
7161 return true;
7162 if (DC->isRecord())
7163 return false;
7164 if (DC->getDeclKind() == Decl::HLSLBuffer)
7165 return false;
7166
7167 if (isa<RequiresExprBodyDecl>(DC))
7168 return false;
7169 llvm_unreachable("Unexpected context");
7170}
7171
7172static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7173 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7174 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7175 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7176 return true;
7177 if (DC->isRecord())
7178 return false;
7179 llvm_unreachable("Unexpected context");
7180}
7181
7182static bool hasParsedAttr(Scope *S, const Declarator &PD,
7183 ParsedAttr::Kind Kind) {
7184 // Check decl attributes on the DeclSpec.
7185 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7186 return true;
7187
7188 // Walk the declarator structure, checking decl attributes that were in a type
7189 // position to the decl itself.
7190 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7191 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7192 return true;
7193 }
7194
7195 // Finally, check attributes on the decl itself.
7196 return PD.getAttributes().hasAttribute(Kind) ||
7198}
7199
7201 if (!DC->isFunctionOrMethod())
7202 return false;
7203
7204 // If this is a local extern function or variable declared within a function
7205 // template, don't add it into the enclosing namespace scope until it is
7206 // instantiated; it might have a dependent type right now.
7207 if (DC->isDependentContext())
7208 return true;
7209
7210 // C++11 [basic.link]p7:
7211 // When a block scope declaration of an entity with linkage is not found to
7212 // refer to some other declaration, then that entity is a member of the
7213 // innermost enclosing namespace.
7214 //
7215 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7216 // semantically-enclosing namespace, not a lexically-enclosing one.
7217 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7218 DC = DC->getParent();
7219 return true;
7220}
7221
7222/// Returns true if given declaration has external C language linkage.
7223static bool isDeclExternC(const Decl *D) {
7224 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7225 return FD->isExternC();
7226 if (const auto *VD = dyn_cast<VarDecl>(D))
7227 return VD->isExternC();
7228
7229 llvm_unreachable("Unknown type of decl!");
7230}
7231
7232/// Returns true if there hasn't been any invalid type diagnosed.
7233static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7234 DeclContext *DC = NewVD->getDeclContext();
7235 QualType R = NewVD->getType();
7236
7237 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7238 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7239 // argument.
7240 if (R->isImageType() || R->isPipeType()) {
7241 Se.Diag(NewVD->getLocation(),
7242 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7243 << R;
7244 NewVD->setInvalidDecl();
7245 return false;
7246 }
7247
7248 // OpenCL v1.2 s6.9.r:
7249 // The event type cannot be used to declare a program scope variable.
7250 // OpenCL v2.0 s6.9.q:
7251 // The clk_event_t and reserve_id_t types cannot be declared in program
7252 // scope.
7253 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7254 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7255 Se.Diag(NewVD->getLocation(),
7256 diag::err_invalid_type_for_program_scope_var)
7257 << R;
7258 NewVD->setInvalidDecl();
7259 return false;
7260 }
7261 }
7262
7263 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7264 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7265 Se.getLangOpts())) {
7266 QualType NR = R.getCanonicalType();
7267 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7268 NR->isReferenceType()) {
7271 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7272 << NR->isReferenceType();
7273 NewVD->setInvalidDecl();
7274 return false;
7275 }
7276 NR = NR->getPointeeType();
7277 }
7278 }
7279
7280 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7281 Se.getLangOpts())) {
7282 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7283 // half array type (unless the cl_khr_fp16 extension is enabled).
7284 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7285 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7286 NewVD->setInvalidDecl();
7287 return false;
7288 }
7289 }
7290
7291 // OpenCL v1.2 s6.9.r:
7292 // The event type cannot be used with the __local, __constant and __global
7293 // address space qualifiers.
7294 if (R->isEventT()) {
7296 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7297 NewVD->setInvalidDecl();
7298 return false;
7299 }
7300 }
7301
7302 if (R->isSamplerT()) {
7303 // OpenCL v1.2 s6.9.b p4:
7304 // The sampler type cannot be used with the __local and __global address
7305 // space qualifiers.
7308 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7309 NewVD->setInvalidDecl();
7310 }
7311
7312 // OpenCL v1.2 s6.12.14.1:
7313 // A global sampler must be declared with either the constant address
7314 // space qualifier or with the const qualifier.
7315 if (DC->isTranslationUnit() &&
7317 R.isConstQualified())) {
7318 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7319 NewVD->setInvalidDecl();
7320 }
7321 if (NewVD->isInvalidDecl())
7322 return false;
7323 }
7324
7325 return true;
7326}
7327
7328template <typename AttrTy>
7329static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7330 const TypedefNameDecl *TND = TT->getDecl();
7331 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7332 AttrTy *Clone = Attribute->clone(S.Context);
7333 Clone->setInherited(true);
7334 D->addAttr(Clone);
7335 }
7336}
7337
7338// This function emits warning and a corresponding note based on the
7339// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7340// declarations of an annotated type must be const qualified.
7342 QualType VarType = VD->getType().getCanonicalType();
7343
7344 // Ignore local declarations (for now) and those with const qualification.
7345 // TODO: Local variables should not be allowed if their type declaration has
7346 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7347 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7348 return;
7349
7350 if (VarType->isArrayType()) {
7351 // Retrieve element type for array declarations.
7352 VarType = S.getASTContext().getBaseElementType(VarType);
7353 }
7354
7355 const RecordDecl *RD = VarType->getAsRecordDecl();
7356
7357 // Check if the record declaration is present and if it has any attributes.
7358 if (RD == nullptr)
7359 return;
7360
7361 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7362 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7363 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7364 return;
7365 }
7366}
7367
7368// Checks if VD is declared at global scope or with C language linkage.
7369static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7370 return Name.getAsIdentifierInfo() &&
7371 Name.getAsIdentifierInfo()->isStr("main") &&
7372 !VD->getDescribedVarTemplate() &&
7374 VD->isExternC());
7375}
7376
7378 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7379 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7380 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7381 QualType R = TInfo->getType();
7383
7384 IdentifierInfo *II = Name.getAsIdentifierInfo();
7385 bool IsPlaceholderVariable = false;
7386
7387 if (D.isDecompositionDeclarator()) {
7388 // Take the name of the first declarator as our name for diagnostic
7389 // purposes.
7390 auto &Decomp = D.getDecompositionDeclarator();
7391 if (!Decomp.bindings().empty()) {
7392 II = Decomp.bindings()[0].Name;
7393 Name = II;
7394 }
7395 } else if (!II) {
7396 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7397 return nullptr;
7398 }
7399
7400
7401 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7403
7404 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7405 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7406 IsPlaceholderVariable = true;
7407 if (!Previous.empty()) {
7408 NamedDecl *PrevDecl = *Previous.begin();
7409 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7410 DC->getRedeclContext());
7411 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7412 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7413 }
7414 }
7415
7416 // dllimport globals without explicit storage class are treated as extern. We
7417 // have to change the storage class this early to get the right DeclContext.
7418 if (SC == SC_None && !DC->isRecord() &&
7419 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7420 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7421 SC = SC_Extern;
7422
7423 DeclContext *OriginalDC = DC;
7424 bool IsLocalExternDecl = SC == SC_Extern &&
7426
7427 if (SCSpec == DeclSpec::SCS_mutable) {
7428 // mutable can only appear on non-static class members, so it's always
7429 // an error here
7430 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7431 D.setInvalidType();
7432 SC = SC_None;
7433 }
7434
7435 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7436 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7437 D.getDeclSpec().getStorageClassSpecLoc())) {
7438 // In C++11, the 'register' storage class specifier is deprecated.
7439 // Suppress the warning in system macros, it's used in macros in some
7440 // popular C system headers, such as in glibc's htonl() macro.
7441 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7442 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7443 : diag::warn_deprecated_register)
7444 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7445 }
7446
7447 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7448
7449 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7450 // C99 6.9p2: The storage-class specifiers auto and register shall not
7451 // appear in the declaration specifiers in an external declaration.
7452 // Global Register+Asm is a GNU extension we support.
7453 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7454 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7455 D.setInvalidType();
7456 }
7457 }
7458
7459 // If this variable has a VLA type and an initializer, try to
7460 // fold to a constant-sized type. This is otherwise invalid.
7461 if (D.hasInitializer() && R->isVariableArrayType())
7462 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7463 /*DiagID=*/0);
7464
7465 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7466 const AutoType *AT = TL.getTypePtr();
7467 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7468 }
7469
7470 bool IsMemberSpecialization = false;
7471 bool IsVariableTemplateSpecialization = false;
7472 bool IsPartialSpecialization = false;
7473 bool IsVariableTemplate = false;
7474 VarDecl *NewVD = nullptr;
7475 VarTemplateDecl *NewTemplate = nullptr;
7476 TemplateParameterList *TemplateParams = nullptr;
7477 if (!getLangOpts().CPlusPlus) {
7478 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7479 II, R, TInfo, SC);
7480
7481 if (R->getContainedDeducedType())
7482 ParsingInitForAutoVars.insert(NewVD);
7483
7484 if (D.isInvalidType())
7485 NewVD->setInvalidDecl();
7486
7488 NewVD->hasLocalStorage())
7489 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7491 } else {
7492 bool Invalid = false;
7493 // Match up the template parameter lists with the scope specifier, then
7494 // determine whether we have a template or a template specialization.
7496 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7497 D.getCXXScopeSpec(),
7499 ? D.getName().TemplateId
7500 : nullptr,
7501 TemplateParamLists,
7502 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7503
7504 if (TemplateParams) {
7505 if (DC->isDependentContext()) {
7506 ContextRAII SavedContext(*this, DC);
7508 Invalid = true;
7509 }
7510
7511 if (!TemplateParams->size() &&
7513 // There is an extraneous 'template<>' for this variable. Complain
7514 // about it, but allow the declaration of the variable.
7515 Diag(TemplateParams->getTemplateLoc(),
7516 diag::err_template_variable_noparams)
7517 << II
7518 << SourceRange(TemplateParams->getTemplateLoc(),
7519 TemplateParams->getRAngleLoc());
7520 TemplateParams = nullptr;
7521 } else {
7522 // Check that we can declare a template here.
7523 if (CheckTemplateDeclScope(S, TemplateParams))
7524 return nullptr;
7525
7526 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7527 // This is an explicit specialization or a partial specialization.
7528 IsVariableTemplateSpecialization = true;
7529 IsPartialSpecialization = TemplateParams->size() > 0;
7530 } else { // if (TemplateParams->size() > 0)
7531 // This is a template declaration.
7532 IsVariableTemplate = true;
7533
7534 // Only C++1y supports variable templates (N3651).
7535 Diag(D.getIdentifierLoc(),
7537 ? diag::warn_cxx11_compat_variable_template
7538 : diag::ext_variable_template);
7539 }
7540 }
7541 } else {
7542 // Check that we can declare a member specialization here.
7543 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7544 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7545 return nullptr;
7546 assert((Invalid ||
7547 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7548 "should have a 'template<>' for this decl");
7549 }
7550
7551 bool IsExplicitSpecialization =
7552 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7553
7554 // C++ [temp.expl.spec]p2:
7555 // The declaration in an explicit-specialization shall not be an
7556 // export-declaration. An explicit specialization shall not use a
7557 // storage-class-specifier other than thread_local.
7558 //
7559 // We use the storage-class-specifier from DeclSpec because we may have
7560 // added implicit 'extern' for declarations with __declspec(dllimport)!
7561 if (SCSpec != DeclSpec::SCS_unspecified &&
7562 (IsExplicitSpecialization || IsMemberSpecialization)) {
7563 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7564 diag::ext_explicit_specialization_storage_class)
7565 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7566 }
7567
7568 if (CurContext->isRecord()) {
7569 if (SC == SC_Static) {
7570 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7571 // Walk up the enclosing DeclContexts to check for any that are
7572 // incompatible with static data members.
7573 const DeclContext *FunctionOrMethod = nullptr;
7574 const CXXRecordDecl *AnonStruct = nullptr;
7575 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7576 if (Ctxt->isFunctionOrMethod()) {
7577 FunctionOrMethod = Ctxt;
7578 break;
7579 }
7580 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7581 if (ParentDecl && !ParentDecl->getDeclName()) {
7582 AnonStruct = ParentDecl;
7583 break;
7584 }
7585 }
7586 if (FunctionOrMethod) {
7587 // C++ [class.static.data]p5: A local class shall not have static
7588 // data members.
7589 Diag(D.getIdentifierLoc(),
7590 diag::err_static_data_member_not_allowed_in_local_class)
7591 << Name << RD->getDeclName()
7592 << llvm::to_underlying(RD->getTagKind());
7593 } else if (AnonStruct) {
7594 // C++ [class.static.data]p4: Unnamed classes and classes contained
7595 // directly or indirectly within unnamed classes shall not contain
7596 // static data members.
7597 Diag(D.getIdentifierLoc(),
7598 diag::err_static_data_member_not_allowed_in_anon_struct)
7599 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7600 Invalid = true;
7601 } else if (RD->isUnion()) {
7602 // C++98 [class.union]p1: If a union contains a static data member,
7603 // the program is ill-formed. C++11 drops this restriction.
7604 Diag(D.getIdentifierLoc(),
7606 ? diag::warn_cxx98_compat_static_data_member_in_union
7607 : diag::ext_static_data_member_in_union)
7608 << Name;
7609 }
7610 }
7611 } else if (IsVariableTemplate || IsPartialSpecialization) {
7612 // There is no such thing as a member field template.
7613 Diag(D.getIdentifierLoc(), diag::err_template_member)
7614 << II << TemplateParams->getSourceRange();
7615 // Recover by pretending this is a static data member template.
7616 SC = SC_Static;
7617 }
7618 } else if (DC->isRecord()) {
7619 // This is an out-of-line definition of a static data member.
7620 switch (SC) {
7621 case SC_None:
7622 break;
7623 case SC_Static:
7624 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7625 diag::err_static_out_of_line)
7627 D.getDeclSpec().getStorageClassSpecLoc());
7628 break;
7629 case SC_Auto:
7630 case SC_Register:
7631 case SC_Extern:
7632 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7633 // to names of variables declared in a block or to function parameters.
7634 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7635 // of class members
7636
7637 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7638 diag::err_storage_class_for_static_member)
7640 D.getDeclSpec().getStorageClassSpecLoc());
7641 break;
7642 case SC_PrivateExtern:
7643 llvm_unreachable("C storage class in c++!");
7644 }
7645 }
7646
7647 if (IsVariableTemplateSpecialization) {
7648 SourceLocation TemplateKWLoc =
7649 TemplateParamLists.size() > 0
7650 ? TemplateParamLists[0]->getTemplateLoc()
7651 : SourceLocation();
7653 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7655 if (Res.isInvalid())
7656 return nullptr;
7657 NewVD = cast<VarDecl>(Res.get());
7658 AddToScope = false;
7659 } else if (D.isDecompositionDeclarator()) {
7661 D.getIdentifierLoc(), R, TInfo, SC,
7662 Bindings);
7663 } else
7664 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7665 D.getIdentifierLoc(), II, R, TInfo, SC);
7666
7667 // If this is supposed to be a variable template, create it as such.
7668 if (IsVariableTemplate) {
7669 NewTemplate =
7670 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7671 TemplateParams, NewVD);
7672 NewVD->setDescribedVarTemplate(NewTemplate);
7673 }
7674
7675 // If this decl has an auto type in need of deduction, make a note of the
7676 // Decl so we can diagnose uses of it in its own initializer.
7677 if (R->getContainedDeducedType())
7678 ParsingInitForAutoVars.insert(NewVD);
7679
7680 if (D.isInvalidType() || Invalid) {
7681 NewVD->setInvalidDecl();
7682 if (NewTemplate)
7683 NewTemplate->setInvalidDecl();
7684 }
7685
7686 SetNestedNameSpecifier(*this, NewVD, D);
7687
7688 // If we have any template parameter lists that don't directly belong to
7689 // the variable (matching the scope specifier), store them.
7690 // An explicit variable template specialization does not own any template
7691 // parameter lists.
7692 unsigned VDTemplateParamLists =
7693 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7694 if (TemplateParamLists.size() > VDTemplateParamLists)
7696 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7697 }
7698
7699 if (D.getDeclSpec().isInlineSpecified()) {
7700 if (!getLangOpts().CPlusPlus) {
7701 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7702 << 0;
7703 } else if (CurContext->isFunctionOrMethod()) {
7704 // 'inline' is not allowed on block scope variable declaration.
7705 Diag(D.getDeclSpec().getInlineSpecLoc(),
7706 diag::err_inline_declaration_block_scope) << Name
7707 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7708 } else {
7709 Diag(D.getDeclSpec().getInlineSpecLoc(),
7710 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7711 : diag::ext_inline_variable);
7712 NewVD->setInlineSpecified();
7713 }
7714 }
7715
7716 // Set the lexical context. If the declarator has a C++ scope specifier, the
7717 // lexical context will be different from the semantic context.
7719 if (NewTemplate)
7720 NewTemplate->setLexicalDeclContext(CurContext);
7721
7722 if (IsLocalExternDecl) {
7723 if (D.isDecompositionDeclarator())
7724 for (auto *B : Bindings)
7725 B->setLocalExternDecl();
7726 else
7727 NewVD->setLocalExternDecl();
7728 }
7729
7730 bool EmitTLSUnsupportedError = false;
7731 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7732 // C++11 [dcl.stc]p4:
7733 // When thread_local is applied to a variable of block scope the
7734 // storage-class-specifier static is implied if it does not appear
7735 // explicitly.
7736 // Core issue: 'static' is not implied if the variable is declared
7737 // 'extern'.
7738 if (NewVD->hasLocalStorage() &&
7739 (SCSpec != DeclSpec::SCS_unspecified ||
7741 !DC->isFunctionOrMethod()))
7742 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7743 diag::err_thread_non_global)
7745 else if (!Context.getTargetInfo().isTLSSupported()) {
7746 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7747 getLangOpts().SYCLIsDevice) {
7748 // Postpone error emission until we've collected attributes required to
7749 // figure out whether it's a host or device variable and whether the
7750 // error should be ignored.
7751 EmitTLSUnsupportedError = true;
7752 // We still need to mark the variable as TLS so it shows up in AST with
7753 // proper storage class for other tools to use even if we're not going
7754 // to emit any code for it.
7755 NewVD->setTSCSpec(TSCS);
7756 } else
7757 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7758 diag::err_thread_unsupported);
7759 } else
7760 NewVD->setTSCSpec(TSCS);
7761 }
7762
7763 switch (D.getDeclSpec().getConstexprSpecifier()) {
7765 break;
7766
7768 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7769 diag::err_constexpr_wrong_decl_kind)
7770 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7771 [[fallthrough]];
7772
7774 NewVD->setConstexpr(true);
7775 // C++1z [dcl.spec.constexpr]p1:
7776 // A static data member declared with the constexpr specifier is
7777 // implicitly an inline variable.
7778 if (NewVD->isStaticDataMember() &&
7779 (getLangOpts().CPlusPlus17 ||
7781 NewVD->setImplicitlyInline();
7782 break;
7783
7785 if (!NewVD->hasGlobalStorage())
7786 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7787 diag::err_constinit_local_variable);
7788 else
7789 NewVD->addAttr(
7790 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7791 ConstInitAttr::Keyword_constinit));
7792 break;
7793 }
7794
7795 // C99 6.7.4p3
7796 // An inline definition of a function with external linkage shall
7797 // not contain a definition of a modifiable object with static or
7798 // thread storage duration...
7799 // We only apply this when the function is required to be defined
7800 // elsewhere, i.e. when the function is not 'extern inline'. Note
7801 // that a local variable with thread storage duration still has to
7802 // be marked 'static'. Also note that it's possible to get these
7803 // semantics in C++ using __attribute__((gnu_inline)).
7804 if (SC == SC_Static && S->getFnParent() != nullptr &&
7805 !NewVD->getType().isConstQualified()) {
7807 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7808 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7809 diag::warn_static_local_in_extern_inline);
7811 }
7812 }
7813
7814 if (D.getDeclSpec().isModulePrivateSpecified()) {
7815 if (IsVariableTemplateSpecialization)
7816 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7817 << (IsPartialSpecialization ? 1 : 0)
7819 D.getDeclSpec().getModulePrivateSpecLoc());
7820 else if (IsMemberSpecialization)
7821 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7822 << 2
7823 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7824 else if (NewVD->hasLocalStorage())
7825 Diag(NewVD->getLocation(), diag::err_module_private_local)
7826 << 0 << NewVD
7827 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7829 D.getDeclSpec().getModulePrivateSpecLoc());
7830 else {
7831 NewVD->setModulePrivate();
7832 if (NewTemplate)
7833 NewTemplate->setModulePrivate();
7834 for (auto *B : Bindings)
7835 B->setModulePrivate();
7836 }
7837 }
7838
7839 if (getLangOpts().OpenCL) {
7841
7842 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7843 if (TSC != TSCS_unspecified) {
7844 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7845 diag::err_opencl_unknown_type_specifier)
7847 << DeclSpec::getSpecifierName(TSC) << 1;
7848 NewVD->setInvalidDecl();
7849 }
7850 }
7851
7852 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7853 // address space if the table has local storage (semantic checks elsewhere
7854 // will produce an error anyway).
7855 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7856 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7857 !NewVD->hasLocalStorage()) {
7860 NewVD->setType(Type);
7861 }
7862 }
7863
7864 // Handle attributes prior to checking for duplicates in MergeVarDecl
7865 ProcessDeclAttributes(S, NewVD, D);
7866
7867 // FIXME: This is probably the wrong location to be doing this and we should
7868 // probably be doing this for more attributes (especially for function
7869 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7870 // the code to copy attributes would be generated by TableGen.
7871 if (R->isFunctionPointerType())
7872 if (const auto *TT = R->getAs<TypedefType>())
7873 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7874
7875 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7876 getLangOpts().SYCLIsDevice) {
7877 if (EmitTLSUnsupportedError &&
7879 (getLangOpts().OpenMPIsTargetDevice &&
7880 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7881 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7882 diag::err_thread_unsupported);
7883
7884 if (EmitTLSUnsupportedError &&
7885 (LangOpts.SYCLIsDevice ||
7886 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7887 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7888 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7889 // storage [duration]."
7890 if (SC == SC_None && S->getFnParent() != nullptr &&
7891 (NewVD->hasAttr<CUDASharedAttr>() ||
7892 NewVD->hasAttr<CUDAConstantAttr>())) {
7893 NewVD->setStorageClass(SC_Static);
7894 }
7895 }
7896
7897 // Ensure that dllimport globals without explicit storage class are treated as
7898 // extern. The storage class is set above using parsed attributes. Now we can
7899 // check the VarDecl itself.
7900 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7901 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7902 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7903
7904 // In auto-retain/release, infer strong retension for variables of
7905 // retainable type.
7906 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7907 NewVD->setInvalidDecl();
7908
7909 // Handle GNU asm-label extension (encoded as an attribute).
7910 if (Expr *E = (Expr*)D.getAsmLabel()) {
7911 // The parser guarantees this is a string.
7912 StringLiteral *SE = cast<StringLiteral>(E);
7913 StringRef Label = SE->getString();
7914 if (S->getFnParent() != nullptr) {
7915 switch (SC) {
7916 case SC_None:
7917 case SC_Auto:
7918 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7919 break;
7920 case SC_Register:
7921 // Local Named register
7924 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7925 break;
7926 case SC_Static:
7927 case SC_Extern:
7928 case SC_PrivateExtern:
7929 break;
7930 }
7931 } else if (SC == SC_Register) {
7932 // Global Named register
7933 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7934 const auto &TI = Context.getTargetInfo();
7935 bool HasSizeMismatch;
7936
7937 if (!TI.isValidGCCRegisterName(Label))
7938 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7939 else if (!TI.validateGlobalRegisterVariable(Label,
7941 HasSizeMismatch))
7942 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7943 else if (HasSizeMismatch)
7944 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7945 }
7946
7947 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7948 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7949 NewVD->setInvalidDecl(true);
7950 }
7951 }
7952
7953 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7954 /*IsLiteralLabel=*/true,
7955 SE->getStrTokenLoc(0)));
7956 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7957 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7959 if (I != ExtnameUndeclaredIdentifiers.end()) {
7960 if (isDeclExternC(NewVD)) {
7961 NewVD->addAttr(I->second);
7963 } else
7964 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7965 << /*Variable*/1 << NewVD;
7966 }
7967 }
7968
7969 // Find the shadowed declaration before filtering for scope.
7970 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7972 : nullptr;
7973
7974 // Don't consider existing declarations that are in a different
7975 // scope and are out-of-semantic-context declarations (if the new
7976 // declaration has linkage).
7978 D.getCXXScopeSpec().isNotEmpty() ||
7979 IsMemberSpecialization ||
7980 IsVariableTemplateSpecialization);
7981
7982 // Check whether the previous declaration is in the same block scope. This
7983 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7984 if (getLangOpts().CPlusPlus &&
7985 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7987 Previous.isSingleResult() && !Previous.isShadowed() &&
7988 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7989
7990 if (!getLangOpts().CPlusPlus) {
7991 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7992 } else {
7993 // If this is an explicit specialization of a static data member, check it.
7994 if (IsMemberSpecialization && !IsVariableTemplate &&
7995 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
7997 NewVD->setInvalidDecl();
7998
7999 // Merge the decl with the existing one if appropriate.
8000 if (!Previous.empty()) {
8001 if (Previous.isSingleResult() &&
8002 isa<FieldDecl>(Previous.getFoundDecl()) &&
8003 D.getCXXScopeSpec().isSet()) {
8004 // The user tried to define a non-static data member
8005 // out-of-line (C++ [dcl.meaning]p1).
8006 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8007 << D.getCXXScopeSpec().getRange();
8008 Previous.clear();
8009 NewVD->setInvalidDecl();
8010 }
8011 } else if (D.getCXXScopeSpec().isSet() &&
8012 !IsVariableTemplateSpecialization) {
8013 // No previous declaration in the qualifying scope.
8014 Diag(D.getIdentifierLoc(), diag::err_no_member)
8015 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8016 << D.getCXXScopeSpec().getRange();
8017 NewVD->setInvalidDecl();
8018 }
8019
8020 if (!IsPlaceholderVariable)
8021 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8022
8023 // CheckVariableDeclaration will set NewVD as invalid if something is in
8024 // error like WebAssembly tables being declared as arrays with a non-zero
8025 // size, but then parsing continues and emits further errors on that line.
8026 // To avoid that we check here if it happened and return nullptr.
8027 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8028 return nullptr;
8029
8030 if (NewTemplate) {
8031 VarTemplateDecl *PrevVarTemplate =
8032 NewVD->getPreviousDecl()
8034 : nullptr;
8035
8036 // Check the template parameter list of this declaration, possibly
8037 // merging in the template parameter list from the previous variable
8038 // template declaration.
8040 TemplateParams,
8041 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8042 : nullptr,
8043 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8044 DC->isDependentContext())
8046 : TPC_VarTemplate))
8047 NewVD->setInvalidDecl();
8048
8049 // If we are providing an explicit specialization of a static variable
8050 // template, make a note of that.
8051 if (PrevVarTemplate &&
8052 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8053 PrevVarTemplate->setMemberSpecialization();
8054 }
8055 }
8056
8057 // Diagnose shadowed variables iff this isn't a redeclaration.
8058 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8059 CheckShadow(NewVD, ShadowedDecl, Previous);
8060
8061 ProcessPragmaWeak(S, NewVD);
8062
8063 // If this is the first declaration of an extern C variable, update
8064 // the map of such variables.
8065 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8066 isIncompleteDeclExternC(*this, NewVD))
8068
8069 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8071 Decl *ManglingContextDecl;
8072 std::tie(MCtx, ManglingContextDecl) =
8074 if (MCtx) {
8076 NewVD, MCtx->getManglingNumber(
8077 NewVD, getMSManglingNumber(getLangOpts(), S)));
8079 }
8080 }
8081
8082 // Special handling of variable named 'main'.
8083 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8084 // C++ [basic.start.main]p3:
8085 // A program that declares
8086 // - a variable main at global scope, or
8087 // - an entity named main with C language linkage (in any namespace)
8088 // is ill-formed
8089 if (getLangOpts().CPlusPlus)
8090 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8091 << NewVD->isExternC();
8092
8093 // In C, and external-linkage variable named main results in undefined
8094 // behavior.
8095 else if (NewVD->hasExternalFormalLinkage())
8096 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8097 }
8098
8099 if (D.isRedeclaration() && !Previous.empty()) {
8100 NamedDecl *Prev = Previous.getRepresentativeDecl();
8101 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8102 D.isFunctionDefinition());
8103 }
8104
8105 if (NewTemplate) {
8106 if (NewVD->isInvalidDecl())
8107 NewTemplate->setInvalidDecl();
8108 ActOnDocumentableDecl(NewTemplate);
8109 return NewTemplate;
8110 }
8111
8112 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8114
8116
8117 return NewVD;
8118}
8119
8120/// Enum describing the %select options in diag::warn_decl_shadow.
8130
8131/// Determine what kind of declaration we're shadowing.
8133 const DeclContext *OldDC) {
8134 if (isa<TypeAliasDecl>(ShadowedDecl))
8135 return SDK_Using;
8136 else if (isa<TypedefDecl>(ShadowedDecl))
8137 return SDK_Typedef;
8138 else if (isa<BindingDecl>(ShadowedDecl))
8139 return SDK_StructuredBinding;
8140 else if (isa<RecordDecl>(OldDC))
8141 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8142
8143 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8144}
8145
8146/// Return the location of the capture if the given lambda captures the given
8147/// variable \p VD, or an invalid source location otherwise.
8149 const VarDecl *VD) {
8150 for (const Capture &Capture : LSI->Captures) {
8152 return Capture.getLocation();
8153 }
8154 return SourceLocation();
8155}
8156
8158 const LookupResult &R) {
8159 // Only diagnose if we're shadowing an unambiguous field or variable.
8161 return false;
8162
8163 // Return false if warning is ignored.
8164 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8165}
8166
8168 const LookupResult &R) {
8170 return nullptr;
8171
8172 // Don't diagnose declarations at file scope.
8173 if (D->hasGlobalStorage() && !D->isStaticLocal())
8174 return nullptr;
8175
8176 NamedDecl *ShadowedDecl = R.getFoundDecl();
8177 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8178 : nullptr;
8179}
8180
8182 const LookupResult &R) {
8183 // Don't warn if typedef declaration is part of a class
8184 if (D->getDeclContext()->isRecord())
8185 return nullptr;
8186
8188 return nullptr;
8189
8190 NamedDecl *ShadowedDecl = R.getFoundDecl();
8191 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8192}
8193
8195 const LookupResult &R) {
8197 return nullptr;
8198
8199 NamedDecl *ShadowedDecl = R.getFoundDecl();
8200 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8201 : nullptr;
8202}
8203
8205 const LookupResult &R) {
8206 DeclContext *NewDC = D->getDeclContext();
8207
8208 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8209 // Fields are not shadowed by variables in C++ static methods.
8210 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8211 if (MD->isStatic())
8212 return;
8213
8214 // Fields shadowed by constructor parameters are a special case. Usually
8215 // the constructor initializes the field with the parameter.
8216 if (isa<CXXConstructorDecl>(NewDC))
8217 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8218 // Remember that this was shadowed so we can either warn about its
8219 // modification or its existence depending on warning settings.
8220 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8221 return;
8222 }
8223 }
8224
8225 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8226 if (shadowedVar->isExternC()) {
8227 // For shadowing external vars, make sure that we point to the global
8228 // declaration, not a locally scoped extern declaration.
8229 for (auto *I : shadowedVar->redecls())
8230 if (I->isFileVarDecl()) {
8231 ShadowedDecl = I;
8232 break;
8233 }
8234 }
8235
8236 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8237
8238 unsigned WarningDiag = diag::warn_decl_shadow;
8239 SourceLocation CaptureLoc;
8240 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8241 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8242 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8243 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8244 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8245 if (RD->getLambdaCaptureDefault() == LCD_None) {
8246 // Try to avoid warnings for lambdas with an explicit capture
8247 // list. Warn only when the lambda captures the shadowed decl
8248 // explicitly.
8249 CaptureLoc = getCaptureLocation(LSI, VD);
8250 if (CaptureLoc.isInvalid())
8251 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8252 } else {
8253 // Remember that this was shadowed so we can avoid the warning if
8254 // the shadowed decl isn't captured and the warning settings allow
8255 // it.
8256 cast<LambdaScopeInfo>(getCurFunction())
8257 ->ShadowingDecls.push_back({D, VD});
8258 return;
8259 }
8260 }
8261 if (isa<FieldDecl>(ShadowedDecl)) {
8262 // If lambda can capture this, then emit default shadowing warning,
8263 // Otherwise it is not really a shadowing case since field is not
8264 // available in lambda's body.
8265 // At this point we don't know that lambda can capture this, so
8266 // remember that this was shadowed and delay until we know.
8267 cast<LambdaScopeInfo>(getCurFunction())
8268 ->ShadowingDecls.push_back({D, ShadowedDecl});
8269 return;
8270 }
8271 }
8272 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8273 VD && VD->hasLocalStorage()) {
8274 // A variable can't shadow a local variable in an enclosing scope, if
8275 // they are separated by a non-capturing declaration context.
8276 for (DeclContext *ParentDC = NewDC;
8277 ParentDC && !ParentDC->Equals(OldDC);
8278 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8279 // Only block literals, captured statements, and lambda expressions
8280 // can capture; other scopes don't.
8281 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8282 !isLambdaCallOperator(ParentDC)) {
8283 return;
8284 }
8285 }
8286 }
8287 }
8288 }
8289
8290 // Never warn about shadowing a placeholder variable.
8291 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8292 return;
8293
8294 // Only warn about certain kinds of shadowing for class members.
8295 if (NewDC && NewDC->isRecord()) {
8296 // In particular, don't warn about shadowing non-class members.
8297 if (!OldDC->isRecord())
8298 return;
8299
8300 // TODO: should we warn about static data members shadowing
8301 // static data members from base classes?
8302
8303 // TODO: don't diagnose for inaccessible shadowed members.
8304 // This is hard to do perfectly because we might friend the
8305 // shadowing context, but that's just a false negative.
8306 }
8307
8308
8309 DeclarationName Name = R.getLookupName();
8310
8311 // Emit warning and note.
8312 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8313 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8314 if (!CaptureLoc.isInvalid())
8315 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8316 << Name << /*explicitly*/ 1;
8317 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8318}
8319
8321 for (const auto &Shadow : LSI->ShadowingDecls) {
8322 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8323 // Try to avoid the warning when the shadowed decl isn't captured.
8324 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8325 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8326 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8327 Diag(Shadow.VD->getLocation(),
8328 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8329 : diag::warn_decl_shadow)
8330 << Shadow.VD->getDeclName()
8331 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8332 if (CaptureLoc.isValid())
8333 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8334 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8335 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8336 } else if (isa<FieldDecl>(ShadowedDecl)) {
8337 Diag(Shadow.VD->getLocation(),
8338 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8339 : diag::warn_decl_shadow_uncaptured_local)
8340 << Shadow.VD->getDeclName()
8341 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8342 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8343 }
8344 }
8345}
8346
8348 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8349 return;
8350
8351 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8353 RedeclarationKind::ForVisibleRedeclaration);
8354 LookupName(R, S);
8355 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8356 CheckShadow(D, ShadowedDecl, R);
8357}
8358
8359/// Check if 'E', which is an expression that is about to be modified, refers
8360/// to a constructor parameter that shadows a field.
8362 // Quickly ignore expressions that can't be shadowing ctor parameters.
8363 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8364 return;
8365 E = E->IgnoreParenImpCasts();
8366 auto *DRE = dyn_cast<DeclRefExpr>(E);
8367 if (!DRE)
8368 return;
8369 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8370 auto I = ShadowingDecls.find(D);
8371 if (I == ShadowingDecls.end())
8372 return;
8373 const NamedDecl *ShadowedDecl = I->second;
8374 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8375 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8376 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8377 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8378
8379 // Avoid issuing multiple warnings about the same decl.
8380 ShadowingDecls.erase(I);
8381}
8382
8383/// Check for conflict between this global or extern "C" declaration and
8384/// previous global or extern "C" declarations. This is only used in C++.
8385template<typename T>
8387 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8388 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8389 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8390
8391 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8392 // The common case: this global doesn't conflict with any extern "C"
8393 // declaration.
8394 return false;
8395 }
8396
8397 if (Prev) {
8398 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8399 // Both the old and new declarations have C language linkage. This is a
8400 // redeclaration.
8401 Previous.clear();
8402 Previous.addDecl(Prev);
8403 return true;
8404 }
8405
8406 // This is a global, non-extern "C" declaration, and there is a previous
8407 // non-global extern "C" declaration. Diagnose if this is a variable
8408 // declaration.
8409 if (!isa<VarDecl>(ND))
8410 return false;
8411 } else {
8412 // The declaration is extern "C". Check for any declaration in the
8413 // translation unit which might conflict.
8414 if (IsGlobal) {
8415 // We have already performed the lookup into the translation unit.
8416 IsGlobal = false;
8417 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8418 I != E; ++I) {
8419 if (isa<VarDecl>(*I)) {
8420 Prev = *I;
8421 break;
8422 }
8423 }
8424 } else {
8426 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8427 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8428 I != E; ++I) {
8429 if (isa<VarDecl>(*I)) {
8430 Prev = *I;
8431 break;
8432 }
8433 // FIXME: If we have any other entity with this name in global scope,
8434 // the declaration is ill-formed, but that is a defect: it breaks the
8435 // 'stat' hack, for instance. Only variables can have mangled name
8436 // clashes with extern "C" declarations, so only they deserve a
8437 // diagnostic.
8438 }
8439 }
8440
8441 if (!Prev)
8442 return false;
8443 }
8444
8445 // Use the first declaration's location to ensure we point at something which
8446 // is lexically inside an extern "C" linkage-spec.
8447 assert(Prev && "should have found a previous declaration to diagnose");
8448 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8449 Prev = FD->getFirstDecl();
8450 else
8451 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8452
8453 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8454 << IsGlobal << ND;
8455 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8456 << IsGlobal;
8457 return false;
8458}
8459
8460/// Apply special rules for handling extern "C" declarations. Returns \c true
8461/// if we have found that this is a redeclaration of some prior entity.
8462///
8463/// Per C++ [dcl.link]p6:
8464/// Two declarations [for a function or variable] with C language linkage
8465/// with the same name that appear in different scopes refer to the same
8466/// [entity]. An entity with C language linkage shall not be declared with
8467/// the same name as an entity in global scope.
8468template<typename T>
8471 if (!S.getLangOpts().CPlusPlus) {
8472 // In C, when declaring a global variable, look for a corresponding 'extern'
8473 // variable declared in function scope. We don't need this in C++, because
8474 // we find local extern decls in the surrounding file-scope DeclContext.
8475 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8476 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8477 Previous.clear();
8478 Previous.addDecl(Prev);
8479 return true;
8480 }
8481 }
8482 return false;
8483 }
8484
8485 // A declaration in the translation unit can conflict with an extern "C"
8486 // declaration.
8487 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8488 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8489
8490 // An extern "C" declaration can conflict with a declaration in the
8491 // translation unit or can be a redeclaration of an extern "C" declaration
8492 // in another scope.
8493 if (isIncompleteDeclExternC(S,ND))
8494 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8495
8496 // Neither global nor extern "C": nothing to do.
8497 return false;
8498}
8499
8500static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8501 QualType T) {
8502 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8503 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8504 // any of its members, even recursively, shall not have an atomic type, or a
8505 // variably modified type, or a type that is volatile or restrict qualified.
8506 if (CanonT->isVariablyModifiedType()) {
8507 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8508 return true;
8509 }
8510
8511 // Arrays are qualified by their element type, so get the base type (this
8512 // works on non-arrays as well).
8513 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8514
8515 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8516 CanonT.isRestrictQualified()) {
8517 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8518 return true;
8519 }
8520
8521 if (CanonT->isRecordType()) {
8522 const RecordDecl *RD = CanonT->getAsRecordDecl();
8523 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8524 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8525 }))
8526 return true;
8527 }
8528
8529 return false;
8530}
8531
8533 // If the decl is already known invalid, don't check it.
8534 if (NewVD->isInvalidDecl())
8535 return;
8536
8537 QualType T = NewVD->getType();
8538
8539 // Defer checking an 'auto' type until its initializer is attached.
8540 if (T->isUndeducedType())
8541 return;
8542
8543 if (NewVD->hasAttrs())
8545
8546 if (T->isObjCObjectType()) {
8547 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8548 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8550 NewVD->setType(T);
8551 }
8552
8553 // Emit an error if an address space was applied to decl with local storage.
8554 // This includes arrays of objects with address space qualifiers, but not
8555 // automatic variables that point to other address spaces.
8556 // ISO/IEC TR 18037 S5.1.2
8557 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8558 T.getAddressSpace() != LangAS::Default) {
8559 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8560 NewVD->setInvalidDecl();
8561 return;
8562 }
8563
8564 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8565 // scope.
8566 if (getLangOpts().OpenCLVersion == 120 &&
8567 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8568 getLangOpts()) &&
8569 NewVD->isStaticLocal()) {
8570 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8571 NewVD->setInvalidDecl();
8572 return;
8573 }
8574
8575 if (getLangOpts().OpenCL) {
8576 if (!diagnoseOpenCLTypes(*this, NewVD))
8577 return;
8578
8579 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8580 if (NewVD->hasAttr<BlocksAttr>()) {
8581 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8582 return;
8583 }
8584
8585 if (T->isBlockPointerType()) {
8586 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8587 // can't use 'extern' storage class.
8588 if (!T.isConstQualified()) {
8589 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8590 << 0 /*const*/;
8591 NewVD->setInvalidDecl();
8592 return;
8593 }
8594 if (NewVD->hasExternalStorage()) {
8595 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8596 NewVD->setInvalidDecl();
8597 return;
8598 }
8599 }
8600
8601 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8602 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8603 NewVD->hasExternalStorage()) {
8604 if (!T->isSamplerT() && !T->isDependentType() &&
8605 !(T.getAddressSpace() == LangAS::opencl_constant ||
8606 (T.getAddressSpace() == LangAS::opencl_global &&
8607 getOpenCLOptions().areProgramScopeVariablesSupported(
8608 getLangOpts())))) {
8609 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8610 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8611 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8612 << Scope << "global or constant";
8613 else
8614 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8615 << Scope << "constant";
8616 NewVD->setInvalidDecl();
8617 return;
8618 }
8619 } else {
8620 if (T.getAddressSpace() == LangAS::opencl_global) {
8621 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8622 << 1 /*is any function*/ << "global";
8623 NewVD->setInvalidDecl();
8624 return;
8625 }
8626 if (T.getAddressSpace() == LangAS::opencl_constant ||
8627 T.getAddressSpace() == LangAS::opencl_local) {
8629 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8630 // in functions.
8631 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8632 if (T.getAddressSpace() == LangAS::opencl_constant)
8633 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8634 << 0 /*non-kernel only*/ << "constant";
8635 else
8636 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8637 << 0 /*non-kernel only*/ << "local";
8638 NewVD->setInvalidDecl();
8639 return;
8640 }
8641 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8642 // in the outermost scope of a kernel function.
8643 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8644 if (!getCurScope()->isFunctionScope()) {
8645 if (T.getAddressSpace() == LangAS::opencl_constant)
8646 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8647 << "constant";
8648 else
8649 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8650 << "local";
8651 NewVD->setInvalidDecl();
8652 return;
8653 }
8654 }
8655 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8656 // If we are parsing a template we didn't deduce an addr
8657 // space yet.
8658 T.getAddressSpace() != LangAS::Default) {
8659 // Do not allow other address spaces on automatic variable.
8660 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8661 NewVD->setInvalidDecl();
8662 return;
8663 }
8664 }
8665 }
8666
8667 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8668 && !NewVD->hasAttr<BlocksAttr>()) {
8669 if (getLangOpts().getGC() != LangOptions::NonGC)
8670 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8671 else {
8672 assert(!getLangOpts().ObjCAutoRefCount);
8673 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8674 }
8675 }
8676
8677 // WebAssembly tables must be static with a zero length and can't be
8678 // declared within functions.
8679 if (T->isWebAssemblyTableType()) {
8680 if (getCurScope()->getParent()) { // Parent is null at top-level
8681 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8682 NewVD->setInvalidDecl();
8683 return;
8684 }
8685 if (NewVD->getStorageClass() != SC_Static) {
8686 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8687 NewVD->setInvalidDecl();
8688 return;
8689 }
8690 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8691 if (!ATy || ATy->getZExtSize() != 0) {
8692 Diag(NewVD->getLocation(),
8693 diag::err_typecheck_wasm_table_must_have_zero_length);
8694 NewVD->setInvalidDecl();
8695 return;
8696 }
8697 }
8698
8699 bool isVM = T->isVariablyModifiedType();
8700 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8701 NewVD->hasAttr<BlocksAttr>())
8703
8704 if ((isVM && NewVD->hasLinkage()) ||
8705 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8706 bool SizeIsNegative;
8707 llvm::APSInt Oversized;
8709 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8710 QualType FixedT;
8711 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8712 FixedT = FixedTInfo->getType();
8713 else if (FixedTInfo) {
8714 // Type and type-as-written are canonically different. We need to fix up
8715 // both types separately.
8716 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8717 Oversized);
8718 }
8719 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8721 // FIXME: This won't give the correct result for
8722 // int a[10][n];
8723 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8724
8725 if (NewVD->isFileVarDecl())
8726 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8727 << SizeRange;
8728 else if (NewVD->isStaticLocal())
8729 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8730 << SizeRange;
8731 else
8732 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8733 << SizeRange;
8734 NewVD->setInvalidDecl();
8735 return;
8736 }
8737
8738 if (!FixedTInfo) {
8739 if (NewVD->isFileVarDecl())
8740 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8741 else
8742 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8743 NewVD->setInvalidDecl();
8744 return;
8745 }
8746
8747 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8748 NewVD->setType(FixedT);
8749 NewVD->setTypeSourceInfo(FixedTInfo);
8750 }
8751
8752 if (T->isVoidType()) {
8753 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8754 // of objects and functions.
8756 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8757 << T;
8758 NewVD->setInvalidDecl();
8759 return;
8760 }
8761 }
8762
8763 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8764 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8765 NewVD->setInvalidDecl();
8766 return;
8767 }
8768
8769 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8770 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8771 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8772 NewVD->setInvalidDecl();
8773 return;
8774 }
8775
8776 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8777 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8778 NewVD->setInvalidDecl();
8779 return;
8780 }
8781
8782 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8783 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8784 NewVD->setInvalidDecl();
8785 return;
8786 }
8787
8788 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8789 !T->isDependentType() &&
8791 diag::err_constexpr_var_non_literal)) {
8792 NewVD->setInvalidDecl();
8793 return;
8794 }
8795
8796 // PPC MMA non-pointer types are not allowed as non-local variable types.
8797 if (Context.getTargetInfo().getTriple().isPPC64() &&
8798 !NewVD->isLocalVarDecl() &&
8799 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8800 NewVD->setInvalidDecl();
8801 return;
8802 }
8803
8804 // Check that SVE types are only used in functions with SVE available.
8805 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8806 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8807 llvm::StringMap<bool> CallerFeatureMap;
8808 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8809
8810 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8811 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8812 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8813 NewVD->setInvalidDecl();
8814 return;
8815 } else if (!IsArmStreamingFunction(FD,
8816 /*IncludeLocallyStreaming=*/true)) {
8817 Diag(NewVD->getLocation(),
8818 diag::err_sve_vector_in_non_streaming_function)
8819 << T;
8820 NewVD->setInvalidDecl();
8821 return;
8822 }
8823 }
8824 }
8825
8826 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8827 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8828 llvm::StringMap<bool> CallerFeatureMap;
8829 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8830 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8831 CallerFeatureMap);
8832 }
8833}
8834
8837
8838 // If the decl is already known invalid, don't check it.
8839 if (NewVD->isInvalidDecl())
8840 return false;
8841
8842 // If we did not find anything by this name, look for a non-visible
8843 // extern "C" declaration with the same name.
8844 if (Previous.empty() &&
8846 Previous.setShadowed();
8847
8848 if (!Previous.empty()) {
8849 MergeVarDecl(NewVD, Previous);
8850 return true;
8851 }
8852 return false;
8853}
8854
8857
8858 // Look for methods in base classes that this method might override.
8859 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8860 /*DetectVirtual=*/false);
8861 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8862 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8863 DeclarationName Name = MD->getDeclName();
8864
8865 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8866 // We really want to find the base class destructor here.
8867 QualType T = Context.getTypeDeclType(BaseRecord);
8870 }
8871
8872 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8873 CXXMethodDecl *BaseMD =
8874 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8875 if (!BaseMD || !BaseMD->isVirtual() ||
8876 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8877 /*ConsiderCudaAttrs=*/true))
8878 continue;
8879 if (!CheckExplicitObjectOverride(MD, BaseMD))
8880 continue;
8881 if (Overridden.insert(BaseMD).second) {
8882 MD->addOverriddenMethod(BaseMD);
8887 }
8888
8889 // A method can only override one function from each base class. We
8890 // don't track indirectly overridden methods from bases of bases.
8891 return true;
8892 }
8893
8894 return false;
8895 };
8896
8897 DC->lookupInBases(VisitBase, Paths);
8898 return !Overridden.empty();
8899}
8900
8901namespace {
8902 // Struct for holding all of the extra arguments needed by
8903 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8904 struct ActOnFDArgs {
8905 Scope *S;
8906 Declarator &D;
8907 MultiTemplateParamsArg TemplateParamLists;
8908 bool AddToScope;
8909 };
8910} // end anonymous namespace
8911
8912namespace {
8913
8914// Callback to only accept typo corrections that have a non-zero edit distance.
8915// Also only accept corrections that have the same parent decl.
8916class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8917 public:
8918 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8920 : Context(Context), OriginalFD(TypoFD),
8921 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8922
8923 bool ValidateCandidate(const TypoCorrection &candidate) override {
8924 if (candidate.getEditDistance() == 0)
8925 return false;
8926
8927 SmallVector<unsigned, 1> MismatchedParams;
8928 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8929 CDeclEnd = candidate.end();
8930 CDecl != CDeclEnd; ++CDecl) {
8931 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8932
8933 if (FD && !FD->hasBody() &&
8934 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8936 CXXRecordDecl *Parent = MD->getParent();
8937 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8938 return true;
8939 } else if (!ExpectedParent) {
8940 return true;
8941 }
8942 }
8943 }
8944
8945 return false;
8946 }
8947
8948 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8949 return std::make_unique<DifferentNameValidatorCCC>(*this);
8950 }
8951
8952 private:
8953 ASTContext &Context;
8954 FunctionDecl *OriginalFD;
8955 CXXRecordDecl *ExpectedParent;
8956};
8957
8958} // end anonymous namespace
8959
8962}
8963
8964/// Generate diagnostics for an invalid function redeclaration.
8965///
8966/// This routine handles generating the diagnostic messages for an invalid
8967/// function redeclaration, including finding possible similar declarations
8968/// or performing typo correction if there are no previous declarations with
8969/// the same name.
8970///
8971/// Returns a NamedDecl iff typo correction was performed and substituting in
8972/// the new declaration name does not cause new errors.
8974 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8975 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8976 DeclarationName Name = NewFD->getDeclName();
8977 DeclContext *NewDC = NewFD->getDeclContext();
8978 SmallVector<unsigned, 1> MismatchedParams;
8980 TypoCorrection Correction;
8981 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8982 unsigned DiagMsg =
8983 IsLocalFriend ? diag::err_no_matching_local_friend :
8984 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8985 diag::err_member_decl_does_not_match;
8986 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8987 IsLocalFriend ? Sema::LookupLocalFriendName
8989 RedeclarationKind::ForVisibleRedeclaration);
8990
8991 NewFD->setInvalidDecl();
8992 if (IsLocalFriend)
8993 SemaRef.LookupName(Prev, S);
8994 else
8995 SemaRef.LookupQualifiedName(Prev, NewDC);
8996 assert(!Prev.isAmbiguous() &&
8997 "Cannot have an ambiguity in previous-declaration lookup");
8998 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8999 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9000 MD ? MD->getParent() : nullptr);
9001 if (!Prev.empty()) {
9002 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9003 Func != FuncEnd; ++Func) {
9004 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9005 if (FD &&
9006 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9007 // Add 1 to the index so that 0 can mean the mismatch didn't
9008 // involve a parameter
9009 unsigned ParamNum =
9010 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9011 NearMatches.push_back(std::make_pair(FD, ParamNum));
9012 }
9013 }
9014 // If the qualified name lookup yielded nothing, try typo correction
9015 } else if ((Correction = SemaRef.CorrectTypo(
9016 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9017 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9018 IsLocalFriend ? nullptr : NewDC))) {
9019 // Set up everything for the call to ActOnFunctionDeclarator
9020 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9021 ExtraArgs.D.getIdentifierLoc());
9022 Previous.clear();
9023 Previous.setLookupName(Correction.getCorrection());
9024 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9025 CDeclEnd = Correction.end();
9026 CDecl != CDeclEnd; ++CDecl) {
9027 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9028 if (FD && !FD->hasBody() &&
9029 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9030 Previous.addDecl(FD);
9031 }
9032 }
9033 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9034
9036 // Retry building the function declaration with the new previous
9037 // declarations, and with errors suppressed.
9038 {
9039 // Trap errors.
9040 Sema::SFINAETrap Trap(SemaRef);
9041
9042 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9043 // pieces need to verify the typo-corrected C++ declaration and hopefully
9044 // eliminate the need for the parameter pack ExtraArgs.
9046 ExtraArgs.S, ExtraArgs.D,
9047 Correction.getCorrectionDecl()->getDeclContext(),
9048 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9049 ExtraArgs.AddToScope);
9050
9051 if (Trap.hasErrorOccurred())
9052 Result = nullptr;
9053 }
9054
9055 if (Result) {
9056 // Determine which correction we picked.
9057 Decl *Canonical = Result->getCanonicalDecl();
9058 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9059 I != E; ++I)
9060 if ((*I)->getCanonicalDecl() == Canonical)
9061 Correction.setCorrectionDecl(*I);
9062
9063 // Let Sema know about the correction.
9065 SemaRef.diagnoseTypo(
9066 Correction,
9067 SemaRef.PDiag(IsLocalFriend
9068 ? diag::err_no_matching_local_friend_suggest
9069 : diag::err_member_decl_does_not_match_suggest)
9070 << Name << NewDC << IsDefinition);
9071 return Result;
9072 }
9073
9074 // Pretend the typo correction never occurred
9075 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9076 ExtraArgs.D.getIdentifierLoc());
9077 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9078 Previous.clear();
9079 Previous.setLookupName(Name);
9080 }
9081
9082 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9083 << Name << NewDC << IsDefinition << NewFD->getLocation();
9084
9085 bool NewFDisConst = false;
9086 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9087 NewFDisConst = NewMD->isConst();
9088
9089 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9090 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9091 NearMatch != NearMatchEnd; ++NearMatch) {
9092 FunctionDecl *FD = NearMatch->first;
9093 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9094 bool FDisConst = MD && MD->isConst();
9095 bool IsMember = MD || !IsLocalFriend;
9096
9097 // FIXME: These notes are poorly worded for the local friend case.
9098 if (unsigned Idx = NearMatch->second) {
9099 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9101 if (Loc.isInvalid()) Loc = FD->getLocation();
9102 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9103 : diag::note_local_decl_close_param_match)
9104 << Idx << FDParam->getType()
9105 << NewFD->getParamDecl(Idx - 1)->getType();
9106 } else if (FDisConst != NewFDisConst) {
9107 auto DB = SemaRef.Diag(FD->getLocation(),
9108 diag::note_member_def_close_const_match)
9109 << NewFDisConst << FD->getSourceRange().getEnd();
9110 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9111 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9112 " const");
9113 else if (FTI.hasMethodTypeQualifiers() &&
9114 FTI.getConstQualifierLoc().isValid())
9115 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9116 } else {
9117 SemaRef.Diag(FD->getLocation(),
9118 IsMember ? diag::note_member_def_close_match
9119 : diag::note_local_decl_close_match);
9120 }
9121 }
9122 return nullptr;
9123}
9124
9126 switch (D.getDeclSpec().getStorageClassSpec()) {
9127 default: llvm_unreachable("Unknown storage class!");
9128 case DeclSpec::SCS_auto:
9131 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9132 diag::err_typecheck_sclass_func);
9133 D.getMutableDeclSpec().ClearStorageClassSpecs();
9134 D.setInvalidType();
9135 break;
9136 case DeclSpec::SCS_unspecified: break;
9138 if (D.getDeclSpec().isExternInLinkageSpec())
9139 return SC_None;
9140 return SC_Extern;
9141 case DeclSpec::SCS_static: {
9143 // C99 6.7.1p5:
9144 // The declaration of an identifier for a function that has
9145 // block scope shall have no explicit storage-class specifier
9146 // other than extern
9147 // See also (C++ [dcl.stc]p4).
9148 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9149 diag::err_static_block_func);
9150 break;
9151 } else
9152 return SC_Static;
9153 }
9155 }
9156
9157 // No explicit storage class has already been returned
9158 return SC_None;
9159}
9160
9162 DeclContext *DC, QualType &R,
9163 TypeSourceInfo *TInfo,
9164 StorageClass SC,
9165 bool &IsVirtualOkay) {
9166 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9167 DeclarationName Name = NameInfo.getName();
9168
9169 FunctionDecl *NewFD = nullptr;
9170 bool isInline = D.getDeclSpec().isInlineSpecified();
9171
9172 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9173 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9174 (SemaRef.getLangOpts().C23 &&
9175 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9176
9177 if (SemaRef.getLangOpts().C23)
9178 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9179 diag::err_c23_constexpr_not_variable);
9180 else
9181 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9182 diag::err_constexpr_wrong_decl_kind)
9183 << static_cast<int>(ConstexprKind);
9184 ConstexprKind = ConstexprSpecKind::Unspecified;
9185 D.getMutableDeclSpec().ClearConstexprSpec();
9186 }
9187
9188 if (!SemaRef.getLangOpts().CPlusPlus) {
9189 // Determine whether the function was written with a prototype. This is
9190 // true when:
9191 // - there is a prototype in the declarator, or
9192 // - the type R of the function is some kind of typedef or other non-
9193 // attributed reference to a type name (which eventually refers to a
9194 // function type). Note, we can't always look at the adjusted type to
9195 // check this case because attributes may cause a non-function
9196 // declarator to still have a function type. e.g.,
9197 // typedef void func(int a);
9198 // __attribute__((noreturn)) func other_func; // This has a prototype
9199 bool HasPrototype =
9200 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9201 (D.getDeclSpec().isTypeRep() &&
9202 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9203 ->isFunctionProtoType()) ||
9205 assert(
9206 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9207 "Strict prototypes are required");
9208
9209 NewFD = FunctionDecl::Create(
9210 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9211 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9213 /*TrailingRequiresClause=*/nullptr);
9214 if (D.isInvalidType())
9215 NewFD->setInvalidDecl();
9216
9217 return NewFD;
9218 }
9219
9220 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9221 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9222
9223 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9224
9225 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9226 // This is a C++ constructor declaration.
9227 assert(DC->isRecord() &&
9228 "Constructors can only be declared in a member context");
9229
9230 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9232 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9234 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9235 InheritedConstructor(), TrailingRequiresClause);
9236
9237 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9238 // This is a C++ destructor declaration.
9239 if (DC->isRecord()) {
9240 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9241 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9243 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9244 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9245 /*isImplicitlyDeclared=*/false, ConstexprKind,
9246 TrailingRequiresClause);
9247 // User defined destructors start as not selected if the class definition is still
9248 // not done.
9249 if (Record->isBeingDefined())
9250 NewDD->setIneligibleOrNotSelected(true);
9251
9252 // If the destructor needs an implicit exception specification, set it
9253 // now. FIXME: It'd be nice to be able to create the right type to start
9254 // with, but the type needs to reference the destructor declaration.
9255 if (SemaRef.getLangOpts().CPlusPlus11)
9256 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9257
9258 IsVirtualOkay = true;
9259 return NewDD;
9260
9261 } else {
9262 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9263 D.setInvalidType();
9264
9265 // Create a FunctionDecl to satisfy the function definition parsing
9266 // code path.
9267 return FunctionDecl::Create(
9268 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9269 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9270 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9271 }
9272
9273 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9274 if (!DC->isRecord()) {
9275 SemaRef.Diag(D.getIdentifierLoc(),
9276 diag::err_conv_function_not_member);
9277 return nullptr;
9278 }
9279
9280 SemaRef.CheckConversionDeclarator(D, R, SC);
9281 if (D.isInvalidType())
9282 return nullptr;
9283
9284 IsVirtualOkay = true;
9286 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9287 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9288 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9289 TrailingRequiresClause);
9290
9291 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9292 if (TrailingRequiresClause)
9293 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9294 diag::err_trailing_requires_clause_on_deduction_guide)
9295 << TrailingRequiresClause->getSourceRange();
9296 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9297 return nullptr;
9298 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9299 ExplicitSpecifier, NameInfo, R, TInfo,
9300 D.getEndLoc());
9301 } else if (DC->isRecord()) {
9302 // If the name of the function is the same as the name of the record,
9303 // then this must be an invalid constructor that has a return type.
9304 // (The parser checks for a return type and makes the declarator a
9305 // constructor if it has no return type).
9306 if (Name.getAsIdentifierInfo() &&
9307 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9308 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9309 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9310 << SourceRange(D.getIdentifierLoc());
9311 return nullptr;
9312 }
9313
9314 // This is a C++ method declaration.
9316 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9317 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9318 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9319 IsVirtualOkay = !Ret->isStatic();
9320 return Ret;
9321 } else {
9322 bool isFriend =
9323 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9324 if (!isFriend && SemaRef.CurContext->isRecord())
9325 return nullptr;
9326
9327 // Determine whether the function was written with a
9328 // prototype. This true when:
9329 // - we're in C++ (where every function has a prototype),
9330 return FunctionDecl::Create(
9331 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9332 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9333 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9334 }
9335}
9336
9345
9347 // Size dependent types are just typedefs to normal integer types
9348 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9349 // integers other than by their names.
9350 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9351
9352 // Remove typedefs one by one until we reach a typedef
9353 // for a size dependent type.
9354 QualType DesugaredTy = Ty;
9355 do {
9356 ArrayRef<StringRef> Names(SizeTypeNames);
9357 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9358 if (Names.end() != Match)
9359 return true;
9360
9361 Ty = DesugaredTy;
9362 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9363 } while (DesugaredTy != Ty);
9364
9365 return false;
9366}
9367
9369 if (PT->isDependentType())
9370 return InvalidKernelParam;
9371
9372 if (PT->isPointerOrReferenceType()) {
9373 QualType PointeeType = PT->getPointeeType();
9374 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9375 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9376 PointeeType.getAddressSpace() == LangAS::Default)
9378
9379 if (PointeeType->isPointerType()) {
9380 // This is a pointer to pointer parameter.
9381 // Recursively check inner type.
9382 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9383 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9384 ParamKind == InvalidKernelParam)
9385 return ParamKind;
9386
9387 // OpenCL v3.0 s6.11.a:
9388 // A restriction to pass pointers to pointers only applies to OpenCL C
9389 // v1.2 or below.
9391 return ValidKernelParam;
9392
9393 return PtrPtrKernelParam;
9394 }
9395
9396 // C++ for OpenCL v1.0 s2.4:
9397 // Moreover the types used in parameters of the kernel functions must be:
9398 // Standard layout types for pointer parameters. The same applies to
9399 // reference if an implementation supports them in kernel parameters.
9400 if (S.getLangOpts().OpenCLCPlusPlus &&
9402 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9403 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9404 bool IsStandardLayoutType = true;
9405 if (CXXRec) {
9406 // If template type is not ODR-used its definition is only available
9407 // in the template definition not its instantiation.
9408 // FIXME: This logic doesn't work for types that depend on template
9409 // parameter (PR58590).
9410 if (!CXXRec->hasDefinition())
9411 CXXRec = CXXRec->getTemplateInstantiationPattern();
9412 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9413 IsStandardLayoutType = false;
9414 }
9415 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9416 !IsStandardLayoutType)
9417 return InvalidKernelParam;
9418 }
9419
9420 // OpenCL v1.2 s6.9.p:
9421 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9423 return ValidKernelParam;
9424
9425 return PtrKernelParam;
9426 }
9427
9428 // OpenCL v1.2 s6.9.k:
9429 // Arguments to kernel functions in a program cannot be declared with the
9430 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9431 // uintptr_t or a struct and/or union that contain fields declared to be one
9432 // of these built-in scalar types.
9434 return InvalidKernelParam;
9435
9436 if (PT->isImageType())
9437 return PtrKernelParam;
9438
9439 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9440 return InvalidKernelParam;
9441
9442 // OpenCL extension spec v1.2 s9.5:
9443 // This extension adds support for half scalar and vector types as built-in
9444 // types that can be used for arithmetic operations, conversions etc.
9445 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9446 PT->isHalfType())
9447 return InvalidKernelParam;
9448
9449 // Look into an array argument to check if it has a forbidden type.
9450 if (PT->isArrayType()) {
9451 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9452 // Call ourself to check an underlying type of an array. Since the
9453 // getPointeeOrArrayElementType returns an innermost type which is not an
9454 // array, this recursive call only happens once.
9455 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9456 }
9457
9458 // C++ for OpenCL v1.0 s2.4:
9459 // Moreover the types used in parameters of the kernel functions must be:
9460 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9461 // types) for parameters passed by value;
9462 if (S.getLangOpts().OpenCLCPlusPlus &&
9464 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9465 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9466 return InvalidKernelParam;
9467
9468 if (PT->isRecordType())
9469 return RecordKernelParam;
9470
9471 return ValidKernelParam;
9472}
9473
9475 Sema &S,
9476 Declarator &D,
9477 ParmVarDecl *Param,
9478 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9479 QualType PT = Param->getType();
9480
9481 // Cache the valid types we encounter to avoid rechecking structs that are
9482 // used again
9483 if (ValidTypes.count(PT.getTypePtr()))
9484 return;
9485
9486 switch (getOpenCLKernelParameterType(S, PT)) {
9487 case PtrPtrKernelParam:
9488 // OpenCL v3.0 s6.11.a:
9489 // A kernel function argument cannot be declared as a pointer to a pointer
9490 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9491 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9492 D.setInvalidType();
9493 return;
9494
9496 // OpenCL v1.0 s6.5:
9497 // __kernel function arguments declared to be a pointer of a type can point
9498 // to one of the following address spaces only : __global, __local or
9499 // __constant.
9500 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9501 D.setInvalidType();
9502 return;
9503
9504 // OpenCL v1.2 s6.9.k:
9505 // Arguments to kernel functions in a program cannot be declared with the
9506 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9507 // uintptr_t or a struct and/or union that contain fields declared to be
9508 // one of these built-in scalar types.
9509
9510 case InvalidKernelParam:
9511 // OpenCL v1.2 s6.8 n:
9512 // A kernel function argument cannot be declared
9513 // of event_t type.
9514 // Do not diagnose half type since it is diagnosed as invalid argument
9515 // type for any function elsewhere.
9516 if (!PT->isHalfType()) {
9517 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9518
9519 // Explain what typedefs are involved.
9520 const TypedefType *Typedef = nullptr;
9521 while ((Typedef = PT->getAs<TypedefType>())) {
9522 SourceLocation Loc = Typedef->getDecl()->getLocation();
9523 // SourceLocation may be invalid for a built-in type.
9524 if (Loc.isValid())
9525 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9526 PT = Typedef->desugar();
9527 }
9528 }
9529
9530 D.setInvalidType();
9531 return;
9532
9533 case PtrKernelParam:
9534 case ValidKernelParam:
9535 ValidTypes.insert(PT.getTypePtr());
9536 return;
9537
9538 case RecordKernelParam:
9539 break;
9540 }
9541
9542 // Track nested structs we will inspect
9544
9545 // Track where we are in the nested structs. Items will migrate from
9546 // VisitStack to HistoryStack as we do the DFS for bad field.
9548 HistoryStack.push_back(nullptr);
9549
9550 // At this point we already handled everything except of a RecordType or
9551 // an ArrayType of a RecordType.
9552 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9553 const RecordType *RecTy =
9555 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9556
9557 VisitStack.push_back(RecTy->getDecl());
9558 assert(VisitStack.back() && "First decl null?");
9559
9560 do {
9561 const Decl *Next = VisitStack.pop_back_val();
9562 if (!Next) {
9563 assert(!HistoryStack.empty());
9564 // Found a marker, we have gone up a level
9565 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9566 ValidTypes.insert(Hist->getType().getTypePtr());
9567
9568 continue;
9569 }
9570
9571 // Adds everything except the original parameter declaration (which is not a
9572 // field itself) to the history stack.
9573 const RecordDecl *RD;
9574 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9575 HistoryStack.push_back(Field);
9576
9577 QualType FieldTy = Field->getType();
9578 // Other field types (known to be valid or invalid) are handled while we
9579 // walk around RecordDecl::fields().
9580 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9581 "Unexpected type.");
9582 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9583
9584 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9585 } else {
9586 RD = cast<RecordDecl>(Next);
9587 }
9588
9589 // Add a null marker so we know when we've gone back up a level
9590 VisitStack.push_back(nullptr);
9591
9592 for (const auto *FD : RD->fields()) {
9593 QualType QT = FD->getType();
9594
9595 if (ValidTypes.count(QT.getTypePtr()))
9596 continue;
9597
9599 if (ParamType == ValidKernelParam)
9600 continue;
9601
9602 if (ParamType == RecordKernelParam) {
9603 VisitStack.push_back(FD);
9604 continue;
9605 }
9606
9607 // OpenCL v1.2 s6.9.p:
9608 // Arguments to kernel functions that are declared to be a struct or union
9609 // do not allow OpenCL objects to be passed as elements of the struct or
9610 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9611 // of SVM.
9612 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9613 ParamType == InvalidAddrSpacePtrKernelParam) {
9614 S.Diag(Param->getLocation(),
9615 diag::err_record_with_pointers_kernel_param)
9616 << PT->isUnionType()
9617 << PT;
9618 } else {
9619 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9620 }
9621
9622 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9623 << OrigRecDecl->getDeclName();
9624
9625 // We have an error, now let's go back up through history and show where
9626 // the offending field came from
9628 I = HistoryStack.begin() + 1,
9629 E = HistoryStack.end();
9630 I != E; ++I) {
9631 const FieldDecl *OuterField = *I;
9632 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9633 << OuterField->getType();
9634 }
9635
9636 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9637 << QT->isPointerType()
9638 << QT;
9639 D.setInvalidType();
9640 return;
9641 }
9642 } while (!VisitStack.empty());
9643}
9644
9645/// Find the DeclContext in which a tag is implicitly declared if we see an
9646/// elaborated type specifier in the specified context, and lookup finds
9647/// nothing.
9649 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9650 DC = DC->getParent();
9651 return DC;
9652}
9653
9654/// Find the Scope in which a tag is implicitly declared if we see an
9655/// elaborated type specifier in the specified context, and lookup finds
9656/// nothing.
9657static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9658 while (S->isClassScope() ||
9659 (LangOpts.CPlusPlus &&
9660 S->isFunctionPrototypeScope()) ||
9661 ((S->getFlags() & Scope::DeclScope) == 0) ||
9662 (S->getEntity() && S->getEntity()->isTransparentContext()))
9663 S = S->getParent();
9664 return S;
9665}
9666
9667/// Determine whether a declaration matches a known function in namespace std.
9669 unsigned BuiltinID) {
9670 switch (BuiltinID) {
9671 case Builtin::BI__GetExceptionInfo:
9672 // No type checking whatsoever.
9673 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9674
9675 case Builtin::BIaddressof:
9676 case Builtin::BI__addressof:
9677 case Builtin::BIforward:
9678 case Builtin::BIforward_like:
9679 case Builtin::BImove:
9680 case Builtin::BImove_if_noexcept:
9681 case Builtin::BIas_const: {
9682 // Ensure that we don't treat the algorithm
9683 // OutputIt std::move(InputIt, InputIt, OutputIt)
9684 // as the builtin std::move.
9685 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9686 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9687 }
9688
9689 default:
9690 return false;
9691 }
9692}
9693
9694NamedDecl*
9697 MultiTemplateParamsArg TemplateParamListsRef,
9698 bool &AddToScope) {
9699 QualType R = TInfo->getType();
9700
9701 assert(R->isFunctionType());
9703 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9704
9705 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9706 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9707 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9708 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9709 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9710 TemplateParamLists.back() = Invented;
9711 else
9712 TemplateParamLists.push_back(Invented);
9713 }
9714
9715 // TODO: consider using NameInfo for diagnostic.
9717 DeclarationName Name = NameInfo.getName();
9719
9720 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9721 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9722 diag::err_invalid_thread)
9724
9725 if (D.isFirstDeclarationOfMember())
9727 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9728 D.isCtorOrDtor(), D.getIdentifierLoc());
9729
9730 bool isFriend = false;
9732 bool isMemberSpecialization = false;
9733 bool isFunctionTemplateSpecialization = false;
9734
9735 bool HasExplicitTemplateArgs = false;
9736 TemplateArgumentListInfo TemplateArgs;
9737
9738 bool isVirtualOkay = false;
9739
9740 DeclContext *OriginalDC = DC;
9741 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9742
9743 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9744 isVirtualOkay);
9745 if (!NewFD) return nullptr;
9746
9749
9750 // Set the lexical context. If this is a function-scope declaration, or has a
9751 // C++ scope specifier, or is the object of a friend declaration, the lexical
9752 // context will be different from the semantic context.
9754
9755 if (IsLocalExternDecl)
9756 NewFD->setLocalExternDecl();
9757
9758 if (getLangOpts().CPlusPlus) {
9759 // The rules for implicit inlines changed in C++20 for methods and friends
9760 // with an in-class definition (when such a definition is not attached to
9761 // the global module). User-specified 'inline' overrides this (set when
9762 // the function decl is created above).
9763 // FIXME: We need a better way to separate C++ standard and clang modules.
9764 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9765 !NewFD->getOwningModule() ||
9766 NewFD->isFromExplicitGlobalModule() ||
9768 bool isInline = D.getDeclSpec().isInlineSpecified();
9769 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9770 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9771 isFriend = D.getDeclSpec().isFriendSpecified();
9772 if (isFriend && !isInline && D.isFunctionDefinition()) {
9773 // Pre-C++20 [class.friend]p5
9774 // A function can be defined in a friend declaration of a
9775 // class . . . . Such a function is implicitly inline.
9776 // Post C++20 [class.friend]p7
9777 // Such a function is implicitly an inline function if it is attached
9778 // to the global module.
9779 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9780 }
9781
9782 // If this is a method defined in an __interface, and is not a constructor
9783 // or an overloaded operator, then set the pure flag (isVirtual will already
9784 // return true).
9785 if (const CXXRecordDecl *Parent =
9786 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9787 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9788 NewFD->setIsPureVirtual(true);
9789
9790 // C++ [class.union]p2
9791 // A union can have member functions, but not virtual functions.
9792 if (isVirtual && Parent->isUnion()) {
9793 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9794 NewFD->setInvalidDecl();
9795 }
9796 if ((Parent->isClass() || Parent->isStruct()) &&
9797 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9798 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9799 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9800 if (auto *Def = Parent->getDefinition())
9801 Def->setInitMethod(true);
9802 }
9803 }
9804
9805 SetNestedNameSpecifier(*this, NewFD, D);
9806 isMemberSpecialization = false;
9807 isFunctionTemplateSpecialization = false;
9808 if (D.isInvalidType())
9809 NewFD->setInvalidDecl();
9810
9811 // Match up the template parameter lists with the scope specifier, then
9812 // determine whether we have a template or a template specialization.
9813 bool Invalid = false;
9814 TemplateIdAnnotation *TemplateId =
9816 ? D.getName().TemplateId
9817 : nullptr;
9818 TemplateParameterList *TemplateParams =
9820 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9821 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9822 isMemberSpecialization, Invalid);
9823 if (TemplateParams) {
9824 // Check that we can declare a template here.
9825 if (CheckTemplateDeclScope(S, TemplateParams))
9826 NewFD->setInvalidDecl();
9827
9828 if (TemplateParams->size() > 0) {
9829 // This is a function template
9830
9831 // A destructor cannot be a template.
9832 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9833 Diag(NewFD->getLocation(), diag::err_destructor_template);
9834 NewFD->setInvalidDecl();
9835 // Function template with explicit template arguments.
9836 } else if (TemplateId) {
9837 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9838 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9839 NewFD->setInvalidDecl();
9840 }
9841
9842 // If we're adding a template to a dependent context, we may need to
9843 // rebuilding some of the types used within the template parameter list,
9844 // now that we know what the current instantiation is.
9845 if (DC->isDependentContext()) {
9846 ContextRAII SavedContext(*this, DC);
9848 Invalid = true;
9849 }
9850
9852 NewFD->getLocation(),
9853 Name, TemplateParams,
9854 NewFD);
9855 FunctionTemplate->setLexicalDeclContext(CurContext);
9857
9858 // For source fidelity, store the other template param lists.
9859 if (TemplateParamLists.size() > 1) {
9861 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9862 .drop_back(1));
9863 }
9864 } else {
9865 // This is a function template specialization.
9866 isFunctionTemplateSpecialization = true;
9867 // For source fidelity, store all the template param lists.
9868 if (TemplateParamLists.size() > 0)
9869 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9870
9871 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9872 if (isFriend) {
9873 // We want to remove the "template<>", found here.
9874 SourceRange RemoveRange = TemplateParams->getSourceRange();
9875
9876 // If we remove the template<> and the name is not a
9877 // template-id, we're actually silently creating a problem:
9878 // the friend declaration will refer to an untemplated decl,
9879 // and clearly the user wants a template specialization. So
9880 // we need to insert '<>' after the name.
9881 SourceLocation InsertLoc;
9882 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9883 InsertLoc = D.getName().getSourceRange().getEnd();
9884 InsertLoc = getLocForEndOfToken(InsertLoc);
9885 }
9886
9887 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9888 << Name << RemoveRange
9889 << FixItHint::CreateRemoval(RemoveRange)
9890 << FixItHint::CreateInsertion(InsertLoc, "<>");
9891 Invalid = true;
9892
9893 // Recover by faking up an empty template argument list.
9894 HasExplicitTemplateArgs = true;
9895 TemplateArgs.setLAngleLoc(InsertLoc);
9896 TemplateArgs.setRAngleLoc(InsertLoc);
9897 }
9898 }
9899 } else {
9900 // Check that we can declare a template here.
9901 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9902 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9903 NewFD->setInvalidDecl();
9904
9905 // All template param lists were matched against the scope specifier:
9906 // this is NOT (an explicit specialization of) a template.
9907 if (TemplateParamLists.size() > 0)
9908 // For source fidelity, store all the template param lists.
9909 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9910
9911 // "friend void foo<>(int);" is an implicit specialization decl.
9912 if (isFriend && TemplateId)
9913 isFunctionTemplateSpecialization = true;
9914 }
9915
9916 // If this is a function template specialization and the unqualified-id of
9917 // the declarator-id is a template-id, convert the template argument list
9918 // into our AST format and check for unexpanded packs.
9919 if (isFunctionTemplateSpecialization && TemplateId) {
9920 HasExplicitTemplateArgs = true;
9921
9922 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9923 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9924 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9925 TemplateId->NumArgs);
9926 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
9927
9928 // FIXME: Should we check for unexpanded packs if this was an (invalid)
9929 // declaration of a function template partial specialization? Should we
9930 // consider the unexpanded pack context to be a partial specialization?
9931 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
9933 ArgLoc, isFriend ? UPPC_FriendDeclaration
9935 NewFD->setInvalidDecl();
9936 }
9937 }
9938
9939 if (Invalid) {
9940 NewFD->setInvalidDecl();
9941 if (FunctionTemplate)
9942 FunctionTemplate->setInvalidDecl();
9943 }
9944
9945 // C++ [dcl.fct.spec]p5:
9946 // The virtual specifier shall only be used in declarations of
9947 // nonstatic class member functions that appear within a
9948 // member-specification of a class declaration; see 10.3.
9949 //
9950 if (isVirtual && !NewFD->isInvalidDecl()) {
9951 if (!isVirtualOkay) {
9952 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9953 diag::err_virtual_non_function);
9954 } else if (!CurContext->isRecord()) {
9955 // 'virtual' was specified outside of the class.
9956 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9957 diag::err_virtual_out_of_class)
9958 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9959 } else if (NewFD->getDescribedFunctionTemplate()) {
9960 // C++ [temp.mem]p3:
9961 // A member function template shall not be virtual.
9962 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9963 diag::err_virtual_member_function_template)
9964 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9965 } else {
9966 // Okay: Add virtual to the method.
9967 NewFD->setVirtualAsWritten(true);
9968 }
9969
9970 if (getLangOpts().CPlusPlus14 &&
9971 NewFD->getReturnType()->isUndeducedType())
9972 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9973 }
9974
9975 // C++ [dcl.fct.spec]p3:
9976 // The inline specifier shall not appear on a block scope function
9977 // declaration.
9978 if (isInline && !NewFD->isInvalidDecl()) {
9980 // 'inline' is not allowed on block scope function declaration.
9981 Diag(D.getDeclSpec().getInlineSpecLoc(),
9982 diag::err_inline_declaration_block_scope) << Name
9983 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9984 }
9985 }
9986
9987 // C++ [dcl.fct.spec]p6:
9988 // The explicit specifier shall be used only in the declaration of a
9989 // constructor or conversion function within its class definition;
9990 // see 12.3.1 and 12.3.2.
9991 if (hasExplicit && !NewFD->isInvalidDecl() &&
9992 !isa<CXXDeductionGuideDecl>(NewFD)) {
9993 if (!CurContext->isRecord()) {
9994 // 'explicit' was specified outside of the class.
9995 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9996 diag::err_explicit_out_of_class)
9997 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9998 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9999 !isa<CXXConversionDecl>(NewFD)) {
10000 // 'explicit' was specified on a function that wasn't a constructor
10001 // or conversion function.
10002 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10003 diag::err_explicit_non_ctor_or_conv_function)
10004 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10005 }
10006 }
10007
10008 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10009 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10010 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10011 // are implicitly inline.
10012 NewFD->setImplicitlyInline();
10013
10014 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10015 // be either constructors or to return a literal type. Therefore,
10016 // destructors cannot be declared constexpr.
10017 if (isa<CXXDestructorDecl>(NewFD) &&
10019 ConstexprKind == ConstexprSpecKind::Consteval)) {
10020 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10021 << static_cast<int>(ConstexprKind);
10022 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10025 }
10026 // C++20 [dcl.constexpr]p2: An allocation function, or a
10027 // deallocation function shall not be declared with the consteval
10028 // specifier.
10029 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10030 (NewFD->getOverloadedOperator() == OO_New ||
10031 NewFD->getOverloadedOperator() == OO_Array_New ||
10032 NewFD->getOverloadedOperator() == OO_Delete ||
10033 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10034 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10035 diag::err_invalid_consteval_decl_kind)
10036 << NewFD;
10038 }
10039 }
10040
10041 // If __module_private__ was specified, mark the function accordingly.
10042 if (D.getDeclSpec().isModulePrivateSpecified()) {
10043 if (isFunctionTemplateSpecialization) {
10044 SourceLocation ModulePrivateLoc
10045 = D.getDeclSpec().getModulePrivateSpecLoc();
10046 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10047 << 0
10048 << FixItHint::CreateRemoval(ModulePrivateLoc);
10049 } else {
10050 NewFD->setModulePrivate();
10051 if (FunctionTemplate)
10052 FunctionTemplate->setModulePrivate();
10053 }
10054 }
10055
10056 if (isFriend) {
10057 if (FunctionTemplate) {
10058 FunctionTemplate->setObjectOfFriendDecl();
10059 FunctionTemplate->setAccess(AS_public);
10060 }
10061 NewFD->setObjectOfFriendDecl();
10062 NewFD->setAccess(AS_public);
10063 }
10064
10065 // If a function is defined as defaulted or deleted, mark it as such now.
10066 // We'll do the relevant checks on defaulted / deleted functions later.
10067 switch (D.getFunctionDefinitionKind()) {
10070 break;
10071
10073 NewFD->setDefaulted();
10074 break;
10075
10077 NewFD->setDeletedAsWritten();
10078 break;
10079 }
10080
10081 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10082 D.isFunctionDefinition() && !isInline) {
10083 // Pre C++20 [class.mfct]p2:
10084 // A member function may be defined (8.4) in its class definition, in
10085 // which case it is an inline member function (7.1.2)
10086 // Post C++20 [class.mfct]p1:
10087 // If a member function is attached to the global module and is defined
10088 // in its class definition, it is inline.
10089 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10090 }
10091
10092 if (!isFriend && SC != SC_None) {
10093 // C++ [temp.expl.spec]p2:
10094 // The declaration in an explicit-specialization shall not be an
10095 // export-declaration. An explicit specialization shall not use a
10096 // storage-class-specifier other than thread_local.
10097 //
10098 // We diagnose friend declarations with storage-class-specifiers
10099 // elsewhere.
10100 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10101 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10102 diag::ext_explicit_specialization_storage_class)
10104 D.getDeclSpec().getStorageClassSpecLoc());
10105 }
10106
10107 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10108 assert(isa<CXXMethodDecl>(NewFD) &&
10109 "Out-of-line member function should be a CXXMethodDecl");
10110 // C++ [class.static]p1:
10111 // A data or function member of a class may be declared static
10112 // in a class definition, in which case it is a static member of
10113 // the class.
10114
10115 // Complain about the 'static' specifier if it's on an out-of-line
10116 // member function definition.
10117
10118 // MSVC permits the use of a 'static' storage specifier on an
10119 // out-of-line member function template declaration and class member
10120 // template declaration (MSVC versions before 2015), warn about this.
10121 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10122 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10123 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10124 (getLangOpts().MSVCCompat &&
10126 ? diag::ext_static_out_of_line
10127 : diag::err_static_out_of_line)
10129 D.getDeclSpec().getStorageClassSpecLoc());
10130 }
10131 }
10132
10133 // C++11 [except.spec]p15:
10134 // A deallocation function with no exception-specification is treated
10135 // as if it were specified with noexcept(true).
10136 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10137 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10138 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10139 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10141 FPT->getReturnType(), FPT->getParamTypes(),
10143
10144 // C++20 [dcl.inline]/7
10145 // If an inline function or variable that is attached to a named module
10146 // is declared in a definition domain, it shall be defined in that
10147 // domain.
10148 // So, if the current declaration does not have a definition, we must
10149 // check at the end of the TU (or when the PMF starts) to see that we
10150 // have a definition at that point.
10151 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10152 NewFD->isInNamedModule()) {
10153 PendingInlineFuncDecls.insert(NewFD);
10154 }
10155 }
10156
10157 // Filter out previous declarations that don't match the scope.
10159 D.getCXXScopeSpec().isNotEmpty() ||
10160 isMemberSpecialization ||
10161 isFunctionTemplateSpecialization);
10162
10163 // Handle GNU asm-label extension (encoded as an attribute).
10164 if (Expr *E = (Expr*) D.getAsmLabel()) {
10165 // The parser guarantees this is a string.
10166 StringLiteral *SE = cast<StringLiteral>(E);
10167 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10168 /*IsLiteralLabel=*/true,
10169 SE->getStrTokenLoc(0)));
10170 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10171 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10173 if (I != ExtnameUndeclaredIdentifiers.end()) {
10174 if (isDeclExternC(NewFD)) {
10175 NewFD->addAttr(I->second);
10177 } else
10178 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10179 << /*Variable*/0 << NewFD;
10180 }
10181 }
10182
10183 // Copy the parameter declarations from the declarator D to the function
10184 // declaration NewFD, if they are available. First scavenge them into Params.
10186 unsigned FTIIdx;
10187 if (D.isFunctionDeclarator(FTIIdx)) {
10188 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10189
10190 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10191 // function that takes no arguments, not a function that takes a
10192 // single void argument.
10193 // We let through "const void" here because Sema::GetTypeForDeclarator
10194 // already checks for that case.
10195 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10196 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10197 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10198 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10199 Param->setDeclContext(NewFD);
10200 Params.push_back(Param);
10201
10202 if (Param->isInvalidDecl())
10203 NewFD->setInvalidDecl();
10204 }
10205 }
10206
10207 if (!getLangOpts().CPlusPlus) {
10208 // In C, find all the tag declarations from the prototype and move them
10209 // into the function DeclContext. Remove them from the surrounding tag
10210 // injection context of the function, which is typically but not always
10211 // the TU.
10212 DeclContext *PrototypeTagContext =
10214 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10215 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10216
10217 // We don't want to reparent enumerators. Look at their parent enum
10218 // instead.
10219 if (!TD) {
10220 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10221 TD = cast<EnumDecl>(ECD->getDeclContext());
10222 }
10223 if (!TD)
10224 continue;
10225 DeclContext *TagDC = TD->getLexicalDeclContext();
10226 if (!TagDC->containsDecl(TD))
10227 continue;
10228 TagDC->removeDecl(TD);
10229 TD->setDeclContext(NewFD);
10230 NewFD->addDecl(TD);
10231
10232 // Preserve the lexical DeclContext if it is not the surrounding tag
10233 // injection context of the FD. In this example, the semantic context of
10234 // E will be f and the lexical context will be S, while both the
10235 // semantic and lexical contexts of S will be f:
10236 // void f(struct S { enum E { a } f; } s);
10237 if (TagDC != PrototypeTagContext)
10238 TD->setLexicalDeclContext(TagDC);
10239 }
10240 }
10241 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10242 // When we're declaring a function with a typedef, typeof, etc as in the
10243 // following example, we'll need to synthesize (unnamed)
10244 // parameters for use in the declaration.
10245 //
10246 // @code
10247 // typedef void fn(int);
10248 // fn f;
10249 // @endcode
10250
10251 // Synthesize a parameter for each argument type.
10252 for (const auto &AI : FT->param_types()) {
10253 ParmVarDecl *Param =
10254 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10255 Param->setScopeInfo(0, Params.size());
10256 Params.push_back(Param);
10257 }
10258 } else {
10259 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10260 "Should not need args for typedef of non-prototype fn");
10261 }
10262
10263 // Finally, we know we have the right number of parameters, install them.
10264 NewFD->setParams(Params);
10265
10266 if (D.getDeclSpec().isNoreturnSpecified())
10267 NewFD->addAttr(
10268 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10269
10270 // Functions returning a variably modified type violate C99 6.7.5.2p2
10271 // because all functions have linkage.
10272 if (!NewFD->isInvalidDecl() &&
10274 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10275 NewFD->setInvalidDecl();
10276 }
10277
10278 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10279 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10280 !NewFD->hasAttr<SectionAttr>())
10281 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10284
10285 // Apply an implicit SectionAttr if #pragma code_seg is active.
10286 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10287 !NewFD->hasAttr<SectionAttr>()) {
10288 NewFD->addAttr(SectionAttr::CreateImplicit(
10289 Context, CodeSegStack.CurrentValue->getString(),
10290 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10291 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10294 NewFD))
10295 NewFD->dropAttr<SectionAttr>();
10296 }
10297
10298 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10299 // active.
10300 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10301 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10302 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10304
10305 // Apply an implicit CodeSegAttr from class declspec or
10306 // apply an implicit SectionAttr from #pragma code_seg if active.
10307 if (!NewFD->hasAttr<CodeSegAttr>()) {
10309 D.isFunctionDefinition())) {
10310 NewFD->addAttr(SAttr);
10311 }
10312 }
10313
10314 // Handle attributes.
10315 ProcessDeclAttributes(S, NewFD, D);
10316 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10317 if (NewTVA && !NewTVA->isDefaultVersion() &&
10318 !Context.getTargetInfo().hasFeature("fmv")) {
10319 // Don't add to scope fmv functions declarations if fmv disabled
10320 AddToScope = false;
10321 return NewFD;
10322 }
10323
10324 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10325 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10326 // type.
10327 //
10328 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10329 // type declaration will generate a compilation error.
10330 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10331 if (AddressSpace != LangAS::Default) {
10332 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10333 NewFD->setInvalidDecl();
10334 }
10335 }
10336
10337 if (!getLangOpts().CPlusPlus) {
10338 // Perform semantic checking on the function declaration.
10339 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10340 CheckMain(NewFD, D.getDeclSpec());
10341
10342 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10343 CheckMSVCRTEntryPoint(NewFD);
10344
10345 if (!NewFD->isInvalidDecl())
10346 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10347 isMemberSpecialization,
10348 D.isFunctionDefinition()));
10349 else if (!Previous.empty())
10350 // Recover gracefully from an invalid redeclaration.
10351 D.setRedeclaration(true);
10352 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10353 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10354 "previous declaration set still overloaded");
10355
10356 // Diagnose no-prototype function declarations with calling conventions that
10357 // don't support variadic calls. Only do this in C and do it after merging
10358 // possibly prototyped redeclarations.
10359 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10360 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10361 CallingConv CC = FT->getExtInfo().getCC();
10362 if (!supportsVariadicCall(CC)) {
10363 // Windows system headers sometimes accidentally use stdcall without
10364 // (void) parameters, so we relax this to a warning.
10365 int DiagID =
10366 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10367 Diag(NewFD->getLocation(), DiagID)
10369 }
10370 }
10371
10377 } else {
10378 // C++11 [replacement.functions]p3:
10379 // The program's definitions shall not be specified as inline.
10380 //
10381 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10382 //
10383 // Suppress the diagnostic if the function is __attribute__((used)), since
10384 // that forces an external definition to be emitted.
10385 if (D.getDeclSpec().isInlineSpecified() &&
10387 !NewFD->hasAttr<UsedAttr>())
10388 Diag(D.getDeclSpec().getInlineSpecLoc(),
10389 diag::ext_operator_new_delete_declared_inline)
10390 << NewFD->getDeclName();
10391
10392 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10393 // C++20 [dcl.decl.general]p4:
10394 // The optional requires-clause in an init-declarator or
10395 // member-declarator shall be present only if the declarator declares a
10396 // templated function.
10397 //
10398 // C++20 [temp.pre]p8:
10399 // An entity is templated if it is
10400 // - a template,
10401 // - an entity defined or created in a templated entity,
10402 // - a member of a templated entity,
10403 // - an enumerator for an enumeration that is a templated entity, or
10404 // - the closure type of a lambda-expression appearing in the
10405 // declaration of a templated entity.
10406 //
10407 // [Note 6: A local class, a local or block variable, or a friend
10408 // function defined in a templated entity is a templated entity.
10409 // — end note]
10410 //
10411 // A templated function is a function template or a function that is
10412 // templated. A templated class is a class template or a class that is
10413 // templated. A templated variable is a variable template or a variable
10414 // that is templated.
10415 if (!FunctionTemplate) {
10416 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10417 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10418 // An explicit specialization shall not have a trailing
10419 // requires-clause unless it declares a function template.
10420 //
10421 // Since a friend function template specialization cannot be
10422 // definition, and since a non-template friend declaration with a
10423 // trailing requires-clause must be a definition, we diagnose
10424 // friend function template specializations with trailing
10425 // requires-clauses on the same path as explicit specializations
10426 // even though they aren't necessarily prohibited by the same
10427 // language rule.
10428 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10429 << isFriend;
10430 } else if (isFriend && NewFD->isTemplated() &&
10431 !D.isFunctionDefinition()) {
10432 // C++ [temp.friend]p9:
10433 // A non-template friend declaration with a requires-clause shall be
10434 // a definition.
10435 Diag(NewFD->getBeginLoc(),
10436 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10437 NewFD->setInvalidDecl();
10438 } else if (!NewFD->isTemplated() ||
10439 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10440 Diag(TRC->getBeginLoc(),
10441 diag::err_constrained_non_templated_function);
10442 }
10443 }
10444 }
10445
10446 // We do not add HD attributes to specializations here because
10447 // they may have different constexpr-ness compared to their
10448 // templates and, after maybeAddHostDeviceAttrs() is applied,
10449 // may end up with different effective targets. Instead, a
10450 // specialization inherits its target attributes from its template
10451 // in the CheckFunctionTemplateSpecialization() call below.
10452 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10454
10455 // Handle explicit specializations of function templates
10456 // and friend function declarations with an explicit
10457 // template argument list.
10458 if (isFunctionTemplateSpecialization) {
10459 bool isDependentSpecialization = false;
10460 if (isFriend) {
10461 // For friend function specializations, this is a dependent
10462 // specialization if its semantic context is dependent, its
10463 // type is dependent, or if its template-id is dependent.
10464 isDependentSpecialization =
10465 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10466 (HasExplicitTemplateArgs &&
10469 TemplateArgs.arguments()));
10470 assert((!isDependentSpecialization ||
10471 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10472 "dependent friend function specialization without template "
10473 "args");
10474 } else {
10475 // For class-scope explicit specializations of function templates,
10476 // if the lexical context is dependent, then the specialization
10477 // is dependent.
10478 isDependentSpecialization =
10480 }
10481
10482 TemplateArgumentListInfo *ExplicitTemplateArgs =
10483 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10484 if (isDependentSpecialization) {
10485 // If it's a dependent specialization, it may not be possible
10486 // to determine the primary template (for explicit specializations)
10487 // or befriended declaration (for friends) until the enclosing
10488 // template is instantiated. In such cases, we store the declarations
10489 // found by name lookup and defer resolution until instantiation.
10491 NewFD, ExplicitTemplateArgs, Previous))
10492 NewFD->setInvalidDecl();
10493 } else if (!NewFD->isInvalidDecl()) {
10494 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10495 Previous))
10496 NewFD->setInvalidDecl();
10497 }
10498 } else if (isMemberSpecialization && !FunctionTemplate) {
10500 NewFD->setInvalidDecl();
10501 }
10502
10503 // Perform semantic checking on the function declaration.
10504 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10505 CheckMain(NewFD, D.getDeclSpec());
10506
10507 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10508 CheckMSVCRTEntryPoint(NewFD);
10509
10510 if (!NewFD->isInvalidDecl())
10511 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10512 isMemberSpecialization,
10513 D.isFunctionDefinition()));
10514 else if (!Previous.empty())
10515 // Recover gracefully from an invalid redeclaration.
10516 D.setRedeclaration(true);
10517
10518 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10519 !D.isRedeclaration() ||
10520 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10521 "previous declaration set still overloaded");
10522
10523 NamedDecl *PrincipalDecl = (FunctionTemplate
10524 ? cast<NamedDecl>(FunctionTemplate)
10525 : NewFD);
10526
10527 if (isFriend && NewFD->getPreviousDecl()) {
10528 AccessSpecifier Access = AS_public;
10529 if (!NewFD->isInvalidDecl())
10530 Access = NewFD->getPreviousDecl()->getAccess();
10531
10532 NewFD->setAccess(Access);
10533 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10534 }
10535
10536 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10538 PrincipalDecl->setNonMemberOperator();
10539
10540 // If we have a function template, check the template parameter
10541 // list. This will check and merge default template arguments.
10542 if (FunctionTemplate) {
10543 FunctionTemplateDecl *PrevTemplate =
10544 FunctionTemplate->getPreviousDecl();
10545 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10546 PrevTemplate ? PrevTemplate->getTemplateParameters()
10547 : nullptr,
10548 D.getDeclSpec().isFriendSpecified()
10549 ? (D.isFunctionDefinition()
10552 : (D.getCXXScopeSpec().isSet() &&
10553 DC && DC->isRecord() &&
10554 DC->isDependentContext())
10557 }
10558
10559 if (NewFD->isInvalidDecl()) {
10560 // Ignore all the rest of this.
10561 } else if (!D.isRedeclaration()) {
10562 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10563 AddToScope };
10564 // Fake up an access specifier if it's supposed to be a class member.
10565 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10566 NewFD->setAccess(AS_public);
10567
10568 // Qualified decls generally require a previous declaration.
10569 if (D.getCXXScopeSpec().isSet()) {
10570 // ...with the major exception of templated-scope or
10571 // dependent-scope friend declarations.
10572
10573 // TODO: we currently also suppress this check in dependent
10574 // contexts because (1) the parameter depth will be off when
10575 // matching friend templates and (2) we might actually be
10576 // selecting a friend based on a dependent factor. But there
10577 // are situations where these conditions don't apply and we
10578 // can actually do this check immediately.
10579 //
10580 // Unless the scope is dependent, it's always an error if qualified
10581 // redeclaration lookup found nothing at all. Diagnose that now;
10582 // nothing will diagnose that error later.
10583 if (isFriend &&
10584 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10585 (!Previous.empty() && CurContext->isDependentContext()))) {
10586 // ignore these
10587 } else if (NewFD->isCPUDispatchMultiVersion() ||
10588 NewFD->isCPUSpecificMultiVersion()) {
10589 // ignore this, we allow the redeclaration behavior here to create new
10590 // versions of the function.
10591 } else {
10592 // The user tried to provide an out-of-line definition for a
10593 // function that is a member of a class or namespace, but there
10594 // was no such member function declared (C++ [class.mfct]p2,
10595 // C++ [namespace.memdef]p2). For example:
10596 //
10597 // class X {
10598 // void f() const;
10599 // };
10600 //
10601 // void X::f() { } // ill-formed
10602 //
10603 // Complain about this problem, and attempt to suggest close
10604 // matches (e.g., those that differ only in cv-qualifiers and
10605 // whether the parameter types are references).
10606
10608 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10609 AddToScope = ExtraArgs.AddToScope;
10610 return Result;
10611 }
10612 }
10613
10614 // Unqualified local friend declarations are required to resolve
10615 // to something.
10616 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10618 *this, Previous, NewFD, ExtraArgs, true, S)) {
10619 AddToScope = ExtraArgs.AddToScope;
10620 return Result;
10621 }
10622 }
10623 } else if (!D.isFunctionDefinition() &&
10624 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10625 !isFriend && !isFunctionTemplateSpecialization &&
10626 !isMemberSpecialization) {
10627 // An out-of-line member function declaration must also be a
10628 // definition (C++ [class.mfct]p2).
10629 // Note that this is not the case for explicit specializations of
10630 // function templates or member functions of class templates, per
10631 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10632 // extension for compatibility with old SWIG code which likes to
10633 // generate them.
10634 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10635 << D.getCXXScopeSpec().getRange();
10636 }
10637 }
10638
10639 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10640 // Any top level function could potentially be specified as an entry.
10641 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10642 HLSL().ActOnTopLevelFunction(NewFD);
10643
10644 if (NewFD->hasAttr<HLSLShaderAttr>())
10645 HLSL().CheckEntryPoint(NewFD);
10646 }
10647
10648 // If this is the first declaration of a library builtin function, add
10649 // attributes as appropriate.
10650 if (!D.isRedeclaration()) {
10651 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10652 if (unsigned BuiltinID = II->getBuiltinID()) {
10653 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10654 if (!InStdNamespace &&
10656 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10657 // Validate the type matches unless this builtin is specified as
10658 // matching regardless of its declared type.
10659 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10660 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10661 } else {
10663 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10664 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10665
10666 if (!Error && !BuiltinType.isNull() &&
10668 NewFD->getType(), BuiltinType))
10669 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10670 }
10671 }
10672 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10673 isStdBuiltin(Context, NewFD, BuiltinID)) {
10674 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10675 }
10676 }
10677 }
10678 }
10679
10680 ProcessPragmaWeak(S, NewFD);
10681 checkAttributesAfterMerging(*this, *NewFD);
10682
10684
10685 if (NewFD->hasAttr<OverloadableAttr>() &&
10686 !NewFD->getType()->getAs<FunctionProtoType>()) {
10687 Diag(NewFD->getLocation(),
10688 diag::err_attribute_overloadable_no_prototype)
10689 << NewFD;
10690 NewFD->dropAttr<OverloadableAttr>();
10691 }
10692
10693 // If there's a #pragma GCC visibility in scope, and this isn't a class
10694 // member, set the visibility of this function.
10695 if (!DC->isRecord() && NewFD->isExternallyVisible())
10697
10698 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10699 // marking the function.
10700 ObjC().AddCFAuditedAttribute(NewFD);
10701
10702 // If this is a function definition, check if we have to apply any
10703 // attributes (i.e. optnone and no_builtin) due to a pragma.
10704 if (D.isFunctionDefinition()) {
10705 AddRangeBasedOptnone(NewFD);
10707 AddSectionMSAllocText(NewFD);
10709 }
10710
10711 // If this is the first declaration of an extern C variable, update
10712 // the map of such variables.
10713 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10714 isIncompleteDeclExternC(*this, NewFD))
10716
10717 // Set this FunctionDecl's range up to the right paren.
10718 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10719
10720 if (D.isRedeclaration() && !Previous.empty()) {
10721 NamedDecl *Prev = Previous.getRepresentativeDecl();
10722 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10723 isMemberSpecialization ||
10724 isFunctionTemplateSpecialization,
10725 D.isFunctionDefinition());
10726 }
10727
10728 if (getLangOpts().CUDA) {
10729 IdentifierInfo *II = NewFD->getIdentifier();
10730 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10731 !NewFD->isInvalidDecl() &&
10734 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10737 }
10738
10739 // Variadic functions, other than a *declaration* of printf, are not allowed
10740 // in device-side CUDA code, unless someone passed
10741 // -fcuda-allow-variadic-functions.
10742 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10743 (NewFD->hasAttr<CUDADeviceAttr>() ||
10744 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10745 !(II && II->isStr("printf") && NewFD->isExternC() &&
10746 !D.isFunctionDefinition())) {
10747 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10748 }
10749 }
10750
10752
10753
10754
10755 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10756 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10757 if (SC == SC_Static) {
10758 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10759 D.setInvalidType();
10760 }
10761
10762 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10763 if (!NewFD->getReturnType()->isVoidType()) {
10764 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10765 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10766 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10767 : FixItHint());
10768 D.setInvalidType();
10769 }
10770
10772 for (auto *Param : NewFD->parameters())
10773 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10774
10775 if (getLangOpts().OpenCLCPlusPlus) {
10776 if (DC->isRecord()) {
10777 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10778 D.setInvalidType();
10779 }
10780 if (FunctionTemplate) {
10781 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10782 D.setInvalidType();
10783 }
10784 }
10785 }
10786
10787 if (getLangOpts().CPlusPlus) {
10788 // Precalculate whether this is a friend function template with a constraint
10789 // that depends on an enclosing template, per [temp.friend]p9.
10790 if (isFriend && FunctionTemplate &&
10793
10794 // C++ [temp.friend]p9:
10795 // A friend function template with a constraint that depends on a
10796 // template parameter from an enclosing template shall be a definition.
10797 if (!D.isFunctionDefinition()) {
10798 Diag(NewFD->getBeginLoc(),
10799 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10800 NewFD->setInvalidDecl();
10801 }
10802 }
10803
10804 if (FunctionTemplate) {
10805 if (NewFD->isInvalidDecl())
10806 FunctionTemplate->setInvalidDecl();
10807 return FunctionTemplate;
10808 }
10809
10810 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10812 }
10813
10814 for (const ParmVarDecl *Param : NewFD->parameters()) {
10815 QualType PT = Param->getType();
10816
10817 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10818 // types.
10819 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10820 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10821 QualType ElemTy = PipeTy->getElementType();
10822 if (ElemTy->isPointerOrReferenceType()) {
10823 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
10824 D.setInvalidType();
10825 }
10826 }
10827 }
10828 // WebAssembly tables can't be used as function parameters.
10829 if (Context.getTargetInfo().getTriple().isWasm()) {
10831 Diag(Param->getTypeSpecStartLoc(),
10832 diag::err_wasm_table_as_function_parameter);
10833 D.setInvalidType();
10834 }
10835 }
10836 }
10837
10838 // Diagnose availability attributes. Availability cannot be used on functions
10839 // that are run during load/unload.
10840 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10841 if (NewFD->hasAttr<ConstructorAttr>()) {
10842 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10843 << 1;
10844 NewFD->dropAttr<AvailabilityAttr>();
10845 }
10846 if (NewFD->hasAttr<DestructorAttr>()) {
10847 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10848 << 2;
10849 NewFD->dropAttr<AvailabilityAttr>();
10850 }
10851 }
10852
10853 // Diagnose no_builtin attribute on function declaration that are not a
10854 // definition.
10855 // FIXME: We should really be doing this in
10856 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10857 // the FunctionDecl and at this point of the code
10858 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10859 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10860 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10861 switch (D.getFunctionDefinitionKind()) {
10864 Diag(NBA->getLocation(),
10865 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10866 << NBA->getSpelling();
10867 break;
10869 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10870 << NBA->getSpelling();
10871 break;
10873 break;
10874 }
10875
10876 // Similar to no_builtin logic above, at this point of the code
10877 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
10878 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10880 !NewFD->isInvalidDecl() &&
10881 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
10882 ExternalDeclarations.push_back(NewFD);
10883
10884 return NewFD;
10885}
10886
10887/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10888/// when __declspec(code_seg) "is applied to a class, all member functions of
10889/// the class and nested classes -- this includes compiler-generated special
10890/// member functions -- are put in the specified segment."
10891/// The actual behavior is a little more complicated. The Microsoft compiler
10892/// won't check outer classes if there is an active value from #pragma code_seg.
10893/// The CodeSeg is always applied from the direct parent but only from outer
10894/// classes when the #pragma code_seg stack is empty. See:
10895/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10896/// available since MS has removed the page.
10898 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10899 if (!Method)
10900 return nullptr;
10901 const CXXRecordDecl *Parent = Method->getParent();
10902 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10903 Attr *NewAttr = SAttr->clone(S.getASTContext());
10904 NewAttr->setImplicit(true);
10905 return NewAttr;
10906 }
10907
10908 // The Microsoft compiler won't check outer classes for the CodeSeg
10909 // when the #pragma code_seg stack is active.
10910 if (S.CodeSegStack.CurrentValue)
10911 return nullptr;
10912
10913 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10914 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10915 Attr *NewAttr = SAttr->clone(S.getASTContext());
10916 NewAttr->setImplicit(true);
10917 return NewAttr;
10918 }
10919 }
10920 return nullptr;
10921}
10922
10924 bool IsDefinition) {
10925 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10926 return A;
10927 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10928 CodeSegStack.CurrentValue)
10929 return SectionAttr::CreateImplicit(
10930 getASTContext(), CodeSegStack.CurrentValue->getString(),
10931 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10932 return nullptr;
10933}
10934
10936 QualType NewT, QualType OldT) {
10938 return true;
10939
10940 // For dependently-typed local extern declarations and friends, we can't
10941 // perform a correct type check in general until instantiation:
10942 //
10943 // int f();
10944 // template<typename T> void g() { T f(); }
10945 //
10946 // (valid if g() is only instantiated with T = int).
10947 if (NewT->isDependentType() &&
10948 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10949 return false;
10950
10951 // Similarly, if the previous declaration was a dependent local extern
10952 // declaration, we don't really know its type yet.
10953 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10954 return false;
10955
10956 return true;
10957}
10958
10961 return true;
10962
10963 // Don't chain dependent friend function definitions until instantiation, to
10964 // permit cases like
10965 //
10966 // void func();
10967 // template<typename T> class C1 { friend void func() {} };
10968 // template<typename T> class C2 { friend void func() {} };
10969 //
10970 // ... which is valid if only one of C1 and C2 is ever instantiated.
10971 //
10972 // FIXME: This need only apply to function definitions. For now, we proxy
10973 // this by checking for a file-scope function. We do not want this to apply
10974 // to friend declarations nominating member functions, because that gets in
10975 // the way of access checks.
10977 return false;
10978
10979 auto *VD = dyn_cast<ValueDecl>(D);
10980 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10981 return !VD || !PrevVD ||
10982 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10983 PrevVD->getType());
10984}
10985
10986/// Check the target or target_version attribute of the function for
10987/// MultiVersion validity.
10988///
10989/// Returns true if there was an error, false otherwise.
10990static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10991 const auto *TA = FD->getAttr<TargetAttr>();
10992 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10993 assert(
10994 (TA || TVA) &&
10995 "MultiVersion candidate requires a target or target_version attribute");
10997 enum ErrType { Feature = 0, Architecture = 1 };
10998
10999 if (TA) {
11000 ParsedTargetAttr ParseInfo =
11001 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11002 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11003 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11004 << Architecture << ParseInfo.CPU;
11005 return true;
11006 }
11007 for (const auto &Feat : ParseInfo.Features) {
11008 auto BareFeat = StringRef{Feat}.substr(1);
11009 if (Feat[0] == '-') {
11010 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11011 << Feature << ("no-" + BareFeat).str();
11012 return true;
11013 }
11014
11015 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11016 !TargetInfo.isValidFeatureName(BareFeat)) {
11017 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11018 << Feature << BareFeat;
11019 return true;
11020 }
11021 }
11022 }
11023
11024 if (TVA) {
11026 TVA->getFeatures(Feats);
11027 for (const auto &Feat : Feats) {
11028 if (!TargetInfo.validateCpuSupports(Feat)) {
11029 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11030 << Feature << Feat;
11031 return true;
11032 }
11033 }
11034 }
11035 return false;
11036}
11037
11038// Provide a white-list of attributes that are allowed to be combined with
11039// multiversion functions.
11041 MultiVersionKind MVKind) {
11042 // Note: this list/diagnosis must match the list in
11043 // checkMultiversionAttributesAllSame.
11044 switch (Kind) {
11045 default:
11046 return false;
11047 case attr::ArmLocallyStreaming:
11048 return MVKind == MultiVersionKind::TargetVersion ||
11050 case attr::Used:
11051 return MVKind == MultiVersionKind::Target;
11052 case attr::NonNull:
11053 case attr::NoThrow:
11054 return true;
11055 }
11056}
11057
11059 const FunctionDecl *FD,
11060 const FunctionDecl *CausedFD,
11061 MultiVersionKind MVKind) {
11062 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11063 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11064 << static_cast<unsigned>(MVKind) << A;
11065 if (CausedFD)
11066 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11067 return true;
11068 };
11069
11070 for (const Attr *A : FD->attrs()) {
11071 switch (A->getKind()) {
11072 case attr::CPUDispatch:
11073 case attr::CPUSpecific:
11074 if (MVKind != MultiVersionKind::CPUDispatch &&
11076 return Diagnose(S, A);
11077 break;
11078 case attr::Target:
11079 if (MVKind != MultiVersionKind::Target)
11080 return Diagnose(S, A);
11081 break;
11082 case attr::TargetVersion:
11083 if (MVKind != MultiVersionKind::TargetVersion &&
11085 return Diagnose(S, A);
11086 break;
11087 case attr::TargetClones:
11088 if (MVKind != MultiVersionKind::TargetClones &&
11090 return Diagnose(S, A);
11091 break;
11092 default:
11093 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11094 return Diagnose(S, A);
11095 break;
11096 }
11097 }
11098 return false;
11099}
11100
11102 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11103 const PartialDiagnostic &NoProtoDiagID,
11104 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11105 const PartialDiagnosticAt &NoSupportDiagIDAt,
11106 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11107 bool ConstexprSupported, bool CLinkageMayDiffer) {
11108 enum DoesntSupport {
11109 FuncTemplates = 0,
11110 VirtFuncs = 1,
11111 DeducedReturn = 2,
11112 Constructors = 3,
11113 Destructors = 4,
11114 DeletedFuncs = 5,
11115 DefaultedFuncs = 6,
11116 ConstexprFuncs = 7,
11117 ConstevalFuncs = 8,
11118 Lambda = 9,
11119 };
11120 enum Different {
11121 CallingConv = 0,
11122 ReturnType = 1,
11123 ConstexprSpec = 2,
11124 InlineSpec = 3,
11125 Linkage = 4,
11126 LanguageLinkage = 5,
11127 };
11128
11129 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11130 !OldFD->getType()->getAs<FunctionProtoType>()) {
11131 Diag(OldFD->getLocation(), NoProtoDiagID);
11132 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11133 return true;
11134 }
11135
11136 if (NoProtoDiagID.getDiagID() != 0 &&
11137 !NewFD->getType()->getAs<FunctionProtoType>())
11138 return Diag(NewFD->getLocation(), NoProtoDiagID);
11139
11140 if (!TemplatesSupported &&
11142 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11143 << FuncTemplates;
11144
11145 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11146 if (NewCXXFD->isVirtual())
11147 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11148 << VirtFuncs;
11149
11150 if (isa<CXXConstructorDecl>(NewCXXFD))
11151 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11152 << Constructors;
11153
11154 if (isa<CXXDestructorDecl>(NewCXXFD))
11155 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11156 << Destructors;
11157 }
11158
11159 if (NewFD->isDeleted())
11160 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11161 << DeletedFuncs;
11162
11163 if (NewFD->isDefaulted())
11164 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11165 << DefaultedFuncs;
11166
11167 if (!ConstexprSupported && NewFD->isConstexpr())
11168 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11169 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11170
11171 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11172 const auto *NewType = cast<FunctionType>(NewQType);
11173 QualType NewReturnType = NewType->getReturnType();
11174
11175 if (NewReturnType->isUndeducedType())
11176 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11177 << DeducedReturn;
11178
11179 // Ensure the return type is identical.
11180 if (OldFD) {
11181 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11182 const auto *OldType = cast<FunctionType>(OldQType);
11183 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11184 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11185
11186 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11187 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11188
11189 bool ArmStreamingCCMismatched = false;
11190 if (OldFPT && NewFPT) {
11191 unsigned Diff =
11193 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11194 // cannot be mixed.
11197 ArmStreamingCCMismatched = true;
11198 }
11199
11200 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11201 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11202
11203 QualType OldReturnType = OldType->getReturnType();
11204
11205 if (OldReturnType != NewReturnType)
11206 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11207
11208 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11209 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11210
11211 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11212 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11213
11214 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11215 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11216
11217 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11218 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11219
11220 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11221 NewFD->getLocation()))
11222 return true;
11223 }
11224 return false;
11225}
11226
11228 const FunctionDecl *NewFD,
11229 bool CausesMV,
11230 MultiVersionKind MVKind) {
11232 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11233 if (OldFD)
11234 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11235 return true;
11236 }
11237
11238 bool IsCPUSpecificCPUDispatchMVKind =
11241
11242 if (CausesMV && OldFD &&
11243 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11244 return true;
11245
11246 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11247 return true;
11248
11249 // Only allow transition to MultiVersion if it hasn't been used.
11250 if (OldFD && CausesMV && OldFD->isUsed(false))
11251 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11252
11254 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11256 S.PDiag(diag::note_multiversioning_caused_here)),
11258 S.PDiag(diag::err_multiversion_doesnt_support)
11259 << static_cast<unsigned>(MVKind)),
11261 S.PDiag(diag::err_multiversion_diff)),
11262 /*TemplatesSupported=*/false,
11263 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11264 /*CLinkageMayDiffer=*/false);
11265}
11266
11267/// Check the validity of a multiversion function declaration that is the
11268/// first of its kind. Also sets the multiversion'ness' of the function itself.
11269///
11270/// This sets NewFD->isInvalidDecl() to true if there was an error.
11271///
11272/// Returns true if there was an error, false otherwise.
11275 assert(MVKind != MultiVersionKind::None &&
11276 "Function lacks multiversion attribute");
11277 const auto *TA = FD->getAttr<TargetAttr>();
11278 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11279 // The target attribute only causes MV if this declaration is the default,
11280 // otherwise it is treated as a normal function.
11281 if (TA && !TA->isDefaultVersion())
11282 return false;
11283 // The target_version attribute only causes Multiversioning if this
11284 // declaration is NOT the default version.
11285 if (TVA && TVA->isDefaultVersion())
11286 return false;
11287
11288 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11289 FD->setInvalidDecl();
11290 return true;
11291 }
11292
11293 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11294 FD->setInvalidDecl();
11295 return true;
11296 }
11297
11298 FD->setIsMultiVersion();
11299 return false;
11300}
11301
11303 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11305 return true;
11306 }
11307
11308 return false;
11309}
11310
11312 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11313 return;
11314
11315 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11316 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11317
11318 if (MVKindTo == MultiVersionKind::None &&
11319 (MVKindFrom == MultiVersionKind::TargetVersion ||
11320 MVKindFrom == MultiVersionKind::TargetClones))
11321 To->addAttr(TargetVersionAttr::CreateImplicit(
11322 To->getASTContext(), "default", To->getSourceRange()));
11323}
11324
11326 FunctionDecl *NewFD,
11327 bool &Redeclaration,
11328 NamedDecl *&OldDecl,
11330 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11331
11332 // The definitions should be allowed in any order. If we have discovered
11333 // a new target version and the preceeding was the default, then add the
11334 // corresponding attribute to it.
11335 patchDefaultTargetVersion(NewFD, OldFD);
11336
11337 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11338 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11339 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11340
11341 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11342 // to change, this is a simple redeclaration.
11343 if (NewTA && !NewTA->isDefaultVersion() &&
11344 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11345 return false;
11346
11347 // The target_version attribute only causes Multiversioning if this
11348 // declaration is NOT the default version.
11349 if (NewTVA && NewTVA->isDefaultVersion())
11350 return false;
11351
11352 // Otherwise, this decl causes MultiVersioning.
11353 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11356 NewFD->setInvalidDecl();
11357 return true;
11358 }
11359
11360 if (CheckMultiVersionValue(S, NewFD)) {
11361 NewFD->setInvalidDecl();
11362 return true;
11363 }
11364
11365 // If this is 'default', permit the forward declaration.
11366 if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
11367 Redeclaration = true;
11368 OldDecl = OldFD;
11369 OldFD->setIsMultiVersion();
11370 NewFD->setIsMultiVersion();
11371 return false;
11372 }
11373
11374 if (CheckMultiVersionValue(S, OldFD)) {
11375 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11376 NewFD->setInvalidDecl();
11377 return true;
11378 }
11379
11380 if (NewTA) {
11381 ParsedTargetAttr OldParsed =
11383 OldTA->getFeaturesStr());
11384 llvm::sort(OldParsed.Features);
11385 ParsedTargetAttr NewParsed =
11387 NewTA->getFeaturesStr());
11388 // Sort order doesn't matter, it just needs to be consistent.
11389 llvm::sort(NewParsed.Features);
11390 if (OldParsed == NewParsed) {
11391 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11392 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11393 NewFD->setInvalidDecl();
11394 return true;
11395 }
11396 }
11397
11398 for (const auto *FD : OldFD->redecls()) {
11399 const auto *CurTA = FD->getAttr<TargetAttr>();
11400 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11401 // We allow forward declarations before ANY multiversioning attributes, but
11402 // nothing after the fact.
11404 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11405 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11406 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11407 << (NewTA ? 0 : 2);
11408 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11409 NewFD->setInvalidDecl();
11410 return true;
11411 }
11412 }
11413
11414 OldFD->setIsMultiVersion();
11415 NewFD->setIsMultiVersion();
11416 Redeclaration = false;
11417 OldDecl = nullptr;
11418 Previous.clear();
11419 return false;
11420}
11421
11423 MultiVersionKind OldKind = Old->getMultiVersionKind();
11424 MultiVersionKind NewKind = New->getMultiVersionKind();
11425
11426 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11427 NewKind == MultiVersionKind::None)
11428 return true;
11429
11430 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11431 switch (OldKind) {
11433 return NewKind == MultiVersionKind::TargetClones;
11435 return NewKind == MultiVersionKind::TargetVersion;
11436 default:
11437 return false;
11438 }
11439 } else {
11440 switch (OldKind) {
11442 return NewKind == MultiVersionKind::CPUSpecific;
11444 return NewKind == MultiVersionKind::CPUDispatch;
11445 default:
11446 return false;
11447 }
11448 }
11449}
11450
11451/// Check the validity of a new function declaration being added to an existing
11452/// multiversioned declaration collection.
11454 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11455 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11456 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11458
11459 // Disallow mixing of multiversioning types.
11460 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11461 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11462 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11463 NewFD->setInvalidDecl();
11464 return true;
11465 }
11466
11467 // Add the default target_version attribute if it's missing.
11468 patchDefaultTargetVersion(OldFD, NewFD);
11469 patchDefaultTargetVersion(NewFD, OldFD);
11470
11471 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11472 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11473 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11474 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11475
11476 ParsedTargetAttr NewParsed;
11477 if (NewTA) {
11479 NewTA->getFeaturesStr());
11480 llvm::sort(NewParsed.Features);
11481 }
11483 if (NewTVA) {
11484 NewTVA->getFeatures(NewFeats);
11485 llvm::sort(NewFeats);
11486 }
11487
11488 bool UseMemberUsingDeclRules =
11489 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11490
11491 bool MayNeedOverloadableChecks =
11493
11494 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11495 // of a previous member of the MultiVersion set.
11496 for (NamedDecl *ND : Previous) {
11497 FunctionDecl *CurFD = ND->getAsFunction();
11498 if (!CurFD || CurFD->isInvalidDecl())
11499 continue;
11500 if (MayNeedOverloadableChecks &&
11501 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11502 continue;
11503
11504 switch (NewMVKind) {
11506 assert(OldMVKind == MultiVersionKind::TargetClones &&
11507 "Only target_clones can be omitted in subsequent declarations");
11508 break;
11510 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11511 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11512 NewFD->setIsMultiVersion();
11513 Redeclaration = true;
11514 OldDecl = ND;
11515 return false;
11516 }
11517
11518 ParsedTargetAttr CurParsed =
11520 CurTA->getFeaturesStr());
11521 llvm::sort(CurParsed.Features);
11522 if (CurParsed == NewParsed) {
11523 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11524 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11525 NewFD->setInvalidDecl();
11526 return true;
11527 }
11528 break;
11529 }
11531 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11532 if (CurTVA->getName() == NewTVA->getName()) {
11533 NewFD->setIsMultiVersion();
11534 Redeclaration = true;
11535 OldDecl = ND;
11536 return false;
11537 }
11539 CurTVA->getFeatures(CurFeats);
11540 llvm::sort(CurFeats);
11541
11542 if (CurFeats == NewFeats) {
11543 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11544 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11545 NewFD->setInvalidDecl();
11546 return true;
11547 }
11548 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11549 // Default
11550 if (NewFeats.empty())
11551 break;
11552
11553 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11555 CurClones->getFeatures(CurFeats, I);
11556 llvm::sort(CurFeats);
11557
11558 if (CurFeats == NewFeats) {
11559 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11560 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11561 NewFD->setInvalidDecl();
11562 return true;
11563 }
11564 }
11565 }
11566 break;
11567 }
11569 assert(NewClones && "MultiVersionKind does not match attribute type");
11570 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11571 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11572 !std::equal(CurClones->featuresStrs_begin(),
11573 CurClones->featuresStrs_end(),
11574 NewClones->featuresStrs_begin())) {
11575 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11576 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11577 NewFD->setInvalidDecl();
11578 return true;
11579 }
11580 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11582 CurTVA->getFeatures(CurFeats);
11583 llvm::sort(CurFeats);
11584
11585 // Default
11586 if (CurFeats.empty())
11587 break;
11588
11589 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11590 NewFeats.clear();
11591 NewClones->getFeatures(NewFeats, I);
11592 llvm::sort(NewFeats);
11593
11594 if (CurFeats == NewFeats) {
11595 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11596 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11597 NewFD->setInvalidDecl();
11598 return true;
11599 }
11600 }
11601 break;
11602 }
11603 Redeclaration = true;
11604 OldDecl = CurFD;
11605 NewFD->setIsMultiVersion();
11606 return false;
11607 }
11610 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11611 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11612 // Handle CPUDispatch/CPUSpecific versions.
11613 // Only 1 CPUDispatch function is allowed, this will make it go through
11614 // the redeclaration errors.
11615 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11616 CurFD->hasAttr<CPUDispatchAttr>()) {
11617 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11618 std::equal(
11619 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11620 NewCPUDisp->cpus_begin(),
11621 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11622 return Cur->getName() == New->getName();
11623 })) {
11624 NewFD->setIsMultiVersion();
11625 Redeclaration = true;
11626 OldDecl = ND;
11627 return false;
11628 }
11629
11630 // If the declarations don't match, this is an error condition.
11631 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11632 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11633 NewFD->setInvalidDecl();
11634 return true;
11635 }
11636 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11637 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11638 std::equal(
11639 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11640 NewCPUSpec->cpus_begin(),
11641 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11642 return Cur->getName() == New->getName();
11643 })) {
11644 NewFD->setIsMultiVersion();
11645 Redeclaration = true;
11646 OldDecl = ND;
11647 return false;
11648 }
11649
11650 // Only 1 version of CPUSpecific is allowed for each CPU.
11651 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11652 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11653 if (CurII == NewII) {
11654 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11655 << NewII;
11656 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11657 NewFD->setInvalidDecl();
11658 return true;
11659 }
11660 }
11661 }
11662 }
11663 break;
11664 }
11665 }
11666 }
11667
11668 // Else, this is simply a non-redecl case. Checking the 'value' is only
11669 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11670 // handled in the attribute adding step.
11671 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11672 NewMVKind == MultiVersionKind::Target) &&
11673 CheckMultiVersionValue(S, NewFD)) {
11674 NewFD->setInvalidDecl();
11675 return true;
11676 }
11677
11678 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11679 !OldFD->isMultiVersion(), NewMVKind)) {
11680 NewFD->setInvalidDecl();
11681 return true;
11682 }
11683
11684 // Permit forward declarations in the case where these two are compatible.
11685 if (!OldFD->isMultiVersion()) {
11686 OldFD->setIsMultiVersion();
11687 NewFD->setIsMultiVersion();
11688 Redeclaration = true;
11689 OldDecl = OldFD;
11690 return false;
11691 }
11692
11693 NewFD->setIsMultiVersion();
11694 Redeclaration = false;
11695 OldDecl = nullptr;
11696 Previous.clear();
11697 return false;
11698}
11699
11700/// Check the validity of a mulitversion function declaration.
11701/// Also sets the multiversion'ness' of the function itself.
11702///
11703/// This sets NewFD->isInvalidDecl() to true if there was an error.
11704///
11705/// Returns true if there was an error, false otherwise.
11707 bool &Redeclaration, NamedDecl *&OldDecl,
11709 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11710 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11711 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11712 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11713 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11714 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11715
11716 // Main isn't allowed to become a multiversion function, however it IS
11717 // permitted to have 'main' be marked with the 'target' optimization hint,
11718 // for 'target_version' only default is allowed.
11719 if (NewFD->isMain()) {
11720 if (MVKind != MultiVersionKind::None &&
11721 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11722 !(MVKind == MultiVersionKind::TargetVersion &&
11723 NewTVA->isDefaultVersion())) {
11724 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11725 NewFD->setInvalidDecl();
11726 return true;
11727 }
11728 return false;
11729 }
11730
11731 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11732
11733 // Target attribute on AArch64 is not used for multiversioning
11734 if (NewTA && T.isAArch64())
11735 return false;
11736
11737 // Target attribute on RISCV is not used for multiversioning
11738 if (NewTA && T.isRISCV())
11739 return false;
11740
11741 if (!OldDecl || !OldDecl->getAsFunction() ||
11742 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11743 NewFD->getDeclContext()->getRedeclContext())) {
11744 // If there's no previous declaration, AND this isn't attempting to cause
11745 // multiversioning, this isn't an error condition.
11746 if (MVKind == MultiVersionKind::None)
11747 return false;
11748 return CheckMultiVersionFirstFunction(S, NewFD);
11749 }
11750
11751 FunctionDecl *OldFD = OldDecl->getAsFunction();
11752
11753 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11754 return false;
11755
11756 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11757 // for target_clones and target_version.
11758 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11761 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11763 NewFD->setInvalidDecl();
11764 return true;
11765 }
11766
11767 if (!OldFD->isMultiVersion()) {
11768 switch (MVKind) {
11772 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11774 if (OldFD->isUsed(false)) {
11775 NewFD->setInvalidDecl();
11776 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11777 }
11778 OldFD->setIsMultiVersion();
11779 break;
11780
11784 break;
11785 }
11786 }
11787
11788 // At this point, we have a multiversion function decl (in OldFD) AND an
11789 // appropriate attribute in the current function decl. Resolve that these are
11790 // still compatible with previous declarations.
11791 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11792 NewCPUSpec, NewClones, Redeclaration,
11793 OldDecl, Previous);
11794}
11795
11797 bool IsPure = NewFD->hasAttr<PureAttr>();
11798 bool IsConst = NewFD->hasAttr<ConstAttr>();
11799
11800 // If there are no pure or const attributes, there's nothing to check.
11801 if (!IsPure && !IsConst)
11802 return;
11803
11804 // If the function is marked both pure and const, we retain the const
11805 // attribute because it makes stronger guarantees than the pure attribute, and
11806 // we drop the pure attribute explicitly to prevent later confusion about
11807 // semantics.
11808 if (IsPure && IsConst) {
11809 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11810 NewFD->dropAttrs<PureAttr>();
11811 }
11812
11813 // Constructors and destructors are functions which return void, so are
11814 // handled here as well.
11815 if (NewFD->getReturnType()->isVoidType()) {
11816 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11817 << IsConst;
11818 NewFD->dropAttrs<PureAttr, ConstAttr>();
11819 }
11820}
11821
11824 bool IsMemberSpecialization,
11825 bool DeclIsDefn) {
11826 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11827 "Variably modified return types are not handled here");
11828
11829 // Determine whether the type of this function should be merged with
11830 // a previous visible declaration. This never happens for functions in C++,
11831 // and always happens in C if the previous declaration was visible.
11832 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11833 !Previous.isShadowed();
11834
11835 bool Redeclaration = false;
11836 NamedDecl *OldDecl = nullptr;
11837 bool MayNeedOverloadableChecks = false;
11838
11839 // Merge or overload the declaration with an existing declaration of
11840 // the same name, if appropriate.
11841 if (!Previous.empty()) {
11842 // Determine whether NewFD is an overload of PrevDecl or
11843 // a declaration that requires merging. If it's an overload,
11844 // there's no more work to do here; we'll just add the new
11845 // function to the scope.
11847 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11848 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11849 Redeclaration = true;
11850 OldDecl = Candidate;
11851 }
11852 } else {
11853 MayNeedOverloadableChecks = true;
11854 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11855 /*NewIsUsingDecl*/ false)) {
11856 case Ovl_Match:
11857 Redeclaration = true;
11858 break;
11859
11860 case Ovl_NonFunction:
11861 Redeclaration = true;
11862 break;
11863
11864 case Ovl_Overload:
11865 Redeclaration = false;
11866 break;
11867 }
11868 }
11869 }
11870
11871 // Check for a previous extern "C" declaration with this name.
11872 if (!Redeclaration &&
11874 if (!Previous.empty()) {
11875 // This is an extern "C" declaration with the same name as a previous
11876 // declaration, and thus redeclares that entity...
11877 Redeclaration = true;
11878 OldDecl = Previous.getFoundDecl();
11879 MergeTypeWithPrevious = false;
11880
11881 // ... except in the presence of __attribute__((overloadable)).
11882 if (OldDecl->hasAttr<OverloadableAttr>() ||
11883 NewFD->hasAttr<OverloadableAttr>()) {
11884 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11885 MayNeedOverloadableChecks = true;
11886 Redeclaration = false;
11887 OldDecl = nullptr;
11888 }
11889 }
11890 }
11891 }
11892
11893 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11894 return Redeclaration;
11895
11896 // PPC MMA non-pointer types are not allowed as function return types.
11897 if (Context.getTargetInfo().getTriple().isPPC64() &&
11898 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11899 NewFD->setInvalidDecl();
11900 }
11901
11902 CheckConstPureAttributesUsage(*this, NewFD);
11903
11904 // C++ [dcl.spec.auto.general]p12:
11905 // Return type deduction for a templated function with a placeholder in its
11906 // declared type occurs when the definition is instantiated even if the
11907 // function body contains a return statement with a non-type-dependent
11908 // operand.
11909 //
11910 // C++ [temp.dep.expr]p3:
11911 // An id-expression is type-dependent if it is a template-id that is not a
11912 // concept-id and is dependent; or if its terminal name is:
11913 // - [...]
11914 // - associated by name lookup with one or more declarations of member
11915 // functions of a class that is the current instantiation declared with a
11916 // return type that contains a placeholder type,
11917 // - [...]
11918 //
11919 // If this is a templated function with a placeholder in its return type,
11920 // make the placeholder type dependent since it won't be deduced until the
11921 // definition is instantiated. We do this here because it needs to happen
11922 // for implicitly instantiated member functions/member function templates.
11923 if (getLangOpts().CPlusPlus14 &&
11924 (NewFD->isDependentContext() &&
11925 NewFD->getReturnType()->isUndeducedType())) {
11926 const FunctionProtoType *FPT =
11927 NewFD->getType()->castAs<FunctionProtoType>();
11928 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
11929 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
11930 FPT->getExtProtoInfo()));
11931 }
11932
11933 // C++11 [dcl.constexpr]p8:
11934 // A constexpr specifier for a non-static member function that is not
11935 // a constructor declares that member function to be const.
11936 //
11937 // This needs to be delayed until we know whether this is an out-of-line
11938 // definition of a static member function.
11939 //
11940 // This rule is not present in C++1y, so we produce a backwards
11941 // compatibility warning whenever it happens in C++11.
11942 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11943 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11944 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11945 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11946 CXXMethodDecl *OldMD = nullptr;
11947 if (OldDecl)
11948 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11949 if (!OldMD || !OldMD->isStatic()) {
11950 const FunctionProtoType *FPT =
11953 EPI.TypeQuals.addConst();
11955 FPT->getParamTypes(), EPI));
11956
11957 // Warn that we did this, if we're not performing template instantiation.
11958 // In that case, we'll have warned already when the template was defined.
11959 if (!inTemplateInstantiation()) {
11960 SourceLocation AddConstLoc;
11963 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11964
11965 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11966 << FixItHint::CreateInsertion(AddConstLoc, " const");
11967 }
11968 }
11969 }
11970
11971 if (Redeclaration) {
11972 // NewFD and OldDecl represent declarations that need to be
11973 // merged.
11974 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11975 DeclIsDefn)) {
11976 NewFD->setInvalidDecl();
11977 return Redeclaration;
11978 }
11979
11980 Previous.clear();
11981 Previous.addDecl(OldDecl);
11982
11983 if (FunctionTemplateDecl *OldTemplateDecl =
11984 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11985 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11986 FunctionTemplateDecl *NewTemplateDecl
11988 assert(NewTemplateDecl && "Template/non-template mismatch");
11989
11990 // The call to MergeFunctionDecl above may have created some state in
11991 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11992 // can add it as a redeclaration.
11993 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11994
11995 NewFD->setPreviousDeclaration(OldFD);
11996 if (NewFD->isCXXClassMember()) {
11997 NewFD->setAccess(OldTemplateDecl->getAccess());
11998 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11999 }
12000
12001 // If this is an explicit specialization of a member that is a function
12002 // template, mark it as a member specialization.
12003 if (IsMemberSpecialization &&
12004 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12005 NewTemplateDecl->setMemberSpecialization();
12006 assert(OldTemplateDecl->isMemberSpecialization());
12007 // Explicit specializations of a member template do not inherit deleted
12008 // status from the parent member template that they are specializing.
12009 if (OldFD->isDeleted()) {
12010 // FIXME: This assert will not hold in the presence of modules.
12011 assert(OldFD->getCanonicalDecl() == OldFD);
12012 // FIXME: We need an update record for this AST mutation.
12013 OldFD->setDeletedAsWritten(false);
12014 }
12015 }
12016
12017 } else {
12018 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12019 auto *OldFD = cast<FunctionDecl>(OldDecl);
12020 // This needs to happen first so that 'inline' propagates.
12021 NewFD->setPreviousDeclaration(OldFD);
12022 if (NewFD->isCXXClassMember())
12023 NewFD->setAccess(OldFD->getAccess());
12024 }
12025 }
12026 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12027 !NewFD->getAttr<OverloadableAttr>()) {
12028 assert((Previous.empty() ||
12029 llvm::any_of(Previous,
12030 [](const NamedDecl *ND) {
12031 return ND->hasAttr<OverloadableAttr>();
12032 })) &&
12033 "Non-redecls shouldn't happen without overloadable present");
12034
12035 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12036 const auto *FD = dyn_cast<FunctionDecl>(ND);
12037 return FD && !FD->hasAttr<OverloadableAttr>();
12038 });
12039
12040 if (OtherUnmarkedIter != Previous.end()) {
12041 Diag(NewFD->getLocation(),
12042 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12043 Diag((*OtherUnmarkedIter)->getLocation(),
12044 diag::note_attribute_overloadable_prev_overload)
12045 << false;
12046
12047 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12048 }
12049 }
12050
12051 if (LangOpts.OpenMP)
12053
12054 // Semantic checking for this function declaration (in isolation).
12055
12056 if (getLangOpts().CPlusPlus) {
12057 // C++-specific checks.
12058 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12059 CheckConstructor(Constructor);
12060 } else if (CXXDestructorDecl *Destructor =
12061 dyn_cast<CXXDestructorDecl>(NewFD)) {
12062 // We check here for invalid destructor names.
12063 // If we have a friend destructor declaration that is dependent, we can't
12064 // diagnose right away because cases like this are still valid:
12065 // template <class T> struct A { friend T::X::~Y(); };
12066 // struct B { struct Y { ~Y(); }; using X = Y; };
12067 // template struct A<B>;
12069 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12070 CXXRecordDecl *Record = Destructor->getParent();
12072
12074 Context.getCanonicalType(ClassType));
12075 if (NewFD->getDeclName() != Name) {
12076 Diag(NewFD->getLocation(), diag::err_destructor_name);
12077 NewFD->setInvalidDecl();
12078 return Redeclaration;
12079 }
12080 }
12081 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12082 if (auto *TD = Guide->getDescribedFunctionTemplate())
12084
12085 // A deduction guide is not on the list of entities that can be
12086 // explicitly specialized.
12087 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12088 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12089 << /*explicit specialization*/ 1;
12090 }
12091
12092 // Find any virtual functions that this function overrides.
12093 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12094 if (!Method->isFunctionTemplateSpecialization() &&
12095 !Method->getDescribedFunctionTemplate() &&
12096 Method->isCanonicalDecl()) {
12097 AddOverriddenMethods(Method->getParent(), Method);
12098 }
12099 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12100 // C++2a [class.virtual]p6
12101 // A virtual method shall not have a requires-clause.
12103 diag::err_constrained_virtual_method);
12104
12105 if (Method->isStatic())
12107 }
12108
12109 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12110 ActOnConversionDeclarator(Conversion);
12111
12112 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12113 if (NewFD->isOverloadedOperator() &&
12115 NewFD->setInvalidDecl();
12116 return Redeclaration;
12117 }
12118
12119 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12120 if (NewFD->getLiteralIdentifier() &&
12122 NewFD->setInvalidDecl();
12123 return Redeclaration;
12124 }
12125
12126 // In C++, check default arguments now that we have merged decls. Unless
12127 // the lexical context is the class, because in this case this is done
12128 // during delayed parsing anyway.
12129 if (!CurContext->isRecord())
12131
12132 // If this function is declared as being extern "C", then check to see if
12133 // the function returns a UDT (class, struct, or union type) that is not C
12134 // compatible, and if it does, warn the user.
12135 // But, issue any diagnostic on the first declaration only.
12136 if (Previous.empty() && NewFD->isExternC()) {
12137 QualType R = NewFD->getReturnType();
12138 if (R->isIncompleteType() && !R->isVoidType())
12139 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12140 << NewFD << R;
12141 else if (!R.isPODType(Context) && !R->isVoidType() &&
12143 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12144 }
12145
12146 // C++1z [dcl.fct]p6:
12147 // [...] whether the function has a non-throwing exception-specification
12148 // [is] part of the function type
12149 //
12150 // This results in an ABI break between C++14 and C++17 for functions whose
12151 // declared type includes an exception-specification in a parameter or
12152 // return type. (Exception specifications on the function itself are OK in
12153 // most cases, and exception specifications are not permitted in most other
12154 // contexts where they could make it into a mangling.)
12155 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12156 auto HasNoexcept = [&](QualType T) -> bool {
12157 // Strip off declarator chunks that could be between us and a function
12158 // type. We don't need to look far, exception specifications are very
12159 // restricted prior to C++17.
12160 if (auto *RT = T->getAs<ReferenceType>())
12161 T = RT->getPointeeType();
12162 else if (T->isAnyPointerType())
12163 T = T->getPointeeType();
12164 else if (auto *MPT = T->getAs<MemberPointerType>())
12165 T = MPT->getPointeeType();
12166 if (auto *FPT = T->getAs<FunctionProtoType>())
12167 if (FPT->isNothrow())
12168 return true;
12169 return false;
12170 };
12171
12172 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12173 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12174 for (QualType T : FPT->param_types())
12175 AnyNoexcept |= HasNoexcept(T);
12176 if (AnyNoexcept)
12177 Diag(NewFD->getLocation(),
12178 diag::warn_cxx17_compat_exception_spec_in_signature)
12179 << NewFD;
12180 }
12181
12182 if (!Redeclaration && LangOpts.CUDA)
12184 }
12185
12186 // Check if the function definition uses any AArch64 SME features without
12187 // having the '+sme' feature enabled and warn user if sme locally streaming
12188 // function returns or uses arguments with VL-based types.
12189 if (DeclIsDefn) {
12190 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12191 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12192 bool UsesZA = Attr && Attr->isNewZA();
12193 bool UsesZT0 = Attr && Attr->isNewZT0();
12194
12195 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12196 if (NewFD->getReturnType()->isSizelessVectorType())
12197 Diag(NewFD->getLocation(),
12198 diag::warn_sme_locally_streaming_has_vl_args_returns)
12199 << /*IsArg=*/false;
12200 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12201 return P->getOriginalType()->isSizelessVectorType();
12202 }))
12203 Diag(NewFD->getLocation(),
12204 diag::warn_sme_locally_streaming_has_vl_args_returns)
12205 << /*IsArg=*/true;
12206 }
12207 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12208 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12209 UsesSM |=
12215 }
12216
12217 if (UsesSM || UsesZA) {
12218 llvm::StringMap<bool> FeatureMap;
12219 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12220 if (!FeatureMap.contains("sme")) {
12221 if (UsesSM)
12222 Diag(NewFD->getLocation(),
12223 diag::err_sme_definition_using_sm_in_non_sme_target);
12224 else
12225 Diag(NewFD->getLocation(),
12226 diag::err_sme_definition_using_za_in_non_sme_target);
12227 }
12228 }
12229 if (UsesZT0) {
12230 llvm::StringMap<bool> FeatureMap;
12231 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12232 if (!FeatureMap.contains("sme2")) {
12233 Diag(NewFD->getLocation(),
12234 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12235 }
12236 }
12237 }
12238
12239 return Redeclaration;
12240}
12241
12243 // [basic.start.main]p3
12244 // The main function shall not be declared with a linkage-specification.
12245 if (FD->isExternCContext() ||
12246 (FD->isExternCXXContext() &&
12248 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12249 << FD->getLanguageLinkage();
12250
12251 // C++11 [basic.start.main]p3:
12252 // A program that [...] declares main to be inline, static or
12253 // constexpr is ill-formed.
12254 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12255 // appear in a declaration of main.
12256 // static main is not an error under C99, but we should warn about it.
12257 // We accept _Noreturn main as an extension.
12258 if (FD->getStorageClass() == SC_Static)
12260 ? diag::err_static_main : diag::warn_static_main)
12262 if (FD->isInlineSpecified())
12263 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12265 if (DS.isNoreturnSpecified()) {
12266 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12267 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12268 Diag(NoreturnLoc, diag::ext_noreturn_main);
12269 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12270 << FixItHint::CreateRemoval(NoreturnRange);
12271 }
12272 if (FD->isConstexpr()) {
12273 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12274 << FD->isConsteval()
12277 }
12278
12279 if (getLangOpts().OpenCL) {
12280 Diag(FD->getLocation(), diag::err_opencl_no_main)
12281 << FD->hasAttr<OpenCLKernelAttr>();
12282 FD->setInvalidDecl();
12283 return;
12284 }
12285
12286 // Functions named main in hlsl are default entries, but don't have specific
12287 // signatures they are required to conform to.
12288 if (getLangOpts().HLSL)
12289 return;
12290
12291 QualType T = FD->getType();
12292 assert(T->isFunctionType() && "function decl is not of function type");
12293 const FunctionType* FT = T->castAs<FunctionType>();
12294
12295 // Set default calling convention for main()
12296 if (FT->getCallConv() != CC_C) {
12298 FD->setType(QualType(FT, 0));
12300 }
12301
12302 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12303 // In C with GNU extensions we allow main() to have non-integer return
12304 // type, but we should warn about the extension, and we disable the
12305 // implicit-return-zero rule.
12306
12307 // GCC in C mode accepts qualified 'int'.
12309 FD->setHasImplicitReturnZero(true);
12310 else {
12311 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12312 SourceRange RTRange = FD->getReturnTypeSourceRange();
12313 if (RTRange.isValid())
12314 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12315 << FixItHint::CreateReplacement(RTRange, "int");
12316 }
12317 } else {
12318 // In C and C++, main magically returns 0 if you fall off the end;
12319 // set the flag which tells us that.
12320 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12321
12322 // All the standards say that main() should return 'int'.
12324 FD->setHasImplicitReturnZero(true);
12325 else {
12326 // Otherwise, this is just a flat-out error.
12327 SourceRange RTRange = FD->getReturnTypeSourceRange();
12328 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12329 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12330 : FixItHint());
12331 FD->setInvalidDecl(true);
12332 }
12333 }
12334
12335 // Treat protoless main() as nullary.
12336 if (isa<FunctionNoProtoType>(FT)) return;
12337
12338 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12339 unsigned nparams = FTP->getNumParams();
12340 assert(FD->getNumParams() == nparams);
12341
12342 bool HasExtraParameters = (nparams > 3);
12343
12344 if (FTP->isVariadic()) {
12345 Diag(FD->getLocation(), diag::ext_variadic_main);
12346 // FIXME: if we had information about the location of the ellipsis, we
12347 // could add a FixIt hint to remove it as a parameter.
12348 }
12349
12350 // Darwin passes an undocumented fourth argument of type char**. If
12351 // other platforms start sprouting these, the logic below will start
12352 // getting shifty.
12353 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12354 HasExtraParameters = false;
12355
12356 if (HasExtraParameters) {
12357 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12358 FD->setInvalidDecl(true);
12359 nparams = 3;
12360 }
12361
12362 // FIXME: a lot of the following diagnostics would be improved
12363 // if we had some location information about types.
12364
12365 QualType CharPP =
12367 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12368
12369 for (unsigned i = 0; i < nparams; ++i) {
12370 QualType AT = FTP->getParamType(i);
12371
12372 bool mismatch = true;
12373
12375 mismatch = false;
12376 else if (Expected[i] == CharPP) {
12377 // As an extension, the following forms are okay:
12378 // char const **
12379 // char const * const *
12380 // char * const *
12381
12383 const PointerType* PT;
12384 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12385 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12387 Context.CharTy)) {
12388 qs.removeConst();
12389 mismatch = !qs.empty();
12390 }
12391 }
12392
12393 if (mismatch) {
12394 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12395 // TODO: suggest replacing given type with expected type
12396 FD->setInvalidDecl(true);
12397 }
12398 }
12399
12400 if (nparams == 1 && !FD->isInvalidDecl()) {
12401 Diag(FD->getLocation(), diag::warn_main_one_arg);
12402 }
12403
12404 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12405 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12406 FD->setInvalidDecl();
12407 }
12408}
12409
12410static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12411
12412 // Default calling convention for main and wmain is __cdecl
12413 if (FD->getName() == "main" || FD->getName() == "wmain")
12414 return false;
12415
12416 // Default calling convention for MinGW is __cdecl
12417 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12418 if (T.isWindowsGNUEnvironment())
12419 return false;
12420
12421 // Default calling convention for WinMain, wWinMain and DllMain
12422 // is __stdcall on 32 bit Windows
12423 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12424 return true;
12425
12426 return false;
12427}
12428
12430 QualType T = FD->getType();
12431 assert(T->isFunctionType() && "function decl is not of function type");
12432 const FunctionType *FT = T->castAs<FunctionType>();
12433
12434 // Set an implicit return of 'zero' if the function can return some integral,
12435 // enumeration, pointer or nullptr type.
12439 // DllMain is exempt because a return value of zero means it failed.
12440 if (FD->getName() != "DllMain")
12441 FD->setHasImplicitReturnZero(true);
12442
12443 // Explicitly specified calling conventions are applied to MSVC entry points
12444 if (!hasExplicitCallingConv(T)) {
12445 if (isDefaultStdCall(FD, *this)) {
12446 if (FT->getCallConv() != CC_X86StdCall) {
12449 FD->setType(QualType(FT, 0));
12450 }
12451 } else if (FT->getCallConv() != CC_C) {
12454 FD->setType(QualType(FT, 0));
12455 }
12456 }
12457
12458 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12459 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12460 FD->setInvalidDecl();
12461 }
12462}
12463
12465 // FIXME: Need strict checking. In C89, we need to check for
12466 // any assignment, increment, decrement, function-calls, or
12467 // commas outside of a sizeof. In C99, it's the same list,
12468 // except that the aforementioned are allowed in unevaluated
12469 // expressions. Everything else falls under the
12470 // "may accept other forms of constant expressions" exception.
12471 //
12472 // Regular C++ code will not end up here (exceptions: language extensions,
12473 // OpenCL C++ etc), so the constant expression rules there don't matter.
12474 if (Init->isValueDependent()) {
12475 assert(Init->containsErrors() &&
12476 "Dependent code should only occur in error-recovery path.");
12477 return true;
12478 }
12479 const Expr *Culprit;
12480 if (Init->isConstantInitializer(Context, false, &Culprit))
12481 return false;
12482 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12483 return true;
12484}
12485
12486namespace {
12487 // Visits an initialization expression to see if OrigDecl is evaluated in
12488 // its own initialization and throws a warning if it does.
12489 class SelfReferenceChecker
12490 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12491 Sema &S;
12492 Decl *OrigDecl;
12493 bool isRecordType;
12494 bool isPODType;
12495 bool isReferenceType;
12496
12497 bool isInitList;
12498 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12499
12500 public:
12502
12503 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12504 S(S), OrigDecl(OrigDecl) {
12505 isPODType = false;
12506 isRecordType = false;
12507 isReferenceType = false;
12508 isInitList = false;
12509 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12510 isPODType = VD->getType().isPODType(S.Context);
12511 isRecordType = VD->getType()->isRecordType();
12512 isReferenceType = VD->getType()->isReferenceType();
12513 }
12514 }
12515
12516 // For most expressions, just call the visitor. For initializer lists,
12517 // track the index of the field being initialized since fields are
12518 // initialized in order allowing use of previously initialized fields.
12519 void CheckExpr(Expr *E) {
12520 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12521 if (!InitList) {
12522 Visit(E);
12523 return;
12524 }
12525
12526 // Track and increment the index here.
12527 isInitList = true;
12528 InitFieldIndex.push_back(0);
12529 for (auto *Child : InitList->children()) {
12530 CheckExpr(cast<Expr>(Child));
12531 ++InitFieldIndex.back();
12532 }
12533 InitFieldIndex.pop_back();
12534 }
12535
12536 // Returns true if MemberExpr is checked and no further checking is needed.
12537 // Returns false if additional checking is required.
12538 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12540 Expr *Base = E;
12541 bool ReferenceField = false;
12542
12543 // Get the field members used.
12544 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12545 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12546 if (!FD)
12547 return false;
12548 Fields.push_back(FD);
12549 if (FD->getType()->isReferenceType())
12550 ReferenceField = true;
12551 Base = ME->getBase()->IgnoreParenImpCasts();
12552 }
12553
12554 // Keep checking only if the base Decl is the same.
12555 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12556 if (!DRE || DRE->getDecl() != OrigDecl)
12557 return false;
12558
12559 // A reference field can be bound to an unininitialized field.
12560 if (CheckReference && !ReferenceField)
12561 return true;
12562
12563 // Convert FieldDecls to their index number.
12564 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12565 for (const FieldDecl *I : llvm::reverse(Fields))
12566 UsedFieldIndex.push_back(I->getFieldIndex());
12567
12568 // See if a warning is needed by checking the first difference in index
12569 // numbers. If field being used has index less than the field being
12570 // initialized, then the use is safe.
12571 for (auto UsedIter = UsedFieldIndex.begin(),
12572 UsedEnd = UsedFieldIndex.end(),
12573 OrigIter = InitFieldIndex.begin(),
12574 OrigEnd = InitFieldIndex.end();
12575 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12576 if (*UsedIter < *OrigIter)
12577 return true;
12578 if (*UsedIter > *OrigIter)
12579 break;
12580 }
12581
12582 // TODO: Add a different warning which will print the field names.
12583 HandleDeclRefExpr(DRE);
12584 return true;
12585 }
12586
12587 // For most expressions, the cast is directly above the DeclRefExpr.
12588 // For conditional operators, the cast can be outside the conditional
12589 // operator if both expressions are DeclRefExpr's.
12590 void HandleValue(Expr *E) {
12591 E = E->IgnoreParens();
12592 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12593 HandleDeclRefExpr(DRE);
12594 return;
12595 }
12596
12597 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12598 Visit(CO->getCond());
12599 HandleValue(CO->getTrueExpr());
12600 HandleValue(CO->getFalseExpr());
12601 return;
12602 }
12603
12604 if (BinaryConditionalOperator *BCO =
12605 dyn_cast<BinaryConditionalOperator>(E)) {
12606 Visit(BCO->getCond());
12607 HandleValue(BCO->getFalseExpr());
12608 return;
12609 }
12610
12611 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12612 if (Expr *SE = OVE->getSourceExpr())
12613 HandleValue(SE);
12614 return;
12615 }
12616
12617 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12618 if (BO->getOpcode() == BO_Comma) {
12619 Visit(BO->getLHS());
12620 HandleValue(BO->getRHS());
12621 return;
12622 }
12623 }
12624
12625 if (isa<MemberExpr>(E)) {
12626 if (isInitList) {
12627 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12628 false /*CheckReference*/))
12629 return;
12630 }
12631
12633 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12634 // Check for static member variables and don't warn on them.
12635 if (!isa<FieldDecl>(ME->getMemberDecl()))
12636 return;
12637 Base = ME->getBase()->IgnoreParenImpCasts();
12638 }
12639 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12640 HandleDeclRefExpr(DRE);
12641 return;
12642 }
12643
12644 Visit(E);
12645 }
12646
12647 // Reference types not handled in HandleValue are handled here since all
12648 // uses of references are bad, not just r-value uses.
12649 void VisitDeclRefExpr(DeclRefExpr *E) {
12650 if (isReferenceType)
12651 HandleDeclRefExpr(E);
12652 }
12653
12654 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12655 if (E->getCastKind() == CK_LValueToRValue) {
12656 HandleValue(E->getSubExpr());
12657 return;
12658 }
12659
12660 Inherited::VisitImplicitCastExpr(E);
12661 }
12662
12663 void VisitMemberExpr(MemberExpr *E) {
12664 if (isInitList) {
12665 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12666 return;
12667 }
12668
12669 // Don't warn on arrays since they can be treated as pointers.
12670 if (E->getType()->canDecayToPointerType()) return;
12671
12672 // Warn when a non-static method call is followed by non-static member
12673 // field accesses, which is followed by a DeclRefExpr.
12674 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12675 bool Warn = (MD && !MD->isStatic());
12676 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12677 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12678 if (!isa<FieldDecl>(ME->getMemberDecl()))
12679 Warn = false;
12680 Base = ME->getBase()->IgnoreParenImpCasts();
12681 }
12682
12683 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12684 if (Warn)
12685 HandleDeclRefExpr(DRE);
12686 return;
12687 }
12688
12689 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12690 // Visit that expression.
12691 Visit(Base);
12692 }
12693
12694 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12695 Expr *Callee = E->getCallee();
12696
12697 if (isa<UnresolvedLookupExpr>(Callee))
12698 return Inherited::VisitCXXOperatorCallExpr(E);
12699
12700 Visit(Callee);
12701 for (auto Arg: E->arguments())
12702 HandleValue(Arg->IgnoreParenImpCasts());
12703 }
12704
12705 void VisitUnaryOperator(UnaryOperator *E) {
12706 // For POD record types, addresses of its own members are well-defined.
12707 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12708 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12709 if (!isPODType)
12710 HandleValue(E->getSubExpr());
12711 return;
12712 }
12713
12714 if (E->isIncrementDecrementOp()) {
12715 HandleValue(E->getSubExpr());
12716 return;
12717 }
12718
12719 Inherited::VisitUnaryOperator(E);
12720 }
12721
12722 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12723
12724 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12725 if (E->getConstructor()->isCopyConstructor()) {
12726 Expr *ArgExpr = E->getArg(0);
12727 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12728 if (ILE->getNumInits() == 1)
12729 ArgExpr = ILE->getInit(0);
12730 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12731 if (ICE->getCastKind() == CK_NoOp)
12732 ArgExpr = ICE->getSubExpr();
12733 HandleValue(ArgExpr);
12734 return;
12735 }
12736 Inherited::VisitCXXConstructExpr(E);
12737 }
12738
12739 void VisitCallExpr(CallExpr *E) {
12740 // Treat std::move as a use.
12741 if (E->isCallToStdMove()) {
12742 HandleValue(E->getArg(0));
12743 return;
12744 }
12745
12746 Inherited::VisitCallExpr(E);
12747 }
12748
12749 void VisitBinaryOperator(BinaryOperator *E) {
12750 if (E->isCompoundAssignmentOp()) {
12751 HandleValue(E->getLHS());
12752 Visit(E->getRHS());
12753 return;
12754 }
12755
12756 Inherited::VisitBinaryOperator(E);
12757 }
12758
12759 // A custom visitor for BinaryConditionalOperator is needed because the
12760 // regular visitor would check the condition and true expression separately
12761 // but both point to the same place giving duplicate diagnostics.
12762 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12763 Visit(E->getCond());
12764 Visit(E->getFalseExpr());
12765 }
12766
12767 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12768 Decl* ReferenceDecl = DRE->getDecl();
12769 if (OrigDecl != ReferenceDecl) return;
12770 unsigned diag;
12771 if (isReferenceType) {
12772 diag = diag::warn_uninit_self_reference_in_reference_init;
12773 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12774 diag = diag::warn_static_self_reference_in_init;
12775 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12776 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12777 DRE->getDecl()->getType()->isRecordType()) {
12778 diag = diag::warn_uninit_self_reference_in_init;
12779 } else {
12780 // Local variables will be handled by the CFG analysis.
12781 return;
12782 }
12783
12784 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12785 S.PDiag(diag)
12786 << DRE->getDecl() << OrigDecl->getLocation()
12787 << DRE->getSourceRange());
12788 }
12789 };
12790
12791 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12792 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12793 bool DirectInit) {
12794 // Parameters arguments are occassionially constructed with itself,
12795 // for instance, in recursive functions. Skip them.
12796 if (isa<ParmVarDecl>(OrigDecl))
12797 return;
12798
12799 E = E->IgnoreParens();
12800
12801 // Skip checking T a = a where T is not a record or reference type.
12802 // Doing so is a way to silence uninitialized warnings.
12803 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12804 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12805 if (ICE->getCastKind() == CK_LValueToRValue)
12806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12807 if (DRE->getDecl() == OrigDecl)
12808 return;
12809
12810 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12811 }
12812} // end anonymous namespace
12813
12814namespace {
12815 // Simple wrapper to add the name of a variable or (if no variable is
12816 // available) a DeclarationName into a diagnostic.
12817 struct VarDeclOrName {
12818 VarDecl *VDecl;
12819 DeclarationName Name;
12820
12821 friend const Sema::SemaDiagnosticBuilder &
12822 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12823 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12824 }
12825 };
12826} // end anonymous namespace
12827
12830 TypeSourceInfo *TSI,
12832 Expr *Init) {
12833 bool IsInitCapture = !VDecl;
12834 assert((!VDecl || !VDecl->isInitCapture()) &&
12835 "init captures are expected to be deduced prior to initialization");
12836
12837 VarDeclOrName VN{VDecl, Name};
12838
12840 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12841
12842 // Diagnose auto array declarations in C23, unless it's a supported extension.
12843 if (getLangOpts().C23 && Type->isArrayType() &&
12844 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12845 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12846 << (int)Deduced->getContainedAutoType()->getKeyword()
12847 << /*in array decl*/ 23 << Range;
12848 return QualType();
12849 }
12850
12851 // C++11 [dcl.spec.auto]p3
12852 if (!Init) {
12853 assert(VDecl && "no init for init capture deduction?");
12854
12855 // Except for class argument deduction, and then for an initializing
12856 // declaration only, i.e. no static at class scope or extern.
12857 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12858 VDecl->hasExternalStorage() ||
12859 VDecl->isStaticDataMember()) {
12860 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12861 << VDecl->getDeclName() << Type;
12862 return QualType();
12863 }
12864 }
12865
12866 ArrayRef<Expr*> DeduceInits;
12867 if (Init)
12868 DeduceInits = Init;
12869
12870 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12871 if (DirectInit && PL)
12872 DeduceInits = PL->exprs();
12873
12874 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12875 assert(VDecl && "non-auto type for init capture deduction?");
12878 VDecl->getLocation(), DirectInit, Init);
12879 // FIXME: Initialization should not be taking a mutable list of inits.
12880 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12881 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12882 InitsCopy);
12883 }
12884
12885 if (DirectInit) {
12886 if (auto *IL = dyn_cast<InitListExpr>(Init))
12887 DeduceInits = IL->inits();
12888 }
12889
12890 // Deduction only works if we have exactly one source expression.
12891 if (DeduceInits.empty()) {
12892 // It isn't possible to write this directly, but it is possible to
12893 // end up in this situation with "auto x(some_pack...);"
12894 Diag(Init->getBeginLoc(), IsInitCapture
12895 ? diag::err_init_capture_no_expression
12896 : diag::err_auto_var_init_no_expression)
12897 << VN << Type << Range;
12898 return QualType();
12899 }
12900
12901 if (DeduceInits.size() > 1) {
12902 Diag(DeduceInits[1]->getBeginLoc(),
12903 IsInitCapture ? diag::err_init_capture_multiple_expressions
12904 : diag::err_auto_var_init_multiple_expressions)
12905 << VN << Type << Range;
12906 return QualType();
12907 }
12908
12909 Expr *DeduceInit = DeduceInits[0];
12910 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12911 Diag(Init->getBeginLoc(), IsInitCapture
12912 ? diag::err_init_capture_paren_braces
12913 : diag::err_auto_var_init_paren_braces)
12914 << isa<InitListExpr>(Init) << VN << Type << Range;
12915 return QualType();
12916 }
12917
12918 // Expressions default to 'id' when we're in a debugger.
12919 bool DefaultedAnyToId = false;
12920 if (getLangOpts().DebuggerCastResultToId &&
12921 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12923 if (Result.isInvalid()) {
12924 return QualType();
12925 }
12926 Init = Result.get();
12927 DefaultedAnyToId = true;
12928 }
12929
12930 // C++ [dcl.decomp]p1:
12931 // If the assignment-expression [...] has array type A and no ref-qualifier
12932 // is present, e has type cv A
12933 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12935 DeduceInit->getType()->isConstantArrayType())
12936 return Context.getQualifiedType(DeduceInit->getType(),
12937 Type.getQualifiers());
12938
12940 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12942 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12945 if (!IsInitCapture)
12946 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12947 else if (isa<InitListExpr>(Init))
12949 diag::err_init_capture_deduction_failure_from_init_list)
12950 << VN
12951 << (DeduceInit->getType().isNull() ? TSI->getType()
12952 : DeduceInit->getType())
12953 << DeduceInit->getSourceRange();
12954 else
12955 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12956 << VN << TSI->getType()
12957 << (DeduceInit->getType().isNull() ? TSI->getType()
12958 : DeduceInit->getType())
12959 << DeduceInit->getSourceRange();
12960 }
12961
12962 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12963 // 'id' instead of a specific object type prevents most of our usual
12964 // checks.
12965 // We only want to warn outside of template instantiations, though:
12966 // inside a template, the 'id' could have come from a parameter.
12967 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12968 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12970 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12971 }
12972
12973 return DeducedType;
12974}
12975
12977 Expr *Init) {
12978 assert(!Init || !Init->containsErrors());
12980 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12981 VDecl->getSourceRange(), DirectInit, Init);
12982 if (DeducedType.isNull()) {
12983 VDecl->setInvalidDecl();
12984 return true;
12985 }
12986
12987 VDecl->setType(DeducedType);
12988 assert(VDecl->isLinkageValid());
12989
12990 // In ARC, infer lifetime.
12991 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
12992 VDecl->setInvalidDecl();
12993
12994 if (getLangOpts().OpenCL)
12996
12997 // If this is a redeclaration, check that the type we just deduced matches
12998 // the previously declared type.
12999 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13000 // We never need to merge the type, because we cannot form an incomplete
13001 // array of auto, nor deduce such a type.
13002 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13003 }
13004
13005 // Check the deduced type is valid for a variable declaration.
13007 return VDecl->isInvalidDecl();
13008}
13009
13012 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13013 Init = EWC->getSubExpr();
13014
13015 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13016 Init = CE->getSubExpr();
13017
13018 QualType InitType = Init->getType();
13021 "shouldn't be called if type doesn't have a non-trivial C struct");
13022 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13023 for (auto *I : ILE->inits()) {
13024 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13025 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13026 continue;
13027 SourceLocation SL = I->getExprLoc();
13029 }
13030 return;
13031 }
13032
13033 if (isa<ImplicitValueInitExpr>(Init)) {
13036 NTCUK_Init);
13037 } else {
13038 // Assume all other explicit initializers involving copying some existing
13039 // object.
13040 // TODO: ignore any explicit initializers where we can guarantee
13041 // copy-elision.
13044 }
13045}
13046
13047namespace {
13048
13049bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13050 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13051 // in the source code or implicitly by the compiler if it is in a union
13052 // defined in a system header and has non-trivial ObjC ownership
13053 // qualifications. We don't want those fields to participate in determining
13054 // whether the containing union is non-trivial.
13055 return FD->hasAttr<UnavailableAttr>();
13056}
13057
13058struct DiagNonTrivalCUnionDefaultInitializeVisitor
13059 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13060 void> {
13061 using Super =
13062 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13063 void>;
13064
13065 DiagNonTrivalCUnionDefaultInitializeVisitor(
13066 QualType OrigTy, SourceLocation OrigLoc,
13067 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13068 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13069
13070 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13071 const FieldDecl *FD, bool InNonTrivialUnion) {
13072 if (const auto *AT = S.Context.getAsArrayType(QT))
13073 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13074 InNonTrivialUnion);
13075 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13076 }
13077
13078 void visitARCStrong(QualType QT, const FieldDecl *FD,
13079 bool InNonTrivialUnion) {
13080 if (InNonTrivialUnion)
13081 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13082 << 1 << 0 << QT << FD->getName();
13083 }
13084
13085 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13086 if (InNonTrivialUnion)
13087 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13088 << 1 << 0 << QT << FD->getName();
13089 }
13090
13091 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13092 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13093 if (RD->isUnion()) {
13094 if (OrigLoc.isValid()) {
13095 bool IsUnion = false;
13096 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13097 IsUnion = OrigRD->isUnion();
13098 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13099 << 0 << OrigTy << IsUnion << UseContext;
13100 // Reset OrigLoc so that this diagnostic is emitted only once.
13101 OrigLoc = SourceLocation();
13102 }
13103 InNonTrivialUnion = true;
13104 }
13105
13106 if (InNonTrivialUnion)
13107 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13108 << 0 << 0 << QT.getUnqualifiedType() << "";
13109
13110 for (const FieldDecl *FD : RD->fields())
13111 if (!shouldIgnoreForRecordTriviality(FD))
13112 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13113 }
13114
13115 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13116
13117 // The non-trivial C union type or the struct/union type that contains a
13118 // non-trivial C union.
13119 QualType OrigTy;
13120 SourceLocation OrigLoc;
13122 Sema &S;
13123};
13124
13125struct DiagNonTrivalCUnionDestructedTypeVisitor
13126 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13127 using Super =
13129
13130 DiagNonTrivalCUnionDestructedTypeVisitor(
13131 QualType OrigTy, SourceLocation OrigLoc,
13132 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13133 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13134
13135 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13136 const FieldDecl *FD, bool InNonTrivialUnion) {
13137 if (const auto *AT = S.Context.getAsArrayType(QT))
13138 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13139 InNonTrivialUnion);
13140 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13141 }
13142
13143 void visitARCStrong(QualType QT, const FieldDecl *FD,
13144 bool InNonTrivialUnion) {
13145 if (InNonTrivialUnion)
13146 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13147 << 1 << 1 << QT << FD->getName();
13148 }
13149
13150 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13151 if (InNonTrivialUnion)
13152 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13153 << 1 << 1 << QT << FD->getName();
13154 }
13155
13156 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13157 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13158 if (RD->isUnion()) {
13159 if (OrigLoc.isValid()) {
13160 bool IsUnion = false;
13161 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13162 IsUnion = OrigRD->isUnion();
13163 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13164 << 1 << OrigTy << IsUnion << UseContext;
13165 // Reset OrigLoc so that this diagnostic is emitted only once.
13166 OrigLoc = SourceLocation();
13167 }
13168 InNonTrivialUnion = true;
13169 }
13170
13171 if (InNonTrivialUnion)
13172 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13173 << 0 << 1 << QT.getUnqualifiedType() << "";
13174
13175 for (const FieldDecl *FD : RD->fields())
13176 if (!shouldIgnoreForRecordTriviality(FD))
13177 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13178 }
13179
13180 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13181 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13182 bool InNonTrivialUnion) {}
13183
13184 // The non-trivial C union type or the struct/union type that contains a
13185 // non-trivial C union.
13186 QualType OrigTy;
13187 SourceLocation OrigLoc;
13189 Sema &S;
13190};
13191
13192struct DiagNonTrivalCUnionCopyVisitor
13193 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13195
13196 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13198 Sema &S)
13199 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13200
13201 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13202 const FieldDecl *FD, bool InNonTrivialUnion) {
13203 if (const auto *AT = S.Context.getAsArrayType(QT))
13204 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13205 InNonTrivialUnion);
13206 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13207 }
13208
13209 void visitARCStrong(QualType QT, const FieldDecl *FD,
13210 bool InNonTrivialUnion) {
13211 if (InNonTrivialUnion)
13212 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13213 << 1 << 2 << QT << FD->getName();
13214 }
13215
13216 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13217 if (InNonTrivialUnion)
13218 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13219 << 1 << 2 << QT << FD->getName();
13220 }
13221
13222 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13223 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13224 if (RD->isUnion()) {
13225 if (OrigLoc.isValid()) {
13226 bool IsUnion = false;
13227 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13228 IsUnion = OrigRD->isUnion();
13229 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13230 << 2 << OrigTy << IsUnion << UseContext;
13231 // Reset OrigLoc so that this diagnostic is emitted only once.
13232 OrigLoc = SourceLocation();
13233 }
13234 InNonTrivialUnion = true;
13235 }
13236
13237 if (InNonTrivialUnion)
13238 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13239 << 0 << 2 << QT.getUnqualifiedType() << "";
13240
13241 for (const FieldDecl *FD : RD->fields())
13242 if (!shouldIgnoreForRecordTriviality(FD))
13243 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13244 }
13245
13246 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13247 const FieldDecl *FD, bool InNonTrivialUnion) {}
13248 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13249 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13250 bool InNonTrivialUnion) {}
13251
13252 // The non-trivial C union type or the struct/union type that contains a
13253 // non-trivial C union.
13254 QualType OrigTy;
13255 SourceLocation OrigLoc;
13257 Sema &S;
13258};
13259
13260} // namespace
13261
13263 NonTrivialCUnionContext UseContext,
13264 unsigned NonTrivialKind) {
13268 "shouldn't be called if type doesn't have a non-trivial C union");
13269
13270 if ((NonTrivialKind & NTCUK_Init) &&
13272 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13273 .visit(QT, nullptr, false);
13274 if ((NonTrivialKind & NTCUK_Destruct) &&
13276 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13277 .visit(QT, nullptr, false);
13278 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13279 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13280 .visit(QT, nullptr, false);
13281}
13282
13284 // If there is no declaration, there was an error parsing it. Just ignore
13285 // the initializer.
13286 if (!RealDecl) {
13287 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13288 return;
13289 }
13290
13291 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13292 if (!Method->isInvalidDecl()) {
13293 // Pure-specifiers are handled in ActOnPureSpecifier.
13294 Diag(Method->getLocation(), diag::err_member_function_initialization)
13295 << Method->getDeclName() << Init->getSourceRange();
13296 Method->setInvalidDecl();
13297 }
13298 return;
13299 }
13300
13301 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13302 if (!VDecl) {
13303 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13304 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13305 RealDecl->setInvalidDecl();
13306 return;
13307 }
13308
13309 if (VDecl->isInvalidDecl()) {
13311 SmallVector<Expr *> SubExprs;
13312 if (Res.isUsable())
13313 SubExprs.push_back(Res.get());
13314 ExprResult Recovery =
13315 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13316 if (Expr *E = Recovery.get())
13317 VDecl->setInit(E);
13318 return;
13319 }
13320
13321 // WebAssembly tables can't be used to initialise a variable.
13322 if (Init && !Init->getType().isNull() &&
13323 Init->getType()->isWebAssemblyTableType()) {
13324 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13325 VDecl->setInvalidDecl();
13326 return;
13327 }
13328
13329 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13330 if (VDecl->getType()->isUndeducedType()) {
13331 // Attempt typo correction early so that the type of the init expression can
13332 // be deduced based on the chosen correction if the original init contains a
13333 // TypoExpr.
13335 if (!Res.isUsable()) {
13336 // There are unresolved typos in Init, just drop them.
13337 // FIXME: improve the recovery strategy to preserve the Init.
13338 RealDecl->setInvalidDecl();
13339 return;
13340 }
13341 if (Res.get()->containsErrors()) {
13342 // Invalidate the decl as we don't know the type for recovery-expr yet.
13343 RealDecl->setInvalidDecl();
13344 VDecl->setInit(Res.get());
13345 return;
13346 }
13347 Init = Res.get();
13348
13350 return;
13351 }
13352
13353 // dllimport cannot be used on variable definitions.
13354 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13355 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13356 VDecl->setInvalidDecl();
13357 return;
13358 }
13359
13360 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13361 // the identifier has external or internal linkage, the declaration shall
13362 // have no initializer for the identifier.
13363 // C++14 [dcl.init]p5 is the same restriction for C++.
13364 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13365 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13366 VDecl->setInvalidDecl();
13367 return;
13368 }
13369
13370 if (!VDecl->getType()->isDependentType()) {
13371 // A definition must end up with a complete type, which means it must be
13372 // complete with the restriction that an array type might be completed by
13373 // the initializer; note that later code assumes this restriction.
13374 QualType BaseDeclType = VDecl->getType();
13375 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13376 BaseDeclType = Array->getElementType();
13377 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13378 diag::err_typecheck_decl_incomplete_type)) {
13379 RealDecl->setInvalidDecl();
13380 return;
13381 }
13382
13383 // The variable can not have an abstract class type.
13384 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13385 diag::err_abstract_type_in_decl,
13387 VDecl->setInvalidDecl();
13388 }
13389
13390 // C++ [module.import/6] external definitions are not permitted in header
13391 // units.
13392 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13393 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13394 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13395 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13397 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13398 VDecl->setInvalidDecl();
13399 }
13400
13401 // If adding the initializer will turn this declaration into a definition,
13402 // and we already have a definition for this variable, diagnose or otherwise
13403 // handle the situation.
13404 if (VarDecl *Def = VDecl->getDefinition())
13405 if (Def != VDecl &&
13406 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13408 checkVarDeclRedefinition(Def, VDecl))
13409 return;
13410
13411 if (getLangOpts().CPlusPlus) {
13412 // C++ [class.static.data]p4
13413 // If a static data member is of const integral or const
13414 // enumeration type, its declaration in the class definition can
13415 // specify a constant-initializer which shall be an integral
13416 // constant expression (5.19). In that case, the member can appear
13417 // in integral constant expressions. The member shall still be
13418 // defined in a namespace scope if it is used in the program and the
13419 // namespace scope definition shall not contain an initializer.
13420 //
13421 // We already performed a redefinition check above, but for static
13422 // data members we also need to check whether there was an in-class
13423 // declaration with an initializer.
13424 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13425 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13426 << VDecl->getDeclName();
13427 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13428 diag::note_previous_initializer)
13429 << 0;
13430 return;
13431 }
13432
13433 if (VDecl->hasLocalStorage())
13435
13437 VDecl->setInvalidDecl();
13438 return;
13439 }
13440 }
13441
13442 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13443 // a kernel function cannot be initialized."
13444 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13445 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13446 VDecl->setInvalidDecl();
13447 return;
13448 }
13449
13450 // The LoaderUninitialized attribute acts as a definition (of undef).
13451 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13452 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13453 VDecl->setInvalidDecl();
13454 return;
13455 }
13456
13457 // Get the decls type and save a reference for later, since
13458 // CheckInitializerTypes may change it.
13459 QualType DclT = VDecl->getType(), SavT = DclT;
13460
13461 // Expressions default to 'id' when we're in a debugger
13462 // and we are assigning it to a variable of Objective-C pointer type.
13463 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13464 Init->getType() == Context.UnknownAnyTy) {
13466 if (Result.isInvalid()) {
13467 VDecl->setInvalidDecl();
13468 return;
13469 }
13470 Init = Result.get();
13471 }
13472
13473 // Perform the initialization.
13474 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13475 bool IsParenListInit = false;
13476 if (!VDecl->isInvalidDecl()) {
13479 VDecl->getLocation(), DirectInit, Init);
13480
13481 MultiExprArg Args = Init;
13482 if (CXXDirectInit)
13483 Args = MultiExprArg(CXXDirectInit->getExprs(),
13484 CXXDirectInit->getNumExprs());
13485
13486 // Try to correct any TypoExprs in the initialization arguments.
13487 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13489 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13490 [this, Entity, Kind](Expr *E) {
13491 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13492 return Init.Failed() ? ExprError() : E;
13493 });
13494 if (Res.isInvalid()) {
13495 VDecl->setInvalidDecl();
13496 } else if (Res.get() != Args[Idx]) {
13497 Args[Idx] = Res.get();
13498 }
13499 }
13500 if (VDecl->isInvalidDecl())
13501 return;
13502
13503 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13504 /*TopLevelOfInitList=*/false,
13505 /*TreatUnavailableAsInvalid=*/false);
13506 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13507 if (Result.isInvalid()) {
13508 // If the provided initializer fails to initialize the var decl,
13509 // we attach a recovery expr for better recovery.
13510 auto RecoveryExpr =
13511 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13512 if (RecoveryExpr.get())
13513 VDecl->setInit(RecoveryExpr.get());
13514 // In general, for error recovery purposes, the initializer doesn't play
13515 // part in the valid bit of the declaration. There are a few exceptions:
13516 // 1) if the var decl has a deduced auto type, and the type cannot be
13517 // deduced by an invalid initializer;
13518 // 2) if the var decl is a decomposition decl with a non-deduced type,
13519 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13520 // Case 1) was already handled elsewhere.
13521 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13522 VDecl->setInvalidDecl();
13523 return;
13524 }
13525
13526 Init = Result.getAs<Expr>();
13527 IsParenListInit = !InitSeq.steps().empty() &&
13528 InitSeq.step_begin()->Kind ==
13530 QualType VDeclType = VDecl->getType();
13531 if (Init && !Init->getType().isNull() &&
13532 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13533 Context.getAsIncompleteArrayType(VDeclType) &&
13535 // Bail out if it is not possible to deduce array size from the
13536 // initializer.
13537 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13538 << VDeclType;
13539 VDecl->setInvalidDecl();
13540 return;
13541 }
13542 }
13543
13544 // Check for self-references within variable initializers.
13545 // Variables declared within a function/method body (except for references)
13546 // are handled by a dataflow analysis.
13547 // This is undefined behavior in C++, but valid in C.
13548 if (getLangOpts().CPlusPlus)
13549 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13550 VDecl->getType()->isReferenceType())
13551 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13552
13553 // If the type changed, it means we had an incomplete type that was
13554 // completed by the initializer. For example:
13555 // int ary[] = { 1, 3, 5 };
13556 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13557 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13558 VDecl->setType(DclT);
13559
13560 if (!VDecl->isInvalidDecl()) {
13561 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13562
13563 if (VDecl->hasAttr<BlocksAttr>())
13564 ObjC().checkRetainCycles(VDecl, Init);
13565
13566 // It is safe to assign a weak reference into a strong variable.
13567 // Although this code can still have problems:
13568 // id x = self.weakProp;
13569 // id y = self.weakProp;
13570 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13571 // paths through the function. This should be revisited if
13572 // -Wrepeated-use-of-weak is made flow-sensitive.
13573 if (FunctionScopeInfo *FSI = getCurFunction())
13574 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13576 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13577 Init->getBeginLoc()))
13578 FSI->markSafeWeakUse(Init);
13579 }
13580
13581 // The initialization is usually a full-expression.
13582 //
13583 // FIXME: If this is a braced initialization of an aggregate, it is not
13584 // an expression, and each individual field initializer is a separate
13585 // full-expression. For instance, in:
13586 //
13587 // struct Temp { ~Temp(); };
13588 // struct S { S(Temp); };
13589 // struct T { S a, b; } t = { Temp(), Temp() }
13590 //
13591 // we should destroy the first Temp before constructing the second.
13594 /*DiscardedValue*/ false, VDecl->isConstexpr());
13595 if (Result.isInvalid()) {
13596 VDecl->setInvalidDecl();
13597 return;
13598 }
13599 Init = Result.get();
13600
13601 // Attach the initializer to the decl.
13602 VDecl->setInit(Init);
13603
13604 if (VDecl->isLocalVarDecl()) {
13605 // Don't check the initializer if the declaration is malformed.
13606 if (VDecl->isInvalidDecl()) {
13607 // do nothing
13608
13609 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13610 // This is true even in C++ for OpenCL.
13611 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13613
13614 // Otherwise, C++ does not restrict the initializer.
13615 } else if (getLangOpts().CPlusPlus) {
13616 // do nothing
13617
13618 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13619 // static storage duration shall be constant expressions or string literals.
13620 } else if (VDecl->getStorageClass() == SC_Static) {
13622
13623 // C89 is stricter than C99 for aggregate initializers.
13624 // C89 6.5.7p3: All the expressions [...] in an initializer list
13625 // for an object that has aggregate or union type shall be
13626 // constant expressions.
13627 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13628 isa<InitListExpr>(Init)) {
13629 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13630 }
13631
13632 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13633 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13634 if (VDecl->hasLocalStorage())
13635 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13636 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13637 VDecl->getLexicalDeclContext()->isRecord()) {
13638 // This is an in-class initialization for a static data member, e.g.,
13639 //
13640 // struct S {
13641 // static const int value = 17;
13642 // };
13643
13644 // C++ [class.mem]p4:
13645 // A member-declarator can contain a constant-initializer only
13646 // if it declares a static member (9.4) of const integral or
13647 // const enumeration type, see 9.4.2.
13648 //
13649 // C++11 [class.static.data]p3:
13650 // If a non-volatile non-inline const static data member is of integral
13651 // or enumeration type, its declaration in the class definition can
13652 // specify a brace-or-equal-initializer in which every initializer-clause
13653 // that is an assignment-expression is a constant expression. A static
13654 // data member of literal type can be declared in the class definition
13655 // with the constexpr specifier; if so, its declaration shall specify a
13656 // brace-or-equal-initializer in which every initializer-clause that is
13657 // an assignment-expression is a constant expression.
13658
13659 // Do nothing on dependent types.
13660 if (DclT->isDependentType()) {
13661
13662 // Allow any 'static constexpr' members, whether or not they are of literal
13663 // type. We separately check that every constexpr variable is of literal
13664 // type.
13665 } else if (VDecl->isConstexpr()) {
13666
13667 // Require constness.
13668 } else if (!DclT.isConstQualified()) {
13669 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13670 << Init->getSourceRange();
13671 VDecl->setInvalidDecl();
13672
13673 // We allow integer constant expressions in all cases.
13674 } else if (DclT->isIntegralOrEnumerationType()) {
13675 // Check whether the expression is a constant expression.
13678 // In C++11, a non-constexpr const static data member with an
13679 // in-class initializer cannot be volatile.
13680 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13681 else if (Init->isValueDependent())
13682 ; // Nothing to check.
13683 else if (Init->isIntegerConstantExpr(Context, &Loc))
13684 ; // Ok, it's an ICE!
13685 else if (Init->getType()->isScopedEnumeralType() &&
13686 Init->isCXX11ConstantExpr(Context))
13687 ; // Ok, it is a scoped-enum constant expression.
13688 else if (Init->isEvaluatable(Context)) {
13689 // If we can constant fold the initializer through heroics, accept it,
13690 // but report this as a use of an extension for -pedantic.
13691 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13692 << Init->getSourceRange();
13693 } else {
13694 // Otherwise, this is some crazy unknown case. Report the issue at the
13695 // location provided by the isIntegerConstantExpr failed check.
13696 Diag(Loc, diag::err_in_class_initializer_non_constant)
13697 << Init->getSourceRange();
13698 VDecl->setInvalidDecl();
13699 }
13700
13701 // We allow foldable floating-point constants as an extension.
13702 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13703 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13704 // it anyway and provide a fixit to add the 'constexpr'.
13705 if (getLangOpts().CPlusPlus11) {
13706 Diag(VDecl->getLocation(),
13707 diag::ext_in_class_initializer_float_type_cxx11)
13708 << DclT << Init->getSourceRange();
13709 Diag(VDecl->getBeginLoc(),
13710 diag::note_in_class_initializer_float_type_cxx11)
13711 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13712 } else {
13713 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13714 << DclT << Init->getSourceRange();
13715
13716 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13717 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13718 << Init->getSourceRange();
13719 VDecl->setInvalidDecl();
13720 }
13721 }
13722
13723 // Suggest adding 'constexpr' in C++11 for literal types.
13724 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13725 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13726 << DclT << Init->getSourceRange()
13727 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13728 VDecl->setConstexpr(true);
13729
13730 } else {
13731 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13732 << DclT << Init->getSourceRange();
13733 VDecl->setInvalidDecl();
13734 }
13735 } else if (VDecl->isFileVarDecl()) {
13736 // In C, extern is typically used to avoid tentative definitions when
13737 // declaring variables in headers, but adding an initializer makes it a
13738 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13739 // In C++, extern is often used to give implicitly static const variables
13740 // external linkage, so don't warn in that case. If selectany is present,
13741 // this might be header code intended for C and C++ inclusion, so apply the
13742 // C++ rules.
13743 if (VDecl->getStorageClass() == SC_Extern &&
13744 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13746 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13748 Diag(VDecl->getLocation(), diag::warn_extern_init);
13749
13750 // In Microsoft C++ mode, a const variable defined in namespace scope has
13751 // external linkage by default if the variable is declared with
13752 // __declspec(dllexport).
13755 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13756 VDecl->setStorageClass(SC_Extern);
13757
13758 // C99 6.7.8p4. All file scoped initializers need to be constant.
13759 // Avoid duplicate diagnostics for constexpr variables.
13760 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13761 !VDecl->isConstexpr())
13763 }
13764
13765 QualType InitType = Init->getType();
13766 if (!InitType.isNull() &&
13770
13771 // We will represent direct-initialization similarly to copy-initialization:
13772 // int x(1); -as-> int x = 1;
13773 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13774 //
13775 // Clients that want to distinguish between the two forms, can check for
13776 // direct initializer using VarDecl::getInitStyle().
13777 // A major benefit is that clients that don't particularly care about which
13778 // exactly form was it (like the CodeGen) can handle both cases without
13779 // special case code.
13780
13781 // C++ 8.5p11:
13782 // The form of initialization (using parentheses or '=') is generally
13783 // insignificant, but does matter when the entity being initialized has a
13784 // class type.
13785 if (CXXDirectInit) {
13786 assert(DirectInit && "Call-style initializer must be direct init.");
13787 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13789 } else if (DirectInit) {
13790 // This must be list-initialization. No other way is direct-initialization.
13792 }
13793
13794 if (LangOpts.OpenMP &&
13795 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13796 VDecl->isFileVarDecl())
13797 DeclsToCheckForDeferredDiags.insert(VDecl);
13799}
13800
13802 // Our main concern here is re-establishing invariants like "a
13803 // variable's type is either dependent or complete".
13804 if (!D || D->isInvalidDecl()) return;
13805
13806 VarDecl *VD = dyn_cast<VarDecl>(D);
13807 if (!VD) return;
13808
13809 // Bindings are not usable if we can't make sense of the initializer.
13810 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13811 for (auto *BD : DD->bindings())
13812 BD->setInvalidDecl();
13813
13814 // Auto types are meaningless if we can't make sense of the initializer.
13815 if (VD->getType()->isUndeducedType()) {
13816 D->setInvalidDecl();
13817 return;
13818 }
13819
13820 QualType Ty = VD->getType();
13821 if (Ty->isDependentType()) return;
13822
13823 // Require a complete type.
13826 diag::err_typecheck_decl_incomplete_type)) {
13827 VD->setInvalidDecl();
13828 return;
13829 }
13830
13831 // Require a non-abstract type.
13832 if (RequireNonAbstractType(VD->getLocation(), Ty,
13833 diag::err_abstract_type_in_decl,
13835 VD->setInvalidDecl();
13836 return;
13837 }
13838
13839 // Don't bother complaining about constructors or destructors,
13840 // though.
13841}
13842
13844 // If there is no declaration, there was an error parsing it. Just ignore it.
13845 if (!RealDecl)
13846 return;
13847
13848 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13849 QualType Type = Var->getType();
13850
13851 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13852 if (isa<DecompositionDecl>(RealDecl)) {
13853 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13854 Var->setInvalidDecl();
13855 return;
13856 }
13857
13858 if (Type->isUndeducedType() &&
13859 DeduceVariableDeclarationType(Var, false, nullptr))
13860 return;
13861
13862 // C++11 [class.static.data]p3: A static data member can be declared with
13863 // the constexpr specifier; if so, its declaration shall specify
13864 // a brace-or-equal-initializer.
13865 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13866 // the definition of a variable [...] or the declaration of a static data
13867 // member.
13868 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13869 !Var->isThisDeclarationADemotedDefinition()) {
13870 if (Var->isStaticDataMember()) {
13871 // C++1z removes the relevant rule; the in-class declaration is always
13872 // a definition there.
13873 if (!getLangOpts().CPlusPlus17 &&
13875 Diag(Var->getLocation(),
13876 diag::err_constexpr_static_mem_var_requires_init)
13877 << Var;
13878 Var->setInvalidDecl();
13879 return;
13880 }
13881 } else {
13882 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13883 Var->setInvalidDecl();
13884 return;
13885 }
13886 }
13887
13888 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13889 // be initialized.
13890 if (!Var->isInvalidDecl() &&
13891 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13892 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13893 bool HasConstExprDefaultConstructor = false;
13894 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13895 for (auto *Ctor : RD->ctors()) {
13896 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13897 Ctor->getMethodQualifiers().getAddressSpace() ==
13899 HasConstExprDefaultConstructor = true;
13900 }
13901 }
13902 }
13903 if (!HasConstExprDefaultConstructor) {
13904 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13905 Var->setInvalidDecl();
13906 return;
13907 }
13908 }
13909
13910 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13911 if (Var->getStorageClass() == SC_Extern) {
13912 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13913 << Var;
13914 Var->setInvalidDecl();
13915 return;
13916 }
13917 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13918 diag::err_typecheck_decl_incomplete_type)) {
13919 Var->setInvalidDecl();
13920 return;
13921 }
13922 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13923 if (!RD->hasTrivialDefaultConstructor()) {
13924 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13925 Var->setInvalidDecl();
13926 return;
13927 }
13928 }
13929 // The declaration is uninitialized, no need for further checks.
13930 return;
13931 }
13932
13933 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13934 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13935 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13936 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13938
13939
13940 switch (DefKind) {
13942 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13943 break;
13944
13945 // We have an out-of-line definition of a static data member
13946 // that has an in-class initializer, so we type-check this like
13947 // a declaration.
13948 //
13949 [[fallthrough]];
13950
13952 // It's only a declaration.
13953
13954 // Block scope. C99 6.7p7: If an identifier for an object is
13955 // declared with no linkage (C99 6.2.2p6), the type for the
13956 // object shall be complete.
13957 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13958 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13959 RequireCompleteType(Var->getLocation(), Type,
13960 diag::err_typecheck_decl_incomplete_type))
13961 Var->setInvalidDecl();
13962
13963 // Make sure that the type is not abstract.
13964 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13965 RequireNonAbstractType(Var->getLocation(), Type,
13966 diag::err_abstract_type_in_decl,
13968 Var->setInvalidDecl();
13969 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13970 Var->getStorageClass() == SC_PrivateExtern) {
13971 Diag(Var->getLocation(), diag::warn_private_extern);
13972 Diag(Var->getLocation(), diag::note_private_extern);
13973 }
13974
13976 !Var->isInvalidDecl())
13977 ExternalDeclarations.push_back(Var);
13978
13979 return;
13980
13982 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13983 // object that has file scope without an initializer, and without a
13984 // storage-class specifier or with the storage-class specifier "static",
13985 // constitutes a tentative definition. Note: A tentative definition with
13986 // external linkage is valid (C99 6.2.2p5).
13987 if (!Var->isInvalidDecl()) {
13988 if (const IncompleteArrayType *ArrayT
13991 Var->getLocation(), ArrayT->getElementType(),
13992 diag::err_array_incomplete_or_sizeless_type))
13993 Var->setInvalidDecl();
13994 } else if (Var->getStorageClass() == SC_Static) {
13995 // C99 6.9.2p3: If the declaration of an identifier for an object is
13996 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13997 // declared type shall not be an incomplete type.
13998 // NOTE: code such as the following
13999 // static struct s;
14000 // struct s { int a; };
14001 // is accepted by gcc. Hence here we issue a warning instead of
14002 // an error and we do not invalidate the static declaration.
14003 // NOTE: to avoid multiple warnings, only check the first declaration.
14004 if (Var->isFirstDecl())
14005 RequireCompleteType(Var->getLocation(), Type,
14006 diag::ext_typecheck_decl_incomplete_type);
14007 }
14008 }
14009
14010 // Record the tentative definition; we're done.
14011 if (!Var->isInvalidDecl())
14013 return;
14014 }
14015
14016 // Provide a specific diagnostic for uninitialized variable
14017 // definitions with incomplete array type.
14018 if (Type->isIncompleteArrayType()) {
14019 if (Var->isConstexpr())
14020 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14021 << Var;
14022 else
14023 Diag(Var->getLocation(),
14024 diag::err_typecheck_incomplete_array_needs_initializer);
14025 Var->setInvalidDecl();
14026 return;
14027 }
14028
14029 // Provide a specific diagnostic for uninitialized variable
14030 // definitions with reference type.
14031 if (Type->isReferenceType()) {
14032 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14033 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14034 return;
14035 }
14036
14037 // Do not attempt to type-check the default initializer for a
14038 // variable with dependent type.
14039 if (Type->isDependentType())
14040 return;
14041
14042 if (Var->isInvalidDecl())
14043 return;
14044
14045 if (!Var->hasAttr<AliasAttr>()) {
14046 if (RequireCompleteType(Var->getLocation(),
14048 diag::err_typecheck_decl_incomplete_type)) {
14049 Var->setInvalidDecl();
14050 return;
14051 }
14052 } else {
14053 return;
14054 }
14055
14056 // The variable can not have an abstract class type.
14057 if (RequireNonAbstractType(Var->getLocation(), Type,
14058 diag::err_abstract_type_in_decl,
14060 Var->setInvalidDecl();
14061 return;
14062 }
14063
14064 // Check for jumps past the implicit initializer. C++0x
14065 // clarifies that this applies to a "variable with automatic
14066 // storage duration", not a "local variable".
14067 // C++11 [stmt.dcl]p3
14068 // A program that jumps from a point where a variable with automatic
14069 // storage duration is not in scope to a point where it is in scope is
14070 // ill-formed unless the variable has scalar type, class type with a
14071 // trivial default constructor and a trivial destructor, a cv-qualified
14072 // version of one of these types, or an array of one of the preceding
14073 // types and is declared without an initializer.
14074 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14075 if (const RecordType *Record
14077 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14078 // Mark the function (if we're in one) for further checking even if the
14079 // looser rules of C++11 do not require such checks, so that we can
14080 // diagnose incompatibilities with C++98.
14081 if (!CXXRecord->isPOD())
14083 }
14084 }
14085 // In OpenCL, we can't initialize objects in the __local address space,
14086 // even implicitly, so don't synthesize an implicit initializer.
14087 if (getLangOpts().OpenCL &&
14088 Var->getType().getAddressSpace() == LangAS::opencl_local)
14089 return;
14090 // C++03 [dcl.init]p9:
14091 // If no initializer is specified for an object, and the
14092 // object is of (possibly cv-qualified) non-POD class type (or
14093 // array thereof), the object shall be default-initialized; if
14094 // the object is of const-qualified type, the underlying class
14095 // type shall have a user-declared default
14096 // constructor. Otherwise, if no initializer is specified for
14097 // a non- static object, the object and its subobjects, if
14098 // any, have an indeterminate initial value); if the object
14099 // or any of its subobjects are of const-qualified type, the
14100 // program is ill-formed.
14101 // C++0x [dcl.init]p11:
14102 // If no initializer is specified for an object, the object is
14103 // default-initialized; [...].
14106 = InitializationKind::CreateDefault(Var->getLocation());
14107
14108 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14109 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14110
14111 if (Init.get()) {
14112 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14113 // This is important for template substitution.
14114 Var->setInitStyle(VarDecl::CallInit);
14115 } else if (Init.isInvalid()) {
14116 // If default-init fails, attach a recovery-expr initializer to track
14117 // that initialization was attempted and failed.
14118 auto RecoveryExpr =
14119 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14120 if (RecoveryExpr.get())
14121 Var->setInit(RecoveryExpr.get());
14122 }
14123
14125 }
14126}
14127
14129 // If there is no declaration, there was an error parsing it. Ignore it.
14130 if (!D)
14131 return;
14132
14133 VarDecl *VD = dyn_cast<VarDecl>(D);
14134 if (!VD) {
14135 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14136 D->setInvalidDecl();
14137 return;
14138 }
14139
14140 VD->setCXXForRangeDecl(true);
14141
14142 // for-range-declaration cannot be given a storage class specifier.
14143 int Error = -1;
14144 switch (VD->getStorageClass()) {
14145 case SC_None:
14146 break;
14147 case SC_Extern:
14148 Error = 0;
14149 break;
14150 case SC_Static:
14151 Error = 1;
14152 break;
14153 case SC_PrivateExtern:
14154 Error = 2;
14155 break;
14156 case SC_Auto:
14157 Error = 3;
14158 break;
14159 case SC_Register:
14160 Error = 4;
14161 break;
14162 }
14163
14164 // for-range-declaration cannot be given a storage class specifier con't.
14165 switch (VD->getTSCSpec()) {
14166 case TSCS_thread_local:
14167 Error = 6;
14168 break;
14169 case TSCS___thread:
14170 case TSCS__Thread_local:
14171 case TSCS_unspecified:
14172 break;
14173 }
14174
14175 if (Error != -1) {
14176 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14177 << VD << Error;
14178 D->setInvalidDecl();
14179 }
14180}
14181
14183 IdentifierInfo *Ident,
14184 ParsedAttributes &Attrs) {
14185 // C++1y [stmt.iter]p1:
14186 // A range-based for statement of the form
14187 // for ( for-range-identifier : for-range-initializer ) statement
14188 // is equivalent to
14189 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14190 DeclSpec DS(Attrs.getPool().getFactory());
14191
14192 const char *PrevSpec;
14193 unsigned DiagID;
14194 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14196
14198 D.SetIdentifier(Ident, IdentLoc);
14199 D.takeAttributes(Attrs);
14200
14201 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14202 IdentLoc);
14203 Decl *Var = ActOnDeclarator(S, D);
14204 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14206 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14207 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14208 : IdentLoc);
14209}
14210
14212 if (var->isInvalidDecl()) return;
14213
14215
14216 if (getLangOpts().OpenCL) {
14217 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14218 // initialiser
14219 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14220 !var->hasInit()) {
14221 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14222 << 1 /*Init*/;
14223 var->setInvalidDecl();
14224 return;
14225 }
14226 }
14227
14228 // In Objective-C, don't allow jumps past the implicit initialization of a
14229 // local retaining variable.
14230 if (getLangOpts().ObjC &&
14231 var->hasLocalStorage()) {
14232 switch (var->getType().getObjCLifetime()) {
14236 break;
14237
14241 break;
14242 }
14243 }
14244
14245 if (var->hasLocalStorage() &&
14246 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14248
14249 // Warn about externally-visible variables being defined without a
14250 // prior declaration. We only want to do this for global
14251 // declarations, but we also specifically need to avoid doing it for
14252 // class members because the linkage of an anonymous class can
14253 // change if it's later given a typedef name.
14254 if (var->isThisDeclarationADefinition() &&
14255 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14256 var->isExternallyVisible() && var->hasLinkage() &&
14257 !var->isInline() && !var->getDescribedVarTemplate() &&
14258 var->getStorageClass() != SC_Register &&
14259 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14260 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14261 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14262 var->getLocation())) {
14263 // Find a previous declaration that's not a definition.
14264 VarDecl *prev = var->getPreviousDecl();
14265 while (prev && prev->isThisDeclarationADefinition())
14266 prev = prev->getPreviousDecl();
14267
14268 if (!prev) {
14269 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14270 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14271 << /* variable */ 0;
14272 }
14273 }
14274
14275 // Cache the result of checking for constant initialization.
14276 std::optional<bool> CacheHasConstInit;
14277 const Expr *CacheCulprit = nullptr;
14278 auto checkConstInit = [&]() mutable {
14279 if (!CacheHasConstInit)
14280 CacheHasConstInit = var->getInit()->isConstantInitializer(
14281 Context, var->getType()->isReferenceType(), &CacheCulprit);
14282 return *CacheHasConstInit;
14283 };
14284
14285 if (var->getTLSKind() == VarDecl::TLS_Static) {
14286 if (var->getType().isDestructedType()) {
14287 // GNU C++98 edits for __thread, [basic.start.term]p3:
14288 // The type of an object with thread storage duration shall not
14289 // have a non-trivial destructor.
14290 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14292 Diag(var->getLocation(), diag::note_use_thread_local);
14293 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14294 if (!checkConstInit()) {
14295 // GNU C++98 edits for __thread, [basic.start.init]p4:
14296 // An object of thread storage duration shall not require dynamic
14297 // initialization.
14298 // FIXME: Need strict checking here.
14299 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14300 << CacheCulprit->getSourceRange();
14302 Diag(var->getLocation(), diag::note_use_thread_local);
14303 }
14304 }
14305 }
14306
14307
14308 if (!var->getType()->isStructureType() && var->hasInit() &&
14309 isa<InitListExpr>(var->getInit())) {
14310 const auto *ILE = cast<InitListExpr>(var->getInit());
14311 unsigned NumInits = ILE->getNumInits();
14312 if (NumInits > 2)
14313 for (unsigned I = 0; I < NumInits; ++I) {
14314 const auto *Init = ILE->getInit(I);
14315 if (!Init)
14316 break;
14317 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14318 if (!SL)
14319 break;
14320
14321 unsigned NumConcat = SL->getNumConcatenated();
14322 // Diagnose missing comma in string array initialization.
14323 // Do not warn when all the elements in the initializer are concatenated
14324 // together. Do not warn for macros too.
14325 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14326 bool OnlyOneMissingComma = true;
14327 for (unsigned J = I + 1; J < NumInits; ++J) {
14328 const auto *Init = ILE->getInit(J);
14329 if (!Init)
14330 break;
14331 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14332 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14333 OnlyOneMissingComma = false;
14334 break;
14335 }
14336 }
14337
14338 if (OnlyOneMissingComma) {
14340 for (unsigned i = 0; i < NumConcat - 1; ++i)
14341 Hints.push_back(FixItHint::CreateInsertion(
14342 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14343
14344 Diag(SL->getStrTokenLoc(1),
14345 diag::warn_concatenated_literal_array_init)
14346 << Hints;
14347 Diag(SL->getBeginLoc(),
14348 diag::note_concatenated_string_literal_silence);
14349 }
14350 // In any case, stop now.
14351 break;
14352 }
14353 }
14354 }
14355
14356
14357 QualType type = var->getType();
14358
14359 if (var->hasAttr<BlocksAttr>())
14361
14362 Expr *Init = var->getInit();
14363 bool GlobalStorage = var->hasGlobalStorage();
14364 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14366 bool HasConstInit = true;
14367
14368 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14369 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14370 << var;
14371
14372 // Check whether the initializer is sufficiently constant.
14373 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14374 !type->isDependentType() && Init && !Init->isValueDependent() &&
14375 (GlobalStorage || var->isConstexpr() ||
14376 var->mightBeUsableInConstantExpressions(Context))) {
14377 // If this variable might have a constant initializer or might be usable in
14378 // constant expressions, check whether or not it actually is now. We can't
14379 // do this lazily, because the result might depend on things that change
14380 // later, such as which constexpr functions happen to be defined.
14382 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14383 // Prior to C++11, in contexts where a constant initializer is required,
14384 // the set of valid constant initializers is described by syntactic rules
14385 // in [expr.const]p2-6.
14386 // FIXME: Stricter checking for these rules would be useful for constinit /
14387 // -Wglobal-constructors.
14388 HasConstInit = checkConstInit();
14389
14390 // Compute and cache the constant value, and remember that we have a
14391 // constant initializer.
14392 if (HasConstInit) {
14393 (void)var->checkForConstantInitialization(Notes);
14394 Notes.clear();
14395 } else if (CacheCulprit) {
14396 Notes.emplace_back(CacheCulprit->getExprLoc(),
14397 PDiag(diag::note_invalid_subexpr_in_const_expr));
14398 Notes.back().second << CacheCulprit->getSourceRange();
14399 }
14400 } else {
14401 // Evaluate the initializer to see if it's a constant initializer.
14402 HasConstInit = var->checkForConstantInitialization(Notes);
14403 }
14404
14405 if (HasConstInit) {
14406 // FIXME: Consider replacing the initializer with a ConstantExpr.
14407 } else if (var->isConstexpr()) {
14408 SourceLocation DiagLoc = var->getLocation();
14409 // If the note doesn't add any useful information other than a source
14410 // location, fold it into the primary diagnostic.
14411 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14412 diag::note_invalid_subexpr_in_const_expr) {
14413 DiagLoc = Notes[0].first;
14414 Notes.clear();
14415 }
14416 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14417 << var << Init->getSourceRange();
14418 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14419 Diag(Notes[I].first, Notes[I].second);
14420 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14421 auto *Attr = var->getAttr<ConstInitAttr>();
14422 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14423 << Init->getSourceRange();
14424 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14425 << Attr->getRange() << Attr->isConstinit();
14426 for (auto &it : Notes)
14427 Diag(it.first, it.second);
14428 } else if (IsGlobal &&
14429 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14430 var->getLocation())) {
14431 // Warn about globals which don't have a constant initializer. Don't
14432 // warn about globals with a non-trivial destructor because we already
14433 // warned about them.
14434 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14435 if (!(RD && !RD->hasTrivialDestructor())) {
14436 // checkConstInit() here permits trivial default initialization even in
14437 // C++11 onwards, where such an initializer is not a constant initializer
14438 // but nonetheless doesn't require a global constructor.
14439 if (!checkConstInit())
14440 Diag(var->getLocation(), diag::warn_global_constructor)
14441 << Init->getSourceRange();
14442 }
14443 }
14444 }
14445
14446 // Apply section attributes and pragmas to global variables.
14447 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14449 PragmaStack<StringLiteral *> *Stack = nullptr;
14450 int SectionFlags = ASTContext::PSF_Read;
14451 bool MSVCEnv =
14452 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14453 std::optional<QualType::NonConstantStorageReason> Reason;
14454 if (HasConstInit &&
14455 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14456 Stack = &ConstSegStack;
14457 } else {
14458 SectionFlags |= ASTContext::PSF_Write;
14459 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14460 }
14461 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14462 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14463 SectionFlags |= ASTContext::PSF_Implicit;
14464 UnifySection(SA->getName(), SectionFlags, var);
14465 } else if (Stack->CurrentValue) {
14466 if (Stack != &ConstSegStack && MSVCEnv &&
14467 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14468 var->getType().isConstQualified()) {
14469 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14470 NonConstNonReferenceType) &&
14471 "This case should've already been handled elsewhere");
14472 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14473 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14475 : *Reason);
14476 }
14477 SectionFlags |= ASTContext::PSF_Implicit;
14478 auto SectionName = Stack->CurrentValue->getString();
14479 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14480 Stack->CurrentPragmaLocation,
14481 SectionAttr::Declspec_allocate));
14482 if (UnifySection(SectionName, SectionFlags, var))
14483 var->dropAttr<SectionAttr>();
14484 }
14485
14486 // Apply the init_seg attribute if this has an initializer. If the
14487 // initializer turns out to not be dynamic, we'll end up ignoring this
14488 // attribute.
14489 if (CurInitSeg && var->getInit())
14490 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14491 CurInitSegLoc));
14492 }
14493
14494 // All the following checks are C++ only.
14495 if (!getLangOpts().CPlusPlus) {
14496 // If this variable must be emitted, add it as an initializer for the
14497 // current module.
14498 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14499 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14500 return;
14501 }
14502
14503 // Require the destructor.
14504 if (!type->isDependentType())
14505 if (const RecordType *recordType = baseType->getAs<RecordType>())
14507
14508 // If this variable must be emitted, add it as an initializer for the current
14509 // module.
14510 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14511 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14512
14513 // Build the bindings if this is a structured binding declaration.
14514 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14516}
14517
14519 assert(VD->isStaticLocal());
14520
14521 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14522
14523 // Find outermost function when VD is in lambda function.
14524 while (FD && !getDLLAttr(FD) &&
14525 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14526 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14527 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14528 }
14529
14530 if (!FD)
14531 return;
14532
14533 // Static locals inherit dll attributes from their function.
14534 if (Attr *A = getDLLAttr(FD)) {
14535 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14536 NewAttr->setInherited(true);
14537 VD->addAttr(NewAttr);
14538 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14539 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14540 NewAttr->setInherited(true);
14541 VD->addAttr(NewAttr);
14542
14543 // Export this function to enforce exporting this static variable even
14544 // if it is not used in this compilation unit.
14545 if (!FD->hasAttr<DLLExportAttr>())
14546 FD->addAttr(NewAttr);
14547
14548 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14549 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14550 NewAttr->setInherited(true);
14551 VD->addAttr(NewAttr);
14552 }
14553}
14554
14556 assert(VD->getTLSKind());
14557
14558 // Perform TLS alignment check here after attributes attached to the variable
14559 // which may affect the alignment have been processed. Only perform the check
14560 // if the target has a maximum TLS alignment (zero means no constraints).
14561 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14562 // Protect the check so that it's not performed on dependent types and
14563 // dependent alignments (we can't determine the alignment in that case).
14564 if (!VD->hasDependentAlignment()) {
14565 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14566 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14567 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14569 << (unsigned)MaxAlignChars.getQuantity();
14570 }
14571 }
14572 }
14573}
14574
14576 // Note that we are no longer parsing the initializer for this declaration.
14577 ParsingInitForAutoVars.erase(ThisDecl);
14578
14579 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14580 if (!VD)
14581 return;
14582
14583 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14585 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14587 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14591 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14595 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14599 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14602 }
14603
14604 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14605 for (auto *BD : DD->bindings()) {
14607 }
14608 }
14609
14610 checkAttributesAfterMerging(*this, *VD);
14611
14612 if (VD->isStaticLocal())
14614
14615 if (VD->getTLSKind())
14617
14618 // Perform check for initializers of device-side global variables.
14619 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14620 // 7.5). We must also apply the same checks to all __shared__
14621 // variables whether they are local or not. CUDA also allows
14622 // constant initializers for __constant__ and __device__ variables.
14623 if (getLangOpts().CUDA)
14625
14626 // Grab the dllimport or dllexport attribute off of the VarDecl.
14627 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14628
14629 // Imported static data members cannot be defined out-of-line.
14630 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14631 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14633 // We allow definitions of dllimport class template static data members
14634 // with a warning.
14636 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14637 bool IsClassTemplateMember =
14638 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14639 Context->getDescribedClassTemplate();
14640
14641 Diag(VD->getLocation(),
14642 IsClassTemplateMember
14643 ? diag::warn_attribute_dllimport_static_field_definition
14644 : diag::err_attribute_dllimport_static_field_definition);
14645 Diag(IA->getLocation(), diag::note_attribute);
14646 if (!IsClassTemplateMember)
14647 VD->setInvalidDecl();
14648 }
14649 }
14650
14651 // dllimport/dllexport variables cannot be thread local, their TLS index
14652 // isn't exported with the variable.
14653 if (DLLAttr && VD->getTLSKind()) {
14654 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14655 if (F && getDLLAttr(F)) {
14656 assert(VD->isStaticLocal());
14657 // But if this is a static local in a dlimport/dllexport function, the
14658 // function will never be inlined, which means the var would never be
14659 // imported, so having it marked import/export is safe.
14660 } else {
14661 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14662 << DLLAttr;
14663 VD->setInvalidDecl();
14664 }
14665 }
14666
14667 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14668 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14669 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14670 << Attr;
14671 VD->dropAttr<UsedAttr>();
14672 }
14673 }
14674 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14675 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14676 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14677 << Attr;
14678 VD->dropAttr<RetainAttr>();
14679 }
14680 }
14681
14682 const DeclContext *DC = VD->getDeclContext();
14683 // If there's a #pragma GCC visibility in scope, and this isn't a class
14684 // member, set the visibility of this variable.
14687
14688 // FIXME: Warn on unused var template partial specializations.
14689 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14691
14692 // Now we have parsed the initializer and can update the table of magic
14693 // tag values.
14694 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14696 return;
14697
14698 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14699 const Expr *MagicValueExpr = VD->getInit();
14700 if (!MagicValueExpr) {
14701 continue;
14702 }
14703 std::optional<llvm::APSInt> MagicValueInt;
14704 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14705 Diag(I->getRange().getBegin(),
14706 diag::err_type_tag_for_datatype_not_ice)
14707 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14708 continue;
14709 }
14710 if (MagicValueInt->getActiveBits() > 64) {
14711 Diag(I->getRange().getBegin(),
14712 diag::err_type_tag_for_datatype_too_large)
14713 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14714 continue;
14715 }
14716 uint64_t MagicValue = MagicValueInt->getZExtValue();
14717 RegisterTypeTagForDatatype(I->getArgumentKind(),
14718 MagicValue,
14719 I->getMatchingCType(),
14720 I->getLayoutCompatible(),
14721 I->getMustBeNull());
14722 }
14723}
14724
14726 auto *VD = dyn_cast<VarDecl>(DD);
14727 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14728}
14729
14731 ArrayRef<Decl *> Group) {
14733
14734 if (DS.isTypeSpecOwned())
14735 Decls.push_back(DS.getRepAsDecl());
14736
14737 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14738 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14739 bool DiagnosedMultipleDecomps = false;
14740 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14741 bool DiagnosedNonDeducedAuto = false;
14742
14743 for (Decl *D : Group) {
14744 if (!D)
14745 continue;
14746 // Check if the Decl has been declared in '#pragma omp declare target'
14747 // directive and has static storage duration.
14748 if (auto *VD = dyn_cast<VarDecl>(D);
14749 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14750 VD->hasGlobalStorage())
14752 // For declarators, there are some additional syntactic-ish checks we need
14753 // to perform.
14754 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14755 if (!FirstDeclaratorInGroup)
14756 FirstDeclaratorInGroup = DD;
14757 if (!FirstDecompDeclaratorInGroup)
14758 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14759 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14760 !hasDeducedAuto(DD))
14761 FirstNonDeducedAutoInGroup = DD;
14762
14763 if (FirstDeclaratorInGroup != DD) {
14764 // A decomposition declaration cannot be combined with any other
14765 // declaration in the same group.
14766 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14767 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14768 diag::err_decomp_decl_not_alone)
14769 << FirstDeclaratorInGroup->getSourceRange()
14770 << DD->getSourceRange();
14771 DiagnosedMultipleDecomps = true;
14772 }
14773
14774 // A declarator that uses 'auto' in any way other than to declare a
14775 // variable with a deduced type cannot be combined with any other
14776 // declarator in the same group.
14777 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14778 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14779 diag::err_auto_non_deduced_not_alone)
14780 << FirstNonDeducedAutoInGroup->getType()
14782 << FirstDeclaratorInGroup->getSourceRange()
14783 << DD->getSourceRange();
14784 DiagnosedNonDeducedAuto = true;
14785 }
14786 }
14787 }
14788
14789 Decls.push_back(D);
14790 }
14791
14793 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14794 handleTagNumbering(Tag, S);
14795 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14797 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14798 }
14799 }
14800
14801 return BuildDeclaratorGroup(Decls);
14802}
14803
14806 // C++14 [dcl.spec.auto]p7: (DR1347)
14807 // If the type that replaces the placeholder type is not the same in each
14808 // deduction, the program is ill-formed.
14809 if (Group.size() > 1) {
14810 QualType Deduced;
14811 VarDecl *DeducedDecl = nullptr;
14812 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14813 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14814 if (!D || D->isInvalidDecl())
14815 break;
14816 DeducedType *DT = D->getType()->getContainedDeducedType();
14817 if (!DT || DT->getDeducedType().isNull())
14818 continue;
14819 if (Deduced.isNull()) {
14820 Deduced = DT->getDeducedType();
14821 DeducedDecl = D;
14822 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14823 auto *AT = dyn_cast<AutoType>(DT);
14824 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14825 diag::err_auto_different_deductions)
14826 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14827 << DeducedDecl->getDeclName() << DT->getDeducedType()
14828 << D->getDeclName();
14829 if (DeducedDecl->hasInit())
14830 Dia << DeducedDecl->getInit()->getSourceRange();
14831 if (D->getInit())
14832 Dia << D->getInit()->getSourceRange();
14833 D->setInvalidDecl();
14834 break;
14835 }
14836 }
14837 }
14838
14840
14841 return DeclGroupPtrTy::make(
14842 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14843}
14844
14847}
14848
14850 // Don't parse the comment if Doxygen diagnostics are ignored.
14851 if (Group.empty() || !Group[0])
14852 return;
14853
14854 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14855 Group[0]->getLocation()) &&
14856 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14857 Group[0]->getLocation()))
14858 return;
14859
14860 if (Group.size() >= 2) {
14861 // This is a decl group. Normally it will contain only declarations
14862 // produced from declarator list. But in case we have any definitions or
14863 // additional declaration references:
14864 // 'typedef struct S {} S;'
14865 // 'typedef struct S *S;'
14866 // 'struct S *pS;'
14867 // FinalizeDeclaratorGroup adds these as separate declarations.
14868 Decl *MaybeTagDecl = Group[0];
14869 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14870 Group = Group.slice(1);
14871 }
14872 }
14873
14874 // FIMXE: We assume every Decl in the group is in the same file.
14875 // This is false when preprocessor constructs the group from decls in
14876 // different files (e. g. macros or #include).
14878}
14879
14881 // Check that there are no default arguments inside the type of this
14882 // parameter.
14883 if (getLangOpts().CPlusPlus)
14885
14886 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14887 if (D.getCXXScopeSpec().isSet()) {
14888 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14889 << D.getCXXScopeSpec().getRange();
14890 }
14891
14892 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14893 // simple identifier except [...irrelevant cases...].
14894 switch (D.getName().getKind()) {
14896 break;
14897
14905 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14907 break;
14908
14911 // GetNameForDeclarator would not produce a useful name in this case.
14912 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14913 break;
14914 }
14915}
14916
14918 SourceLocation ExplicitThisLoc) {
14919 if (!ExplicitThisLoc.isValid())
14920 return;
14921 assert(S.getLangOpts().CPlusPlus &&
14922 "explicit parameter in non-cplusplus mode");
14923 if (!S.getLangOpts().CPlusPlus23)
14924 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14925 << P->getSourceRange();
14926
14927 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14928 // parameter pack.
14929 if (P->isParameterPack()) {
14930 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14931 << P->getSourceRange();
14932 return;
14933 }
14934 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14935 if (LambdaScopeInfo *LSI = S.getCurLambda())
14936 LSI->ExplicitObjectParameter = P;
14937}
14938
14940 SourceLocation ExplicitThisLoc) {
14941 const DeclSpec &DS = D.getDeclSpec();
14942
14943 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14944
14945 // C++03 [dcl.stc]p2 also permits 'auto'.
14946 StorageClass SC = SC_None;
14948 SC = SC_Register;
14949 // In C++11, the 'register' storage class specifier is deprecated.
14950 // In C++17, it is not allowed, but we tolerate it as an extension.
14951 if (getLangOpts().CPlusPlus11) {
14953 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14954 : diag::warn_deprecated_register)
14956 }
14957 } else if (getLangOpts().CPlusPlus &&
14959 SC = SC_Auto;
14962 diag::err_invalid_storage_class_in_func_decl);
14963 D.getMutableDeclSpec().ClearStorageClassSpecs();
14964 }
14965
14967 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14969 if (DS.isInlineSpecified())
14970 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14971 << getLangOpts().CPlusPlus17;
14972 if (DS.hasConstexprSpecifier())
14973 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14974 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14975
14977
14979
14981 QualType parmDeclType = TInfo->getType();
14982
14983 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14984 const IdentifierInfo *II = D.getIdentifier();
14985 if (II) {
14986 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14987 RedeclarationKind::ForVisibleRedeclaration);
14988 LookupName(R, S);
14989 if (!R.empty()) {
14990 NamedDecl *PrevDecl = *R.begin();
14991 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
14992 // Maybe we will complain about the shadowed template parameter.
14993 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14994 // Just pretend that we didn't see the previous declaration.
14995 PrevDecl = nullptr;
14996 }
14997 if (PrevDecl && S->isDeclScope(PrevDecl)) {
14998 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14999 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15000 // Recover by removing the name
15001 II = nullptr;
15002 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15003 D.setInvalidType(true);
15004 }
15005 }
15006 }
15007
15008 // Temporarily put parameter variables in the translation unit, not
15009 // the enclosing context. This prevents them from accidentally
15010 // looking like class members in C++.
15011 ParmVarDecl *New =
15013 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15014
15015 if (D.isInvalidType())
15016 New->setInvalidDecl();
15017
15018 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15019
15020 assert(S->isFunctionPrototypeScope());
15021 assert(S->getFunctionPrototypeDepth() >= 1);
15022 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15023 S->getNextFunctionPrototypeIndex());
15024
15025 // Add the parameter declaration into this scope.
15026 S->AddDecl(New);
15027 if (II)
15028 IdResolver.AddDecl(New);
15029
15030 ProcessDeclAttributes(S, New, D);
15031
15032 if (D.getDeclSpec().isModulePrivateSpecified())
15033 Diag(New->getLocation(), diag::err_module_private_local)
15034 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15035 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15036
15037 if (New->hasAttr<BlocksAttr>()) {
15038 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15039 }
15040
15041 if (getLangOpts().OpenCL)
15043
15044 return New;
15045}
15046
15049 QualType T) {
15050 /* FIXME: setting StartLoc == Loc.
15051 Would it be worth to modify callers so as to provide proper source
15052 location for the unnamed parameters, embedding the parameter's type? */
15053 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15055 SC_None, nullptr);
15056 Param->setImplicit();
15057 return Param;
15058}
15059
15061 // Don't diagnose unused-parameter errors in template instantiations; we
15062 // will already have done so in the template itself.
15064 return;
15065
15066 for (const ParmVarDecl *Parameter : Parameters) {
15067 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15068 !Parameter->hasAttr<UnusedAttr>() &&
15069 !Parameter->getIdentifier()->isPlaceholder()) {
15070 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15071 << Parameter->getDeclName();
15072 }
15073 }
15074}
15075
15077 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15078 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15079 return;
15080
15081 // Warn if the return value is pass-by-value and larger than the specified
15082 // threshold.
15083 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15084 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15085 if (Size > LangOpts.NumLargeByValueCopy)
15086 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15087 }
15088
15089 // Warn if any parameter is pass-by-value and larger than the specified
15090 // threshold.
15091 for (const ParmVarDecl *Parameter : Parameters) {
15092 QualType T = Parameter->getType();
15093 if (T->isDependentType() || !T.isPODType(Context))
15094 continue;
15095 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15096 if (Size > LangOpts.NumLargeByValueCopy)
15097 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15098 << Parameter << Size;
15099 }
15100}
15101
15103 SourceLocation NameLoc,
15104 const IdentifierInfo *Name, QualType T,
15105 TypeSourceInfo *TSInfo, StorageClass SC) {
15106 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15107 if (getLangOpts().ObjCAutoRefCount &&
15108 T.getObjCLifetime() == Qualifiers::OCL_None &&
15109 T->isObjCLifetimeType()) {
15110
15111 Qualifiers::ObjCLifetime lifetime;
15112
15113 // Special cases for arrays:
15114 // - if it's const, use __unsafe_unretained
15115 // - otherwise, it's an error
15116 if (T->isArrayType()) {
15117 if (!T.isConstQualified()) {
15121 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15122 else
15123 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15124 << TSInfo->getTypeLoc().getSourceRange();
15125 }
15127 } else {
15128 lifetime = T->getObjCARCImplicitLifetime();
15129 }
15130 T = Context.getLifetimeQualifiedType(T, lifetime);
15131 }
15132
15133 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15135 TSInfo, SC, nullptr);
15136
15137 // Make a note if we created a new pack in the scope of a lambda, so that
15138 // we know that references to that pack must also be expanded within the
15139 // lambda scope.
15140 if (New->isParameterPack())
15141 if (auto *LSI = getEnclosingLambda())
15142 LSI->LocalPacks.push_back(New);
15143
15148
15149 // Parameter declarators cannot be interface types. All ObjC objects are
15150 // passed by reference.
15151 if (T->isObjCObjectType()) {
15152 SourceLocation TypeEndLoc =
15154 Diag(NameLoc,
15155 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15156 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15158 New->setType(T);
15159 }
15160
15161 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15162 // duration shall not be qualified by an address-space qualifier."
15163 // Since all parameters have automatic store duration, they can not have
15164 // an address space.
15165 if (T.getAddressSpace() != LangAS::Default &&
15166 // OpenCL allows function arguments declared to be an array of a type
15167 // to be qualified with an address space.
15168 !(getLangOpts().OpenCL &&
15169 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15170 // WebAssembly allows reference types as parameters. Funcref in particular
15171 // lives in a different address space.
15172 !(T->isFunctionPointerType() &&
15173 T.getAddressSpace() == LangAS::wasm_funcref)) {
15174 Diag(NameLoc, diag::err_arg_with_address_space);
15175 New->setInvalidDecl();
15176 }
15177
15178 // PPC MMA non-pointer types are not allowed as function argument types.
15179 if (Context.getTargetInfo().getTriple().isPPC64() &&
15180 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15181 New->setInvalidDecl();
15182 }
15183
15184 return New;
15185}
15186
15188 SourceLocation LocAfterDecls) {
15189 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15190
15191 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15192 // in the declaration list shall have at least one declarator, those
15193 // declarators shall only declare identifiers from the identifier list, and
15194 // every identifier in the identifier list shall be declared.
15195 //
15196 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15197 // identifiers it names shall be declared in the declaration list."
15198 //
15199 // This is why we only diagnose in C99 and later. Note, the other conditions
15200 // listed are checked elsewhere.
15201 if (!FTI.hasPrototype) {
15202 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15203 --i;
15204 if (FTI.Params[i].Param == nullptr) {
15205 if (getLangOpts().C99) {
15206 SmallString<256> Code;
15207 llvm::raw_svector_ostream(Code)
15208 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15209 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15210 << FTI.Params[i].Ident
15211 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15212 }
15213
15214 // Implicitly declare the argument as type 'int' for lack of a better
15215 // type.
15216 AttributeFactory attrs;
15217 DeclSpec DS(attrs);
15218 const char* PrevSpec; // unused
15219 unsigned DiagID; // unused
15220 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15221 DiagID, Context.getPrintingPolicy());
15222 // Use the identifier location for the type source range.
15223 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15224 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15227 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15228 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15229 }
15230 }
15231 }
15232}
15233
15234Decl *
15236 MultiTemplateParamsArg TemplateParameterLists,
15237 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15238 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15239 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15240 Scope *ParentScope = FnBodyScope->getParent();
15241
15242 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15243 // we define a non-templated function definition, we will create a declaration
15244 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15245 // The base function declaration will have the equivalent of an `omp declare
15246 // variant` annotation which specifies the mangled definition as a
15247 // specialization function under the OpenMP context defined as part of the
15248 // `omp begin declare variant`.
15250 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15252 ParentScope, D, TemplateParameterLists, Bases);
15253
15254 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15255 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15256 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15257
15258 if (!Bases.empty())
15260 Bases);
15261
15262 return Dcl;
15263}
15264
15267}
15268
15270 const FunctionDecl *&PossiblePrototype) {
15271 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15272 Prev = Prev->getPreviousDecl()) {
15273 // Ignore any declarations that occur in function or method
15274 // scope, because they aren't visible from the header.
15275 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15276 continue;
15277
15278 PossiblePrototype = Prev;
15279 return Prev->getType()->isFunctionProtoType();
15280 }
15281 return false;
15282}
15283
15284static bool
15286 const FunctionDecl *&PossiblePrototype) {
15287 // Don't warn about invalid declarations.
15288 if (FD->isInvalidDecl())
15289 return false;
15290
15291 // Or declarations that aren't global.
15292 if (!FD->isGlobal())
15293 return false;
15294
15295 // Don't warn about C++ member functions.
15296 if (isa<CXXMethodDecl>(FD))
15297 return false;
15298
15299 // Don't warn about 'main'.
15300 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15301 if (IdentifierInfo *II = FD->getIdentifier())
15302 if (II->isStr("main") || II->isStr("efi_main"))
15303 return false;
15304
15305 if (FD->isMSVCRTEntryPoint())
15306 return false;
15307
15308 // Don't warn about inline functions.
15309 if (FD->isInlined())
15310 return false;
15311
15312 // Don't warn about function templates.
15314 return false;
15315
15316 // Don't warn about function template specializations.
15318 return false;
15319
15320 // Don't warn for OpenCL kernels.
15321 if (FD->hasAttr<OpenCLKernelAttr>())
15322 return false;
15323
15324 // Don't warn on explicitly deleted functions.
15325 if (FD->isDeleted())
15326 return false;
15327
15328 // Don't warn on implicitly local functions (such as having local-typed
15329 // parameters).
15330 if (!FD->isExternallyVisible())
15331 return false;
15332
15333 // If we were able to find a potential prototype, don't warn.
15334 if (FindPossiblePrototype(FD, PossiblePrototype))
15335 return false;
15336
15337 return true;
15338}
15339
15340void
15342 const FunctionDecl *EffectiveDefinition,
15343 SkipBodyInfo *SkipBody) {
15344 const FunctionDecl *Definition = EffectiveDefinition;
15345 if (!Definition &&
15346 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15347 return;
15348
15349 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15350 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15351 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15352 // A merged copy of the same function, instantiated as a member of
15353 // the same class, is OK.
15354 if (declaresSameEntity(OrigFD, OrigDef) &&
15355 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15356 cast<Decl>(FD->getLexicalDeclContext())))
15357 return;
15358 }
15359 }
15360 }
15361
15363 return;
15364
15365 // Don't emit an error when this is redefinition of a typo-corrected
15366 // definition.
15368 return;
15369
15370 // If we don't have a visible definition of the function, and it's inline or
15371 // a template, skip the new definition.
15372 if (SkipBody && !hasVisibleDefinition(Definition) &&
15373 (Definition->getFormalLinkage() == Linkage::Internal ||
15374 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15375 Definition->getNumTemplateParameterLists())) {
15376 SkipBody->ShouldSkip = true;
15377 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15378 if (auto *TD = Definition->getDescribedFunctionTemplate())
15381 return;
15382 }
15383
15384 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15385 Definition->getStorageClass() == SC_Extern)
15386 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15387 << FD << getLangOpts().CPlusPlus;
15388 else
15389 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15390
15391 Diag(Definition->getLocation(), diag::note_previous_definition);
15392 FD->setInvalidDecl();
15393}
15394
15396 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15397
15399 LSI->CallOperator = CallOperator;
15400 LSI->Lambda = LambdaClass;
15401 LSI->ReturnType = CallOperator->getReturnType();
15402 // This function in calls in situation where the context of the call operator
15403 // is not entered, so we set AfterParameterList to false, so that
15404 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15405 LSI->AfterParameterList = false;
15406 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15407
15408 if (LCD == LCD_None)
15410 else if (LCD == LCD_ByCopy)
15412 else if (LCD == LCD_ByRef)
15414 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15415
15417 LSI->Mutable = !CallOperator->isConst();
15418 if (CallOperator->isExplicitObjectMemberFunction())
15419 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15420
15421 // Add the captures to the LSI so they can be noted as already
15422 // captured within tryCaptureVar.
15423 auto I = LambdaClass->field_begin();
15424 for (const auto &C : LambdaClass->captures()) {
15425 if (C.capturesVariable()) {
15426 ValueDecl *VD = C.getCapturedVar();
15427 if (VD->isInitCapture())
15429 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15430 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15431 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15432 /*EllipsisLoc*/C.isPackExpansion()
15433 ? C.getEllipsisLoc() : SourceLocation(),
15434 I->getType(), /*Invalid*/false);
15435
15436 } else if (C.capturesThis()) {
15437 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15438 C.getCaptureKind() == LCK_StarThis);
15439 } else {
15440 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15441 I->getType());
15442 }
15443 ++I;
15444 }
15445 return LSI;
15446}
15447
15449 SkipBodyInfo *SkipBody,
15450 FnBodyKind BodyKind) {
15451 if (!D) {
15452 // Parsing the function declaration failed in some way. Push on a fake scope
15453 // anyway so we can try to parse the function body.
15456 return D;
15457 }
15458
15459 FunctionDecl *FD = nullptr;
15460
15461 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15462 FD = FunTmpl->getTemplatedDecl();
15463 else
15464 FD = cast<FunctionDecl>(D);
15465
15466 // Do not push if it is a lambda because one is already pushed when building
15467 // the lambda in ActOnStartOfLambdaDefinition().
15468 if (!isLambdaCallOperator(FD))
15469 // [expr.const]/p14.1
15470 // An expression or conversion is in an immediate function context if it is
15471 // potentially evaluated and either: its innermost enclosing non-block scope
15472 // is a function parameter scope of an immediate function.
15475 : ExprEvalContexts.back().Context);
15476
15477 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15478 // context is nested in an immediate function context, so smaller contexts
15479 // that appear inside immediate functions (like variable initializers) are
15480 // considered to be inside an immediate function context even though by
15481 // themselves they are not immediate function contexts. But when a new
15482 // function is entered, we need to reset this tracking, since the entered
15483 // function might be not an immediate function.
15484 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15485 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15486 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15487
15488 // Check for defining attributes before the check for redefinition.
15489 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15490 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15491 FD->dropAttr<AliasAttr>();
15492 FD->setInvalidDecl();
15493 }
15494 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15495 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15496 FD->dropAttr<IFuncAttr>();
15497 FD->setInvalidDecl();
15498 }
15499 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15500 if (!Context.getTargetInfo().hasFeature("fmv") &&
15501 !Attr->isDefaultVersion()) {
15502 // If function multi versioning disabled skip parsing function body
15503 // defined with non-default target_version attribute
15504 if (SkipBody)
15505 SkipBody->ShouldSkip = true;
15506 return nullptr;
15507 }
15508 }
15509
15510 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15511 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15512 Ctor->isDefaultConstructor() &&
15514 // If this is an MS ABI dllexport default constructor, instantiate any
15515 // default arguments.
15517 }
15518 }
15519
15520 // See if this is a redefinition. If 'will have body' (or similar) is already
15521 // set, then these checks were already performed when it was set.
15522 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15524 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15525
15526 // If we're skipping the body, we're done. Don't enter the scope.
15527 if (SkipBody && SkipBody->ShouldSkip)
15528 return D;
15529 }
15530
15531 // Mark this function as "will have a body eventually". This lets users to
15532 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15533 // this function.
15534 FD->setWillHaveBody();
15535
15536 // If we are instantiating a generic lambda call operator, push
15537 // a LambdaScopeInfo onto the function stack. But use the information
15538 // that's already been calculated (ActOnLambdaExpr) to prime the current
15539 // LambdaScopeInfo.
15540 // When the template operator is being specialized, the LambdaScopeInfo,
15541 // has to be properly restored so that tryCaptureVariable doesn't try
15542 // and capture any new variables. In addition when calculating potential
15543 // captures during transformation of nested lambdas, it is necessary to
15544 // have the LSI properly restored.
15546 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15547 // instantiated, explicitly specialized.
15550 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15551 FD->setInvalidDecl();
15553 } else {
15554 assert(inTemplateInstantiation() &&
15555 "There should be an active template instantiation on the stack "
15556 "when instantiating a generic lambda!");
15557 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15558 }
15559 } else {
15560 // Enter a new function scope
15562 }
15563
15564 // Builtin functions cannot be defined.
15565 if (unsigned BuiltinID = FD->getBuiltinID()) {
15568 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15569 FD->setInvalidDecl();
15570 }
15571 }
15572
15573 // The return type of a function definition must be complete (C99 6.9.1p3).
15574 // C++23 [dcl.fct.def.general]/p2
15575 // The type of [...] the return for a function definition
15576 // shall not be a (possibly cv-qualified) class type that is incomplete
15577 // or abstract within the function body unless the function is deleted.
15578 QualType ResultType = FD->getReturnType();
15579 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15580 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15581 (RequireCompleteType(FD->getLocation(), ResultType,
15582 diag::err_func_def_incomplete_result) ||
15584 diag::err_abstract_type_in_decl,
15586 FD->setInvalidDecl();
15587
15588 if (FnBodyScope)
15589 PushDeclContext(FnBodyScope, FD);
15590
15591 // Check the validity of our function parameters
15592 if (BodyKind != FnBodyKind::Delete)
15594 /*CheckParameterNames=*/true);
15595
15596 // Add non-parameter declarations already in the function to the current
15597 // scope.
15598 if (FnBodyScope) {
15599 for (Decl *NPD : FD->decls()) {
15600 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15601 if (!NonParmDecl)
15602 continue;
15603 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15604 "parameters should not be in newly created FD yet");
15605
15606 // If the decl has a name, make it accessible in the current scope.
15607 if (NonParmDecl->getDeclName())
15608 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15609
15610 // Similarly, dive into enums and fish their constants out, making them
15611 // accessible in this scope.
15612 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15613 for (auto *EI : ED->enumerators())
15614 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15615 }
15616 }
15617 }
15618
15619 // Introduce our parameters into the function scope
15620 for (auto *Param : FD->parameters()) {
15621 Param->setOwningFunction(FD);
15622
15623 // If this has an identifier, add it to the scope stack.
15624 if (Param->getIdentifier() && FnBodyScope) {
15625 CheckShadow(FnBodyScope, Param);
15626
15627 PushOnScopeChains(Param, FnBodyScope);
15628 }
15629 }
15630
15631 // C++ [module.import/6] external definitions are not permitted in header
15632 // units. Deleted and Defaulted functions are implicitly inline (but the
15633 // inline state is not set at this point, so check the BodyKind explicitly).
15634 // FIXME: Consider an alternate location for the test where the inlined()
15635 // state is complete.
15636 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15637 !FD->isInvalidDecl() && !FD->isInlined() &&
15638 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15639 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15640 !FD->isTemplateInstantiation()) {
15641 assert(FD->isThisDeclarationADefinition());
15642 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15643 FD->setInvalidDecl();
15644 }
15645
15646 // Ensure that the function's exception specification is instantiated.
15647 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15649
15650 // dllimport cannot be applied to non-inline function definitions.
15651 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15652 !FD->isTemplateInstantiation()) {
15653 assert(!FD->hasAttr<DLLExportAttr>());
15654 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15655 FD->setInvalidDecl();
15656 return D;
15657 }
15658
15659 // Some function attributes (like OptimizeNoneAttr) need actions before
15660 // parsing body started.
15662
15663 // We want to attach documentation to original Decl (which might be
15664 // a function template).
15666 if (getCurLexicalContext()->isObjCContainer() &&
15667 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15668 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15669 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15670
15671 return D;
15672}
15673
15675 if (!FD || FD->isInvalidDecl())
15676 return;
15677 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15678 FD = TD->getTemplatedDecl();
15679 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15683 FpPragmaStack.CurrentValue =
15685 }
15686}
15687
15689 ReturnStmt **Returns = Scope->Returns.data();
15690
15691 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15692 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15693 if (!NRVOCandidate->isNRVOVariable())
15694 Returns[I]->setNRVOCandidate(nullptr);
15695 }
15696 }
15697}
15698
15700 // We can't delay parsing the body of a constexpr function template (yet).
15701 if (D.getDeclSpec().hasConstexprSpecifier())
15702 return false;
15703
15704 // We can't delay parsing the body of a function template with a deduced
15705 // return type (yet).
15706 if (D.getDeclSpec().hasAutoTypeSpec()) {
15707 // If the placeholder introduces a non-deduced trailing return type,
15708 // we can still delay parsing it.
15709 if (D.getNumTypeObjects()) {
15710 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15711 if (Outer.Kind == DeclaratorChunk::Function &&
15712 Outer.Fun.hasTrailingReturnType()) {
15713 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15714 return Ty.isNull() || !Ty->isUndeducedType();
15715 }
15716 }
15717 return false;
15718 }
15719
15720 return true;
15721}
15722
15724 // We cannot skip the body of a function (or function template) which is
15725 // constexpr, since we may need to evaluate its body in order to parse the
15726 // rest of the file.
15727 // We cannot skip the body of a function with an undeduced return type,
15728 // because any callers of that function need to know the type.
15729 if (const FunctionDecl *FD = D->getAsFunction()) {
15730 if (FD->isConstexpr())
15731 return false;
15732 // We can't simply call Type::isUndeducedType here, because inside template
15733 // auto can be deduced to a dependent type, which is not considered
15734 // "undeduced".
15735 if (FD->getReturnType()->getContainedDeducedType())
15736 return false;
15737 }
15739}
15740
15742 if (!Decl)
15743 return nullptr;
15744 if (FunctionDecl *FD = Decl->getAsFunction())
15745 FD->setHasSkippedBody();
15746 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15747 MD->setHasSkippedBody();
15748 return Decl;
15749}
15750
15752 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15753}
15754
15755/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15756/// body.
15758public:
15759 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15761 if (!IsLambda)
15763 }
15764
15765private:
15766 Sema &S;
15767 bool IsLambda = false;
15768};
15769
15771 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15772
15773 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15774 if (EscapeInfo.count(BD))
15775 return EscapeInfo[BD];
15776
15777 bool R = false;
15778 const BlockDecl *CurBD = BD;
15779
15780 do {
15781 R = !CurBD->doesNotEscape();
15782 if (R)
15783 break;
15784 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15785 } while (CurBD);
15786
15787 return EscapeInfo[BD] = R;
15788 };
15789
15790 // If the location where 'self' is implicitly retained is inside a escaping
15791 // block, emit a diagnostic.
15792 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15794 if (IsOrNestedInEscapingBlock(P.second))
15795 S.Diag(P.first, diag::warn_implicitly_retains_self)
15796 << FixItHint::CreateInsertion(P.first, "self->");
15797}
15798
15799static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15800 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15801 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15802}
15803
15805 return methodHasName(FD, "get_return_object");
15806}
15807
15809 return FD->isStatic() &&
15810 methodHasName(FD, "get_return_object_on_allocation_failure");
15811}
15812
15815 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15816 return;
15817 // Allow some_promise_type::get_return_object().
15819 return;
15820 if (!FD->hasAttr<CoroWrapperAttr>())
15821 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15822}
15823
15825 bool IsInstantiation) {
15827 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15828
15829 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15830 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15831
15833 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15834
15835 // If we skip function body, we can't tell if a function is a coroutine.
15836 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15837 if (FSI->isCoroutine())
15839 else
15841 }
15842
15843 {
15844 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15845 // one is already popped when finishing the lambda in BuildLambdaExpr().
15846 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15847 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15848 if (FD) {
15849 // If this is called by Parser::ParseFunctionDefinition() after marking
15850 // the declaration as deleted, and if the deleted-function-body contains
15851 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15852 // added to store that message; do not overwrite it in that case.
15853 //
15854 // Since this would always set the body to 'nullptr' in that case anyway,
15855 // which is already done when the function decl is initially created,
15856 // always skipping this irrespective of whether there is a delete message
15857 // should not be a problem.
15858 if (!FD->isDeletedAsWritten())
15859 FD->setBody(Body);
15860 FD->setWillHaveBody(false);
15862
15863 if (getLangOpts().CPlusPlus14) {
15864 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15865 FD->getReturnType()->isUndeducedType()) {
15866 // For a function with a deduced result type to return void,
15867 // the result type as written must be 'auto' or 'decltype(auto)',
15868 // possibly cv-qualified or constrained, but not ref-qualified.
15869 if (!FD->getReturnType()->getAs<AutoType>()) {
15870 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15871 << FD->getReturnType();
15872 FD->setInvalidDecl();
15873 } else {
15874 // Falling off the end of the function is the same as 'return;'.
15875 Expr *Dummy = nullptr;
15877 FD, dcl->getLocation(), Dummy,
15878 FD->getReturnType()->getAs<AutoType>()))
15879 FD->setInvalidDecl();
15880 }
15881 }
15882 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
15883 // In C++11, we don't use 'auto' deduction rules for lambda call
15884 // operators because we don't support return type deduction.
15885 auto *LSI = getCurLambda();
15886 if (LSI->HasImplicitReturnType) {
15888
15889 // C++11 [expr.prim.lambda]p4:
15890 // [...] if there are no return statements in the compound-statement
15891 // [the deduced type is] the type void
15892 QualType RetType =
15893 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15894
15895 // Update the return type to the deduced type.
15896 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15897 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15898 Proto->getExtProtoInfo()));
15899 }
15900 }
15901
15902 // If the function implicitly returns zero (like 'main') or is naked,
15903 // don't complain about missing return statements.
15904 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15906
15907 // MSVC permits the use of pure specifier (=0) on function definition,
15908 // defined at class scope, warn about this non-standard construct.
15909 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
15910 !FD->isOutOfLine())
15911 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15912
15913 if (!FD->isInvalidDecl()) {
15914 // Don't diagnose unused parameters of defaulted, deleted or naked
15915 // functions.
15916 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15917 !FD->hasAttr<NakedAttr>())
15920 FD->getReturnType(), FD);
15921
15922 // If this is a structor, we need a vtable.
15923 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15924 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15925 else if (CXXDestructorDecl *Destructor =
15926 dyn_cast<CXXDestructorDecl>(FD))
15927 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15928
15929 // Try to apply the named return value optimization. We have to check
15930 // if we can do this here because lambdas keep return statements around
15931 // to deduce an implicit return type.
15932 if (FD->getReturnType()->isRecordType() &&
15934 computeNRVO(Body, FSI);
15935 }
15936
15937 // GNU warning -Wmissing-prototypes:
15938 // Warn if a global function is defined without a previous
15939 // prototype declaration. This warning is issued even if the
15940 // definition itself provides a prototype. The aim is to detect
15941 // global functions that fail to be declared in header files.
15942 const FunctionDecl *PossiblePrototype = nullptr;
15943 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15944 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15945
15946 if (PossiblePrototype) {
15947 // We found a declaration that is not a prototype,
15948 // but that could be a zero-parameter prototype
15949 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15950 TypeLoc TL = TI->getTypeLoc();
15952 Diag(PossiblePrototype->getLocation(),
15953 diag::note_declaration_not_a_prototype)
15954 << (FD->getNumParams() != 0)
15956 FTL.getRParenLoc(), "void")
15957 : FixItHint{});
15958 }
15959 } else {
15960 // Returns true if the token beginning at this Loc is `const`.
15961 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15962 const LangOptions &LangOpts) {
15963 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15964 if (LocInfo.first.isInvalid())
15965 return false;
15966
15967 bool Invalid = false;
15968 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15969 if (Invalid)
15970 return false;
15971
15972 if (LocInfo.second > Buffer.size())
15973 return false;
15974
15975 const char *LexStart = Buffer.data() + LocInfo.second;
15976 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15977
15978 return StartTok.consume_front("const") &&
15979 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15980 StartTok.starts_with("/*") || StartTok.starts_with("//"));
15981 };
15982
15983 auto findBeginLoc = [&]() {
15984 // If the return type has `const` qualifier, we want to insert
15985 // `static` before `const` (and not before the typename).
15986 if ((FD->getReturnType()->isAnyPointerType() &&
15989 // But only do this if we can determine where the `const` is.
15990
15991 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15992 getLangOpts()))
15993
15994 return FD->getBeginLoc();
15995 }
15996 return FD->getTypeSpecStartLoc();
15997 };
15999 diag::note_static_for_internal_linkage)
16000 << /* function */ 1
16001 << (FD->getStorageClass() == SC_None
16002 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16003 : FixItHint{});
16004 }
16005 }
16006
16007 // We might not have found a prototype because we didn't wish to warn on
16008 // the lack of a missing prototype. Try again without the checks for
16009 // whether we want to warn on the missing prototype.
16010 if (!PossiblePrototype)
16011 (void)FindPossiblePrototype(FD, PossiblePrototype);
16012
16013 // If the function being defined does not have a prototype, then we may
16014 // need to diagnose it as changing behavior in C23 because we now know
16015 // whether the function accepts arguments or not. This only handles the
16016 // case where the definition has no prototype but does have parameters
16017 // and either there is no previous potential prototype, or the previous
16018 // potential prototype also has no actual prototype. This handles cases
16019 // like:
16020 // void f(); void f(a) int a; {}
16021 // void g(a) int a; {}
16022 // See MergeFunctionDecl() for other cases of the behavior change
16023 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16024 // type without a prototype.
16025 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16026 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16027 !PossiblePrototype->isImplicit()))) {
16028 // The function definition has parameters, so this will change behavior
16029 // in C23. If there is a possible prototype, it comes before the
16030 // function definition.
16031 // FIXME: The declaration may have already been diagnosed as being
16032 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16033 // there's no way to test for the "changes behavior" condition in
16034 // SemaType.cpp when forming the declaration's function type. So, we do
16035 // this awkward dance instead.
16036 //
16037 // If we have a possible prototype and it declares a function with a
16038 // prototype, we don't want to diagnose it; if we have a possible
16039 // prototype and it has no prototype, it may have already been
16040 // diagnosed in SemaType.cpp as deprecated depending on whether
16041 // -Wstrict-prototypes is enabled. If we already warned about it being
16042 // deprecated, add a note that it also changes behavior. If we didn't
16043 // warn about it being deprecated (because the diagnostic is not
16044 // enabled), warn now that it is deprecated and changes behavior.
16045
16046 // This K&R C function definition definitely changes behavior in C23,
16047 // so diagnose it.
16048 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16049 << /*definition*/ 1 << /* not supported in C23 */ 0;
16050
16051 // If we have a possible prototype for the function which is a user-
16052 // visible declaration, we already tested that it has no prototype.
16053 // This will change behavior in C23. This gets a warning rather than a
16054 // note because it's the same behavior-changing problem as with the
16055 // definition.
16056 if (PossiblePrototype)
16057 Diag(PossiblePrototype->getLocation(),
16058 diag::warn_non_prototype_changes_behavior)
16059 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16060 << /*definition*/ 1;
16061 }
16062
16063 // Warn on CPUDispatch with an actual body.
16064 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16065 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16066 if (!CmpndBody->body_empty())
16067 Diag(CmpndBody->body_front()->getBeginLoc(),
16068 diag::warn_dispatch_body_ignored);
16069
16070 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16071 const CXXMethodDecl *KeyFunction;
16072 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16073 MD->isVirtual() &&
16074 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16075 MD == KeyFunction->getCanonicalDecl()) {
16076 // Update the key-function state if necessary for this ABI.
16077 if (FD->isInlined() &&
16080
16081 // If the newly-chosen key function is already defined, then we
16082 // need to mark the vtable as used retroactively.
16083 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16084 const FunctionDecl *Definition;
16085 if (KeyFunction && KeyFunction->isDefined(Definition))
16086 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16087 } else {
16088 // We just defined they key function; mark the vtable as used.
16089 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16090 }
16091 }
16092 }
16093
16094 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16095 "Function parsing confused");
16096 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16097 assert(MD == getCurMethodDecl() && "Method parsing confused");
16098 MD->setBody(Body);
16099 if (!MD->isInvalidDecl()) {
16101 MD->getReturnType(), MD);
16102
16103 if (Body)
16104 computeNRVO(Body, FSI);
16105 }
16106 if (FSI->ObjCShouldCallSuper) {
16107 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16108 << MD->getSelector().getAsString();
16109 FSI->ObjCShouldCallSuper = false;
16110 }
16112 const ObjCMethodDecl *InitMethod = nullptr;
16113 bool isDesignated =
16114 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16115 assert(isDesignated && InitMethod);
16116 (void)isDesignated;
16117
16118 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16119 auto IFace = MD->getClassInterface();
16120 if (!IFace)
16121 return false;
16122 auto SuperD = IFace->getSuperClass();
16123 if (!SuperD)
16124 return false;
16125 return SuperD->getIdentifier() ==
16126 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16127 };
16128 // Don't issue this warning for unavailable inits or direct subclasses
16129 // of NSObject.
16130 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16131 Diag(MD->getLocation(),
16132 diag::warn_objc_designated_init_missing_super_call);
16133 Diag(InitMethod->getLocation(),
16134 diag::note_objc_designated_init_marked_here);
16135 }
16137 }
16138 if (FSI->ObjCWarnForNoInitDelegation) {
16139 // Don't issue this warning for unavailable inits.
16140 if (!MD->isUnavailable())
16141 Diag(MD->getLocation(),
16142 diag::warn_objc_secondary_init_missing_init_call);
16143 FSI->ObjCWarnForNoInitDelegation = false;
16144 }
16145
16147 } else {
16148 // Parsing the function declaration failed in some way. Pop the fake scope
16149 // we pushed on.
16150 PopFunctionScopeInfo(ActivePolicy, dcl);
16151 return nullptr;
16152 }
16153
16154 if (Body && FSI->HasPotentialAvailabilityViolations)
16156
16157 assert(!FSI->ObjCShouldCallSuper &&
16158 "This should only be set for ObjC methods, which should have been "
16159 "handled in the block above.");
16160
16161 // Verify and clean out per-function state.
16162 if (Body && (!FD || !FD->isDefaulted())) {
16163 // C++ constructors that have function-try-blocks can't have return
16164 // statements in the handlers of that block. (C++ [except.handle]p14)
16165 // Verify this.
16166 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16167 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16168
16169 // Verify that gotos and switch cases don't jump into scopes illegally.
16172
16173 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16174 if (!Destructor->getParent()->isDependentType())
16176
16178 Destructor->getParent());
16179 }
16180
16181 // If any errors have occurred, clear out any temporaries that may have
16182 // been leftover. This ensures that these temporaries won't be picked up
16183 // for deletion in some later function.
16186 getDiagnostics().getSuppressAllDiagnostics()) {
16188 }
16189 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16190 // Since the body is valid, issue any analysis-based warnings that are
16191 // enabled.
16192 ActivePolicy = &WP;
16193 }
16194
16195 if (!IsInstantiation && FD &&
16196 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16197 !FD->isInvalidDecl() &&
16199 FD->setInvalidDecl();
16200
16201 if (FD && FD->hasAttr<NakedAttr>()) {
16202 for (const Stmt *S : Body->children()) {
16203 // Allow local register variables without initializer as they don't
16204 // require prologue.
16205 bool RegisterVariables = false;
16206 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16207 for (const auto *Decl : DS->decls()) {
16208 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16209 RegisterVariables =
16210 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16211 if (!RegisterVariables)
16212 break;
16213 }
16214 }
16215 }
16216 if (RegisterVariables)
16217 continue;
16218 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16219 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16220 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16221 FD->setInvalidDecl();
16222 break;
16223 }
16224 }
16225 }
16226
16227 assert(ExprCleanupObjects.size() ==
16228 ExprEvalContexts.back().NumCleanupObjects &&
16229 "Leftover temporaries in function");
16230 assert(!Cleanup.exprNeedsCleanups() &&
16231 "Unaccounted cleanups in function");
16232 assert(MaybeODRUseExprs.empty() &&
16233 "Leftover expressions for odr-use checking");
16234 }
16235 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16236 // the declaration context below. Otherwise, we're unable to transform
16237 // 'this' expressions when transforming immediate context functions.
16238
16239 if (!IsInstantiation)
16241
16242 PopFunctionScopeInfo(ActivePolicy, dcl);
16243 // If any errors have occurred, clear out any temporaries that may have
16244 // been leftover. This ensures that these temporaries won't be picked up for
16245 // deletion in some later function.
16248 }
16249
16250 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16251 !LangOpts.OMPTargetTriples.empty())) ||
16252 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16253 auto ES = getEmissionStatus(FD);
16256 DeclsToCheckForDeferredDiags.insert(FD);
16257 }
16258
16259 if (FD && !FD->isDeleted())
16260 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16261
16262 return dcl;
16263}
16264
16265/// When we finish delayed parsing of an attribute, we must attach it to the
16266/// relevant Decl.
16268 ParsedAttributes &Attrs) {
16269 // Always attach attributes to the underlying decl.
16270 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16271 D = TD->getTemplatedDecl();
16272 ProcessDeclAttributeList(S, D, Attrs);
16274
16275 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16276 if (Method->isStatic())
16278}
16279
16281 IdentifierInfo &II, Scope *S) {
16282 // It is not valid to implicitly define a function in C23.
16284 "Implicit function declarations aren't allowed in this language mode");
16285
16286 // Find the scope in which the identifier is injected and the corresponding
16287 // DeclContext.
16288 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16289 // In that case, we inject the declaration into the translation unit scope
16290 // instead.
16291 Scope *BlockScope = S;
16292 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16293 BlockScope = BlockScope->getParent();
16294
16295 // Loop until we find a DeclContext that is either a function/method or the
16296 // translation unit, which are the only two valid places to implicitly define
16297 // a function. This avoids accidentally defining the function within a tag
16298 // declaration, for example.
16299 Scope *ContextScope = BlockScope;
16300 while (!ContextScope->getEntity() ||
16301 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16302 !ContextScope->getEntity()->isTranslationUnit()))
16303 ContextScope = ContextScope->getParent();
16304 ContextRAII SavedContext(*this, ContextScope->getEntity());
16305
16306 // Before we produce a declaration for an implicitly defined
16307 // function, see whether there was a locally-scoped declaration of
16308 // this name as a function or variable. If so, use that
16309 // (non-visible) declaration, and complain about it.
16310 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16311 if (ExternCPrev) {
16312 // We still need to inject the function into the enclosing block scope so
16313 // that later (non-call) uses can see it.
16314 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16315
16316 // C89 footnote 38:
16317 // If in fact it is not defined as having type "function returning int",
16318 // the behavior is undefined.
16319 if (!isa<FunctionDecl>(ExternCPrev) ||
16321 cast<FunctionDecl>(ExternCPrev)->getType(),
16323 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16324 << ExternCPrev << !getLangOpts().C99;
16325 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16326 return ExternCPrev;
16327 }
16328 }
16329
16330 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16331 unsigned diag_id;
16332 if (II.getName().starts_with("__builtin_"))
16333 diag_id = diag::warn_builtin_unknown;
16334 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16335 else if (getLangOpts().C99)
16336 diag_id = diag::ext_implicit_function_decl_c99;
16337 else
16338 diag_id = diag::warn_implicit_function_decl;
16339
16340 TypoCorrection Corrected;
16341 // Because typo correction is expensive, only do it if the implicit
16342 // function declaration is going to be treated as an error.
16343 //
16344 // Perform the correction before issuing the main diagnostic, as some
16345 // consumers use typo-correction callbacks to enhance the main diagnostic.
16346 if (S && !ExternCPrev &&
16350 S, nullptr, CCC, CTK_NonError);
16351 }
16352
16353 Diag(Loc, diag_id) << &II;
16354 if (Corrected) {
16355 // If the correction is going to suggest an implicitly defined function,
16356 // skip the correction as not being a particularly good idea.
16357 bool Diagnose = true;
16358 if (const auto *D = Corrected.getCorrectionDecl())
16359 Diagnose = !D->isImplicit();
16360 if (Diagnose)
16361 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16362 /*ErrorRecovery*/ false);
16363 }
16364
16365 // If we found a prior declaration of this function, don't bother building
16366 // another one. We've already pushed that one into scope, so there's nothing
16367 // more to do.
16368 if (ExternCPrev)
16369 return ExternCPrev;
16370
16371 // Set a Declarator for the implicit definition: int foo();
16372 const char *Dummy;
16373 AttributeFactory attrFactory;
16374 DeclSpec DS(attrFactory);
16375 unsigned DiagID;
16376 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16378 (void)Error; // Silence warning.
16379 assert(!Error && "Error setting up implicit decl!");
16380 SourceLocation NoLoc;
16382 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16383 /*IsAmbiguous=*/false,
16384 /*LParenLoc=*/NoLoc,
16385 /*Params=*/nullptr,
16386 /*NumParams=*/0,
16387 /*EllipsisLoc=*/NoLoc,
16388 /*RParenLoc=*/NoLoc,
16389 /*RefQualifierIsLvalueRef=*/true,
16390 /*RefQualifierLoc=*/NoLoc,
16391 /*MutableLoc=*/NoLoc, EST_None,
16392 /*ESpecRange=*/SourceRange(),
16393 /*Exceptions=*/nullptr,
16394 /*ExceptionRanges=*/nullptr,
16395 /*NumExceptions=*/0,
16396 /*NoexceptExpr=*/nullptr,
16397 /*ExceptionSpecTokens=*/nullptr,
16398 /*DeclsInPrototype=*/std::nullopt,
16399 Loc, Loc, D),
16400 std::move(DS.getAttributes()), SourceLocation());
16401 D.SetIdentifier(&II, Loc);
16402
16403 // Insert this function into the enclosing block scope.
16404 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16405 FD->setImplicit();
16406
16408
16409 return FD;
16410}
16411
16413 FunctionDecl *FD) {
16414 if (FD->isInvalidDecl())
16415 return;
16416
16417 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16418 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16419 return;
16420
16421 std::optional<unsigned> AlignmentParam;
16422 bool IsNothrow = false;
16423 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16424 return;
16425
16426 // C++2a [basic.stc.dynamic.allocation]p4:
16427 // An allocation function that has a non-throwing exception specification
16428 // indicates failure by returning a null pointer value. Any other allocation
16429 // function never returns a null pointer value and indicates failure only by
16430 // throwing an exception [...]
16431 //
16432 // However, -fcheck-new invalidates this possible assumption, so don't add
16433 // NonNull when that is enabled.
16434 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16435 !getLangOpts().CheckNew)
16436 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16437
16438 // C++2a [basic.stc.dynamic.allocation]p2:
16439 // An allocation function attempts to allocate the requested amount of
16440 // storage. [...] If the request succeeds, the value returned by a
16441 // replaceable allocation function is a [...] pointer value p0 different
16442 // from any previously returned value p1 [...]
16443 //
16444 // However, this particular information is being added in codegen,
16445 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16446
16447 // C++2a [basic.stc.dynamic.allocation]p2:
16448 // An allocation function attempts to allocate the requested amount of
16449 // storage. If it is successful, it returns the address of the start of a
16450 // block of storage whose length in bytes is at least as large as the
16451 // requested size.
16452 if (!FD->hasAttr<AllocSizeAttr>()) {
16453 FD->addAttr(AllocSizeAttr::CreateImplicit(
16454 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16455 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16456 }
16457
16458 // C++2a [basic.stc.dynamic.allocation]p3:
16459 // For an allocation function [...], the pointer returned on a successful
16460 // call shall represent the address of storage that is aligned as follows:
16461 // (3.1) If the allocation function takes an argument of type
16462 // std​::​align_­val_­t, the storage will have the alignment
16463 // specified by the value of this argument.
16464 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16465 FD->addAttr(AllocAlignAttr::CreateImplicit(
16466 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16467 }
16468
16469 // FIXME:
16470 // C++2a [basic.stc.dynamic.allocation]p3:
16471 // For an allocation function [...], the pointer returned on a successful
16472 // call shall represent the address of storage that is aligned as follows:
16473 // (3.2) Otherwise, if the allocation function is named operator new[],
16474 // the storage is aligned for any object that does not have
16475 // new-extended alignment ([basic.align]) and is no larger than the
16476 // requested size.
16477 // (3.3) Otherwise, the storage is aligned for any object that does not
16478 // have new-extended alignment and is of the requested size.
16479}
16480
16482 if (FD->isInvalidDecl())
16483 return;
16484
16485 // If this is a built-in function, map its builtin attributes to
16486 // actual attributes.
16487 if (unsigned BuiltinID = FD->getBuiltinID()) {
16488 // Handle printf-formatting attributes.
16489 unsigned FormatIdx;
16490 bool HasVAListArg;
16491 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16492 if (!FD->hasAttr<FormatAttr>()) {
16493 const char *fmt = "printf";
16494 unsigned int NumParams = FD->getNumParams();
16495 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16496 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16497 fmt = "NSString";
16498 FD->addAttr(FormatAttr::CreateImplicit(Context,
16499 &Context.Idents.get(fmt),
16500 FormatIdx+1,
16501 HasVAListArg ? 0 : FormatIdx+2,
16502 FD->getLocation()));
16503 }
16504 }
16505 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16506 HasVAListArg)) {
16507 if (!FD->hasAttr<FormatAttr>())
16508 FD->addAttr(FormatAttr::CreateImplicit(Context,
16509 &Context.Idents.get("scanf"),
16510 FormatIdx+1,
16511 HasVAListArg ? 0 : FormatIdx+2,
16512 FD->getLocation()));
16513 }
16514
16515 // Handle automatically recognized callbacks.
16516 SmallVector<int, 4> Encoding;
16517 if (!FD->hasAttr<CallbackAttr>() &&
16518 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16519 FD->addAttr(CallbackAttr::CreateImplicit(
16520 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16521
16522 // Mark const if we don't care about errno and/or floating point exceptions
16523 // that are the only thing preventing the function from being const. This
16524 // allows IRgen to use LLVM intrinsics for such functions.
16525 bool NoExceptions =
16527 bool ConstWithoutErrnoAndExceptions =
16529 bool ConstWithoutExceptions =
16531 if (!FD->hasAttr<ConstAttr>() &&
16532 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16533 (!ConstWithoutErrnoAndExceptions ||
16534 (!getLangOpts().MathErrno && NoExceptions)) &&
16535 (!ConstWithoutExceptions || NoExceptions))
16536 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16537
16538 // We make "fma" on GNU or Windows const because we know it does not set
16539 // errno in those environments even though it could set errno based on the
16540 // C standard.
16541 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16542 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16543 !FD->hasAttr<ConstAttr>()) {
16544 switch (BuiltinID) {
16545 case Builtin::BI__builtin_fma:
16546 case Builtin::BI__builtin_fmaf:
16547 case Builtin::BI__builtin_fmal:
16548 case Builtin::BIfma:
16549 case Builtin::BIfmaf:
16550 case Builtin::BIfmal:
16551 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16552 break;
16553 default:
16554 break;
16555 }
16556 }
16557
16558 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16559 !FD->hasAttr<ReturnsTwiceAttr>())
16560 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16561 FD->getLocation()));
16562 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16563 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16564 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16565 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16566 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16567 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16568 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16569 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16570 // Add the appropriate attribute, depending on the CUDA compilation mode
16571 // and which target the builtin belongs to. For example, during host
16572 // compilation, aux builtins are __device__, while the rest are __host__.
16573 if (getLangOpts().CUDAIsDevice !=
16575 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16576 else
16577 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16578 }
16579
16580 // Add known guaranteed alignment for allocation functions.
16581 switch (BuiltinID) {
16582 case Builtin::BImemalign:
16583 case Builtin::BIaligned_alloc:
16584 if (!FD->hasAttr<AllocAlignAttr>())
16585 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16586 FD->getLocation()));
16587 break;
16588 default:
16589 break;
16590 }
16591
16592 // Add allocsize attribute for allocation functions.
16593 switch (BuiltinID) {
16594 case Builtin::BIcalloc:
16595 FD->addAttr(AllocSizeAttr::CreateImplicit(
16596 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16597 break;
16598 case Builtin::BImemalign:
16599 case Builtin::BIaligned_alloc:
16600 case Builtin::BIrealloc:
16601 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16602 ParamIdx(), FD->getLocation()));
16603 break;
16604 case Builtin::BImalloc:
16605 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16606 ParamIdx(), FD->getLocation()));
16607 break;
16608 default:
16609 break;
16610 }
16611
16612 // Add lifetime attribute to std::move, std::fowrard et al.
16613 switch (BuiltinID) {
16614 case Builtin::BIaddressof:
16615 case Builtin::BI__addressof:
16616 case Builtin::BI__builtin_addressof:
16617 case Builtin::BIas_const:
16618 case Builtin::BIforward:
16619 case Builtin::BIforward_like:
16620 case Builtin::BImove:
16621 case Builtin::BImove_if_noexcept:
16622 if (ParmVarDecl *P = FD->getParamDecl(0u);
16623 !P->hasAttr<LifetimeBoundAttr>())
16624 P->addAttr(
16625 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16626 break;
16627 default:
16628 break;
16629 }
16630 }
16631
16633
16634 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16635 // throw, add an implicit nothrow attribute to any extern "C" function we come
16636 // across.
16637 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16638 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16639 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16640 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16641 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16642 }
16643
16644 IdentifierInfo *Name = FD->getIdentifier();
16645 if (!Name)
16646 return;
16648 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16649 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16651 // Okay: this could be a libc/libm/Objective-C function we know
16652 // about.
16653 } else
16654 return;
16655
16656 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16657 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16658 // target-specific builtins, perhaps?
16659 if (!FD->hasAttr<FormatAttr>())
16660 FD->addAttr(FormatAttr::CreateImplicit(Context,
16661 &Context.Idents.get("printf"), 2,
16662 Name->isStr("vasprintf") ? 0 : 3,
16663 FD->getLocation()));
16664 }
16665
16666 if (Name->isStr("__CFStringMakeConstantString")) {
16667 // We already have a __builtin___CFStringMakeConstantString,
16668 // but builds that use -fno-constant-cfstrings don't go through that.
16669 if (!FD->hasAttr<FormatArgAttr>())
16670 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16671 FD->getLocation()));
16672 }
16673}
16674
16676 TypeSourceInfo *TInfo) {
16677 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16678 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16679
16680 if (!TInfo) {
16681 assert(D.isInvalidType() && "no declarator info for valid type");
16683 }
16684
16685 // Scope manipulation handled by caller.
16686 TypedefDecl *NewTD =
16688 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16689
16690 // Bail out immediately if we have an invalid declaration.
16691 if (D.isInvalidType()) {
16692 NewTD->setInvalidDecl();
16693 return NewTD;
16694 }
16695
16696 if (D.getDeclSpec().isModulePrivateSpecified()) {
16698 Diag(NewTD->getLocation(), diag::err_module_private_local)
16699 << 2 << NewTD
16700 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16702 D.getDeclSpec().getModulePrivateSpecLoc());
16703 else
16704 NewTD->setModulePrivate();
16705 }
16706
16707 // C++ [dcl.typedef]p8:
16708 // If the typedef declaration defines an unnamed class (or
16709 // enum), the first typedef-name declared by the declaration
16710 // to be that class type (or enum type) is used to denote the
16711 // class type (or enum type) for linkage purposes only.
16712 // We need to check whether the type was declared in the declaration.
16713 switch (D.getDeclSpec().getTypeSpecType()) {
16714 case TST_enum:
16715 case TST_struct:
16716 case TST_interface:
16717 case TST_union:
16718 case TST_class: {
16719 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16720 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16721 break;
16722 }
16723
16724 default:
16725 break;
16726 }
16727
16728 return NewTD;
16729}
16730
16732 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16733 QualType T = TI->getType();
16734
16735 if (T->isDependentType())
16736 return false;
16737
16738 // This doesn't use 'isIntegralType' despite the error message mentioning
16739 // integral type because isIntegralType would also allow enum types in C.
16740 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16741 if (BT->isInteger())
16742 return false;
16743
16744 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16745 << T << T->isBitIntType();
16746}
16747
16749 QualType EnumUnderlyingTy, bool IsFixed,
16750 const EnumDecl *Prev) {
16751 if (IsScoped != Prev->isScoped()) {
16752 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16753 << Prev->isScoped();
16754 Diag(Prev->getLocation(), diag::note_previous_declaration);
16755 return true;
16756 }
16757
16758 if (IsFixed && Prev->isFixed()) {
16759 if (!EnumUnderlyingTy->isDependentType() &&
16760 !Prev->getIntegerType()->isDependentType() &&
16761 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16762 Prev->getIntegerType())) {
16763 // TODO: Highlight the underlying type of the redeclaration.
16764 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16765 << EnumUnderlyingTy << Prev->getIntegerType();
16766 Diag(Prev->getLocation(), diag::note_previous_declaration)
16767 << Prev->getIntegerTypeRange();
16768 return true;
16769 }
16770 } else if (IsFixed != Prev->isFixed()) {
16771 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16772 << Prev->isFixed();
16773 Diag(Prev->getLocation(), diag::note_previous_declaration);
16774 return true;
16775 }
16776
16777 return false;
16778}
16779
16780/// Get diagnostic %select index for tag kind for
16781/// redeclaration diagnostic message.
16782/// WARNING: Indexes apply to particular diagnostics only!
16783///
16784/// \returns diagnostic %select index.
16786 switch (Tag) {
16788 return 0;
16790 return 1;
16791 case TagTypeKind::Class:
16792 return 2;
16793 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16794 }
16795}
16796
16797/// Determine if tag kind is a class-key compatible with
16798/// class for redeclaration (class, struct, or __interface).
16799///
16800/// \returns true iff the tag kind is compatible.
16802{
16803 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16805}
16806
16808 TagTypeKind TTK) {
16809 if (isa<TypedefDecl>(PrevDecl))
16810 return NTK_Typedef;
16811 else if (isa<TypeAliasDecl>(PrevDecl))
16812 return NTK_TypeAlias;
16813 else if (isa<ClassTemplateDecl>(PrevDecl))
16814 return NTK_Template;
16815 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16816 return NTK_TypeAliasTemplate;
16817 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16819 switch (TTK) {
16822 case TagTypeKind::Class:
16823 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16824 case TagTypeKind::Union:
16825 return NTK_NonUnion;
16826 case TagTypeKind::Enum:
16827 return NTK_NonEnum;
16828 }
16829 llvm_unreachable("invalid TTK");
16830}
16831
16833 TagTypeKind NewTag, bool isDefinition,
16834 SourceLocation NewTagLoc,
16835 const IdentifierInfo *Name) {
16836 // C++ [dcl.type.elab]p3:
16837 // The class-key or enum keyword present in the
16838 // elaborated-type-specifier shall agree in kind with the
16839 // declaration to which the name in the elaborated-type-specifier
16840 // refers. This rule also applies to the form of
16841 // elaborated-type-specifier that declares a class-name or
16842 // friend class since it can be construed as referring to the
16843 // definition of the class. Thus, in any
16844 // elaborated-type-specifier, the enum keyword shall be used to
16845 // refer to an enumeration (7.2), the union class-key shall be
16846 // used to refer to a union (clause 9), and either the class or
16847 // struct class-key shall be used to refer to a class (clause 9)
16848 // declared using the class or struct class-key.
16849 TagTypeKind OldTag = Previous->getTagKind();
16850 if (OldTag != NewTag &&
16851 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16852 return false;
16853
16854 // Tags are compatible, but we might still want to warn on mismatched tags.
16855 // Non-class tags can't be mismatched at this point.
16856 if (!isClassCompatTagKind(NewTag))
16857 return true;
16858
16859 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16860 // by our warning analysis. We don't want to warn about mismatches with (eg)
16861 // declarations in system headers that are designed to be specialized, but if
16862 // a user asks us to warn, we should warn if their code contains mismatched
16863 // declarations.
16864 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16865 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16866 Loc);
16867 };
16868 if (IsIgnoredLoc(NewTagLoc))
16869 return true;
16870
16871 auto IsIgnored = [&](const TagDecl *Tag) {
16872 return IsIgnoredLoc(Tag->getLocation());
16873 };
16874 while (IsIgnored(Previous)) {
16875 Previous = Previous->getPreviousDecl();
16876 if (!Previous)
16877 return true;
16878 OldTag = Previous->getTagKind();
16879 }
16880
16881 bool isTemplate = false;
16882 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16883 isTemplate = Record->getDescribedClassTemplate();
16884
16886 if (OldTag != NewTag) {
16887 // In a template instantiation, do not offer fix-its for tag mismatches
16888 // since they usually mess up the template instead of fixing the problem.
16889 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16890 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16891 << getRedeclDiagFromTagKind(OldTag);
16892 // FIXME: Note previous location?
16893 }
16894 return true;
16895 }
16896
16897 if (isDefinition) {
16898 // On definitions, check all previous tags and issue a fix-it for each
16899 // one that doesn't match the current tag.
16900 if (Previous->getDefinition()) {
16901 // Don't suggest fix-its for redefinitions.
16902 return true;
16903 }
16904
16905 bool previousMismatch = false;
16906 for (const TagDecl *I : Previous->redecls()) {
16907 if (I->getTagKind() != NewTag) {
16908 // Ignore previous declarations for which the warning was disabled.
16909 if (IsIgnored(I))
16910 continue;
16911
16912 if (!previousMismatch) {
16913 previousMismatch = true;
16914 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16915 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16916 << getRedeclDiagFromTagKind(I->getTagKind());
16917 }
16918 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16919 << getRedeclDiagFromTagKind(NewTag)
16920 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16922 }
16923 }
16924 return true;
16925 }
16926
16927 // Identify the prevailing tag kind: this is the kind of the definition (if
16928 // there is a non-ignored definition), or otherwise the kind of the prior
16929 // (non-ignored) declaration.
16930 const TagDecl *PrevDef = Previous->getDefinition();
16931 if (PrevDef && IsIgnored(PrevDef))
16932 PrevDef = nullptr;
16933 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16934 if (Redecl->getTagKind() != NewTag) {
16935 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16936 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16937 << getRedeclDiagFromTagKind(OldTag);
16938 Diag(Redecl->getLocation(), diag::note_previous_use);
16939
16940 // If there is a previous definition, suggest a fix-it.
16941 if (PrevDef) {
16942 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16946 }
16947 }
16948
16949 return true;
16950}
16951
16952/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16953/// from an outer enclosing namespace or file scope inside a friend declaration.
16954/// This should provide the commented out code in the following snippet:
16955/// namespace N {
16956/// struct X;
16957/// namespace M {
16958/// struct Y { friend struct /*N::*/ X; };
16959/// }
16960/// }
16962 SourceLocation NameLoc) {
16963 // While the decl is in a namespace, do repeated lookup of that name and see
16964 // if we get the same namespace back. If we do not, continue until
16965 // translation unit scope, at which point we have a fully qualified NNS.
16968 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16969 // This tag should be declared in a namespace, which can only be enclosed by
16970 // other namespaces. Bail if there's an anonymous namespace in the chain.
16971 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16972 if (!Namespace || Namespace->isAnonymousNamespace())
16973 return FixItHint();
16974 IdentifierInfo *II = Namespace->getIdentifier();
16975 Namespaces.push_back(II);
16976 NamedDecl *Lookup = SemaRef.LookupSingleName(
16977 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16978 if (Lookup == Namespace)
16979 break;
16980 }
16981
16982 // Once we have all the namespaces, reverse them to go outermost first, and
16983 // build an NNS.
16984 SmallString<64> Insertion;
16985 llvm::raw_svector_ostream OS(Insertion);
16986 if (DC->isTranslationUnit())
16987 OS << "::";
16988 std::reverse(Namespaces.begin(), Namespaces.end());
16989 for (auto *II : Namespaces)
16990 OS << II->getName() << "::";
16991 return FixItHint::CreateInsertion(NameLoc, Insertion);
16992}
16993
16994/// Determine whether a tag originally declared in context \p OldDC can
16995/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16996/// found a declaration in \p OldDC as a previous decl, perhaps through a
16997/// using-declaration).
16999 DeclContext *NewDC) {
17000 OldDC = OldDC->getRedeclContext();
17001 NewDC = NewDC->getRedeclContext();
17002
17003 if (OldDC->Equals(NewDC))
17004 return true;
17005
17006 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17007 // encloses the other).
17008 if (S.getLangOpts().MSVCCompat &&
17009 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17010 return true;
17011
17012 return false;
17013}
17014
17016Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17017 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17018 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17019 SourceLocation ModulePrivateLoc,
17020 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17021 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17022 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17023 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17024 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17025 // If this is not a definition, it must have a name.
17026 IdentifierInfo *OrigName = Name;
17027 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17028 "Nameless record must be a definition!");
17029 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17030
17031 OwnedDecl = false;
17033 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17034
17035 // FIXME: Check member specializations more carefully.
17036 bool isMemberSpecialization = false;
17037 bool Invalid = false;
17038
17039 // We only need to do this matching if we have template parameters
17040 // or a scope specifier, which also conveniently avoids this work
17041 // for non-C++ cases.
17042 if (TemplateParameterLists.size() > 0 ||
17043 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17044 TemplateParameterList *TemplateParams =
17046 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17047 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17048
17049 // C++23 [dcl.type.elab] p2:
17050 // If an elaborated-type-specifier is the sole constituent of a
17051 // declaration, the declaration is ill-formed unless it is an explicit
17052 // specialization, an explicit instantiation or it has one of the
17053 // following forms: [...]
17054 // C++23 [dcl.enum] p1:
17055 // If the enum-head-name of an opaque-enum-declaration contains a
17056 // nested-name-specifier, the declaration shall be an explicit
17057 // specialization.
17058 //
17059 // FIXME: Class template partial specializations can be forward declared
17060 // per CWG2213, but the resolution failed to allow qualified forward
17061 // declarations. This is almost certainly unintentional, so we allow them.
17062 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17063 !isMemberSpecialization)
17064 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17066
17067 if (TemplateParams) {
17068 if (Kind == TagTypeKind::Enum) {
17069 Diag(KWLoc, diag::err_enum_template);
17070 return true;
17071 }
17072
17073 if (TemplateParams->size() > 0) {
17074 // This is a declaration or definition of a class template (which may
17075 // be a member of another template).
17076
17077 if (Invalid)
17078 return true;
17079
17080 OwnedDecl = false;
17082 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17083 AS, ModulePrivateLoc,
17084 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17085 TemplateParameterLists.data(), SkipBody);
17086 return Result.get();
17087 } else {
17088 // The "template<>" header is extraneous.
17089 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17090 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17091 isMemberSpecialization = true;
17092 }
17093 }
17094
17095 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17096 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17097 return true;
17098 }
17099
17100 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17101 // C++23 [dcl.type.elab]p4:
17102 // If an elaborated-type-specifier appears with the friend specifier as
17103 // an entire member-declaration, the member-declaration shall have one
17104 // of the following forms:
17105 // friend class-key nested-name-specifier(opt) identifier ;
17106 // friend class-key simple-template-id ;
17107 // friend class-key nested-name-specifier template(opt)
17108 // simple-template-id ;
17109 //
17110 // Since enum is not a class-key, so declarations like "friend enum E;"
17111 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17112 // invalid, most implementations accept so we issue a pedantic warning.
17113 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17114 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17115 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17116 Diag(KWLoc, diag::note_enum_friend)
17117 << (ScopedEnum + ScopedEnumUsesClassTag);
17118 }
17119
17120 // Figure out the underlying type if this a enum declaration. We need to do
17121 // this early, because it's needed to detect if this is an incompatible
17122 // redeclaration.
17123 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17124 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17125
17126 if (Kind == TagTypeKind::Enum) {
17127 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17128 // No underlying type explicitly specified, or we failed to parse the
17129 // type, default to int.
17130 EnumUnderlying = Context.IntTy.getTypePtr();
17131 } else if (UnderlyingType.get()) {
17132 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17133 // integral type; any cv-qualification is ignored.
17134 TypeSourceInfo *TI = nullptr;
17135 GetTypeFromParser(UnderlyingType.get(), &TI);
17136 EnumUnderlying = TI;
17137
17139 // Recover by falling back to int.
17140 EnumUnderlying = Context.IntTy.getTypePtr();
17141
17144 EnumUnderlying = Context.IntTy.getTypePtr();
17145
17146 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17147 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17148 // of 'int'. However, if this is an unfixed forward declaration, don't set
17149 // the underlying type unless the user enables -fms-compatibility. This
17150 // makes unfixed forward declared enums incomplete and is more conforming.
17151 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17152 EnumUnderlying = Context.IntTy.getTypePtr();
17153 }
17154 }
17155
17156 DeclContext *SearchDC = CurContext;
17157 DeclContext *DC = CurContext;
17158 bool isStdBadAlloc = false;
17159 bool isStdAlignValT = false;
17160
17162 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17163 Redecl = RedeclarationKind::NotForRedeclaration;
17164
17165 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17166 /// implemented asks for structural equivalence checking, the returned decl
17167 /// here is passed back to the parser, allowing the tag body to be parsed.
17168 auto createTagFromNewDecl = [&]() -> TagDecl * {
17169 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17170 // If there is an identifier, use the location of the identifier as the
17171 // location of the decl, otherwise use the location of the struct/union
17172 // keyword.
17173 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17174 TagDecl *New = nullptr;
17175
17176 if (Kind == TagTypeKind::Enum) {
17177 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17178 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17179 // If this is an undefined enum, bail.
17180 if (TUK != TagUseKind::Definition && !Invalid)
17181 return nullptr;
17182 if (EnumUnderlying) {
17183 EnumDecl *ED = cast<EnumDecl>(New);
17184 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17186 else
17187 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17188 QualType EnumTy = ED->getIntegerType();
17191 : EnumTy);
17192 }
17193 } else { // struct/union
17194 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17195 nullptr);
17196 }
17197
17198 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17199 // Add alignment attributes if necessary; these attributes are checked
17200 // when the ASTContext lays out the structure.
17201 //
17202 // It is important for implementing the correct semantics that this
17203 // happen here (in ActOnTag). The #pragma pack stack is
17204 // maintained as a result of parser callbacks which can occur at
17205 // many points during the parsing of a struct declaration (because
17206 // the #pragma tokens are effectively skipped over during the
17207 // parsing of the struct).
17208 if (TUK == TagUseKind::Definition &&
17209 (!SkipBody || !SkipBody->ShouldSkip)) {
17212 }
17213 }
17215 return New;
17216 };
17217
17218 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17219 if (Name && SS.isNotEmpty()) {
17220 // We have a nested-name tag ('struct foo::bar').
17221
17222 // Check for invalid 'foo::'.
17223 if (SS.isInvalid()) {
17224 Name = nullptr;
17225 goto CreateNewDecl;
17226 }
17227
17228 // If this is a friend or a reference to a class in a dependent
17229 // context, don't try to make a decl for it.
17230 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17231 DC = computeDeclContext(SS, false);
17232 if (!DC) {
17233 IsDependent = true;
17234 return true;
17235 }
17236 } else {
17237 DC = computeDeclContext(SS, true);
17238 if (!DC) {
17239 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17240 << SS.getRange();
17241 return true;
17242 }
17243 }
17244
17245 if (RequireCompleteDeclContext(SS, DC))
17246 return true;
17247
17248 SearchDC = DC;
17249 // Look-up name inside 'foo::'.
17251
17252 if (Previous.isAmbiguous())
17253 return true;
17254
17255 if (Previous.empty()) {
17256 // Name lookup did not find anything. However, if the
17257 // nested-name-specifier refers to the current instantiation,
17258 // and that current instantiation has any dependent base
17259 // classes, we might find something at instantiation time: treat
17260 // this as a dependent elaborated-type-specifier.
17261 // But this only makes any sense for reference-like lookups.
17262 if (Previous.wasNotFoundInCurrentInstantiation() &&
17263 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17264 IsDependent = true;
17265 return true;
17266 }
17267
17268 // A tag 'foo::bar' must already exist.
17269 Diag(NameLoc, diag::err_not_tag_in_scope)
17270 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17271 Name = nullptr;
17272 Invalid = true;
17273 goto CreateNewDecl;
17274 }
17275 } else if (Name) {
17276 // C++14 [class.mem]p14:
17277 // If T is the name of a class, then each of the following shall have a
17278 // name different from T:
17279 // -- every member of class T that is itself a type
17280 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17281 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17282 return true;
17283
17284 // If this is a named struct, check to see if there was a previous forward
17285 // declaration or definition.
17286 // FIXME: We're looking into outer scopes here, even when we
17287 // shouldn't be. Doing so can result in ambiguities that we
17288 // shouldn't be diagnosing.
17289 LookupName(Previous, S);
17290
17291 // When declaring or defining a tag, ignore ambiguities introduced
17292 // by types using'ed into this scope.
17293 if (Previous.isAmbiguous() &&
17295 LookupResult::Filter F = Previous.makeFilter();
17296 while (F.hasNext()) {
17297 NamedDecl *ND = F.next();
17298 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17299 SearchDC->getRedeclContext()))
17300 F.erase();
17301 }
17302 F.done();
17303 }
17304
17305 // C++11 [namespace.memdef]p3:
17306 // If the name in a friend declaration is neither qualified nor
17307 // a template-id and the declaration is a function or an
17308 // elaborated-type-specifier, the lookup to determine whether
17309 // the entity has been previously declared shall not consider
17310 // any scopes outside the innermost enclosing namespace.
17311 //
17312 // MSVC doesn't implement the above rule for types, so a friend tag
17313 // declaration may be a redeclaration of a type declared in an enclosing
17314 // scope. They do implement this rule for friend functions.
17315 //
17316 // Does it matter that this should be by scope instead of by
17317 // semantic context?
17318 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17319 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17320 LookupResult::Filter F = Previous.makeFilter();
17321 bool FriendSawTagOutsideEnclosingNamespace = false;
17322 while (F.hasNext()) {
17323 NamedDecl *ND = F.next();
17325 if (DC->isFileContext() &&
17326 !EnclosingNS->Encloses(ND->getDeclContext())) {
17327 if (getLangOpts().MSVCCompat)
17328 FriendSawTagOutsideEnclosingNamespace = true;
17329 else
17330 F.erase();
17331 }
17332 }
17333 F.done();
17334
17335 // Diagnose this MSVC extension in the easy case where lookup would have
17336 // unambiguously found something outside the enclosing namespace.
17337 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17338 NamedDecl *ND = Previous.getFoundDecl();
17339 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17340 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17341 }
17342 }
17343
17344 // Note: there used to be some attempt at recovery here.
17345 if (Previous.isAmbiguous())
17346 return true;
17347
17348 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17349 // FIXME: This makes sure that we ignore the contexts associated
17350 // with C structs, unions, and enums when looking for a matching
17351 // tag declaration or definition. See the similar lookup tweak
17352 // in Sema::LookupName; is there a better way to deal with this?
17353 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17354 SearchDC = SearchDC->getParent();
17355 } else if (getLangOpts().CPlusPlus) {
17356 // Inside ObjCContainer want to keep it as a lexical decl context but go
17357 // past it (most often to TranslationUnit) to find the semantic decl
17358 // context.
17359 while (isa<ObjCContainerDecl>(SearchDC))
17360 SearchDC = SearchDC->getParent();
17361 }
17362 } else if (getLangOpts().CPlusPlus) {
17363 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17364 // TagDecl the same way as we skip it for named TagDecl.
17365 while (isa<ObjCContainerDecl>(SearchDC))
17366 SearchDC = SearchDC->getParent();
17367 }
17368
17369 if (Previous.isSingleResult() &&
17370 Previous.getFoundDecl()->isTemplateParameter()) {
17371 // Maybe we will complain about the shadowed template parameter.
17372 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17373 // Just pretend that we didn't see the previous declaration.
17374 Previous.clear();
17375 }
17376
17377 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17378 DC->Equals(getStdNamespace())) {
17379 if (Name->isStr("bad_alloc")) {
17380 // This is a declaration of or a reference to "std::bad_alloc".
17381 isStdBadAlloc = true;
17382
17383 // If std::bad_alloc has been implicitly declared (but made invisible to
17384 // name lookup), fill in this implicit declaration as the previous
17385 // declaration, so that the declarations get chained appropriately.
17386 if (Previous.empty() && StdBadAlloc)
17387 Previous.addDecl(getStdBadAlloc());
17388 } else if (Name->isStr("align_val_t")) {
17389 isStdAlignValT = true;
17390 if (Previous.empty() && StdAlignValT)
17391 Previous.addDecl(getStdAlignValT());
17392 }
17393 }
17394
17395 // If we didn't find a previous declaration, and this is a reference
17396 // (or friend reference), move to the correct scope. In C++, we
17397 // also need to do a redeclaration lookup there, just in case
17398 // there's a shadow friend decl.
17399 if (Name && Previous.empty() &&
17400 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17401 IsTemplateParamOrArg)) {
17402 if (Invalid) goto CreateNewDecl;
17403 assert(SS.isEmpty());
17404
17405 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17406 // C++ [basic.scope.pdecl]p5:
17407 // -- for an elaborated-type-specifier of the form
17408 //
17409 // class-key identifier
17410 //
17411 // if the elaborated-type-specifier is used in the
17412 // decl-specifier-seq or parameter-declaration-clause of a
17413 // function defined in namespace scope, the identifier is
17414 // declared as a class-name in the namespace that contains
17415 // the declaration; otherwise, except as a friend
17416 // declaration, the identifier is declared in the smallest
17417 // non-class, non-function-prototype scope that contains the
17418 // declaration.
17419 //
17420 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17421 // C structs and unions.
17422 //
17423 // It is an error in C++ to declare (rather than define) an enum
17424 // type, including via an elaborated type specifier. We'll
17425 // diagnose that later; for now, declare the enum in the same
17426 // scope as we would have picked for any other tag type.
17427 //
17428 // GNU C also supports this behavior as part of its incomplete
17429 // enum types extension, while GNU C++ does not.
17430 //
17431 // Find the context where we'll be declaring the tag.
17432 // FIXME: We would like to maintain the current DeclContext as the
17433 // lexical context,
17434 SearchDC = getTagInjectionContext(SearchDC);
17435
17436 // Find the scope where we'll be declaring the tag.
17438 } else {
17439 assert(TUK == TagUseKind::Friend);
17440 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17441
17442 // C++ [namespace.memdef]p3:
17443 // If a friend declaration in a non-local class first declares a
17444 // class or function, the friend class or function is a member of
17445 // the innermost enclosing namespace.
17446 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17447 : SearchDC->getEnclosingNamespaceContext();
17448 }
17449
17450 // In C++, we need to do a redeclaration lookup to properly
17451 // diagnose some problems.
17452 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17453 // hidden declaration so that we don't get ambiguity errors when using a
17454 // type declared by an elaborated-type-specifier. In C that is not correct
17455 // and we should instead merge compatible types found by lookup.
17456 if (getLangOpts().CPlusPlus) {
17457 // FIXME: This can perform qualified lookups into function contexts,
17458 // which are meaningless.
17459 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17460 LookupQualifiedName(Previous, SearchDC);
17461 } else {
17462 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17463 LookupName(Previous, S);
17464 }
17465 }
17466
17467 // If we have a known previous declaration to use, then use it.
17468 if (Previous.empty() && SkipBody && SkipBody->Previous)
17469 Previous.addDecl(SkipBody->Previous);
17470
17471 if (!Previous.empty()) {
17472 NamedDecl *PrevDecl = Previous.getFoundDecl();
17473 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17474
17475 // It's okay to have a tag decl in the same scope as a typedef
17476 // which hides a tag decl in the same scope. Finding this
17477 // with a redeclaration lookup can only actually happen in C++.
17478 //
17479 // This is also okay for elaborated-type-specifiers, which is
17480 // technically forbidden by the current standard but which is
17481 // okay according to the likely resolution of an open issue;
17482 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17483 if (getLangOpts().CPlusPlus) {
17484 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17485 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17486 TagDecl *Tag = TT->getDecl();
17487 if (Tag->getDeclName() == Name &&
17488 Tag->getDeclContext()->getRedeclContext()
17489 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17490 PrevDecl = Tag;
17491 Previous.clear();
17492 Previous.addDecl(Tag);
17493 Previous.resolveKind();
17494 }
17495 }
17496 }
17497 }
17498
17499 // If this is a redeclaration of a using shadow declaration, it must
17500 // declare a tag in the same context. In MSVC mode, we allow a
17501 // redefinition if either context is within the other.
17502 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17503 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17504 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17505 TUK != TagUseKind::Friend &&
17506 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17507 !(OldTag && isAcceptableTagRedeclContext(
17508 *this, OldTag->getDeclContext(), SearchDC))) {
17509 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17510 Diag(Shadow->getTargetDecl()->getLocation(),
17511 diag::note_using_decl_target);
17512 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17513 << 0;
17514 // Recover by ignoring the old declaration.
17515 Previous.clear();
17516 goto CreateNewDecl;
17517 }
17518 }
17519
17520 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17521 // If this is a use of a previous tag, or if the tag is already declared
17522 // in the same scope (so that the definition/declaration completes or
17523 // rementions the tag), reuse the decl.
17524 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17525 isDeclInScope(DirectPrevDecl, SearchDC, S,
17526 SS.isNotEmpty() || isMemberSpecialization)) {
17527 // Make sure that this wasn't declared as an enum and now used as a
17528 // struct or something similar.
17529 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17530 TUK == TagUseKind::Definition, KWLoc,
17531 Name)) {
17532 bool SafeToContinue =
17533 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17534 Kind != TagTypeKind::Enum);
17535 if (SafeToContinue)
17536 Diag(KWLoc, diag::err_use_with_wrong_tag)
17537 << Name
17539 PrevTagDecl->getKindName());
17540 else
17541 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17542 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17543
17544 if (SafeToContinue)
17545 Kind = PrevTagDecl->getTagKind();
17546 else {
17547 // Recover by making this an anonymous redefinition.
17548 Name = nullptr;
17549 Previous.clear();
17550 Invalid = true;
17551 }
17552 }
17553
17554 if (Kind == TagTypeKind::Enum &&
17555 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17556 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17557 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17558 return PrevTagDecl;
17559
17560 QualType EnumUnderlyingTy;
17561 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17562 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17563 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17564 EnumUnderlyingTy = QualType(T, 0);
17565
17566 // All conflicts with previous declarations are recovered by
17567 // returning the previous declaration, unless this is a definition,
17568 // in which case we want the caller to bail out.
17569 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17570 ScopedEnum, EnumUnderlyingTy,
17571 IsFixed, PrevEnum))
17572 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17573 }
17574
17575 // C++11 [class.mem]p1:
17576 // A member shall not be declared twice in the member-specification,
17577 // except that a nested class or member class template can be declared
17578 // and then later defined.
17579 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17580 S->isDeclScope(PrevDecl)) {
17581 Diag(NameLoc, diag::ext_member_redeclared);
17582 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17583 }
17584
17585 if (!Invalid) {
17586 // If this is a use, just return the declaration we found, unless
17587 // we have attributes.
17588 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17589 if (!Attrs.empty()) {
17590 // FIXME: Diagnose these attributes. For now, we create a new
17591 // declaration to hold them.
17592 } else if (TUK == TagUseKind::Reference &&
17593 (PrevTagDecl->getFriendObjectKind() ==
17595 PrevDecl->getOwningModule() != getCurrentModule()) &&
17596 SS.isEmpty()) {
17597 // This declaration is a reference to an existing entity, but
17598 // has different visibility from that entity: it either makes
17599 // a friend visible or it makes a type visible in a new module.
17600 // In either case, create a new declaration. We only do this if
17601 // the declaration would have meant the same thing if no prior
17602 // declaration were found, that is, if it was found in the same
17603 // scope where we would have injected a declaration.
17604 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17605 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17606 return PrevTagDecl;
17607 // This is in the injected scope, create a new declaration in
17608 // that scope.
17610 } else {
17611 return PrevTagDecl;
17612 }
17613 }
17614
17615 // Diagnose attempts to redefine a tag.
17616 if (TUK == TagUseKind::Definition) {
17617 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17618 // If we're defining a specialization and the previous definition
17619 // is from an implicit instantiation, don't emit an error
17620 // here; we'll catch this in the general case below.
17621 bool IsExplicitSpecializationAfterInstantiation = false;
17622 if (isMemberSpecialization) {
17623 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17624 IsExplicitSpecializationAfterInstantiation =
17625 RD->getTemplateSpecializationKind() !=
17627 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17628 IsExplicitSpecializationAfterInstantiation =
17629 ED->getTemplateSpecializationKind() !=
17631 }
17632
17633 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17634 // not keep more that one definition around (merge them). However,
17635 // ensure the decl passes the structural compatibility check in
17636 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17637 NamedDecl *Hidden = nullptr;
17638 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17639 // There is a definition of this tag, but it is not visible. We
17640 // explicitly make use of C++'s one definition rule here, and
17641 // assume that this definition is identical to the hidden one
17642 // we already have. Make the existing definition visible and
17643 // use it in place of this one.
17644 if (!getLangOpts().CPlusPlus) {
17645 // Postpone making the old definition visible until after we
17646 // complete parsing the new one and do the structural
17647 // comparison.
17648 SkipBody->CheckSameAsPrevious = true;
17649 SkipBody->New = createTagFromNewDecl();
17650 SkipBody->Previous = Def;
17651 return Def;
17652 } else {
17653 SkipBody->ShouldSkip = true;
17654 SkipBody->Previous = Def;
17656 // Carry on and handle it like a normal definition. We'll
17657 // skip starting the definition later.
17658 }
17659 } else if (!IsExplicitSpecializationAfterInstantiation) {
17660 // A redeclaration in function prototype scope in C isn't
17661 // visible elsewhere, so merely issue a warning.
17662 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17663 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17664 else
17665 Diag(NameLoc, diag::err_redefinition) << Name;
17667 NameLoc.isValid() ? NameLoc : KWLoc);
17668 // If this is a redefinition, recover by making this
17669 // struct be anonymous, which will make any later
17670 // references get the previous definition.
17671 Name = nullptr;
17672 Previous.clear();
17673 Invalid = true;
17674 }
17675 } else {
17676 // If the type is currently being defined, complain
17677 // about a nested redefinition.
17678 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17679 if (TD->isBeingDefined()) {
17680 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17681 Diag(PrevTagDecl->getLocation(),
17682 diag::note_previous_definition);
17683 Name = nullptr;
17684 Previous.clear();
17685 Invalid = true;
17686 }
17687 }
17688
17689 // Okay, this is definition of a previously declared or referenced
17690 // tag. We're going to create a new Decl for it.
17691 }
17692
17693 // Okay, we're going to make a redeclaration. If this is some kind
17694 // of reference, make sure we build the redeclaration in the same DC
17695 // as the original, and ignore the current access specifier.
17696 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17697 SearchDC = PrevTagDecl->getDeclContext();
17698 AS = AS_none;
17699 }
17700 }
17701 // If we get here we have (another) forward declaration or we
17702 // have a definition. Just create a new decl.
17703
17704 } else {
17705 // If we get here, this is a definition of a new tag type in a nested
17706 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17707 // new decl/type. We set PrevDecl to NULL so that the entities
17708 // have distinct types.
17709 Previous.clear();
17710 }
17711 // If we get here, we're going to create a new Decl. If PrevDecl
17712 // is non-NULL, it's a definition of the tag declared by
17713 // PrevDecl. If it's NULL, we have a new definition.
17714
17715 // Otherwise, PrevDecl is not a tag, but was found with tag
17716 // lookup. This is only actually possible in C++, where a few
17717 // things like templates still live in the tag namespace.
17718 } else {
17719 // Use a better diagnostic if an elaborated-type-specifier
17720 // found the wrong kind of type on the first
17721 // (non-redeclaration) lookup.
17722 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17723 !Previous.isForRedeclaration()) {
17724 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17725 Diag(NameLoc, diag::err_tag_reference_non_tag)
17726 << PrevDecl << NTK << llvm::to_underlying(Kind);
17727 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17728 Invalid = true;
17729
17730 // Otherwise, only diagnose if the declaration is in scope.
17731 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17732 SS.isNotEmpty() || isMemberSpecialization)) {
17733 // do nothing
17734
17735 // Diagnose implicit declarations introduced by elaborated types.
17736 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17737 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17738 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17739 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17740 Invalid = true;
17741
17742 // Otherwise it's a declaration. Call out a particularly common
17743 // case here.
17744 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17745 unsigned Kind = 0;
17746 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17747 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17748 << Name << Kind << TND->getUnderlyingType();
17749 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17750 Invalid = true;
17751
17752 // Otherwise, diagnose.
17753 } else {
17754 // The tag name clashes with something else in the target scope,
17755 // issue an error and recover by making this tag be anonymous.
17756 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17757 notePreviousDefinition(PrevDecl, NameLoc);
17758 Name = nullptr;
17759 Invalid = true;
17760 }
17761
17762 // The existing declaration isn't relevant to us; we're in a
17763 // new scope, so clear out the previous declaration.
17764 Previous.clear();
17765 }
17766 }
17767
17768CreateNewDecl:
17769
17770 TagDecl *PrevDecl = nullptr;
17771 if (Previous.isSingleResult())
17772 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17773
17774 // If there is an identifier, use the location of the identifier as the
17775 // location of the decl, otherwise use the location of the struct/union
17776 // keyword.
17777 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17778
17779 // Otherwise, create a new declaration. If there is a previous
17780 // declaration of the same entity, the two will be linked via
17781 // PrevDecl.
17782 TagDecl *New;
17783
17784 if (Kind == TagTypeKind::Enum) {
17785 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17786 // enum X { A, B, C } D; D should chain to X.
17787 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17788 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17789 ScopedEnumUsesClassTag, IsFixed);
17790
17791 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17792 StdAlignValT = cast<EnumDecl>(New);
17793
17794 // If this is an undefined enum, warn.
17795 if (TUK != TagUseKind::Definition && !Invalid) {
17796 TagDecl *Def;
17797 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17798 // C++0x: 7.2p2: opaque-enum-declaration.
17799 // Conflicts are diagnosed above. Do nothing.
17800 }
17801 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17802 Diag(Loc, diag::ext_forward_ref_enum_def)
17803 << New;
17804 Diag(Def->getLocation(), diag::note_previous_definition);
17805 } else {
17806 unsigned DiagID = diag::ext_forward_ref_enum;
17807 if (getLangOpts().MSVCCompat)
17808 DiagID = diag::ext_ms_forward_ref_enum;
17809 else if (getLangOpts().CPlusPlus)
17810 DiagID = diag::err_forward_ref_enum;
17811 Diag(Loc, DiagID);
17812 }
17813 }
17814
17815 if (EnumUnderlying) {
17816 EnumDecl *ED = cast<EnumDecl>(New);
17817 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17819 else
17820 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17821 QualType EnumTy = ED->getIntegerType();
17824 : EnumTy);
17825 assert(ED->isComplete() && "enum with type should be complete");
17826 }
17827 } else {
17828 // struct/union/class
17829
17830 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17831 // struct X { int A; } D; D should chain to X.
17832 if (getLangOpts().CPlusPlus) {
17833 // FIXME: Look for a way to use RecordDecl for simple structs.
17834 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17835 cast_or_null<CXXRecordDecl>(PrevDecl));
17836
17837 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17838 StdBadAlloc = cast<CXXRecordDecl>(New);
17839 } else
17840 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17841 cast_or_null<RecordDecl>(PrevDecl));
17842 }
17843
17844 // Only C23 and later allow defining new types in 'offsetof()'.
17845 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17847 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17848 << (OOK == OOK_Macro) << New->getSourceRange();
17849
17850 // C++11 [dcl.type]p3:
17851 // A type-specifier-seq shall not define a class or enumeration [...].
17852 if (!Invalid && getLangOpts().CPlusPlus &&
17853 (IsTypeSpecifier || IsTemplateParamOrArg) &&
17854 TUK == TagUseKind::Definition) {
17855 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17856 << Context.getTagDeclType(New);
17857 Invalid = true;
17858 }
17859
17861 DC->getDeclKind() == Decl::Enum) {
17862 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17863 << Context.getTagDeclType(New);
17864 Invalid = true;
17865 }
17866
17867 // Maybe add qualifier info.
17868 if (SS.isNotEmpty()) {
17869 if (SS.isSet()) {
17870 // If this is either a declaration or a definition, check the
17871 // nested-name-specifier against the current context.
17872 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
17873 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17874 /*TemplateId=*/nullptr,
17875 isMemberSpecialization))
17876 Invalid = true;
17877
17879 if (TemplateParameterLists.size() > 0) {
17880 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17881 }
17882 }
17883 else
17884 Invalid = true;
17885 }
17886
17887 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17888 // Add alignment attributes if necessary; these attributes are checked when
17889 // the ASTContext lays out the structure.
17890 //
17891 // It is important for implementing the correct semantics that this
17892 // happen here (in ActOnTag). The #pragma pack stack is
17893 // maintained as a result of parser callbacks which can occur at
17894 // many points during the parsing of a struct declaration (because
17895 // the #pragma tokens are effectively skipped over during the
17896 // parsing of the struct).
17897 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17900 }
17901 }
17902
17903 if (ModulePrivateLoc.isValid()) {
17904 if (isMemberSpecialization)
17905 Diag(New->getLocation(), diag::err_module_private_specialization)
17906 << 2
17907 << FixItHint::CreateRemoval(ModulePrivateLoc);
17908 // __module_private__ does not apply to local classes. However, we only
17909 // diagnose this as an error when the declaration specifiers are
17910 // freestanding. Here, we just ignore the __module_private__.
17911 else if (!SearchDC->isFunctionOrMethod())
17912 New->setModulePrivate();
17913 }
17914
17915 // If this is a specialization of a member class (of a class template),
17916 // check the specialization.
17917 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17918 Invalid = true;
17919
17920 // If we're declaring or defining a tag in function prototype scope in C,
17921 // note that this type can only be used within the function and add it to
17922 // the list of decls to inject into the function definition scope.
17923 if ((Name || Kind == TagTypeKind::Enum) &&
17924 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17925 if (getLangOpts().CPlusPlus) {
17926 // C++ [dcl.fct]p6:
17927 // Types shall not be defined in return or parameter types.
17928 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
17929 Diag(Loc, diag::err_type_defined_in_param_type)
17930 << Name;
17931 Invalid = true;
17932 }
17933 } else if (!PrevDecl) {
17934 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17935 }
17936 }
17937
17938 if (Invalid)
17939 New->setInvalidDecl();
17940
17941 // Set the lexical context. If the tag has a C++ scope specifier, the
17942 // lexical context will be different from the semantic context.
17944
17945 // Mark this as a friend decl if applicable.
17946 // In Microsoft mode, a friend declaration also acts as a forward
17947 // declaration so we always pass true to setObjectOfFriendDecl to make
17948 // the tag name visible.
17949 if (TUK == TagUseKind::Friend)
17950 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17951
17952 // Set the access specifier.
17953 if (!Invalid && SearchDC->isRecord())
17954 SetMemberAccessSpecifier(New, PrevDecl, AS);
17955
17956 if (PrevDecl)
17957 CheckRedeclarationInModule(New, PrevDecl);
17958
17959 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
17960 New->startDefinition();
17961
17962 ProcessDeclAttributeList(S, New, Attrs);
17963 AddPragmaAttributes(S, New);
17964
17965 // If this has an identifier, add it to the scope stack.
17966 if (TUK == TagUseKind::Friend) {
17967 // We might be replacing an existing declaration in the lookup tables;
17968 // if so, borrow its access specifier.
17969 if (PrevDecl)
17970 New->setAccess(PrevDecl->getAccess());
17971
17973 DC->makeDeclVisibleInContext(New);
17974 if (Name) // can be null along some error paths
17975 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17976 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17977 } else if (Name) {
17978 S = getNonFieldDeclScope(S);
17979 PushOnScopeChains(New, S, true);
17980 } else {
17981 CurContext->addDecl(New);
17982 }
17983
17984 // If this is the C FILE type, notify the AST context.
17985 if (IdentifierInfo *II = New->getIdentifier())
17986 if (!New->isInvalidDecl() &&
17988 II->isStr("FILE"))
17989 Context.setFILEDecl(New);
17990
17991 if (PrevDecl)
17992 mergeDeclAttributes(New, PrevDecl);
17993
17994 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
17997 }
17998
17999 // If there's a #pragma GCC visibility in scope, set the visibility of this
18000 // record.
18002
18003 if (isMemberSpecialization && !New->isInvalidDecl())
18005
18006 OwnedDecl = true;
18007 // In C++, don't return an invalid declaration. We can't recover well from
18008 // the cases where we make the type anonymous.
18009 if (Invalid && getLangOpts().CPlusPlus) {
18010 if (New->isBeingDefined())
18011 if (auto RD = dyn_cast<RecordDecl>(New))
18012 RD->completeDefinition();
18013 return true;
18014 } else if (SkipBody && SkipBody->ShouldSkip) {
18015 return SkipBody->Previous;
18016 } else {
18017 return New;
18018 }
18019}
18020
18023 TagDecl *Tag = cast<TagDecl>(TagD);
18024
18025 // Enter the tag context.
18026 PushDeclContext(S, Tag);
18027
18029
18030 // If there's a #pragma GCC visibility in scope, set the visibility of this
18031 // record.
18033}
18034
18036 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18037 return false;
18038
18039 // Make the previous decl visible.
18041 return true;
18042}
18043
18045 SourceLocation FinalLoc,
18046 bool IsFinalSpelledSealed,
18047 bool IsAbstract,
18048 SourceLocation LBraceLoc) {
18050 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18051
18052 FieldCollector->StartClass();
18053
18054 if (!Record->getIdentifier())
18055 return;
18056
18057 if (IsAbstract)
18058 Record->markAbstract();
18059
18060 if (FinalLoc.isValid()) {
18061 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18062 IsFinalSpelledSealed
18063 ? FinalAttr::Keyword_sealed
18064 : FinalAttr::Keyword_final));
18065 }
18066 // C++ [class]p2:
18067 // [...] The class-name is also inserted into the scope of the
18068 // class itself; this is known as the injected-class-name. For
18069 // purposes of access checking, the injected-class-name is treated
18070 // as if it were a public member name.
18071 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18072 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18073 Record->getLocation(), Record->getIdentifier(),
18074 /*PrevDecl=*/nullptr,
18075 /*DelayTypeCreation=*/true);
18076 Context.getTypeDeclType(InjectedClassName, Record);
18077 InjectedClassName->setImplicit();
18078 InjectedClassName->setAccess(AS_public);
18079 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18080 InjectedClassName->setDescribedClassTemplate(Template);
18081 PushOnScopeChains(InjectedClassName, S);
18082 assert(InjectedClassName->isInjectedClassName() &&
18083 "Broken injected-class-name");
18084}
18085
18087 SourceRange BraceRange) {
18089 TagDecl *Tag = cast<TagDecl>(TagD);
18090 Tag->setBraceRange(BraceRange);
18091
18092 // Make sure we "complete" the definition even it is invalid.
18093 if (Tag->isBeingDefined()) {
18094 assert(Tag->isInvalidDecl() && "We should already have completed it");
18095 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18096 RD->completeDefinition();
18097 }
18098
18099 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18100 FieldCollector->FinishClass();
18101 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18102 auto *Def = RD->getDefinition();
18103 assert(Def && "The record is expected to have a completed definition");
18104 unsigned NumInitMethods = 0;
18105 for (auto *Method : Def->methods()) {
18106 if (!Method->getIdentifier())
18107 continue;
18108 if (Method->getName() == "__init")
18109 NumInitMethods++;
18110 }
18111 if (NumInitMethods > 1 || !Def->hasInitMethod())
18112 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18113 }
18114
18115 // If we're defining a dynamic class in a module interface unit, we always
18116 // need to produce the vtable for it, even if the vtable is not used in the
18117 // current TU.
18118 //
18119 // The case where the current class is not dynamic is handled in
18120 // MarkVTableUsed.
18121 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18122 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18123 }
18124
18125 // Exit this scope of this tag's definition.
18127
18128 if (getCurLexicalContext()->isObjCContainer() &&
18129 Tag->getDeclContext()->isFileContext())
18130 Tag->setTopLevelDeclInObjCContainer();
18131
18132 // Notify the consumer that we've defined a tag.
18133 if (!Tag->isInvalidDecl())
18135
18136 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18137 // from XLs and instead matches the XL #pragma pack(1) behavior.
18138 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18139 AlignPackStack.hasValue()) {
18140 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18141 // Only diagnose #pragma align(packed).
18142 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18143 return;
18144 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18145 if (!RD)
18146 return;
18147 // Only warn if there is at least 1 bitfield member.
18148 if (llvm::any_of(RD->fields(),
18149 [](const FieldDecl *FD) { return FD->isBitField(); }))
18150 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18151 }
18152}
18153
18156 TagDecl *Tag = cast<TagDecl>(TagD);
18157 Tag->setInvalidDecl();
18158
18159 // Make sure we "complete" the definition even it is invalid.
18160 if (Tag->isBeingDefined()) {
18161 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18162 RD->completeDefinition();
18163 }
18164
18165 // We're undoing ActOnTagStartDefinition here, not
18166 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18167 // the FieldCollector.
18168
18170}
18171
18172// Note that FieldName may be null for anonymous bitfields.
18174 const IdentifierInfo *FieldName,
18175 QualType FieldTy, bool IsMsStruct,
18176 Expr *BitWidth) {
18177 assert(BitWidth);
18178 if (BitWidth->containsErrors())
18179 return ExprError();
18180
18181 // C99 6.7.2.1p4 - verify the field type.
18182 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18183 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18184 // Handle incomplete and sizeless types with a specific error.
18185 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18186 diag::err_field_incomplete_or_sizeless))
18187 return ExprError();
18188 if (FieldName)
18189 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18190 << FieldName << FieldTy << BitWidth->getSourceRange();
18191 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18192 << FieldTy << BitWidth->getSourceRange();
18193 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18195 return ExprError();
18196
18197 // If the bit-width is type- or value-dependent, don't try to check
18198 // it now.
18199 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18200 return BitWidth;
18201
18202 llvm::APSInt Value;
18204 if (ICE.isInvalid())
18205 return ICE;
18206 BitWidth = ICE.get();
18207
18208 // Zero-width bitfield is ok for anonymous field.
18209 if (Value == 0 && FieldName)
18210 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18211 << FieldName << BitWidth->getSourceRange();
18212
18213 if (Value.isSigned() && Value.isNegative()) {
18214 if (FieldName)
18215 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18216 << FieldName << toString(Value, 10);
18217 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18218 << toString(Value, 10);
18219 }
18220
18221 // The size of the bit-field must not exceed our maximum permitted object
18222 // size.
18223 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18224 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18225 << !FieldName << FieldName << toString(Value, 10);
18226 }
18227
18228 if (!FieldTy->isDependentType()) {
18229 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18230 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18231 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18232
18233 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18234 // ABI.
18235 bool CStdConstraintViolation =
18236 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18237 bool MSBitfieldViolation =
18238 Value.ugt(TypeStorageSize) &&
18239 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18240 if (CStdConstraintViolation || MSBitfieldViolation) {
18241 unsigned DiagWidth =
18242 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18243 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18244 << (bool)FieldName << FieldName << toString(Value, 10)
18245 << !CStdConstraintViolation << DiagWidth;
18246 }
18247
18248 // Warn on types where the user might conceivably expect to get all
18249 // specified bits as value bits: that's all integral types other than
18250 // 'bool'.
18251 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18252 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18253 << FieldName << toString(Value, 10)
18254 << (unsigned)TypeWidth;
18255 }
18256 }
18257
18258 return BitWidth;
18259}
18260
18262 Declarator &D, Expr *BitfieldWidth) {
18263 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18264 D, BitfieldWidth,
18265 /*InitStyle=*/ICIS_NoInit, AS_public);
18266 return Res;
18267}
18268
18270 SourceLocation DeclStart,
18271 Declarator &D, Expr *BitWidth,
18272 InClassInitStyle InitStyle,
18273 AccessSpecifier AS) {
18274 if (D.isDecompositionDeclarator()) {
18275 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18276 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18277 << Decomp.getSourceRange();
18278 return nullptr;
18279 }
18280
18281 const IdentifierInfo *II = D.getIdentifier();
18282 SourceLocation Loc = DeclStart;
18283 if (II) Loc = D.getIdentifierLoc();
18284
18286 QualType T = TInfo->getType();
18287 if (getLangOpts().CPlusPlus) {
18289
18290 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18292 D.setInvalidType();
18293 T = Context.IntTy;
18295 }
18296 }
18297
18298 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18299
18300 if (D.getDeclSpec().isInlineSpecified())
18301 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18302 << getLangOpts().CPlusPlus17;
18303 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18304 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18305 diag::err_invalid_thread)
18307
18308 // Check to see if this name was declared as a member previously
18309 NamedDecl *PrevDecl = nullptr;
18311 RedeclarationKind::ForVisibleRedeclaration);
18312 LookupName(Previous, S);
18313 switch (Previous.getResultKind()) {
18316 PrevDecl = Previous.getAsSingle<NamedDecl>();
18317 break;
18318
18320 PrevDecl = Previous.getRepresentativeDecl();
18321 break;
18322
18326 break;
18327 }
18328 Previous.suppressDiagnostics();
18329
18330 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18331 // Maybe we will complain about the shadowed template parameter.
18332 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18333 // Just pretend that we didn't see the previous declaration.
18334 PrevDecl = nullptr;
18335 }
18336
18337 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18338 PrevDecl = nullptr;
18339
18340 bool Mutable
18341 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18342 SourceLocation TSSL = D.getBeginLoc();
18343 FieldDecl *NewFD
18344 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18345 TSSL, AS, PrevDecl, &D);
18346
18347 if (NewFD->isInvalidDecl())
18348 Record->setInvalidDecl();
18349
18350 if (D.getDeclSpec().isModulePrivateSpecified())
18351 NewFD->setModulePrivate();
18352
18353 if (NewFD->isInvalidDecl() && PrevDecl) {
18354 // Don't introduce NewFD into scope; there's already something
18355 // with the same name in the same scope.
18356 } else if (II) {
18357 PushOnScopeChains(NewFD, S);
18358 } else
18359 Record->addDecl(NewFD);
18360
18361 return NewFD;
18362}
18363
18365 TypeSourceInfo *TInfo,
18367 bool Mutable, Expr *BitWidth,
18368 InClassInitStyle InitStyle,
18369 SourceLocation TSSL,
18370 AccessSpecifier AS, NamedDecl *PrevDecl,
18371 Declarator *D) {
18372 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18373 bool InvalidDecl = false;
18374 if (D) InvalidDecl = D->isInvalidType();
18375
18376 // If we receive a broken type, recover by assuming 'int' and
18377 // marking this declaration as invalid.
18378 if (T.isNull() || T->containsErrors()) {
18379 InvalidDecl = true;
18380 T = Context.IntTy;
18381 }
18382
18384 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18385 bool isIncomplete =
18386 LangOpts.HLSL // HLSL allows sizeless builtin types
18387 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18389 diag::err_field_incomplete_or_sizeless);
18390 if (isIncomplete) {
18391 // Fields of incomplete type force their record to be invalid.
18392 Record->setInvalidDecl();
18393 InvalidDecl = true;
18394 } else {
18395 NamedDecl *Def;
18396 EltTy->isIncompleteType(&Def);
18397 if (Def && Def->isInvalidDecl()) {
18398 Record->setInvalidDecl();
18399 InvalidDecl = true;
18400 }
18401 }
18402 }
18403
18404 // TR 18037 does not allow fields to be declared with address space
18405 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18407 Diag(Loc, diag::err_field_with_address_space);
18408 Record->setInvalidDecl();
18409 InvalidDecl = true;
18410 }
18411
18412 if (LangOpts.OpenCL) {
18413 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18414 // used as structure or union field: image, sampler, event or block types.
18415 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18416 T->isBlockPointerType()) {
18417 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18418 Record->setInvalidDecl();
18419 InvalidDecl = true;
18420 }
18421 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18422 // is enabled.
18423 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18424 "__cl_clang_bitfields", LangOpts)) {
18425 Diag(Loc, diag::err_opencl_bitfields);
18426 InvalidDecl = true;
18427 }
18428 }
18429
18430 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18431 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18432 T.hasQualifiers()) {
18433 InvalidDecl = true;
18434 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18435 }
18436
18437 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18438 // than a variably modified type.
18439 if (!InvalidDecl && T->isVariablyModifiedType()) {
18441 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18442 InvalidDecl = true;
18443 }
18444
18445 // Fields can not have abstract class types
18446 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18447 diag::err_abstract_type_in_decl,
18449 InvalidDecl = true;
18450
18451 if (InvalidDecl)
18452 BitWidth = nullptr;
18453 // If this is declared as a bit-field, check the bit-field.
18454 if (BitWidth) {
18455 BitWidth =
18456 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18457 if (!BitWidth) {
18458 InvalidDecl = true;
18459 BitWidth = nullptr;
18460 }
18461 }
18462
18463 // Check that 'mutable' is consistent with the type of the declaration.
18464 if (!InvalidDecl && Mutable) {
18465 unsigned DiagID = 0;
18466 if (T->isReferenceType())
18467 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18468 : diag::err_mutable_reference;
18469 else if (T.isConstQualified())
18470 DiagID = diag::err_mutable_const;
18471
18472 if (DiagID) {
18473 SourceLocation ErrLoc = Loc;
18474 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18475 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18476 Diag(ErrLoc, DiagID);
18477 if (DiagID != diag::ext_mutable_reference) {
18478 Mutable = false;
18479 InvalidDecl = true;
18480 }
18481 }
18482 }
18483
18484 // C++11 [class.union]p8 (DR1460):
18485 // At most one variant member of a union may have a
18486 // brace-or-equal-initializer.
18487 if (InitStyle != ICIS_NoInit)
18488 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18489
18490 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18491 BitWidth, Mutable, InitStyle);
18492 if (InvalidDecl)
18493 NewFD->setInvalidDecl();
18494
18495 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18496 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18497 Diag(Loc, diag::err_duplicate_member) << II;
18498 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18499 NewFD->setInvalidDecl();
18500 }
18501
18502 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18503 if (Record->isUnion()) {
18504 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18505 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18506 if (RDecl->getDefinition()) {
18507 // C++ [class.union]p1: An object of a class with a non-trivial
18508 // constructor, a non-trivial copy constructor, a non-trivial
18509 // destructor, or a non-trivial copy assignment operator
18510 // cannot be a member of a union, nor can an array of such
18511 // objects.
18512 if (CheckNontrivialField(NewFD))
18513 NewFD->setInvalidDecl();
18514 }
18515 }
18516
18517 // C++ [class.union]p1: If a union contains a member of reference type,
18518 // the program is ill-formed, except when compiling with MSVC extensions
18519 // enabled.
18520 if (EltTy->isReferenceType()) {
18521 const bool HaveMSExt =
18522 getLangOpts().MicrosoftExt &&
18524
18525 Diag(NewFD->getLocation(),
18526 HaveMSExt ? diag::ext_union_member_of_reference_type
18527 : diag::err_union_member_of_reference_type)
18528 << NewFD->getDeclName() << EltTy;
18529 if (!HaveMSExt)
18530 NewFD->setInvalidDecl();
18531 }
18532 }
18533 }
18534
18535 // FIXME: We need to pass in the attributes given an AST
18536 // representation, not a parser representation.
18537 if (D) {
18538 // FIXME: The current scope is almost... but not entirely... correct here.
18540
18541 if (NewFD->hasAttrs())
18543 }
18544
18545 // In auto-retain/release, infer strong retension for fields of
18546 // retainable type.
18547 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18548 NewFD->setInvalidDecl();
18549
18550 if (T.isObjCGCWeak())
18551 Diag(Loc, diag::warn_attribute_weak_on_field);
18552
18553 // PPC MMA non-pointer types are not allowed as field types.
18554 if (Context.getTargetInfo().getTriple().isPPC64() &&
18555 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18556 NewFD->setInvalidDecl();
18557
18558 NewFD->setAccess(AS);
18559 return NewFD;
18560}
18561
18563 assert(FD);
18564 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18565
18566 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18567 return false;
18568
18570 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18571 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18572 if (RDecl->getDefinition()) {
18573 // We check for copy constructors before constructors
18574 // because otherwise we'll never get complaints about
18575 // copy constructors.
18576
18578 // We're required to check for any non-trivial constructors. Since the
18579 // implicit default constructor is suppressed if there are any
18580 // user-declared constructors, we just need to check that there is a
18581 // trivial default constructor and a trivial copy constructor. (We don't
18582 // worry about move constructors here, since this is a C++98 check.)
18583 if (RDecl->hasNonTrivialCopyConstructor())
18585 else if (!RDecl->hasTrivialDefaultConstructor())
18587 else if (RDecl->hasNonTrivialCopyAssignment())
18589 else if (RDecl->hasNonTrivialDestructor())
18591
18592 if (member != CXXSpecialMemberKind::Invalid) {
18593 if (!getLangOpts().CPlusPlus11 &&
18594 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18595 // Objective-C++ ARC: it is an error to have a non-trivial field of
18596 // a union. However, system headers in Objective-C programs
18597 // occasionally have Objective-C lifetime objects within unions,
18598 // and rather than cause the program to fail, we make those
18599 // members unavailable.
18601 if (getSourceManager().isInSystemHeader(Loc)) {
18602 if (!FD->hasAttr<UnavailableAttr>())
18603 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18604 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18605 return false;
18606 }
18607 }
18608
18609 Diag(
18610 FD->getLocation(),
18612 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18613 : diag::err_illegal_union_or_anon_struct_member)
18614 << FD->getParent()->isUnion() << FD->getDeclName()
18615 << llvm::to_underlying(member);
18616 DiagnoseNontrivial(RDecl, member);
18617 return !getLangOpts().CPlusPlus11;
18618 }
18619 }
18620 }
18621
18622 return false;
18623}
18624
18626 SmallVectorImpl<Decl *> &AllIvarDecls) {
18627 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18628 return;
18629
18630 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18631 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18632
18633 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18634 return;
18635 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18636 if (!ID) {
18637 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18638 if (!CD->IsClassExtension())
18639 return;
18640 }
18641 // No need to add this to end of @implementation.
18642 else
18643 return;
18644 }
18645 // All conditions are met. Add a new bitfield to the tail end of ivars.
18646 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18647 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18648
18649 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18650 DeclLoc, DeclLoc, nullptr,
18653 DeclLoc),
18655 true);
18656 AllIvarDecls.push_back(Ivar);
18657}
18658
18659/// [class.dtor]p4:
18660/// At the end of the definition of a class, overload resolution is
18661/// performed among the prospective destructors declared in that class with
18662/// an empty argument list to select the destructor for the class, also
18663/// known as the selected destructor.
18664///
18665/// We do the overload resolution here, then mark the selected constructor in the AST.
18666/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18668 if (!Record->hasUserDeclaredDestructor()) {
18669 return;
18670 }
18671
18672 SourceLocation Loc = Record->getLocation();
18674
18675 for (auto *Decl : Record->decls()) {
18676 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18677 if (DD->isInvalidDecl())
18678 continue;
18679 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18680 OCS);
18681 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18682 }
18683 }
18684
18685 if (OCS.empty()) {
18686 return;
18687 }
18689 unsigned Msg = 0;
18690 OverloadCandidateDisplayKind DisplayKind;
18691
18692 switch (OCS.BestViableFunction(S, Loc, Best)) {
18693 case OR_Success:
18694 case OR_Deleted:
18695 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18696 break;
18697
18698 case OR_Ambiguous:
18699 Msg = diag::err_ambiguous_destructor;
18700 DisplayKind = OCD_AmbiguousCandidates;
18701 break;
18702
18704 Msg = diag::err_no_viable_destructor;
18705 DisplayKind = OCD_AllCandidates;
18706 break;
18707 }
18708
18709 if (Msg) {
18710 // OpenCL have got their own thing going with destructors. It's slightly broken,
18711 // but we allow it.
18712 if (!S.LangOpts.OpenCL) {
18713 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18714 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18715 Record->setInvalidDecl();
18716 }
18717 // It's a bit hacky: At this point we've raised an error but we want the
18718 // rest of the compiler to continue somehow working. However almost
18719 // everything we'll try to do with the class will depend on there being a
18720 // destructor. So let's pretend the first one is selected and hope for the
18721 // best.
18722 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18723 }
18724}
18725
18726/// [class.mem.special]p5
18727/// Two special member functions are of the same kind if:
18728/// - they are both default constructors,
18729/// - they are both copy or move constructors with the same first parameter
18730/// type, or
18731/// - they are both copy or move assignment operators with the same first
18732/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18734 CXXMethodDecl *M1,
18735 CXXMethodDecl *M2,
18737 // We don't want to compare templates to non-templates: See
18738 // https://github.com/llvm/llvm-project/issues/59206
18740 return bool(M1->getDescribedFunctionTemplate()) ==
18742 // FIXME: better resolve CWG
18743 // https://cplusplus.github.io/CWG/issues/2787.html
18744 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18745 M2->getNonObjectParameter(0)->getType()))
18746 return false;
18749 return false;
18750
18751 return true;
18752}
18753
18754/// [class.mem.special]p6:
18755/// An eligible special member function is a special member function for which:
18756/// - the function is not deleted,
18757/// - the associated constraints, if any, are satisfied, and
18758/// - no special member function of the same kind whose associated constraints
18759/// [CWG2595], if any, are satisfied is more constrained.
18763 SmallVector<bool, 4> SatisfactionStatus;
18764
18765 for (CXXMethodDecl *Method : Methods) {
18766 const Expr *Constraints = Method->getTrailingRequiresClause();
18767 if (!Constraints)
18768 SatisfactionStatus.push_back(true);
18769 else {
18770 ConstraintSatisfaction Satisfaction;
18771 if (S.CheckFunctionConstraints(Method, Satisfaction))
18772 SatisfactionStatus.push_back(false);
18773 else
18774 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18775 }
18776 }
18777
18778 for (size_t i = 0; i < Methods.size(); i++) {
18779 if (!SatisfactionStatus[i])
18780 continue;
18781 CXXMethodDecl *Method = Methods[i];
18782 CXXMethodDecl *OrigMethod = Method;
18783 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18784 OrigMethod = cast<CXXMethodDecl>(MF);
18785
18786 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18787 bool AnotherMethodIsMoreConstrained = false;
18788 for (size_t j = 0; j < Methods.size(); j++) {
18789 if (i == j || !SatisfactionStatus[j])
18790 continue;
18791 CXXMethodDecl *OtherMethod = Methods[j];
18792 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18793 OtherMethod = cast<CXXMethodDecl>(MF);
18794
18795 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18796 CSM))
18797 continue;
18798
18799 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18800 if (!OtherConstraints)
18801 continue;
18802 if (!Constraints) {
18803 AnotherMethodIsMoreConstrained = true;
18804 break;
18805 }
18806 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18807 {Constraints},
18808 AnotherMethodIsMoreConstrained)) {
18809 // There was an error with the constraints comparison. Exit the loop
18810 // and don't consider this function eligible.
18811 AnotherMethodIsMoreConstrained = true;
18812 }
18813 if (AnotherMethodIsMoreConstrained)
18814 break;
18815 }
18816 // FIXME: Do not consider deleted methods as eligible after implementing
18817 // DR1734 and DR1496.
18818 if (!AnotherMethodIsMoreConstrained) {
18819 Method->setIneligibleOrNotSelected(false);
18820 Record->addedEligibleSpecialMemberFunction(Method,
18821 1 << llvm::to_underlying(CSM));
18822 }
18823 }
18824}
18825
18828 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18829 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18830 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18831 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18832 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18833
18834 for (auto *Decl : Record->decls()) {
18835 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18836 if (!MD) {
18837 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18838 if (FTD)
18839 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18840 }
18841 if (!MD)
18842 continue;
18843 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18844 if (CD->isInvalidDecl())
18845 continue;
18846 if (CD->isDefaultConstructor())
18847 DefaultConstructors.push_back(MD);
18848 else if (CD->isCopyConstructor())
18849 CopyConstructors.push_back(MD);
18850 else if (CD->isMoveConstructor())
18851 MoveConstructors.push_back(MD);
18852 } else if (MD->isCopyAssignmentOperator()) {
18853 CopyAssignmentOperators.push_back(MD);
18854 } else if (MD->isMoveAssignmentOperator()) {
18855 MoveAssignmentOperators.push_back(MD);
18856 }
18857 }
18858
18859 SetEligibleMethods(S, Record, DefaultConstructors,
18861 SetEligibleMethods(S, Record, CopyConstructors,
18863 SetEligibleMethods(S, Record, MoveConstructors,
18865 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18867 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18869}
18870
18871void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18872 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18873 SourceLocation RBrac,
18874 const ParsedAttributesView &Attrs) {
18875 assert(EnclosingDecl && "missing record or interface decl");
18876
18877 // If this is an Objective-C @implementation or category and we have
18878 // new fields here we should reset the layout of the interface since
18879 // it will now change.
18880 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18881 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18882 switch (DC->getKind()) {
18883 default: break;
18884 case Decl::ObjCCategory:
18885 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18886 break;
18887 case Decl::ObjCImplementation:
18888 Context.
18889 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18890 break;
18891 }
18892 }
18893
18894 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18895 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18896
18897 // Start counting up the number of named members; make sure to include
18898 // members of anonymous structs and unions in the total.
18899 unsigned NumNamedMembers = 0;
18900 if (Record) {
18901 for (const auto *I : Record->decls()) {
18902 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18903 if (IFD->getDeclName())
18904 ++NumNamedMembers;
18905 }
18906 }
18907
18908 // Verify that all the fields are okay.
18910
18911 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18912 i != end; ++i) {
18913 FieldDecl *FD = cast<FieldDecl>(*i);
18914
18915 // Get the type for the field.
18916 const Type *FDTy = FD->getType().getTypePtr();
18917
18918 if (!FD->isAnonymousStructOrUnion()) {
18919 // Remember all fields written by the user.
18920 RecFields.push_back(FD);
18921 }
18922
18923 // If the field is already invalid for some reason, don't emit more
18924 // diagnostics about it.
18925 if (FD->isInvalidDecl()) {
18926 EnclosingDecl->setInvalidDecl();
18927 continue;
18928 }
18929
18930 // C99 6.7.2.1p2:
18931 // A structure or union shall not contain a member with
18932 // incomplete or function type (hence, a structure shall not
18933 // contain an instance of itself, but may contain a pointer to
18934 // an instance of itself), except that the last member of a
18935 // structure with more than one named member may have incomplete
18936 // array type; such a structure (and any union containing,
18937 // possibly recursively, a member that is such a structure)
18938 // shall not be a member of a structure or an element of an
18939 // array.
18940 bool IsLastField = (i + 1 == Fields.end());
18941 if (FDTy->isFunctionType()) {
18942 // Field declared as a function.
18943 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18944 << FD->getDeclName();
18945 FD->setInvalidDecl();
18946 EnclosingDecl->setInvalidDecl();
18947 continue;
18948 } else if (FDTy->isIncompleteArrayType() &&
18949 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18950 if (Record) {
18951 // Flexible array member.
18952 // Microsoft and g++ is more permissive regarding flexible array.
18953 // It will accept flexible array in union and also
18954 // as the sole element of a struct/class.
18955 unsigned DiagID = 0;
18956 if (!Record->isUnion() && !IsLastField) {
18957 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18958 << FD->getDeclName() << FD->getType()
18959 << llvm::to_underlying(Record->getTagKind());
18960 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18961 FD->setInvalidDecl();
18962 EnclosingDecl->setInvalidDecl();
18963 continue;
18964 } else if (Record->isUnion())
18965 DiagID = getLangOpts().MicrosoftExt
18966 ? diag::ext_flexible_array_union_ms
18967 : diag::ext_flexible_array_union_gnu;
18968 else if (NumNamedMembers < 1)
18969 DiagID = getLangOpts().MicrosoftExt
18970 ? diag::ext_flexible_array_empty_aggregate_ms
18971 : diag::ext_flexible_array_empty_aggregate_gnu;
18972
18973 if (DiagID)
18974 Diag(FD->getLocation(), DiagID)
18975 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18976 // While the layout of types that contain virtual bases is not specified
18977 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18978 // virtual bases after the derived members. This would make a flexible
18979 // array member declared at the end of an object not adjacent to the end
18980 // of the type.
18981 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18982 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18983 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18984 if (!getLangOpts().C99)
18985 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18986 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18987
18988 // If the element type has a non-trivial destructor, we would not
18989 // implicitly destroy the elements, so disallow it for now.
18990 //
18991 // FIXME: GCC allows this. We should probably either implicitly delete
18992 // the destructor of the containing class, or just allow this.
18993 QualType BaseElem = Context.getBaseElementType(FD->getType());
18994 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18995 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18996 << FD->getDeclName() << FD->getType();
18997 FD->setInvalidDecl();
18998 EnclosingDecl->setInvalidDecl();
18999 continue;
19000 }
19001 // Okay, we have a legal flexible array member at the end of the struct.
19002 Record->setHasFlexibleArrayMember(true);
19003 } else {
19004 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19005 // unless they are followed by another ivar. That check is done
19006 // elsewhere, after synthesized ivars are known.
19007 }
19008 } else if (!FDTy->isDependentType() &&
19009 (LangOpts.HLSL // HLSL allows sizeless builtin types
19011 diag::err_incomplete_type)
19013 FD->getLocation(), FD->getType(),
19014 diag::err_field_incomplete_or_sizeless))) {
19015 // Incomplete type
19016 FD->setInvalidDecl();
19017 EnclosingDecl->setInvalidDecl();
19018 continue;
19019 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19020 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19021 // A type which contains a flexible array member is considered to be a
19022 // flexible array member.
19023 Record->setHasFlexibleArrayMember(true);
19024 if (!Record->isUnion()) {
19025 // If this is a struct/class and this is not the last element, reject
19026 // it. Note that GCC supports variable sized arrays in the middle of
19027 // structures.
19028 if (!IsLastField)
19029 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19030 << FD->getDeclName() << FD->getType();
19031 else {
19032 // We support flexible arrays at the end of structs in
19033 // other structs as an extension.
19034 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19035 << FD->getDeclName();
19036 }
19037 }
19038 }
19039 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19041 diag::err_abstract_type_in_decl,
19043 // Ivars can not have abstract class types
19044 FD->setInvalidDecl();
19045 }
19046 if (Record && FDTTy->getDecl()->hasObjectMember())
19047 Record->setHasObjectMember(true);
19048 if (Record && FDTTy->getDecl()->hasVolatileMember())
19049 Record->setHasVolatileMember(true);
19050 } else if (FDTy->isObjCObjectType()) {
19051 /// A field cannot be an Objective-c object
19052 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19055 FD->setType(T);
19056 } else if (Record && Record->isUnion() &&
19058 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19059 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19062 // For backward compatibility, fields of C unions declared in system
19063 // headers that have non-trivial ObjC ownership qualifications are marked
19064 // as unavailable unless the qualifier is explicit and __strong. This can
19065 // break ABI compatibility between programs compiled with ARC and MRR, but
19066 // is a better option than rejecting programs using those unions under
19067 // ARC.
19068 FD->addAttr(UnavailableAttr::CreateImplicit(
19069 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19070 FD->getLocation()));
19071 } else if (getLangOpts().ObjC &&
19072 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19073 !Record->hasObjectMember()) {
19074 if (FD->getType()->isObjCObjectPointerType() ||
19075 FD->getType().isObjCGCStrong())
19076 Record->setHasObjectMember(true);
19077 else if (Context.getAsArrayType(FD->getType())) {
19078 QualType BaseType = Context.getBaseElementType(FD->getType());
19079 if (BaseType->isRecordType() &&
19080 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19081 Record->setHasObjectMember(true);
19082 else if (BaseType->isObjCObjectPointerType() ||
19083 BaseType.isObjCGCStrong())
19084 Record->setHasObjectMember(true);
19085 }
19086 }
19087
19088 if (Record && !getLangOpts().CPlusPlus &&
19089 !shouldIgnoreForRecordTriviality(FD)) {
19090 QualType FT = FD->getType();
19092 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19094 Record->isUnion())
19095 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19096 }
19099 Record->setNonTrivialToPrimitiveCopy(true);
19100 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19101 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19102 }
19103 if (FT.isDestructedType()) {
19104 Record->setNonTrivialToPrimitiveDestroy(true);
19105 Record->setParamDestroyedInCallee(true);
19106 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19107 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19108 }
19109
19110 if (const auto *RT = FT->getAs<RecordType>()) {
19111 if (RT->getDecl()->getArgPassingRestrictions() ==
19113 Record->setArgPassingRestrictions(
19116 Record->setArgPassingRestrictions(
19118 }
19119
19120 if (Record && FD->getType().isVolatileQualified())
19121 Record->setHasVolatileMember(true);
19122 // Keep track of the number of named members.
19123 if (FD->getIdentifier())
19124 ++NumNamedMembers;
19125 }
19126
19127 // Okay, we successfully defined 'Record'.
19128 if (Record) {
19129 bool Completed = false;
19130 if (S) {
19131 Scope *Parent = S->getParent();
19132 if (Parent && Parent->isTypeAliasScope() &&
19133 Parent->isTemplateParamScope())
19134 Record->setInvalidDecl();
19135 }
19136
19137 if (CXXRecord) {
19138 if (!CXXRecord->isInvalidDecl()) {
19139 // Set access bits correctly on the directly-declared conversions.
19141 I = CXXRecord->conversion_begin(),
19142 E = CXXRecord->conversion_end(); I != E; ++I)
19143 I.setAccess((*I)->getAccess());
19144 }
19145
19146 // Add any implicitly-declared members to this class.
19148
19149 if (!CXXRecord->isDependentType()) {
19150 if (!CXXRecord->isInvalidDecl()) {
19151 // If we have virtual base classes, we may end up finding multiple
19152 // final overriders for a given virtual function. Check for this
19153 // problem now.
19154 if (CXXRecord->getNumVBases()) {
19155 CXXFinalOverriderMap FinalOverriders;
19156 CXXRecord->getFinalOverriders(FinalOverriders);
19157
19158 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19159 MEnd = FinalOverriders.end();
19160 M != MEnd; ++M) {
19161 for (OverridingMethods::iterator SO = M->second.begin(),
19162 SOEnd = M->second.end();
19163 SO != SOEnd; ++SO) {
19164 assert(SO->second.size() > 0 &&
19165 "Virtual function without overriding functions?");
19166 if (SO->second.size() == 1)
19167 continue;
19168
19169 // C++ [class.virtual]p2:
19170 // In a derived class, if a virtual member function of a base
19171 // class subobject has more than one final overrider the
19172 // program is ill-formed.
19173 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19174 << (const NamedDecl *)M->first << Record;
19175 Diag(M->first->getLocation(),
19176 diag::note_overridden_virtual_function);
19178 OM = SO->second.begin(),
19179 OMEnd = SO->second.end();
19180 OM != OMEnd; ++OM)
19181 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19182 << (const NamedDecl *)M->first << OM->Method->getParent();
19183
19184 Record->setInvalidDecl();
19185 }
19186 }
19187 CXXRecord->completeDefinition(&FinalOverriders);
19188 Completed = true;
19189 }
19190 }
19191 ComputeSelectedDestructor(*this, CXXRecord);
19193 }
19194 }
19195
19196 if (!Completed)
19197 Record->completeDefinition();
19198
19199 // Handle attributes before checking the layout.
19201
19202 // Check to see if a FieldDecl is a pointer to a function.
19203 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19204 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19205 if (!FD) {
19206 // Check whether this is a forward declaration that was inserted by
19207 // Clang. This happens when a non-forward declared / defined type is
19208 // used, e.g.:
19209 //
19210 // struct foo {
19211 // struct bar *(*f)();
19212 // struct bar *(*g)();
19213 // };
19214 //
19215 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19216 // incomplete definition.
19217 if (const auto *TD = dyn_cast<TagDecl>(D))
19218 return !TD->isCompleteDefinition();
19219 return false;
19220 }
19221 QualType FieldType = FD->getType().getDesugaredType(Context);
19222 if (isa<PointerType>(FieldType)) {
19223 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19224 return PointeeType.getDesugaredType(Context)->isFunctionType();
19225 }
19226 return false;
19227 };
19228
19229 // Maybe randomize the record's decls. We automatically randomize a record
19230 // of function pointers, unless it has the "no_randomize_layout" attribute.
19231 if (!getLangOpts().CPlusPlus &&
19232 (Record->hasAttr<RandomizeLayoutAttr>() ||
19233 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19234 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19235 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19236 !Record->isRandomized()) {
19237 SmallVector<Decl *, 32> NewDeclOrdering;
19239 NewDeclOrdering))
19240 Record->reorderDecls(NewDeclOrdering);
19241 }
19242
19243 // We may have deferred checking for a deleted destructor. Check now.
19244 if (CXXRecord) {
19245 auto *Dtor = CXXRecord->getDestructor();
19246 if (Dtor && Dtor->isImplicit() &&
19248 CXXRecord->setImplicitDestructorIsDeleted();
19249 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19250 }
19251 }
19252
19253 if (Record->hasAttrs()) {
19255
19256 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19257 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19258 IA->getRange(), IA->getBestCase(),
19259 IA->getInheritanceModel());
19260 }
19261
19262 // Check if the structure/union declaration is a type that can have zero
19263 // size in C. For C this is a language extension, for C++ it may cause
19264 // compatibility problems.
19265 bool CheckForZeroSize;
19266 if (!getLangOpts().CPlusPlus) {
19267 CheckForZeroSize = true;
19268 } else {
19269 // For C++ filter out types that cannot be referenced in C code.
19270 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19271 CheckForZeroSize =
19272 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19273 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19274 CXXRecord->isCLike();
19275 }
19276 if (CheckForZeroSize) {
19277 bool ZeroSize = true;
19278 bool IsEmpty = true;
19279 unsigned NonBitFields = 0;
19280 for (RecordDecl::field_iterator I = Record->field_begin(),
19281 E = Record->field_end();
19282 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19283 IsEmpty = false;
19284 if (I->isUnnamedBitField()) {
19285 if (!I->isZeroLengthBitField(Context))
19286 ZeroSize = false;
19287 } else {
19288 ++NonBitFields;
19289 QualType FieldType = I->getType();
19290 if (FieldType->isIncompleteType() ||
19291 !Context.getTypeSizeInChars(FieldType).isZero())
19292 ZeroSize = false;
19293 }
19294 }
19295
19296 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19297 // allowed in C++, but warn if its declaration is inside
19298 // extern "C" block.
19299 if (ZeroSize) {
19300 Diag(RecLoc, getLangOpts().CPlusPlus ?
19301 diag::warn_zero_size_struct_union_in_extern_c :
19302 diag::warn_zero_size_struct_union_compat)
19303 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19304 }
19305
19306 // Structs without named members are extension in C (C99 6.7.2.1p7),
19307 // but are accepted by GCC.
19308 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19309 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19310 diag::ext_no_named_members_in_struct_union)
19311 << Record->isUnion();
19312 }
19313 }
19314 } else {
19315 ObjCIvarDecl **ClsFields =
19316 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19317 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19318 ID->setEndOfDefinitionLoc(RBrac);
19319 // Add ivar's to class's DeclContext.
19320 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19321 ClsFields[i]->setLexicalDeclContext(ID);
19322 ID->addDecl(ClsFields[i]);
19323 }
19324 // Must enforce the rule that ivars in the base classes may not be
19325 // duplicates.
19326 if (ID->getSuperClass())
19327 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19328 } else if (ObjCImplementationDecl *IMPDecl =
19329 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19330 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19331 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19332 // Ivar declared in @implementation never belongs to the implementation.
19333 // Only it is in implementation's lexical context.
19334 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19335 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19336 RBrac);
19337 IMPDecl->setIvarLBraceLoc(LBrac);
19338 IMPDecl->setIvarRBraceLoc(RBrac);
19339 } else if (ObjCCategoryDecl *CDecl =
19340 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19341 // case of ivars in class extension; all other cases have been
19342 // reported as errors elsewhere.
19343 // FIXME. Class extension does not have a LocEnd field.
19344 // CDecl->setLocEnd(RBrac);
19345 // Add ivar's to class extension's DeclContext.
19346 // Diagnose redeclaration of private ivars.
19347 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19348 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19349 if (IDecl) {
19350 if (const ObjCIvarDecl *ClsIvar =
19351 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19352 Diag(ClsFields[i]->getLocation(),
19353 diag::err_duplicate_ivar_declaration);
19354 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19355 continue;
19356 }
19357 for (const auto *Ext : IDecl->known_extensions()) {
19358 if (const ObjCIvarDecl *ClsExtIvar
19359 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19360 Diag(ClsFields[i]->getLocation(),
19361 diag::err_duplicate_ivar_declaration);
19362 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19363 continue;
19364 }
19365 }
19366 }
19367 ClsFields[i]->setLexicalDeclContext(CDecl);
19368 CDecl->addDecl(ClsFields[i]);
19369 }
19370 CDecl->setIvarLBraceLoc(LBrac);
19371 CDecl->setIvarRBraceLoc(RBrac);
19372 }
19373 }
19375}
19376
19377/// Determine whether the given integral value is representable within
19378/// the given type T.
19380 llvm::APSInt &Value,
19381 QualType T) {
19382 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19383 "Integral type required!");
19384 unsigned BitWidth = Context.getIntWidth(T);
19385
19386 if (Value.isUnsigned() || Value.isNonNegative()) {
19388 --BitWidth;
19389 return Value.getActiveBits() <= BitWidth;
19390 }
19391 return Value.getSignificantBits() <= BitWidth;
19392}
19393
19394// Given an integral type, return the next larger integral type
19395// (or a NULL type of no such type exists).
19397 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19398 // enum checking below.
19399 assert((T->isIntegralType(Context) ||
19400 T->isEnumeralType()) && "Integral type required!");
19401 const unsigned NumTypes = 4;
19402 QualType SignedIntegralTypes[NumTypes] = {
19403 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19404 };
19405 QualType UnsignedIntegralTypes[NumTypes] = {
19406 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19407 Context.UnsignedLongLongTy
19408 };
19409
19410 unsigned BitWidth = Context.getTypeSize(T);
19411 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19412 : UnsignedIntegralTypes;
19413 for (unsigned I = 0; I != NumTypes; ++I)
19414 if (Context.getTypeSize(Types[I]) > BitWidth)
19415 return Types[I];
19416
19417 return QualType();
19418}
19419
19421 EnumConstantDecl *LastEnumConst,
19422 SourceLocation IdLoc,
19424 Expr *Val) {
19425 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19426 llvm::APSInt EnumVal(IntWidth);
19427 QualType EltTy;
19428
19430 Val = nullptr;
19431
19432 if (Val)
19433 Val = DefaultLvalueConversion(Val).get();
19434
19435 if (Val) {
19436 if (Enum->isDependentType() || Val->isTypeDependent() ||
19437 Val->containsErrors())
19438 EltTy = Context.DependentTy;
19439 else {
19440 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19441 // underlying type, but do allow it in all other contexts.
19442 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19443 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19444 // constant-expression in the enumerator-definition shall be a converted
19445 // constant expression of the underlying type.
19446 EltTy = Enum->getIntegerType();
19447 ExprResult Converted =
19448 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19450 if (Converted.isInvalid())
19451 Val = nullptr;
19452 else
19453 Val = Converted.get();
19454 } else if (!Val->isValueDependent() &&
19455 !(Val =
19457 .get())) {
19458 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19459 } else {
19460 if (Enum->isComplete()) {
19461 EltTy = Enum->getIntegerType();
19462
19463 // In Obj-C and Microsoft mode, require the enumeration value to be
19464 // representable in the underlying type of the enumeration. In C++11,
19465 // we perform a non-narrowing conversion as part of converted constant
19466 // expression checking.
19467 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19469 .getTriple()
19470 .isWindowsMSVCEnvironment()) {
19471 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19472 } else {
19473 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19474 }
19475 }
19476
19477 // Cast to the underlying type.
19478 Val = ImpCastExprToType(Val, EltTy,
19479 EltTy->isBooleanType() ? CK_IntegralToBoolean
19480 : CK_IntegralCast)
19481 .get();
19482 } else if (getLangOpts().CPlusPlus) {
19483 // C++11 [dcl.enum]p5:
19484 // If the underlying type is not fixed, the type of each enumerator
19485 // is the type of its initializing value:
19486 // - If an initializer is specified for an enumerator, the
19487 // initializing value has the same type as the expression.
19488 EltTy = Val->getType();
19489 } else {
19490 // C99 6.7.2.2p2:
19491 // The expression that defines the value of an enumeration constant
19492 // shall be an integer constant expression that has a value
19493 // representable as an int.
19494
19495 // Complain if the value is not representable in an int.
19497 Diag(IdLoc, diag::ext_enum_value_not_int)
19498 << toString(EnumVal, 10) << Val->getSourceRange()
19499 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19500 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19501 // Force the type of the expression to 'int'.
19502 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19503 }
19504 EltTy = Val->getType();
19505 }
19506 }
19507 }
19508 }
19509
19510 if (!Val) {
19511 if (Enum->isDependentType())
19512 EltTy = Context.DependentTy;
19513 else if (!LastEnumConst) {
19514 // C++0x [dcl.enum]p5:
19515 // If the underlying type is not fixed, the type of each enumerator
19516 // is the type of its initializing value:
19517 // - If no initializer is specified for the first enumerator, the
19518 // initializing value has an unspecified integral type.
19519 //
19520 // GCC uses 'int' for its unspecified integral type, as does
19521 // C99 6.7.2.2p3.
19522 if (Enum->isFixed()) {
19523 EltTy = Enum->getIntegerType();
19524 }
19525 else {
19526 EltTy = Context.IntTy;
19527 }
19528 } else {
19529 // Assign the last value + 1.
19530 EnumVal = LastEnumConst->getInitVal();
19531 ++EnumVal;
19532 EltTy = LastEnumConst->getType();
19533
19534 // Check for overflow on increment.
19535 if (EnumVal < LastEnumConst->getInitVal()) {
19536 // C++0x [dcl.enum]p5:
19537 // If the underlying type is not fixed, the type of each enumerator
19538 // is the type of its initializing value:
19539 //
19540 // - Otherwise the type of the initializing value is the same as
19541 // the type of the initializing value of the preceding enumerator
19542 // unless the incremented value is not representable in that type,
19543 // in which case the type is an unspecified integral type
19544 // sufficient to contain the incremented value. If no such type
19545 // exists, the program is ill-formed.
19547 if (T.isNull() || Enum->isFixed()) {
19548 // There is no integral type larger enough to represent this
19549 // value. Complain, then allow the value to wrap around.
19550 EnumVal = LastEnumConst->getInitVal();
19551 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19552 ++EnumVal;
19553 if (Enum->isFixed())
19554 // When the underlying type is fixed, this is ill-formed.
19555 Diag(IdLoc, diag::err_enumerator_wrapped)
19556 << toString(EnumVal, 10)
19557 << EltTy;
19558 else
19559 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19560 << toString(EnumVal, 10);
19561 } else {
19562 EltTy = T;
19563 }
19564
19565 // Retrieve the last enumerator's value, extent that type to the
19566 // type that is supposed to be large enough to represent the incremented
19567 // value, then increment.
19568 EnumVal = LastEnumConst->getInitVal();
19569 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19570 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19571 ++EnumVal;
19572
19573 // If we're not in C++, diagnose the overflow of enumerator values,
19574 // which in C99 means that the enumerator value is not representable in
19575 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19576 // permits enumerator values that are representable in some larger
19577 // integral type.
19578 if (!getLangOpts().CPlusPlus && !T.isNull())
19579 Diag(IdLoc, diag::warn_enum_value_overflow);
19580 } else if (!getLangOpts().CPlusPlus &&
19581 !EltTy->isDependentType() &&
19582 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19583 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19584 Diag(IdLoc, diag::ext_enum_value_not_int)
19585 << toString(EnumVal, 10) << 1;
19586 }
19587 }
19588 }
19589
19590 if (!EltTy->isDependentType()) {
19591 // Make the enumerator value match the signedness and size of the
19592 // enumerator's type.
19593 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19594 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19595 }
19596
19597 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19598 Val, EnumVal);
19599}
19600
19602 SourceLocation IILoc) {
19603 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19605 return SkipBodyInfo();
19606
19607 // We have an anonymous enum definition. Look up the first enumerator to
19608 // determine if we should merge the definition with an existing one and
19609 // skip the body.
19610 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19612 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19613 if (!PrevECD)
19614 return SkipBodyInfo();
19615
19616 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19617 NamedDecl *Hidden;
19618 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19619 SkipBodyInfo Skip;
19620 Skip.Previous = Hidden;
19621 return Skip;
19622 }
19623
19624 return SkipBodyInfo();
19625}
19626
19627Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19629 const ParsedAttributesView &Attrs,
19630 SourceLocation EqualLoc, Expr *Val) {
19631 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19632 EnumConstantDecl *LastEnumConst =
19633 cast_or_null<EnumConstantDecl>(lastEnumConst);
19634
19635 // The scope passed in may not be a decl scope. Zip up the scope tree until
19636 // we find one that is.
19637 S = getNonFieldDeclScope(S);
19638
19639 // Verify that there isn't already something declared with this name in this
19640 // scope.
19641 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19642 RedeclarationKind::ForVisibleRedeclaration);
19643 LookupName(R, S);
19644 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19645
19646 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19647 // Maybe we will complain about the shadowed template parameter.
19648 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19649 // Just pretend that we didn't see the previous declaration.
19650 PrevDecl = nullptr;
19651 }
19652
19653 // C++ [class.mem]p15:
19654 // If T is the name of a class, then each of the following shall have a name
19655 // different from T:
19656 // - every enumerator of every member of class T that is an unscoped
19657 // enumerated type
19658 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19660 DeclarationNameInfo(Id, IdLoc));
19661
19662 EnumConstantDecl *New =
19663 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19664 if (!New)
19665 return nullptr;
19666
19667 if (PrevDecl) {
19668 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19669 // Check for other kinds of shadowing not already handled.
19670 CheckShadow(New, PrevDecl, R);
19671 }
19672
19673 // When in C++, we may get a TagDecl with the same name; in this case the
19674 // enum constant will 'hide' the tag.
19675 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19676 "Received TagDecl when not in C++!");
19677 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19678 if (isa<EnumConstantDecl>(PrevDecl))
19679 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19680 else
19681 Diag(IdLoc, diag::err_redefinition) << Id;
19682 notePreviousDefinition(PrevDecl, IdLoc);
19683 return nullptr;
19684 }
19685 }
19686
19687 // Process attributes.
19688 ProcessDeclAttributeList(S, New, Attrs);
19689 AddPragmaAttributes(S, New);
19690 ProcessAPINotes(New);
19691
19692 // Register this decl in the current scope stack.
19693 New->setAccess(TheEnumDecl->getAccess());
19694 PushOnScopeChains(New, S);
19695
19697
19698 return New;
19699}
19700
19701// Returns true when the enum initial expression does not trigger the
19702// duplicate enum warning. A few common cases are exempted as follows:
19703// Element2 = Element1
19704// Element2 = Element1 + 1
19705// Element2 = Element1 - 1
19706// Where Element2 and Element1 are from the same enum.
19708 Expr *InitExpr = ECD->getInitExpr();
19709 if (!InitExpr)
19710 return true;
19711 InitExpr = InitExpr->IgnoreImpCasts();
19712
19713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19714 if (!BO->isAdditiveOp())
19715 return true;
19716 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19717 if (!IL)
19718 return true;
19719 if (IL->getValue() != 1)
19720 return true;
19721
19722 InitExpr = BO->getLHS();
19723 }
19724
19725 // This checks if the elements are from the same enum.
19726 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19727 if (!DRE)
19728 return true;
19729
19730 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19731 if (!EnumConstant)
19732 return true;
19733
19734 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19735 Enum)
19736 return true;
19737
19738 return false;
19739}
19740
19741// Emits a warning when an element is implicitly set a value that
19742// a previous element has already been set to.
19745 // Avoid anonymous enums
19746 if (!Enum->getIdentifier())
19747 return;
19748
19749 // Only check for small enums.
19750 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19751 return;
19752
19753 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19754 return;
19755
19756 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19757 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19758
19759 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19760
19761 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19762 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19763
19764 // Use int64_t as a key to avoid needing special handling for map keys.
19765 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19766 llvm::APSInt Val = D->getInitVal();
19767 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19768 };
19769
19770 DuplicatesVector DupVector;
19771 ValueToVectorMap EnumMap;
19772
19773 // Populate the EnumMap with all values represented by enum constants without
19774 // an initializer.
19775 for (auto *Element : Elements) {
19776 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19777
19778 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19779 // this constant. Skip this enum since it may be ill-formed.
19780 if (!ECD) {
19781 return;
19782 }
19783
19784 // Constants with initializers are handled in the next loop.
19785 if (ECD->getInitExpr())
19786 continue;
19787
19788 // Duplicate values are handled in the next loop.
19789 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19790 }
19791
19792 if (EnumMap.size() == 0)
19793 return;
19794
19795 // Create vectors for any values that has duplicates.
19796 for (auto *Element : Elements) {
19797 // The last loop returned if any constant was null.
19798 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19799 if (!ValidDuplicateEnum(ECD, Enum))
19800 continue;
19801
19802 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19803 if (Iter == EnumMap.end())
19804 continue;
19805
19806 DeclOrVector& Entry = Iter->second;
19807 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19808 // Ensure constants are different.
19809 if (D == ECD)
19810 continue;
19811
19812 // Create new vector and push values onto it.
19813 auto Vec = std::make_unique<ECDVector>();
19814 Vec->push_back(D);
19815 Vec->push_back(ECD);
19816
19817 // Update entry to point to the duplicates vector.
19818 Entry = Vec.get();
19819
19820 // Store the vector somewhere we can consult later for quick emission of
19821 // diagnostics.
19822 DupVector.emplace_back(std::move(Vec));
19823 continue;
19824 }
19825
19826 ECDVector *Vec = Entry.get<ECDVector*>();
19827 // Make sure constants are not added more than once.
19828 if (*Vec->begin() == ECD)
19829 continue;
19830
19831 Vec->push_back(ECD);
19832 }
19833
19834 // Emit diagnostics.
19835 for (const auto &Vec : DupVector) {
19836 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19837
19838 // Emit warning for one enum constant.
19839 auto *FirstECD = Vec->front();
19840 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19841 << FirstECD << toString(FirstECD->getInitVal(), 10)
19842 << FirstECD->getSourceRange();
19843
19844 // Emit one note for each of the remaining enum constants with
19845 // the same value.
19846 for (auto *ECD : llvm::drop_begin(*Vec))
19847 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19848 << ECD << toString(ECD->getInitVal(), 10)
19849 << ECD->getSourceRange();
19850 }
19851}
19852
19853bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19854 bool AllowMask) const {
19855 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19856 assert(ED->isCompleteDefinition() && "expected enum definition");
19857
19858 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19859 llvm::APInt &FlagBits = R.first->second;
19860
19861 if (R.second) {
19862 for (auto *E : ED->enumerators()) {
19863 const auto &EVal = E->getInitVal();
19864 // Only single-bit enumerators introduce new flag values.
19865 if (EVal.isPowerOf2())
19866 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19867 }
19868 }
19869
19870 // A value is in a flag enum if either its bits are a subset of the enum's
19871 // flag bits (the first condition) or we are allowing masks and the same is
19872 // true of its complement (the second condition). When masks are allowed, we
19873 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19874 //
19875 // While it's true that any value could be used as a mask, the assumption is
19876 // that a mask will have all of the insignificant bits set. Anything else is
19877 // likely a logic error.
19878 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19879 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19880}
19881
19883 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19884 const ParsedAttributesView &Attrs) {
19885 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19887
19888 ProcessDeclAttributeList(S, Enum, Attrs);
19890
19891 if (Enum->isDependentType()) {
19892 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19893 EnumConstantDecl *ECD =
19894 cast_or_null<EnumConstantDecl>(Elements[i]);
19895 if (!ECD) continue;
19896
19897 ECD->setType(EnumType);
19898 }
19899
19900 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19901 return;
19902 }
19903
19904 // TODO: If the result value doesn't fit in an int, it must be a long or long
19905 // long value. ISO C does not support this, but GCC does as an extension,
19906 // emit a warning.
19907 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19908 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19909 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19910
19911 // Verify that all the values are okay, compute the size of the values, and
19912 // reverse the list.
19913 unsigned NumNegativeBits = 0;
19914 unsigned NumPositiveBits = 0;
19915
19916 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19917 EnumConstantDecl *ECD =
19918 cast_or_null<EnumConstantDecl>(Elements[i]);
19919 if (!ECD) continue; // Already issued a diagnostic.
19920
19921 const llvm::APSInt &InitVal = ECD->getInitVal();
19922
19923 // Keep track of the size of positive and negative values.
19924 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19925 // If the enumerator is zero that should still be counted as a positive
19926 // bit since we need a bit to store the value zero.
19927 unsigned ActiveBits = InitVal.getActiveBits();
19928 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19929 } else {
19930 NumNegativeBits =
19931 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19932 }
19933 }
19934
19935 // If we have an empty set of enumerators we still need one bit.
19936 // From [dcl.enum]p8
19937 // If the enumerator-list is empty, the values of the enumeration are as if
19938 // the enumeration had a single enumerator with value 0
19939 if (!NumPositiveBits && !NumNegativeBits)
19940 NumPositiveBits = 1;
19941
19942 // Figure out the type that should be used for this enum.
19943 QualType BestType;
19944 unsigned BestWidth;
19945
19946 // C++0x N3000 [conv.prom]p3:
19947 // An rvalue of an unscoped enumeration type whose underlying
19948 // type is not fixed can be converted to an rvalue of the first
19949 // of the following types that can represent all the values of
19950 // the enumeration: int, unsigned int, long int, unsigned long
19951 // int, long long int, or unsigned long long int.
19952 // C99 6.4.4.3p2:
19953 // An identifier declared as an enumeration constant has type int.
19954 // The C99 rule is modified by a gcc extension
19955 QualType BestPromotionType;
19956
19957 bool Packed = Enum->hasAttr<PackedAttr>();
19958 // -fshort-enums is the equivalent to specifying the packed attribute on all
19959 // enum definitions.
19960 if (LangOpts.ShortEnums)
19961 Packed = true;
19962
19963 // If the enum already has a type because it is fixed or dictated by the
19964 // target, promote that type instead of analyzing the enumerators.
19965 if (Enum->isComplete()) {
19966 BestType = Enum->getIntegerType();
19967 if (Context.isPromotableIntegerType(BestType))
19968 BestPromotionType = Context.getPromotedIntegerType(BestType);
19969 else
19970 BestPromotionType = BestType;
19971
19972 BestWidth = Context.getIntWidth(BestType);
19973 }
19974 else if (NumNegativeBits) {
19975 // If there is a negative value, figure out the smallest integer type (of
19976 // int/long/longlong) that fits.
19977 // If it's packed, check also if it fits a char or a short.
19978 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19979 BestType = Context.SignedCharTy;
19980 BestWidth = CharWidth;
19981 } else if (Packed && NumNegativeBits <= ShortWidth &&
19982 NumPositiveBits < ShortWidth) {
19983 BestType = Context.ShortTy;
19984 BestWidth = ShortWidth;
19985 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19986 BestType = Context.IntTy;
19987 BestWidth = IntWidth;
19988 } else {
19989 BestWidth = Context.getTargetInfo().getLongWidth();
19990
19991 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19992 BestType = Context.LongTy;
19993 } else {
19994 BestWidth = Context.getTargetInfo().getLongLongWidth();
19995
19996 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19997 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19998 BestType = Context.LongLongTy;
19999 }
20000 }
20001 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20002 } else {
20003 // If there is no negative value, figure out the smallest type that fits
20004 // all of the enumerator values.
20005 // If it's packed, check also if it fits a char or a short.
20006 if (Packed && NumPositiveBits <= CharWidth) {
20007 BestType = Context.UnsignedCharTy;
20008 BestPromotionType = Context.IntTy;
20009 BestWidth = CharWidth;
20010 } else if (Packed && NumPositiveBits <= ShortWidth) {
20011 BestType = Context.UnsignedShortTy;
20012 BestPromotionType = Context.IntTy;
20013 BestWidth = ShortWidth;
20014 } else if (NumPositiveBits <= IntWidth) {
20015 BestType = Context.UnsignedIntTy;
20016 BestWidth = IntWidth;
20017 BestPromotionType
20018 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20020 } else if (NumPositiveBits <=
20021 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20022 BestType = Context.UnsignedLongTy;
20023 BestPromotionType
20024 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20026 } else {
20027 BestWidth = Context.getTargetInfo().getLongLongWidth();
20028 if (NumPositiveBits > BestWidth) {
20029 // This can happen with bit-precise integer types, but those are not
20030 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20031 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20032 // a 128-bit integer, we should consider doing the same.
20033 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20034 }
20035 BestType = Context.UnsignedLongLongTy;
20036 BestPromotionType
20037 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20039 }
20040 }
20041
20042 // Loop over all of the enumerator constants, changing their types to match
20043 // the type of the enum if needed.
20044 for (auto *D : Elements) {
20045 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20046 if (!ECD) continue; // Already issued a diagnostic.
20047
20048 // Standard C says the enumerators have int type, but we allow, as an
20049 // extension, the enumerators to be larger than int size. If each
20050 // enumerator value fits in an int, type it as an int, otherwise type it the
20051 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20052 // that X has type 'int', not 'unsigned'.
20053
20054 // Determine whether the value fits into an int.
20055 llvm::APSInt InitVal = ECD->getInitVal();
20056
20057 // If it fits into an integer type, force it. Otherwise force it to match
20058 // the enum decl type.
20059 QualType NewTy;
20060 unsigned NewWidth;
20061 bool NewSign;
20062 if (!getLangOpts().CPlusPlus &&
20063 !Enum->isFixed() &&
20065 NewTy = Context.IntTy;
20066 NewWidth = IntWidth;
20067 NewSign = true;
20068 } else if (ECD->getType() == BestType) {
20069 // Already the right type!
20070 if (getLangOpts().CPlusPlus)
20071 // C++ [dcl.enum]p4: Following the closing brace of an
20072 // enum-specifier, each enumerator has the type of its
20073 // enumeration.
20074 ECD->setType(EnumType);
20075 continue;
20076 } else {
20077 NewTy = BestType;
20078 NewWidth = BestWidth;
20079 NewSign = BestType->isSignedIntegerOrEnumerationType();
20080 }
20081
20082 // Adjust the APSInt value.
20083 InitVal = InitVal.extOrTrunc(NewWidth);
20084 InitVal.setIsSigned(NewSign);
20085 ECD->setInitVal(Context, InitVal);
20086
20087 // Adjust the Expr initializer and type.
20088 if (ECD->getInitExpr() &&
20089 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20090 ECD->setInitExpr(ImplicitCastExpr::Create(
20091 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20092 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20093 if (getLangOpts().CPlusPlus)
20094 // C++ [dcl.enum]p4: Following the closing brace of an
20095 // enum-specifier, each enumerator has the type of its
20096 // enumeration.
20097 ECD->setType(EnumType);
20098 else
20099 ECD->setType(NewTy);
20100 }
20101
20102 Enum->completeDefinition(BestType, BestPromotionType,
20103 NumPositiveBits, NumNegativeBits);
20104
20105 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20106
20107 if (Enum->isClosedFlag()) {
20108 for (Decl *D : Elements) {
20109 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20110 if (!ECD) continue; // Already issued a diagnostic.
20111
20112 llvm::APSInt InitVal = ECD->getInitVal();
20113 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20114 !IsValueInFlagEnum(Enum, InitVal, true))
20115 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20116 << ECD << Enum;
20117 }
20118 }
20119
20120 // Now that the enum type is defined, ensure it's not been underaligned.
20121 if (Enum->hasAttrs())
20123}
20124
20126 SourceLocation StartLoc,
20127 SourceLocation EndLoc) {
20128 StringLiteral *AsmString = cast<StringLiteral>(expr);
20129
20131 AsmString, StartLoc,
20132 EndLoc);
20133 CurContext->addDecl(New);
20134 return New;
20135}
20136
20138 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20139 CurContext->addDecl(New);
20140 PushDeclContext(S, New);
20142 PushCompoundScope(false);
20143 return New;
20144}
20145
20147 D->setStmt(Statement);
20151}
20152
20154 IdentifierInfo* AliasName,
20155 SourceLocation PragmaLoc,
20156 SourceLocation NameLoc,
20157 SourceLocation AliasNameLoc) {
20158 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20160 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20162 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20163 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20164
20165 // If a declaration that:
20166 // 1) declares a function or a variable
20167 // 2) has external linkage
20168 // already exists, add a label attribute to it.
20169 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20170 if (isDeclExternC(PrevDecl))
20171 PrevDecl->addAttr(Attr);
20172 else
20173 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20174 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20175 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20176 } else
20177 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20178}
20179
20181 SourceLocation PragmaLoc,
20182 SourceLocation NameLoc) {
20183 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20184
20185 if (PrevDecl) {
20186 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20187 } else {
20188 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20189 }
20190}
20191
20193 IdentifierInfo* AliasName,
20194 SourceLocation PragmaLoc,
20195 SourceLocation NameLoc,
20196 SourceLocation AliasNameLoc) {
20197 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20199 WeakInfo W = WeakInfo(Name, NameLoc);
20200
20201 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20202 if (!PrevDecl->hasAttr<AliasAttr>())
20203 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20205 } else {
20206 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20207 }
20208}
20209
20211 bool Final) {
20212 assert(FD && "Expected non-null FunctionDecl");
20213
20214 // SYCL functions can be template, so we check if they have appropriate
20215 // attribute prior to checking if it is a template.
20216 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20218
20219 // Templates are emitted when they're instantiated.
20220 if (FD->isDependentContext())
20222
20223 // Check whether this function is an externally visible definition.
20224 auto IsEmittedForExternalSymbol = [this, FD]() {
20225 // We have to check the GVA linkage of the function's *definition* -- if we
20226 // only have a declaration, we don't know whether or not the function will
20227 // be emitted, because (say) the definition could include "inline".
20228 const FunctionDecl *Def = FD->getDefinition();
20229
20230 // We can't compute linkage when we skip function bodies.
20231 return Def && !Def->hasSkippedBody() &&
20233 getASTContext().GetGVALinkageForFunction(Def));
20234 };
20235
20236 if (LangOpts.OpenMPIsTargetDevice) {
20237 // In OpenMP device mode we will not emit host only functions, or functions
20238 // we don't need due to their linkage.
20239 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20240 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20241 // DevTy may be changed later by
20242 // #pragma omp declare target to(*) device_type(*).
20243 // Therefore DevTy having no value does not imply host. The emission status
20244 // will be checked again at the end of compilation unit with Final = true.
20245 if (DevTy)
20246 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20248 // If we have an explicit value for the device type, or we are in a target
20249 // declare context, we need to emit all extern and used symbols.
20250 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20251 if (IsEmittedForExternalSymbol())
20253 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20254 // we'll omit it.
20255 if (Final)
20257 } else if (LangOpts.OpenMP > 45) {
20258 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20259 // function. In 5.0, no_host was introduced which might cause a function to
20260 // be omitted.
20261 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20262 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20263 if (DevTy)
20264 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20266 }
20267
20268 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20270
20271 if (LangOpts.CUDA) {
20272 // When compiling for device, host functions are never emitted. Similarly,
20273 // when compiling for host, device and global functions are never emitted.
20274 // (Technically, we do emit a host-side stub for global functions, but this
20275 // doesn't count for our purposes here.)
20277 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20279 if (!LangOpts.CUDAIsDevice &&
20282
20283 if (IsEmittedForExternalSymbol())
20285 }
20286
20287 // Otherwise, the function is known-emitted if it's in our set of
20288 // known-emitted functions.
20290}
20291
20293 // Host-side references to a __global__ function refer to the stub, so the
20294 // function itself is never emitted and therefore should not be marked.
20295 // If we have host fn calls kernel fn calls host+device, the HD function
20296 // does not get instantiated on the host. We model this by omitting at the
20297 // call to the kernel from the callgraph. This ensures that, when compiling
20298 // for host, only HD functions actually called from the host get marked as
20299 // known-emitted.
20300 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20302}
20303
20305 const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc,
20306 SourceLocation OldLoc) {
20307 for (const FunctionEffectSet::Conflict &Conflict : Errs) {
20308 Diag(NewLoc, diag::warn_conflicting_func_effects)
20309 << Conflict.Kept.description() << Conflict.Rejected.description();
20310 Diag(OldLoc, diag::note_previous_declaration);
20311 }
20312}
20313
20315 const FunctionEffectsRef &FX, const FunctionEffectWithCondition &NewEC,
20316 SourceLocation NewAttrLoc) {
20317 // If the new effect has a condition, we can't detect conflicts until the
20318 // condition is resolved.
20319 if (NewEC.Cond.getCondition() != nullptr)
20320 return false;
20321
20322 // Diagnose the new attribute as incompatible with a previous one.
20323 auto Incompatible = [&](const FunctionEffectWithCondition &PrevEC) {
20324 Diag(NewAttrLoc, diag::err_attributes_are_not_compatible)
20325 << ("'" + NewEC.description() + "'")
20326 << ("'" + PrevEC.description() + "'") << false;
20327 // We don't necessarily have the location of the previous attribute,
20328 // so no note.
20329 return true;
20330 };
20331
20332 // Compare against previous attributes.
20333 FunctionEffect::Kind NewKind = NewEC.Effect.kind();
20334
20335 for (const FunctionEffectWithCondition &PrevEC : FX) {
20336 // Again, can't check yet when the effect is conditional.
20337 if (PrevEC.Cond.getCondition() != nullptr)
20338 continue;
20339
20340 FunctionEffect::Kind PrevKind = PrevEC.Effect.kind();
20341 // Note that we allow PrevKind == NewKind; it's redundant and ignored.
20342
20343 if (PrevEC.Effect.oppositeKind() == NewKind)
20344 return Incompatible(PrevEC);
20345
20346 // A new allocating is incompatible with a previous nonblocking.
20347 if (PrevKind == FunctionEffect::Kind::NonBlocking &&
20349 return Incompatible(PrevEC);
20350
20351 // A new nonblocking is incompatible with a previous allocating.
20352 if (PrevKind == FunctionEffect::Kind::Allocating &&
20354 return Incompatible(PrevEC);
20355 }
20356
20357 return false;
20358}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1656::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2211
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines helper utilities for supporting the HLSL runtime environment.
unsigned Iter
Definition: HTMLLogger.cpp:154
static const Decl * getCanonicalDecl(const Decl *D)
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:58
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.
Definition: Redeclaration.h:18
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15770
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6811
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:153
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15285
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7369
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11302
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:208
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3329
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
Definition: SemaDecl.cpp:3496
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:795
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6509
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1470
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...
Definition: SemaDecl.cpp:6547
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2269
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9125
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
Definition: SemaDecl.cpp:3443
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2783
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8132
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9474
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3227
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7341
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8500
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11706
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...
Definition: SemaDecl.cpp:2672
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4431
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11796
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15269
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11422
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2036
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:14917
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:561
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11311
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...
Definition: SemaDecl.cpp:7110
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
Definition: SemaDecl.cpp:19379
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19743
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:4975
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:2911
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16801
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3478
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6858
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:5911
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
Definition: SemaDecl.cpp:4845
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9161
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...
Definition: SemaDecl.cpp:9657
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15799
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3385
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8469
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2641
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9346
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3026
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8157
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 ...
Definition: SemaDecl.cpp:16961
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...
Definition: SemaDecl.cpp:5262
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...
Definition: SemaDecl.cpp:8386
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1912
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9668
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 ...
Definition: SemaDecl.cpp:5338
OpenCLParamType
Definition: SemaDecl.cpp:9337
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9341
@ ValidKernelParam
Definition: SemaDecl.cpp:9338
@ InvalidKernelParam
Definition: SemaDecl.cpp:9342
@ RecordKernelParam
Definition: SemaDecl.cpp:9343
@ PtrKernelParam
Definition: SemaDecl.cpp:9340
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9339
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
Definition: SemaDecl.cpp:6020
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:
Definition: SemaDecl.cpp:18733
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:581
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...
Definition: SemaDecl.cpp:18667
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7155
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5422
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11227
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:9648
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3290
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3422
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16785
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2163
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4328
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:8973
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5946
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:
Definition: SemaDecl.cpp:18760
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:810
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7182
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8121
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8128
@ SDK_Field
Definition: SemaDecl.cpp:8125
@ SDK_Global
Definition: SemaDecl.cpp:8123
@ SDK_Local
Definition: SemaDecl.cpp:8122
@ SDK_Typedef
Definition: SemaDecl.cpp:8126
@ SDK_StaticMember
Definition: SemaDecl.cpp:8124
@ SDK_Using
Definition: SemaDecl.cpp:8127
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4791
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3406
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9368
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5436
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12410
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7233
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1781
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18826
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11040
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1770
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2885
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...
Definition: SemaDecl.cpp:6431
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14725
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7329
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5893
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1823
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:10990
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6772
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5401
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:250
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...
Definition: SemaDecl.cpp:11453
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
Definition: SemaDecl.cpp:8148
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
Definition: SemaDecl.cpp:11273
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:6961
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11058
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...
Definition: SemaDecl.cpp:2396
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19707
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19396
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7141
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2660
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10897
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11325
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1797
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...
Definition: SemaDecl.cpp:16998
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
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 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)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
StateNode * Previous
std::string Label
__device__ int
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15757
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15759
llvm::APInt getValue() const
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual void HandleInlineFunctionDefinition(FunctionDecl *D)
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition: ASTConsumer.h:58
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:146
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:721
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1128
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2139
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1925
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2029
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1951
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2007
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2831
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
Definition: ASTContext.h:1147
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
IdentifierTable & Idents
Definition: ASTContext.h:660
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:498
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2127
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2041
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2924
CanQualType CharTy
Definition: ASTContext.h:1121
CanQualType IntTy
Definition: ASTContext.h:1128
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1128
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2117
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1467
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2828
CanQualType ShortTy
Definition: ASTContext.h:1128
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1938
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2233
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2017
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1128
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2296
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2302
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2299
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2308
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2305
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2425
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3351
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1563
Expr * getSizeExpr() const
Definition: TypeLoc.h:1583
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1571
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3571
QualType getElementType() const
Definition: Type.h:3583
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:102
SourceLocation getLocation() const
Definition: Attr.h:95
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:639
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:735
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6025
QualType getModifiedType() const
Definition: Type.h:6047
bool isCallingConv() const
Definition: Type.cpp:4147
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:6080
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6380
AutoTypeKeyword getKeyword() const
Definition: Type.h:6411
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4275
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
bool doesNotEscape() const
Definition: Decl.h:4622
This class is used for builtin types like 'int'.
Definition: Type.h:3028
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:215
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
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:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:137
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:284
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:247
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:202
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:167
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:210
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:205
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:251
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:174
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:116
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:122
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
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
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(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2761
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2928
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)
Definition: DeclCXX.cpp:2195
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2895
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:2064
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:2493
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2547
bool isVirtual() const
Definition: DeclCXX.h:2119
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2614
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2526
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2312
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2225
bool isConst() const
Definition: DeclCXX.h:2116
bool isStatic() const
Definition: DeclCXX.cpp:2224
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2504
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2160
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1339
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1245
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1371
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1552
base_class_range bases()
Definition: DeclCXX.h:620
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1381
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1969
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:627
capture_const_range captures() const
Definition: DeclCXX.h:1102
bool hasDefinition() const
Definition: DeclCXX.h:572
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1936
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1064
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1940
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1293
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
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:178
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:218
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3665
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isFileContext() const
Definition: DeclBase.h:2161
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2043
bool isObjCContainer() const
Definition: DeclBase.h:2129
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1399
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
bool isClosure() const
Definition: DeclBase.h:2123
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2106
bool isNamespace() const
Definition: DeclBase.h:2179
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1300
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1685
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1635
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2006
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1423
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1284
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1384
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1403
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2083
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1414
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:68
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:829
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:595
static const TST TST_typename
Definition: DeclSpec.h:306
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:648
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:863
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:505
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:830
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1504
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:788
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:626
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_decltype
Definition: DeclSpec.h:311
static bool isDeclRep(TST T)
Definition: DeclSpec.h:469
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
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:561
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:792
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:328
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
static const TST TST_struct
Definition: DeclSpec.h:303
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:1051
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1066
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:317
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:580
bool hasAttrs() const
Definition: DeclBase.h:525
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:527
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:765
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1167
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1141
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:639
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:883
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1208
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1112
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:577
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:836
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1159
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
void dropAttrs()
Definition: DeclBase.cpp:1006
@ 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:1170
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2767
bool isInvalidDecl() const
Definition: DeclBase.h:595
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1159
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:509
SourceLocation getLocation() const
Definition: DeclBase.h:446
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:823
void setImplicit(bool I=true)
Definition: DeclBase.h:601
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:615
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:552
DeclContext * getDeclContext()
Definition: DeclBase.h:455
attr_range attrs() const
Definition: DeclBase.h:542
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
void dropAttr()
Definition: DeclBase.h:563
AttrVec & getAttrs()
Definition: DeclBase.h:531
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1225
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
Kind getKind() const
Definition: DeclBase.h:449
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
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:731
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:789
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:774
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2032
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2072
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1970
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:819
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1982
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2016
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2686
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2342
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2689
A decomposition declaration.
Definition: DeclCXX.h:4170
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3375
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6346
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6367
bool isDeduced() const
Definition: Type.h:6368
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
Expr * getCondition() const
Definition: Type.h:4815
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3274
llvm::APSInt getInitVal() const
Definition: Decl.h:3294
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5452
const Expr * getInitExpr() const
Definition: Decl.h:3292
Represents an enum.
Definition: Decl.h:3844
enumerator_range enumerators() const
Definition: Decl.h:3977
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4049
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4013
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4016
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4063
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4851
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4896
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4058
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4871
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3999
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4004
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5996
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
This represents one expression.
Definition: Expr.h:110
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:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1060
bool isFPConstrained() const
Definition: LangOptions.h:875
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1054
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4546
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4583
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
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:4531
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5585
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4040
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3589
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4033
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3243
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2246
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2574
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2553
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3859
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
param_iterator param_end()
Definition: Decl.h:2659
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2568
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3562
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2314
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3474
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2373
void setWillHaveBody(bool V=true)
Definition: Decl.h:2559
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2368
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4158
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3603
param_iterator param_begin()
Definition: Decl.h:2658
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3006
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3300
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4092
@ TK_MemberSpecialization
Definition: Decl.h:1944
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2760
bool isStatic() const
Definition: Decl.h:2801
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4358
void setTrivial(bool IT)
Definition: Decl.h:2303
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isDeletedAsWritten() const
Definition: Decl.h:2469
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2390
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2285
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3478
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2289
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2353
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2281
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2552
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2214
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3294
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2788
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3352
bool param_empty() const
Definition: Decl.h:2657
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, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2121
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3168
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2150
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3558
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2346
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4381
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2805
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3973
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
void setDefaulted(bool D=true)
Definition: Decl.h:2311
bool isConsteval() const
Definition: Decl.h:2407
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:2734
void setBody(Stmt *B)
Definition: Decl.cpp:3236
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3492
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3114
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2384
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2143
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2360
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:3191
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2771
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3544
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4944
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5289
Kind kind() const
The kind of the effect.
Definition: Type.h:4748
Kind
Identifies the particular effect.
Definition: Type.h:4711
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4887
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5007
unsigned getNumParams() const
Definition: Type.h:5260
QualType getParamType(unsigned i) const
Definition: Type.h:5262
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5466
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5293
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5384
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5271
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5267
ArrayRef< QualType > param_types() const
Definition: Type.h:5416
Declaration of a template function.
Definition: DeclTemplate.h:957
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.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:536
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4424
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4539
CallingConv getCC() const
Definition: Type.h:4486
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4505
unsigned getRegParm() const
Definition: Type.h:4479
bool getNoCallerSavedRegs() const
Definition: Type.h:4475
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4498
bool getHasRegParm() const
Definition: Type.h:4477
bool getNoReturn() const
Definition: Type.h:4472
bool getProducesResult() const
Definition: Type.h:4473
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4519
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4533
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4313
ExtInfo getExtInfo() const
Definition: Type.h:4647
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3492
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4605
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4601
unsigned getRegParmType() const
Definition: Type.h:4638
CallingConv getCallConv() const
Definition: Type.h:4646
QualType getReturnType() const
Definition: Type.h:4635
bool getCmseNSCallAttr() const
Definition: Type.h:4645
@ SME_PStateSMEnabledMask
Definition: Type.h:4579
@ SME_PStateSMCompatibleMask
Definition: Type.h:4580
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.
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void InsertDeclAfter(iterator Pos, NamedDecl *D)
Insert the given declaration after the given iterator position.
iterator end()
Returns the end iterator.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
bool isDeclInScope(Decl *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',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents a C array with an unspecified size.
Definition: Type.h:3756
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5480
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2510
Describes an C or C++ initializer list.
Definition: Expr.h:5039
child_range children()
Definition: Expr.h:5231
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...
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7522
@ 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:977
Represents the declaration of a label.
Definition: Decl.h:499
bool isResolvedMSAsmLabel() const
Definition: Decl.h:534
LabelStmt * getStmt() const
Definition: Decl.h:523
bool isMSAsmLabel() const
Definition: Decl.h:533
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:278
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:649
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:785
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:690
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:568
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:696
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:550
void push_back(const T &LocalValue)
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:1358
Represents a linkage specification.
Definition: DeclCXX.h:2938
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2958
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:670
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
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.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3513
Describes a module or submodule.
Definition: Module.h:105
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
Module * Parent
The parent of this module.
Definition: Module.h:154
bool isPrivateModule() const
Definition: Module.h:210
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:592
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:608
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:597
bool isImplicitGlobalModule() const
Definition: Module.h:206
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:244
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:666
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1079
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:454
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:404
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:700
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1912
bool isExternallyVisible() const
Definition: Decl.h:408
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:598
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.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2774
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:81
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
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)
Definition: DeclObjC.cpp:1833
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
bool isOptional() const
Definition: DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
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:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
Expr ** getExprs()
Definition: Expr.h:5856
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5845
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1216
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Sugar for parentheses used when specifying types.
Definition: Type.h:3166
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1786
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
QualType getOriginalType() const
Definition: Decl.cpp:2912
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:2903
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
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
PipeType - OpenCL20.
Definition: Type.h:7604
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1282
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3192
QualType getPointeeType() const
Definition: Type.h:3202
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
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: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7839
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7833
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:7902
@ DK_nontrivial_c_struct
Definition: Type.h:1535
PrimitiveDefaultInitializeKind
Definition: Type.h:1463
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2822
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1221
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1303
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
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:2870
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7755
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7881
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:7896
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7795
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getCanonicalType() const
Definition: Type.h:7807
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7849
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2854
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1439
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7828
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
bool isCanonical() const
Definition: Type.h:7812
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1316
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2596
NonConstantStorageReason
Definition: Type.h:1025
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1498
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:7890
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7695
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7702
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4356
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
bool hasConst() const
Definition: Type.h:444
void removeConst()
Definition: Type.h:446
void addConst()
Definition: Type.h:447
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
bool empty() const
Definition: Type.h:634
Represents a struct/union/class.
Definition: Decl.h:4145
bool hasObjectMember() const
Definition: Decl.h:4205
field_range fields() const
Definition: Decl.h:4351
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5014
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5034
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5080
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4336
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5970
RecordDecl * getDecl() const
Definition: Type.h:5980
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7101
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:865
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
redecl_iterator redecls_end() const
Definition: Redeclarable.h:304
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:227
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4978
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:224
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:297
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3433
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3029
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3077
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:381
void RemoveDecl(Decl *D)
Definition: Scope.h:353
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:384
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:581
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ 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
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:658
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1070
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
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:740
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1005
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:805
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:214
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:133
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:181
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:148
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.
Definition: SemaObjC.cpp:1161
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,...
Definition: SemaObjC.cpp:1447
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:601
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)
Definition: SemaRISCV.cpp:1380
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaWasm.cpp:266
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaWasm.cpp:245
bool IsAlignAttr() const
Definition: Sema.h:1552
Mode getAlignMode() const
Definition: Sema.h:1554
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3023
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1038
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:1050
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3267
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3277
static NameClassification Unknown()
Definition: Sema.h:3247
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3251
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3295
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3283
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3257
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3289
static NameClassification UndeclaredNonType()
Definition: Sema.h:3263
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3271
static NameClassification Error()
Definition: Sema.h:3245
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12099
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12129
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14182
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.
Definition: SemaDecl.cpp:10923
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6329
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3115
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6666
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12656
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:763
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...
Definition: SemaDecl.cpp:2468
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:8921
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:6586
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9695
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',...
Definition: SemaDecl.cpp:1558
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.
Definition: SemaDecl.cpp:15060
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:7873
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5845
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:9011
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9034
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9050
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9047
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9018
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6602
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2179
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5295
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15741
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12828
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:37
NonTrivialCUnionContext
Definition: Sema.h:3635
@ NTCUC_CopyInit
Definition: Sema.h:3645
@ NTCUC_AutoVar
Definition: Sema.h:3643
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3641
@ NTCUC_FunctionReturn
Definition: Sema.h:3639
@ NTCUC_FunctionParam
Definition: Sema.h:3637
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...
Definition: SemaDecl.cpp:3536
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.
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.
Definition: SemaDecl.cpp:6079
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:991
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18154
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
SemaOpenMP & OpenMP()
Definition: Sema.h:1179
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,...
Definition: SemaDecl.cpp:6064
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:918
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18086
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4336
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3097
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1478
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16280
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6042
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:14939
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1094
SemaCUDA & CUDA()
Definition: Sema.h:1124
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)
Definition: SemaExpr.cpp:17181
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()
Definition: SemaDecl.cpp:1454
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2296
Preprocessor & getPreprocessor() const
Definition: Sema.h:559
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6817
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1709
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1703
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Definition: SemaAttr.cpp:1162
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)
Definition: SemaDecl.cpp:6207
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16939
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)
Definition: SemaDecl.cpp:4797
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:53
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)
Definition: SemaDecl.cpp:12242
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16481
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2098
@ Delete
deleted-function-body
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,...
Definition: SemaDecl.cpp:18173
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.
Definition: SemaDecl.cpp:18269
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)
Definition: SemaDecl.cpp:14555
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1430
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15395
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:1567
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3414
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:640
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
Definition: SemaDecl.cpp:1656
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:20125
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15047
ASTContext & Context
Definition: Sema.h:962
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14575
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5771
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20146
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding an effect to a set would create a conflict.
Definition: SemaDecl.cpp:20314
void * SkippedDefinitionContext
Definition: Sema.h:3960
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:917
SemaObjC & ObjC()
Definition: Sema.h:1164
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5300
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4907
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:72
@ AllowFold
Definition: Sema.h:7265
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1706
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:3105
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2330
ASTContext & getASTContext() const
Definition: Sema.h:560
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)
Definition: SemaDecl.cpp:15813
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.
Definition: SemaDecl.cpp:1712
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.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17602
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1702
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:702
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:664
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3087
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4754
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9274
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20292
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:868
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5453
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1572
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...
Definition: SemaDecl.cpp:16832
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:8960
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11802
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7987
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:694
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...
Definition: SemaDecl.cpp:4344
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2184
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.
Definition: SemaDecl.cpp:1246
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:4175
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16731
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:555
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2202
void PopCompoundScope()
Definition: Sema.cpp:2334
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19601
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13915
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13918
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13930
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13924
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13903
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13942
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13927
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13906
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13909
const LangOptions & getLangOpts() const
Definition: Sema.h:553
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)
SourceLocation CurInitSegLoc
Definition: Sema.h:1742
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3122
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1387
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.
Definition: SemaDecl.cpp:6562
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.
Definition: SemaDecl.cpp:6596
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1597
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:961
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)
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 ...
Definition: SemaDecl.cpp:8181
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:1984
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:960
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2409
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:14996
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15235
SemaHLSL & HLSL()
Definition: Sema.h:1129
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1829
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11822
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.
Definition: SemaDecl.cpp:18364
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:1479
SemaRISCV & RISCV()
Definition: Sema.h:1194
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
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....
Definition: SemaStmt.cpp:3626
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
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.
Definition: SemaExpr.cpp:19812
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:1204
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
Definition: SemaAttr.cpp:1206
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1691
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:15699
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6487
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1701
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:767
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9370
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 CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:7991
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:859
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...
Definition: SemaDecl.cpp:16807
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1374
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8320
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.
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12429
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19627
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:993
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2329
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14805
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2286
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2261
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20180
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18562
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6484
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1216
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...
Definition: SemaDecl.cpp:18044
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, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9726
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8835
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3175
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14990
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1741
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20210
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9613
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,...
Definition: SemaDecl.cpp:8855
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15341
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18035
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15265
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14845
SemaOpenCL & OpenCL()
Definition: Sema.h:1174
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5776
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)
Definition: SemaDecl.cpp:15102
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.
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7680
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8361
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1288
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4699
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15674
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3119
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9029
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...
Definition: SemaDecl.cpp:15723
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.
Definition: SemaDecl.cpp:10935
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13497
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3853
@ NTK_Typedef
Definition: Sema.h:3858
@ NTK_NonUnion
Definition: Sema.h:3856
@ NTK_TypeAlias
Definition: Sema.h:3859
@ NTK_NonClass
Definition: Sema.h:3855
@ NTK_NonEnum
Definition: Sema.h:3857
@ NTK_NonStruct
Definition: Sema.h:3854
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3862
@ NTK_TypeAliasTemplate
Definition: Sema.h:3861
@ NTK_Template
Definition: Sema.h:3860
SourceManager & getSourceManager() const
Definition: Sema.h:558
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_bits attribute.
Definition: Sema.h:3072
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4269
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:19882
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1339
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.
Definition: SemaDecl.cpp:11101
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18021
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:1480
@ NTCUK_Destruct
Definition: Sema.h:3665
@ NTCUK_Init
Definition: Sema.h:3664
@ NTCUK_Copy
Definition: Sema.h:3666
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1477
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20000
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15751
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13801
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.
Definition: SemaDecl.cpp:1227
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:20153
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:89
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:6297
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
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)
Definition: SemaDecl.cpp:20137
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8204
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".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_NonError
Definition: Sema.h:9408
@ CTK_ErrorRecovery
Definition: Sema.h:9409
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14211
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14730
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2350
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...
Definition: SemaDecl.cpp:4460
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6064
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:591
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:10025
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18625
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3078
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1892
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3093
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:288
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19420
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12464
ASTConsumer & Consumer
Definition: Sema.h:963
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4238
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9812
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9804
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9808
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6491
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2049
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:998
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1690
@ FirstDecl
Parsing the first decl in a TU.
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....
Definition: SemaDecl.cpp:16412
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:4054
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:4056
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:4062
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:4065
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:4068
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:4059
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14849
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5653
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14518
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 {'.
Definition: SemaDecl.cpp:17016
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....
Definition: SemaDecl.cpp:4777
SemaPPC & PPC()
Definition: Sema.h:1184
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:79
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15187
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1335
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20646
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18871
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,...
Definition: SemaAttr.cpp:1185
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:10959
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3112
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17680
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
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.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:965
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.
Definition: SemaDecl.cpp:5729
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15808
DiagnosticsEngine & Diags
Definition: Sema.h:964
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:554
FPOptions CurFPFeatures
Definition: Sema.h:958
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15804
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6619
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1700
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:691
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7200
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 ...
Definition: SemaDecl.cpp:14880
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11300
@ TPC_ClassTemplateMember
Definition: Sema.h:11298
@ TPC_FunctionTemplate
Definition: Sema.h:11297
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11301
@ TPC_VarTemplate
Definition: Sema.h:11296
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6703
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16267
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2067
void PopDeclContext()
Definition: SemaDecl.cpp:1314
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:6076
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.
Definition: SemaDecl.cpp:1578
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)
Definition: SemaExpr.cpp:8807
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13843
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13010
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1563
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16675
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2392
OffsetOfKind
Definition: Sema.h:3877
@ OOK_Outside
Definition: Sema.h:3879
@ OOK_Macro
Definition: Sema.h:3884
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13283
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...
Definition: SemaDecl.cpp:18261
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4305
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...
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:14128
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.
Definition: SemaLambda.cpp:282
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
Definition: SemaDecl.cpp:20304
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:3087
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1967
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20913
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1476
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6038
@ AbstractVariableType
Definition: Sema.h:5769
@ AbstractReturnType
Definition: Sema.h:5767
@ AbstractFieldType
Definition: Sema.h:5770
@ AbstractIvarType
Definition: Sema.h:5771
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.
Definition: SemaDecl.cpp:1702
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7991
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.
Definition: SemaDecl.cpp:1236
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.
Definition: SemaType.cpp:8005
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20192
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8532
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.
Definition: SemaDecl.cpp:1321
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12976
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)
Definition: SemaDecl.cpp:2434
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2731
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:3068
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1169
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15688
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...
Definition: SemaDecl.cpp:13262
SemaWasm & Wasm()
Definition: Sema.h:1214
IdentifierResolver IdResolver
Definition: Sema.h:3016
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.
Definition: SemaDecl.cpp:19853
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2341
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:680
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...
Definition: SemaDecl.cpp:15076
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:7954
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:3388
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6025
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:16748
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:219
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7377
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8293
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1263
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.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1931
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3561
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3836
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3684
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3659
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3645
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3664
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4736
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4727
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4719
bool isUnion() const
Definition: Decl.h:3767
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4782
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4819
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3785
TagKind getTagKind() const
Definition: Decl.h:3756
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1533
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:501
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1812
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:519
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1576
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1584
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1519
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1393
unsigned getCharWidth() const
Definition: TargetInfo.h:496
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:548
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1498
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:639
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() 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.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6485
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4277
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:99
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
A declaration that models statements at global scope.
Definition: Decl.h:4434
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5600
Represents a declaration of a type.
Definition: Decl.h:3367
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3392
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
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:338
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:1225
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:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
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:744
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:751
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7726
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7737
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6748
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3133
The base class of the type hierarchy.
Definition: Type.h:1829
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2477
bool isStructureType() const
Definition: Type.cpp:629
bool isDecltypeType() const
Definition: Type.h:8205
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isDependentSizedArrayType() const
Definition: Type.h:8100
bool isBlockPointerType() const
Definition: Type.h:8022
bool isVoidType() const
Definition: Type.h:8324
bool isBooleanType() const
Definition: Type.h:8452
bool isFunctionReferenceType() const
Definition: Type.h:8055
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8502
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2892
bool isIncompleteArrayType() const
Definition: Type.h:8088
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8621
bool isDependentAddressSpaceType() const
Definition: Type.h:8146
bool isConstantArrayType() const
Definition: Type.h:8084
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8482
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8080
bool isFunctionPointerType() const
Definition: Type.h:8048
bool isPointerType() const
Definition: Type.h:8008
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2483
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8612
bool isReferenceType() const
Definition: Type.h:8026
bool isEnumeralType() const
Definition: Type.h:8112
bool isScalarType() const
Definition: Type.h:8423
bool isVariableArrayType() const
Definition: Type.h:8092
bool isClkEventT() const
Definition: Type.h:8223
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8439
bool isImageType() const
Definition: Type.h:8235
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2805
bool isPipeType() const
Definition: Type.h:8242
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2708
bool isBitIntType() const
Definition: Type.h:8246
bool isOpenCLSpecificType() const
Definition: Type.h:8271
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2700
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isHalfType() const
Definition: Type.h:8328
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
bool isHLSLSpecificType() const
Definition: Type.h:8282
const RecordType * getAsStructureType() const
Definition: Type.cpp:721
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2467
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2694
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8495
bool isAtomicType() const
Definition: Type.h:8163
bool isFunctionProtoType() const
Definition: Type.h:2533
bool isObjCIdType() const
Definition: Type.h:8183
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2718
bool isObjCObjectType() const
Definition: Type.h:8154
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4970
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8458
bool isEventT() const
Definition: Type.h:8219
bool isPointerOrReferenceType() const
Definition: Type.h:8012
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4913
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8562
bool isFunctionType() const
Definition: Type.h:8004
bool isObjCObjectPointerType() const
Definition: Type.h:8150
bool isMemberFunctionPointerType() const
Definition: Type.h:8066
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2497
bool isFloatingType() const
Definition: Type.cpp:2249
bool isAnyPointerType() const
Definition: Type.h:8016
TypeClass getTypeClass() const
Definition: Type.h:2339
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2016
bool isSamplerT() const
Definition: Type.h:8215
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8545
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:8357
bool isRecordType() const
Definition: Type.h:8108
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
bool isUnionType() const
Definition: Type.cpp:671
bool isFunctionNoProtoType() const
Definition: Type.h:2532
bool isReserveIDT() const
Definition: Type.h:8231
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1890
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2479
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3511
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5502
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3459
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3475
QualType getUnderlyingType() const
Definition: Decl.h:3464
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3471
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5511
TypedefNameDecl * getDecl() const
Definition: Type.h:5645
QualType desugar() const
Definition: Type.cpp:3875
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 end()
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.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
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:420
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3388
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3128
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5370
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1466
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
TLSKind getTLSKind() const
Definition: Decl.cpp:2150
bool hasInit() const
Definition: Decl.cpp:2380
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1393
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2242
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2172
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:2426
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2239
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
bool isCXXCondDecl() const
Definition: Decl.h:1556
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:890
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:893
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:887
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2145
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1538
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
void setInlineSpecified()
Definition: Decl.h:1499
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1290
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1121
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1492
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1165
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2411
void setConstexpr(bool IC)
Definition: Decl.h:1513
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:902
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:905
void setInit(Expr *I)
Definition: Decl.cpp:2442
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2327
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1246
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1249
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2780
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2227
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1201
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
void setImplicitlyInline()
Definition: Decl.h:1504
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1417
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1533
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2671
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1210
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:2744
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1427
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
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: Type.h:3800
Expr * getSizeExpr() const
Definition: Type.h:3819
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
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:498
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
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:878
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:875
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:175
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_struct
Definition: Specifiers.h:81
@ TST_class
Definition: Specifiers.h:82
@ TST_union
Definition: Specifiers.h:80
@ TST_enum
Definition: Specifiers.h:79
@ TST_interface
Definition: Specifiers.h:83
ImplicitTypenameContext
Definition: DeclSpec.h:1886
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ GNUMode
Definition: LangStandard.h:64
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
@ 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
@ GVA_AvailableExternally
Definition: Linkage.h:74
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:28
CUDAFunctionTarget
Definition: Cuda.h:140
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
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
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:40
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:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_PrivateExtern
Definition: Specifiers.h:253
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:241
@ TSCS_unspecified
Definition: Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:238
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
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...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:307
TagUseKind
Definition: Sema.h:427
TagTypeKind
The kind of a tag type.
Definition: Type.h:6695
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:108
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1542
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1067
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:31
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:403
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
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:135
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1911
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:345
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_X86StdCall
Definition: Specifiers.h:280
@ None
The alignment was not explicit in code.
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5759
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define bool
Definition: stdbool.h:24
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:1428
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1579
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1362
const IdentifierInfo * Ident
Definition: DeclSpec.h:1334
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1663
enum clang::DeclaratorChunk::@222 Kind
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:161
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1644
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1687
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition: Type.h:4825
EffectConditionExpr Cond
Definition: Type.h:4827
std::string description() const
Return a textual description of the effect, and its condition, if any.
Definition: Type.cpp:5332
Extra information about a function prototype.
Definition: Type.h:5092
FunctionEffectsRef FunctionEffects
Definition: Type.h:5102
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5112
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
std::vector< std::string > Features
Definition: TargetInfo.h:58
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1473
ValueType CurrentValue
Definition: Sema.h:1676
bool CheckSameAsPrevious
Definition: Sema.h:331
NamedDecl * Previous
Definition: Sema.h:332
NamedDecl * New
Definition: Sema.h:333
Information about a template-id annotation token.
unsigned NumArgs
NumArgs - The number of template arguments.
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.