clang 19.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"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
51#include "clang/Sema/SemaObjC.h"
53#include "clang/Sema/Template.h"
54#include "llvm/ADT/STLForwardCompat.h"
55#include "llvm/ADT/SmallString.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/TargetParser/Triple.h"
58#include <algorithm>
59#include <cstring>
60#include <functional>
61#include <optional>
62#include <unordered_map>
63
64using namespace clang;
65using namespace sema;
66
68 if (OwnedType) {
69 Decl *Group[2] = { OwnedType, Ptr };
71 }
72
74}
75
76namespace {
77
78class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
79 public:
80 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
81 bool AllowTemplates = false,
82 bool AllowNonTemplates = true)
83 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
84 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
85 WantExpressionKeywords = false;
86 WantCXXNamedCasts = false;
87 WantRemainingKeywords = false;
88 }
89
90 bool ValidateCandidate(const TypoCorrection &candidate) override {
91 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
92 if (!AllowInvalidDecl && ND->isInvalidDecl())
93 return false;
94
96 return AllowTemplates;
97
98 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
99 if (!IsType)
100 return false;
101
102 if (AllowNonTemplates)
103 return true;
104
105 // An injected-class-name of a class template (specialization) is valid
106 // as a template or as a non-template.
107 if (AllowTemplates) {
108 auto *RD = dyn_cast<CXXRecordDecl>(ND);
109 if (!RD || !RD->isInjectedClassName())
110 return false;
111 RD = cast<CXXRecordDecl>(RD->getDeclContext());
112 return RD->getDescribedClassTemplate() ||
113 isa<ClassTemplateSpecializationDecl>(RD);
114 }
115
116 return false;
117 }
118
119 return !WantClassName && candidate.isKeyword();
120 }
121
122 std::unique_ptr<CorrectionCandidateCallback> clone() override {
123 return std::make_unique<TypeNameValidatorCCC>(*this);
124 }
125
126 private:
127 bool AllowInvalidDecl;
128 bool WantClassName;
129 bool AllowTemplates;
130 bool AllowNonTemplates;
131};
132
133} // end anonymous namespace
134
135namespace {
136enum class UnqualifiedTypeNameLookupResult {
137 NotFound,
138 FoundNonType,
139 FoundType
140};
141} // end anonymous namespace
142
143/// Tries to perform unqualified lookup of the type decls in bases for
144/// dependent class.
145/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
146/// type decl, \a FoundType if only type decls are found.
147static UnqualifiedTypeNameLookupResult
149 SourceLocation NameLoc,
150 const CXXRecordDecl *RD) {
151 if (!RD->hasDefinition())
152 return UnqualifiedTypeNameLookupResult::NotFound;
153 // Look for type decls in base classes.
154 UnqualifiedTypeNameLookupResult FoundTypeDecl =
155 UnqualifiedTypeNameLookupResult::NotFound;
156 for (const auto &Base : RD->bases()) {
157 const CXXRecordDecl *BaseRD = nullptr;
158 if (auto *BaseTT = Base.getType()->getAs<TagType>())
159 BaseRD = BaseTT->getAsCXXRecordDecl();
160 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
161 // Look for type decls in dependent base classes that have known primary
162 // templates.
163 if (!TST || !TST->isDependentType())
164 continue;
165 auto *TD = TST->getTemplateName().getAsTemplateDecl();
166 if (!TD)
167 continue;
168 if (auto *BasePrimaryTemplate =
169 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
170 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
171 BaseRD = BasePrimaryTemplate;
172 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
174 CTD->findPartialSpecialization(Base.getType()))
175 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
176 BaseRD = PS;
177 }
178 }
179 }
180 if (BaseRD) {
181 for (NamedDecl *ND : BaseRD->lookup(&II)) {
182 if (!isa<TypeDecl>(ND))
183 return UnqualifiedTypeNameLookupResult::FoundNonType;
184 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
185 }
186 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
187 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
188 case UnqualifiedTypeNameLookupResult::FoundNonType:
189 return UnqualifiedTypeNameLookupResult::FoundNonType;
190 case UnqualifiedTypeNameLookupResult::FoundType:
191 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
192 break;
193 case UnqualifiedTypeNameLookupResult::NotFound:
194 break;
195 }
196 }
197 }
198 }
199
200 return FoundTypeDecl;
201}
202
204 const IdentifierInfo &II,
205 SourceLocation NameLoc) {
206 // Lookup in the parent class template context, if any.
207 const CXXRecordDecl *RD = nullptr;
208 UnqualifiedTypeNameLookupResult FoundTypeDecl =
209 UnqualifiedTypeNameLookupResult::NotFound;
210 for (DeclContext *DC = S.CurContext;
211 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
212 DC = DC->getParent()) {
213 // Look for type decls in dependent base classes that have known primary
214 // templates.
215 RD = dyn_cast<CXXRecordDecl>(DC);
216 if (RD && RD->getDescribedClassTemplate())
217 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
218 }
219 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
220 return nullptr;
221
222 // We found some types in dependent base classes. Recover as if the user
223 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
224 // lookup during template instantiation.
225 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
226
227 ASTContext &Context = S.Context;
228 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
229 cast<Type>(Context.getRecordType(RD)));
230 QualType T =
232
233 CXXScopeSpec SS;
234 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
235
236 TypeLocBuilder Builder;
237 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
238 DepTL.setNameLoc(NameLoc);
240 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
241 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
242}
243
244/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
246 SourceLocation NameLoc,
247 bool WantNontrivialTypeSourceInfo = true) {
248 switch (T->getTypeClass()) {
249 case Type::DeducedTemplateSpecialization:
250 case Type::Enum:
251 case Type::InjectedClassName:
252 case Type::Record:
253 case Type::Typedef:
254 case Type::UnresolvedUsing:
255 case Type::Using:
256 break;
257 // These can never be qualified so an ElaboratedType node
258 // would carry no additional meaning.
259 case Type::ObjCInterface:
260 case Type::ObjCTypeParam:
261 case Type::TemplateTypeParm:
262 return ParsedType::make(T);
263 default:
264 llvm_unreachable("Unexpected Type Class");
265 }
266
267 if (!SS || SS->isEmpty())
269 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
270
272 if (!WantNontrivialTypeSourceInfo)
273 return ParsedType::make(ElTy);
274
275 TypeLocBuilder Builder;
276 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
277 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
280 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
281}
282
283/// If the identifier refers to a type name within this scope,
284/// return the declaration of that type.
285///
286/// This routine performs ordinary name lookup of the identifier II
287/// within the given scope, with optional C++ scope specifier SS, to
288/// determine whether the name refers to a type. If so, returns an
289/// opaque pointer (actually a QualType) corresponding to that
290/// type. Otherwise, returns NULL.
292 Scope *S, CXXScopeSpec *SS, bool isClassName,
293 bool HasTrailingDot, ParsedType ObjectTypePtr,
294 bool IsCtorOrDtorName,
295 bool WantNontrivialTypeSourceInfo,
296 bool IsClassTemplateDeductionContext,
297 ImplicitTypenameContext AllowImplicitTypename,
298 IdentifierInfo **CorrectedII) {
299 // FIXME: Consider allowing this outside C++1z mode as an extension.
300 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
301 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
302 !isClassName && !HasTrailingDot;
303
304 // Determine where we will perform name lookup.
305 DeclContext *LookupCtx = nullptr;
306 if (ObjectTypePtr) {
307 QualType ObjectType = ObjectTypePtr.get();
308 if (ObjectType->isRecordType())
309 LookupCtx = computeDeclContext(ObjectType);
310 } else if (SS && SS->isNotEmpty()) {
311 LookupCtx = computeDeclContext(*SS, false);
312
313 if (!LookupCtx) {
314 if (isDependentScopeSpecifier(*SS)) {
315 // C++ [temp.res]p3:
316 // A qualified-id that refers to a type and in which the
317 // nested-name-specifier depends on a template-parameter (14.6.2)
318 // shall be prefixed by the keyword typename to indicate that the
319 // qualified-id denotes a type, forming an
320 // elaborated-type-specifier (7.1.5.3).
321 //
322 // We therefore do not perform any name lookup if the result would
323 // refer to a member of an unknown specialization.
324 // In C++2a, in several contexts a 'typename' is not required. Also
325 // allow this as an extension.
326 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
327 !isClassName && !IsCtorOrDtorName)
328 return nullptr;
329 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
330 if (IsImplicitTypename) {
331 SourceLocation QualifiedLoc = SS->getRange().getBegin();
333 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
334 else
335 Diag(QualifiedLoc, diag::ext_implicit_typename)
336 << SS->getScopeRep() << II.getName()
337 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
338 }
339
340 // We know from the grammar that this name refers to a type,
341 // so build a dependent node to describe the type.
342 if (WantNontrivialTypeSourceInfo)
343 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
344 (ImplicitTypenameContext)IsImplicitTypename)
345 .get();
346
349 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
351 SourceLocation(), QualifierLoc, II, NameLoc);
352 return ParsedType::make(T);
353 }
354
355 return nullptr;
356 }
357
358 if (!LookupCtx->isDependentContext() &&
359 RequireCompleteDeclContext(*SS, LookupCtx))
360 return nullptr;
361 }
362
363 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
364 // lookup for class-names.
365 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
367 LookupResult Result(*this, &II, NameLoc, Kind);
368 if (LookupCtx) {
369 // Perform "qualified" name lookup into the declaration context we
370 // computed, which is either the type of the base of a member access
371 // expression or the declaration context associated with a prior
372 // nested-name-specifier.
373 LookupQualifiedName(Result, LookupCtx);
374
375 if (ObjectTypePtr && Result.empty()) {
376 // C++ [basic.lookup.classref]p3:
377 // If the unqualified-id is ~type-name, the type-name is looked up
378 // in the context of the entire postfix-expression. If the type T of
379 // the object expression is of a class type C, the type-name is also
380 // looked up in the scope of class C. At least one of the lookups shall
381 // find a name that refers to (possibly cv-qualified) T.
382 LookupName(Result, S);
383 }
384 } else {
385 // Perform unqualified name lookup.
386 LookupName(Result, S);
387
388 // For unqualified lookup in a class template in MSVC mode, look into
389 // dependent base classes where the primary class template is known.
390 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
391 if (ParsedType TypeInBase =
392 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
393 return TypeInBase;
394 }
395 }
396
397 NamedDecl *IIDecl = nullptr;
398 UsingShadowDecl *FoundUsingShadow = nullptr;
399 switch (Result.getResultKind()) {
401 if (CorrectedII) {
402 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
403 AllowDeducedTemplate);
404 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
405 S, SS, CCC, CTK_ErrorRecovery);
406 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
407 TemplateTy Template;
408 bool MemberOfUnknownSpecialization;
410 TemplateName.setIdentifier(NewII, NameLoc);
412 CXXScopeSpec NewSS, *NewSSPtr = SS;
413 if (SS && NNS) {
414 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
415 NewSSPtr = &NewSS;
416 }
417 if (Correction && (NNS || NewII != &II) &&
418 // Ignore a correction to a template type as the to-be-corrected
419 // identifier is not a template (typo correction for template names
420 // is handled elsewhere).
421 !(getLangOpts().CPlusPlus && NewSSPtr &&
422 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
423 Template, MemberOfUnknownSpecialization))) {
424 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
425 isClassName, HasTrailingDot, ObjectTypePtr,
426 IsCtorOrDtorName,
427 WantNontrivialTypeSourceInfo,
428 IsClassTemplateDeductionContext);
429 if (Ty) {
430 diagnoseTypo(Correction,
431 PDiag(diag::err_unknown_type_or_class_name_suggest)
432 << Result.getLookupName() << isClassName);
433 if (SS && NNS)
434 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
435 *CorrectedII = NewII;
436 return Ty;
437 }
438 }
439 }
440 Result.suppressDiagnostics();
441 return nullptr;
443 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
445 SS->getScopeRep(), &II);
446 TypeLocBuilder TLB;
450 TL.setNameLoc(NameLoc);
452 }
453 [[fallthrough]];
456 Result.suppressDiagnostics();
457 return nullptr;
458
460 // Recover from type-hiding ambiguities by hiding the type. We'll
461 // do the lookup again when looking for an object, and we can
462 // diagnose the error then. If we don't do this, then the error
463 // about hiding the type will be immediately followed by an error
464 // that only makes sense if the identifier was treated like a type.
465 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
466 Result.suppressDiagnostics();
467 return nullptr;
468 }
469
470 // Look to see if we have a type anywhere in the list of results.
471 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
472 Res != ResEnd; ++Res) {
473 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
474 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
475 RealRes) ||
476 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
477 if (!IIDecl ||
478 // Make the selection of the recovery decl deterministic.
479 RealRes->getLocation() < IIDecl->getLocation()) {
480 IIDecl = RealRes;
481 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
482 }
483 }
484 }
485
486 if (!IIDecl) {
487 // None of the entities we found is a type, so there is no way
488 // to even assume that the result is a type. In this case, don't
489 // complain about the ambiguity. The parser will either try to
490 // perform this lookup again (e.g., as an object name), which
491 // will produce the ambiguity, or will complain that it expected
492 // a type name.
493 Result.suppressDiagnostics();
494 return nullptr;
495 }
496
497 // We found a type within the ambiguous lookup; diagnose the
498 // ambiguity and then return that type. This might be the right
499 // answer, or it might not be, but it suppresses any attempt to
500 // perform the name lookup again.
501 break;
502
504 IIDecl = Result.getFoundDecl();
505 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
506 break;
507 }
508
509 assert(IIDecl && "Didn't find decl");
510
511 QualType T;
512 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
513 // C++ [class.qual]p2: A lookup that would find the injected-class-name
514 // instead names the constructors of the class, except when naming a class.
515 // This is ill-formed when we're not actually forming a ctor or dtor name.
516 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
517 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
518 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
519 FoundRD->isInjectedClassName() &&
520 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
521 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
522 << &II << /*Type*/1;
523
524 DiagnoseUseOfDecl(IIDecl, NameLoc);
525
527 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
528 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
529 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
530 if (!HasTrailingDot)
532 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
533 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
534 (void)DiagnoseUseOfDecl(UD, NameLoc);
535 // Recover with 'int'
537 } else if (AllowDeducedTemplate) {
538 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
539 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
540 TemplateName Template =
541 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
543 false);
544 // Don't wrap in a further UsingType.
545 FoundUsingShadow = nullptr;
546 }
547 }
548
549 if (T.isNull()) {
550 // If it's not plausibly a type, suppress diagnostics.
551 Result.suppressDiagnostics();
552 return nullptr;
553 }
554
555 if (FoundUsingShadow)
556 T = Context.getUsingType(FoundUsingShadow, T);
557
558 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
559}
560
561// Builds a fake NNS for the given decl context.
562static NestedNameSpecifier *
564 for (;; DC = DC->getLookupParent()) {
565 DC = DC->getPrimaryContext();
566 auto *ND = dyn_cast<NamespaceDecl>(DC);
567 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
568 return NestedNameSpecifier::Create(Context, nullptr, ND);
569 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
570 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
571 RD->getTypeForDecl());
572 else if (isa<TranslationUnitDecl>(DC))
574 }
575 llvm_unreachable("something isn't in TU scope?");
576}
577
578/// Find the parent class with dependent bases of the innermost enclosing method
579/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
580/// up allowing unqualified dependent type names at class-level, which MSVC
581/// correctly rejects.
582static const CXXRecordDecl *
584 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
585 DC = DC->getPrimaryContext();
586 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
587 if (MD->getParent()->hasAnyDependentBases())
588 return MD->getParent();
589 }
590 return nullptr;
591}
592
594 SourceLocation NameLoc,
595 bool IsTemplateTypeArg) {
596 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
597
598 NestedNameSpecifier *NNS = nullptr;
599 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
600 // If we weren't able to parse a default template argument, delay lookup
601 // until instantiation time by making a non-dependent DependentTypeName. We
602 // pretend we saw a NestedNameSpecifier referring to the current scope, and
603 // lookup is retried.
604 // FIXME: This hurts our diagnostic quality, since we get errors like "no
605 // type named 'Foo' in 'current_namespace'" when the user didn't write any
606 // name specifiers.
608 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
609 } else if (const CXXRecordDecl *RD =
611 // Build a DependentNameType that will perform lookup into RD at
612 // instantiation time.
613 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
614 RD->getTypeForDecl());
615
616 // Diagnose that this identifier was undeclared, and retry the lookup during
617 // template instantiation.
618 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
619 << RD;
620 } else {
621 // This is not a situation that we should recover from.
622 return ParsedType();
623 }
624
625 QualType T =
627
628 // Build type location information. We synthesized the qualifier, so we have
629 // to build a fake NestedNameSpecifierLoc.
630 NestedNameSpecifierLocBuilder NNSLocBuilder;
631 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
632 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
633
634 TypeLocBuilder Builder;
635 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
636 DepTL.setNameLoc(NameLoc);
638 DepTL.setQualifierLoc(QualifierLoc);
639 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
640}
641
642/// isTagName() - This method is called *for error recovery purposes only*
643/// to determine if the specified name is a valid tag name ("struct foo"). If
644/// so, this returns the TST for the tag corresponding to it (TST_enum,
645/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
646/// cases in C where the user forgot to specify the tag.
648 // Do a tag name lookup in this scope.
649 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
650 LookupName(R, S, false);
653 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
654 switch (TD->getTagKind()) {
660 return DeclSpec::TST_union;
662 return DeclSpec::TST_class;
664 return DeclSpec::TST_enum;
665 }
666 }
667
669}
670
671/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
672/// if a CXXScopeSpec's type is equal to the type of one of the base classes
673/// then downgrade the missing typename error to a warning.
674/// This is needed for MSVC compatibility; Example:
675/// @code
676/// template<class T> class A {
677/// public:
678/// typedef int TYPE;
679/// };
680/// template<class T> class B : public A<T> {
681/// public:
682/// A<T>::TYPE a; // no typename required because A<T> is a base class.
683/// };
684/// @endcode
686 if (CurContext->isRecord()) {
688 return true;
689
690 const Type *Ty = SS->getScopeRep()->getAsType();
691
692 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
693 for (const auto &Base : RD->bases())
694 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
695 return true;
696 return S->isFunctionPrototypeScope();
697 }
698 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
699}
700
702 SourceLocation IILoc,
703 Scope *S,
704 CXXScopeSpec *SS,
705 ParsedType &SuggestedType,
706 bool IsTemplateName) {
707 // Don't report typename errors for editor placeholders.
708 if (II->isEditorPlaceholder())
709 return;
710 // We don't have anything to suggest (yet).
711 SuggestedType = nullptr;
712
713 // There may have been a typo in the name of the type. Look up typo
714 // results, in case we have something that we can suggest.
715 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
716 /*AllowTemplates=*/IsTemplateName,
717 /*AllowNonTemplates=*/!IsTemplateName);
718 if (TypoCorrection Corrected =
720 CCC, CTK_ErrorRecovery)) {
721 // FIXME: Support error recovery for the template-name case.
722 bool CanRecover = !IsTemplateName;
723 if (Corrected.isKeyword()) {
724 // We corrected to a keyword.
725 diagnoseTypo(Corrected,
726 PDiag(IsTemplateName ? diag::err_no_template_suggest
727 : diag::err_unknown_typename_suggest)
728 << II);
729 II = Corrected.getCorrectionAsIdentifierInfo();
730 } else {
731 // We found a similarly-named type or interface; suggest that.
732 if (!SS || !SS->isSet()) {
733 diagnoseTypo(Corrected,
734 PDiag(IsTemplateName ? diag::err_no_template_suggest
735 : diag::err_unknown_typename_suggest)
736 << II, CanRecover);
737 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
738 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
739 bool DroppedSpecifier =
740 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
741 diagnoseTypo(Corrected,
742 PDiag(IsTemplateName
743 ? diag::err_no_member_template_suggest
744 : diag::err_unknown_nested_typename_suggest)
745 << II << DC << DroppedSpecifier << SS->getRange(),
746 CanRecover);
747 } else {
748 llvm_unreachable("could not have corrected a typo here");
749 }
750
751 if (!CanRecover)
752 return;
753
754 CXXScopeSpec tmpSS;
755 if (Corrected.getCorrectionSpecifier())
756 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
757 SourceRange(IILoc));
758 // FIXME: Support class template argument deduction here.
759 SuggestedType =
760 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
761 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
762 /*IsCtorOrDtorName=*/false,
763 /*WantNontrivialTypeSourceInfo=*/true);
764 }
765 return;
766 }
767
768 if (getLangOpts().CPlusPlus && !IsTemplateName) {
769 // See if II is a class template that the user forgot to pass arguments to.
770 UnqualifiedId Name;
771 Name.setIdentifier(II, IILoc);
772 CXXScopeSpec EmptySS;
773 TemplateTy TemplateResult;
774 bool MemberOfUnknownSpecialization;
775 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
776 Name, nullptr, true, TemplateResult,
777 MemberOfUnknownSpecialization) == TNK_Type_template) {
778 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
779 return;
780 }
781 }
782
783 // FIXME: Should we move the logic that tries to recover from a missing tag
784 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
785
786 if (!SS || (!SS->isSet() && !SS->isInvalid()))
787 Diag(IILoc, IsTemplateName ? diag::err_no_template
788 : diag::err_unknown_typename)
789 << II;
790 else if (DeclContext *DC = computeDeclContext(*SS, false))
791 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
792 : diag::err_typename_nested_not_found)
793 << II << DC << SS->getRange();
794 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
795 SuggestedType =
796 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
797 } else if (isDependentScopeSpecifier(*SS)) {
798 unsigned DiagID = diag::err_typename_missing;
799 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
800 DiagID = diag::ext_typename_missing;
801
802 Diag(SS->getRange().getBegin(), DiagID)
803 << SS->getScopeRep() << II->getName()
804 << SourceRange(SS->getRange().getBegin(), IILoc)
805 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
806 SuggestedType = ActOnTypenameType(S, SourceLocation(),
807 *SS, *II, IILoc).get();
808 } else {
809 assert(SS && SS->isInvalid() &&
810 "Invalid scope specifier has already been diagnosed");
811 }
812}
813
814/// Determine whether the given result set contains either a type name
815/// or
816static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
817 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
818 NextToken.is(tok::less);
819
820 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
821 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
822 return true;
823
824 if (CheckTemplate && isa<TemplateDecl>(*I))
825 return true;
826 }
827
828 return false;
829}
830
832 Scope *S, CXXScopeSpec &SS,
833 IdentifierInfo *&Name,
834 SourceLocation NameLoc) {
835 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
836 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
837 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
838 StringRef FixItTagName;
839 switch (Tag->getTagKind()) {
841 FixItTagName = "class ";
842 break;
843
845 FixItTagName = "enum ";
846 break;
847
849 FixItTagName = "struct ";
850 break;
851
853 FixItTagName = "__interface ";
854 break;
855
857 FixItTagName = "union ";
858 break;
859 }
860
861 StringRef TagName = FixItTagName.drop_back();
862 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
863 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
864 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
865
866 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
867 I != IEnd; ++I)
868 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
869 << Name << TagName;
870
871 // Replace lookup results with just the tag decl.
873 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
874 return true;
875 }
876
877 return false;
878}
879
881 IdentifierInfo *&Name,
882 SourceLocation NameLoc,
883 const Token &NextToken,
885 DeclarationNameInfo NameInfo(Name, NameLoc);
886 ObjCMethodDecl *CurMethod = getCurMethodDecl();
887
888 assert(NextToken.isNot(tok::coloncolon) &&
889 "parse nested name specifiers before calling ClassifyName");
890 if (getLangOpts().CPlusPlus && SS.isSet() &&
891 isCurrentClassName(*Name, S, &SS)) {
892 // Per [class.qual]p2, this names the constructors of SS, not the
893 // injected-class-name. We don't have a classification for that.
894 // There's not much point caching this result, since the parser
895 // will reject it later.
897 }
898
899 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
900 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
901 /*AllowBuiltinCreation=*/!CurMethod);
902
903 if (SS.isInvalid())
905
906 // For unqualified lookup in a class template in MSVC mode, look into
907 // dependent base classes where the primary class template is known.
908 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
909 if (ParsedType TypeInBase =
910 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
911 return TypeInBase;
912 }
913
914 // Perform lookup for Objective-C instance variables (including automatically
915 // synthesized instance variables), if we're in an Objective-C method.
916 // FIXME: This lookup really, really needs to be folded in to the normal
917 // unqualified lookup mechanism.
918 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
919 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
920 if (Ivar.isInvalid())
922 if (Ivar.isUsable())
923 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
924
925 // We defer builtin creation until after ivar lookup inside ObjC methods.
926 if (Result.empty())
928 }
929
930 bool SecondTry = false;
931 bool IsFilteredTemplateName = false;
932
933Corrected:
934 switch (Result.getResultKind()) {
936 // If an unqualified-id is followed by a '(', then we have a function
937 // call.
938 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
939 // In C++, this is an ADL-only call.
940 // FIXME: Reference?
943
944 // C90 6.3.2.2:
945 // If the expression that precedes the parenthesized argument list in a
946 // function call consists solely of an identifier, and if no
947 // declaration is visible for this identifier, the identifier is
948 // implicitly declared exactly as if, in the innermost block containing
949 // the function call, the declaration
950 //
951 // extern int identifier ();
952 //
953 // appeared.
954 //
955 // We also allow this in C99 as an extension. However, this is not
956 // allowed in all language modes as functions without prototypes may not
957 // be supported.
958 if (getLangOpts().implicitFunctionsAllowed()) {
959 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
961 }
962 }
963
964 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
965 // In C++20 onwards, this could be an ADL-only call to a function
966 // template, and we're required to assume that this is a template name.
967 //
968 // FIXME: Find a way to still do typo correction in this case.
969 TemplateName Template =
972 }
973
974 // In C, we first see whether there is a tag type by the same name, in
975 // which case it's likely that the user just forgot to write "enum",
976 // "struct", or "union".
977 if (!getLangOpts().CPlusPlus && !SecondTry &&
978 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
979 break;
980 }
981
982 // Perform typo correction to determine if there is another name that is
983 // close to this name.
984 if (!SecondTry && CCC) {
985 SecondTry = true;
986 if (TypoCorrection Corrected =
987 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
988 &SS, *CCC, CTK_ErrorRecovery)) {
989 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
990 unsigned QualifiedDiag = diag::err_no_member_suggest;
991
992 NamedDecl *FirstDecl = Corrected.getFoundDecl();
993 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
994 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
995 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
996 UnqualifiedDiag = diag::err_no_template_suggest;
997 QualifiedDiag = diag::err_no_member_template_suggest;
998 } else if (UnderlyingFirstDecl &&
999 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1000 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1001 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1002 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1003 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1004 }
1005
1006 if (SS.isEmpty()) {
1007 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1008 } else {// FIXME: is this even reachable? Test it.
1009 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1010 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1011 Name->getName() == CorrectedStr;
1012 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1013 << Name << computeDeclContext(SS, false)
1014 << DroppedSpecifier << SS.getRange());
1015 }
1016
1017 // Update the name, so that the caller has the new name.
1018 Name = Corrected.getCorrectionAsIdentifierInfo();
1019
1020 // Typo correction corrected to a keyword.
1021 if (Corrected.isKeyword())
1022 return Name;
1023
1024 // Also update the LookupResult...
1025 // FIXME: This should probably go away at some point
1026 Result.clear();
1027 Result.setLookupName(Corrected.getCorrection());
1028 if (FirstDecl)
1029 Result.addDecl(FirstDecl);
1030
1031 // If we found an Objective-C instance variable, let
1032 // LookupInObjCMethod build the appropriate expression to
1033 // reference the ivar.
1034 // FIXME: This is a gross hack.
1035 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1036 DeclResult R =
1037 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1038 if (R.isInvalid())
1040 if (R.isUsable())
1041 return NameClassification::NonType(Ivar);
1042 }
1043
1044 goto Corrected;
1045 }
1046 }
1047
1048 // We failed to correct; just fall through and let the parser deal with it.
1049 Result.suppressDiagnostics();
1051
1053 // We performed name lookup into the current instantiation, and there were
1054 // dependent bases, so we treat this result the same way as any other
1055 // dependent nested-name-specifier.
1056
1057 // C++ [temp.res]p2:
1058 // A name used in a template declaration or definition and that is
1059 // dependent on a template-parameter is assumed not to name a type
1060 // unless the applicable name lookup finds a type name or the name is
1061 // qualified by the keyword typename.
1062 //
1063 // FIXME: If the next token is '<', we might want to ask the parser to
1064 // perform some heroics to see if we actually have a
1065 // template-argument-list, which would indicate a missing 'template'
1066 // keyword here.
1068 }
1069
1073 break;
1074
1076 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1078 /*AllowDependent=*/false)) {
1079 // C++ [temp.local]p3:
1080 // A lookup that finds an injected-class-name (10.2) can result in an
1081 // ambiguity in certain cases (for example, if it is found in more than
1082 // one base class). If all of the injected-class-names that are found
1083 // refer to specializations of the same class template, and if the name
1084 // is followed by a template-argument-list, the reference refers to the
1085 // class template itself and not a specialization thereof, and is not
1086 // ambiguous.
1087 //
1088 // This filtering can make an ambiguous result into an unambiguous one,
1089 // so try again after filtering out template names.
1091 if (!Result.isAmbiguous()) {
1092 IsFilteredTemplateName = true;
1093 break;
1094 }
1095 }
1096
1097 // Diagnose the ambiguity and return an error.
1099 }
1100
1101 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1102 (IsFilteredTemplateName ||
1104 Result, /*AllowFunctionTemplates=*/true,
1105 /*AllowDependent=*/false,
1106 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1108 // C++ [temp.names]p3:
1109 // After name lookup (3.4) finds that a name is a template-name or that
1110 // an operator-function-id or a literal- operator-id refers to a set of
1111 // overloaded functions any member of which is a function template if
1112 // this is followed by a <, the < is always taken as the delimiter of a
1113 // template-argument-list and never as the less-than operator.
1114 // C++2a [temp.names]p2:
1115 // A name is also considered to refer to a template if it is an
1116 // unqualified-id followed by a < and name lookup finds either one
1117 // or more functions or finds nothing.
1118 if (!IsFilteredTemplateName)
1120
1121 bool IsFunctionTemplate;
1122 bool IsVarTemplate;
1123 TemplateName Template;
1124 if (Result.end() - Result.begin() > 1) {
1125 IsFunctionTemplate = true;
1126 Template = Context.getOverloadedTemplateName(Result.begin(),
1127 Result.end());
1128 } else if (!Result.empty()) {
1129 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1130 *Result.begin(), /*AllowFunctionTemplates=*/true,
1131 /*AllowDependent=*/false));
1132 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1133 IsVarTemplate = isa<VarTemplateDecl>(TD);
1134
1135 UsingShadowDecl *FoundUsingShadow =
1136 dyn_cast<UsingShadowDecl>(*Result.begin());
1137 assert(!FoundUsingShadow ||
1138 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1139 Template =
1140 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1141 if (SS.isNotEmpty())
1143 /*TemplateKeyword=*/false,
1144 Template);
1145 } else {
1146 // All results were non-template functions. This is a function template
1147 // name.
1148 IsFunctionTemplate = true;
1149 Template = Context.getAssumedTemplateName(NameInfo.getName());
1150 }
1151
1152 if (IsFunctionTemplate) {
1153 // Function templates always go through overload resolution, at which
1154 // point we'll perform the various checks (e.g., accessibility) we need
1155 // to based on which function we selected.
1156 Result.suppressDiagnostics();
1157
1158 return NameClassification::FunctionTemplate(Template);
1159 }
1160
1161 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1163 }
1164
1165 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1167 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1168 T = Context.getUsingType(USD, T);
1169 return buildNamedType(*this, &SS, T, NameLoc);
1170 };
1171
1172 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1173 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1174 DiagnoseUseOfDecl(Type, NameLoc);
1175 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1176 return BuildTypeFor(Type, *Result.begin());
1177 }
1178
1179 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1180 if (!Class) {
1181 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1182 if (ObjCCompatibleAliasDecl *Alias =
1183 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1184 Class = Alias->getClassInterface();
1185 }
1186
1187 if (Class) {
1188 DiagnoseUseOfDecl(Class, NameLoc);
1189
1190 if (NextToken.is(tok::period)) {
1191 // Interface. <something> is parsed as a property reference expression.
1192 // Just return "unknown" as a fall-through for now.
1193 Result.suppressDiagnostics();
1195 }
1196
1198 return ParsedType::make(T);
1199 }
1200
1201 if (isa<ConceptDecl>(FirstDecl)) {
1202 // We want to preserve the UsingShadowDecl for concepts.
1203 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1206 TemplateName(cast<TemplateDecl>(FirstDecl)));
1207 }
1208
1209 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1210 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1212 }
1213
1214 // We can have a type template here if we're classifying a template argument.
1215 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1216 !isa<VarTemplateDecl>(FirstDecl))
1218 TemplateName(cast<TemplateDecl>(FirstDecl)));
1219
1220 // Check for a tag type hidden by a non-type decl in a few cases where it
1221 // seems likely a type is wanted instead of the non-type that was found.
1222 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1223 if ((NextToken.is(tok::identifier) ||
1224 (NextIsOp &&
1225 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1226 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1227 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1228 DiagnoseUseOfDecl(Type, NameLoc);
1229 return BuildTypeFor(Type, *Result.begin());
1230 }
1231
1232 // If we already know which single declaration is referenced, just annotate
1233 // that declaration directly. Defer resolving even non-overloaded class
1234 // member accesses, as we need to defer certain access checks until we know
1235 // the context.
1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237 if (Result.isSingleResult() && !ADL &&
1238 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1239 return NameClassification::NonType(Result.getRepresentativeDecl());
1240
1241 // Otherwise, this is an overload set that we will need to resolve later.
1242 Result.suppressDiagnostics();
1244 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1245 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1246 /*KnownDependent=*/false));
1247}
1248
1251 SourceLocation NameLoc) {
1252 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1253 CXXScopeSpec SS;
1254 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1255 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1256}
1257
1260 IdentifierInfo *Name,
1261 SourceLocation NameLoc,
1262 bool IsAddressOfOperand) {
1263 DeclarationNameInfo NameInfo(Name, NameLoc);
1264 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1265 NameInfo, IsAddressOfOperand,
1266 /*TemplateArgs=*/nullptr);
1267}
1268
1270 NamedDecl *Found,
1271 SourceLocation NameLoc,
1272 const Token &NextToken) {
1273 if (getCurMethodDecl() && SS.isEmpty())
1274 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1275 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1276
1277 // Reconstruct the lookup result.
1278 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1279 Result.addDecl(Found);
1280 Result.resolveKind();
1281
1282 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1283 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1284}
1285
1287 // For an implicit class member access, transform the result into a member
1288 // access expression if necessary.
1289 auto *ULE = cast<UnresolvedLookupExpr>(E);
1290 if ((*ULE->decls_begin())->isCXXClassMember()) {
1291 CXXScopeSpec SS;
1292 SS.Adopt(ULE->getQualifierLoc());
1293
1294 // Reconstruct the lookup result.
1295 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1297 Result.setNamingClass(ULE->getNamingClass());
1298 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1299 Result.addDecl(*I, I.getAccess());
1300 Result.resolveKind();
1302 nullptr, S);
1303 }
1304
1305 // Otherwise, this is already in the form we needed, and no further checks
1306 // are necessary.
1307 return ULE;
1308}
1309
1312 auto *TD = Name.getAsTemplateDecl();
1313 if (!TD)
1315 if (isa<ClassTemplateDecl>(TD))
1317 if (isa<FunctionTemplateDecl>(TD))
1319 if (isa<VarTemplateDecl>(TD))
1321 if (isa<TypeAliasTemplateDecl>(TD))
1323 if (isa<TemplateTemplateParmDecl>(TD))
1325 if (isa<ConceptDecl>(TD))
1328}
1329
1331 assert(DC->getLexicalParent() == CurContext &&
1332 "The next DeclContext should be lexically contained in the current one.");
1333 CurContext = DC;
1334 S->setEntity(DC);
1335}
1336
1338 assert(CurContext && "DeclContext imbalance!");
1339
1341 assert(CurContext && "Popped translation unit!");
1342}
1343
1345 Decl *D) {
1346 // Unlike PushDeclContext, the context to which we return is not necessarily
1347 // the containing DC of TD, because the new context will be some pre-existing
1348 // TagDecl definition instead of a fresh one.
1349 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1350 CurContext = cast<TagDecl>(D)->getDefinition();
1351 assert(CurContext && "skipping definition of undefined tag");
1352 // Start lookups from the parent of the current context; we don't want to look
1353 // into the pre-existing complete definition.
1354 S->setEntity(CurContext->getLookupParent());
1355 return Result;
1356}
1357
1359 CurContext = static_cast<decltype(CurContext)>(Context);
1360}
1361
1362/// EnterDeclaratorContext - Used when we must lookup names in the context
1363/// of a declarator's nested name specifier.
1364///
1366 // C++0x [basic.lookup.unqual]p13:
1367 // A name used in the definition of a static data member of class
1368 // X (after the qualified-id of the static member) is looked up as
1369 // if the name was used in a member function of X.
1370 // C++0x [basic.lookup.unqual]p14:
1371 // If a variable member of a namespace is defined outside of the
1372 // scope of its namespace then any name used in the definition of
1373 // the variable member (after the declarator-id) is looked up as
1374 // if the definition of the variable member occurred in its
1375 // namespace.
1376 // Both of these imply that we should push a scope whose context
1377 // is the semantic context of the declaration. We can't use
1378 // PushDeclContext here because that context is not necessarily
1379 // lexically contained in the current context. Fortunately,
1380 // the containing scope should have the appropriate information.
1381
1382 assert(!S->getEntity() && "scope already has entity");
1383
1384#ifndef NDEBUG
1385 Scope *Ancestor = S->getParent();
1386 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1387 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1388#endif
1389
1390 CurContext = DC;
1391 S->setEntity(DC);
1392
1393 if (S->getParent()->isTemplateParamScope()) {
1394 // Also set the corresponding entities for all immediately-enclosing
1395 // template parameter scopes.
1396 EnterTemplatedContext(S->getParent(), DC);
1397 }
1398}
1399
1401 assert(S->getEntity() == CurContext && "Context imbalance!");
1402
1403 // Switch back to the lexical context. The safety of this is
1404 // enforced by an assert in EnterDeclaratorContext.
1405 Scope *Ancestor = S->getParent();
1406 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1407 CurContext = Ancestor->getEntity();
1408
1409 // We don't need to do anything with the scope, which is going to
1410 // disappear.
1411}
1412
1414 assert(S->isTemplateParamScope() &&
1415 "expected to be initializing a template parameter scope");
1416
1417 // C++20 [temp.local]p7:
1418 // In the definition of a member of a class template that appears outside
1419 // of the class template definition, the name of a member of the class
1420 // template hides the name of a template-parameter of any enclosing class
1421 // templates (but not a template-parameter of the member if the member is a
1422 // class or function template).
1423 // C++20 [temp.local]p9:
1424 // In the definition of a class template or in the definition of a member
1425 // of such a template that appears outside of the template definition, for
1426 // each non-dependent base class (13.8.2.1), if the name of the base class
1427 // or the name of a member of the base class is the same as the name of a
1428 // template-parameter, the base class name or member name hides the
1429 // template-parameter name (6.4.10).
1430 //
1431 // This means that a template parameter scope should be searched immediately
1432 // after searching the DeclContext for which it is a template parameter
1433 // scope. For example, for
1434 // template<typename T> template<typename U> template<typename V>
1435 // void N::A<T>::B<U>::f(...)
1436 // we search V then B<U> (and base classes) then U then A<T> (and base
1437 // classes) then T then N then ::.
1438 unsigned ScopeDepth = getTemplateDepth(S);
1439 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1440 DeclContext *SearchDCAfterScope = DC;
1441 for (; DC; DC = DC->getLookupParent()) {
1442 if (const TemplateParameterList *TPL =
1443 cast<Decl>(DC)->getDescribedTemplateParams()) {
1444 unsigned DCDepth = TPL->getDepth() + 1;
1445 if (DCDepth > ScopeDepth)
1446 continue;
1447 if (ScopeDepth == DCDepth)
1448 SearchDCAfterScope = DC = DC->getLookupParent();
1449 break;
1450 }
1451 }
1452 S->setLookupEntity(SearchDCAfterScope);
1453 }
1454}
1455
1457 // We assume that the caller has already called
1458 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1459 FunctionDecl *FD = D->getAsFunction();
1460 if (!FD)
1461 return;
1462
1463 // Same implementation as PushDeclContext, but enters the context
1464 // from the lexical parent, rather than the top-level class.
1465 assert(CurContext == FD->getLexicalParent() &&
1466 "The next DeclContext should be lexically contained in the current one.");
1467 CurContext = FD;
1468 S->setEntity(CurContext);
1469
1470 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1471 ParmVarDecl *Param = FD->getParamDecl(P);
1472 // If the parameter has an identifier, then add it to the scope
1473 if (Param->getIdentifier()) {
1474 S->AddDecl(Param);
1475 IdResolver.AddDecl(Param);
1476 }
1477 }
1478}
1479
1481 // Same implementation as PopDeclContext, but returns to the lexical parent,
1482 // rather than the top-level class.
1483 assert(CurContext && "DeclContext imbalance!");
1485 assert(CurContext && "Popped translation unit!");
1486}
1487
1488/// Determine whether overloading is allowed for a new function
1489/// declaration considering prior declarations of the same name.
1490///
1491/// This routine determines whether overloading is possible, not
1492/// whether a new declaration actually overloads a previous one.
1493/// It will return true in C++ (where overloads are alway permitted)
1494/// or, as a C extension, when either the new declaration or a
1495/// previous one is declared with the 'overloadable' attribute.
1497 ASTContext &Context,
1498 const FunctionDecl *New) {
1499 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1500 return true;
1501
1502 // Multiversion function declarations are not overloads in the
1503 // usual sense of that term, but lookup will report that an
1504 // overload set was found if more than one multiversion function
1505 // declaration is present for the same name. It is therefore
1506 // inadequate to assume that some prior declaration(s) had
1507 // the overloadable attribute; checking is required. Since one
1508 // declaration is permitted to omit the attribute, it is necessary
1509 // to check at least two; hence the 'any_of' check below. Note that
1510 // the overloadable attribute is implicitly added to declarations
1511 // that were required to have it but did not.
1512 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1513 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1514 return ND->hasAttr<OverloadableAttr>();
1515 });
1516 } else if (Previous.getResultKind() == LookupResult::Found)
1517 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1518
1519 return false;
1520}
1521
1522/// Add this decl to the scope shadowed decl chains.
1523void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1524 // Move up the scope chain until we find the nearest enclosing
1525 // non-transparent context. The declaration will be introduced into this
1526 // scope.
1527 while (S->getEntity() && S->getEntity()->isTransparentContext())
1528 S = S->getParent();
1529
1530 // Add scoped declarations into their context, so that they can be
1531 // found later. Declarations without a context won't be inserted
1532 // into any context.
1533 if (AddToContext)
1534 CurContext->addDecl(D);
1535
1536 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1537 // are function-local declarations.
1538 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1539 return;
1540
1541 // Template instantiations should also not be pushed into scope.
1542 if (isa<FunctionDecl>(D) &&
1543 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1544 return;
1545
1546 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1547 S->AddDecl(D);
1548 return;
1549 }
1550 // If this replaces anything in the current scope,
1552 IEnd = IdResolver.end();
1553 for (; I != IEnd; ++I) {
1554 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1555 S->RemoveDecl(*I);
1557
1558 // Should only need to replace one decl.
1559 break;
1560 }
1561 }
1562
1563 S->AddDecl(D);
1564
1565 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1566 // Implicitly-generated labels may end up getting generated in an order that
1567 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1568 // the label at the appropriate place in the identifier chain.
1569 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1570 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1571 if (IDC == CurContext) {
1572 if (!S->isDeclScope(*I))
1573 continue;
1574 } else if (IDC->Encloses(CurContext))
1575 break;
1576 }
1577
1579 } else {
1581 }
1583}
1584
1586 bool AllowInlineNamespace) const {
1587 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1588}
1589
1591 DeclContext *TargetDC = DC->getPrimaryContext();
1592 do {
1593 if (DeclContext *ScopeDC = S->getEntity())
1594 if (ScopeDC->getPrimaryContext() == TargetDC)
1595 return S;
1596 } while ((S = S->getParent()));
1597
1598 return nullptr;
1599}
1600
1602 DeclContext*,
1603 ASTContext&);
1604
1605/// Filters out lookup results that don't fall within the given scope
1606/// as determined by isDeclInScope.
1608 bool ConsiderLinkage,
1609 bool AllowInlineNamespace) {
1611 while (F.hasNext()) {
1612 NamedDecl *D = F.next();
1613
1614 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1615 continue;
1616
1617 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1618 continue;
1619
1620 F.erase();
1621 }
1622
1623 F.done();
1624}
1625
1626/// We've determined that \p New is a redeclaration of \p Old. Check that they
1627/// have compatible owning modules.
1629 // [module.interface]p7:
1630 // A declaration is attached to a module as follows:
1631 // - If the declaration is a non-dependent friend declaration that nominates a
1632 // function with a declarator-id that is a qualified-id or template-id or that
1633 // nominates a class other than with an elaborated-type-specifier with neither
1634 // a nested-name-specifier nor a simple-template-id, it is attached to the
1635 // module to which the friend is attached ([basic.link]).
1636 if (New->getFriendObjectKind() &&
1640 return false;
1641 }
1642
1643 Module *NewM = New->getOwningModule();
1644 Module *OldM = Old->getOwningModule();
1645
1646 if (NewM && NewM->isPrivateModule())
1647 NewM = NewM->Parent;
1648 if (OldM && OldM->isPrivateModule())
1649 OldM = OldM->Parent;
1650
1651 if (NewM == OldM)
1652 return false;
1653
1654 if (NewM && OldM) {
1655 // A module implementation unit has visibility of the decls in its
1656 // implicitly imported interface.
1657 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1658 return false;
1659
1660 // Partitions are part of the module, but a partition could import another
1661 // module, so verify that the PMIs agree.
1662 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1665 return false;
1666 }
1667
1668 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1669 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1670 if (NewIsModuleInterface || OldIsModuleInterface) {
1671 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1672 // if a declaration of D [...] appears in the purview of a module, all
1673 // other such declarations shall appear in the purview of the same module
1674 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1675 << New
1676 << NewIsModuleInterface
1677 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1678 << OldIsModuleInterface
1679 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1680 Diag(Old->getLocation(), diag::note_previous_declaration);
1681 New->setInvalidDecl();
1682 return true;
1683 }
1684
1685 return false;
1686}
1687
1688// [module.interface]p6:
1689// A redeclaration of an entity X is implicitly exported if X was introduced by
1690// an exported declaration; otherwise it shall not be exported.
1692 // [module.interface]p1:
1693 // An export-declaration shall inhabit a namespace scope.
1694 //
1695 // So it is meaningless to talk about redeclaration which is not at namespace
1696 // scope.
1697 if (!New->getLexicalDeclContext()
1699 ->isFileContext() ||
1700 !Old->getLexicalDeclContext()
1702 ->isFileContext())
1703 return false;
1704
1705 bool IsNewExported = New->isInExportDeclContext();
1706 bool IsOldExported = Old->isInExportDeclContext();
1707
1708 // It should be irrevelant if both of them are not exported.
1709 if (!IsNewExported && !IsOldExported)
1710 return false;
1711
1712 if (IsOldExported)
1713 return false;
1714
1715 assert(IsNewExported);
1716
1717 auto Lk = Old->getFormalLinkage();
1718 int S = 0;
1719 if (Lk == Linkage::Internal)
1720 S = 1;
1721 else if (Lk == Linkage::Module)
1722 S = 2;
1723 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1724 Diag(Old->getLocation(), diag::note_previous_declaration);
1725 return true;
1726}
1727
1728// A wrapper function for checking the semantic restrictions of
1729// a redeclaration within a module.
1732 return true;
1733
1734 if (CheckRedeclarationExported(New, Old))
1735 return true;
1736
1737 return false;
1738}
1739
1740// Check the redefinition in C++20 Modules.
1741//
1742// [basic.def.odr]p14:
1743// For any definable item D with definitions in multiple translation units,
1744// - if D is a non-inline non-templated function or variable, or
1745// - if the definitions in different translation units do not satisfy the
1746// following requirements,
1747// the program is ill-formed; a diagnostic is required only if the definable
1748// item is attached to a named module and a prior definition is reachable at
1749// the point where a later definition occurs.
1750// - Each such definition shall not be attached to a named module
1751// ([module.unit]).
1752// - Each such definition shall consist of the same sequence of tokens, ...
1753// ...
1754//
1755// Return true if the redefinition is not allowed. Return false otherwise.
1757 const NamedDecl *Old) const {
1758 assert(getASTContext().isSameEntity(New, Old) &&
1759 "New and Old are not the same definition, we should diagnostic it "
1760 "immediately instead of checking it.");
1761 assert(const_cast<Sema *>(this)->isReachable(New) &&
1762 const_cast<Sema *>(this)->isReachable(Old) &&
1763 "We shouldn't see unreachable definitions here.");
1764
1765 Module *NewM = New->getOwningModule();
1766 Module *OldM = Old->getOwningModule();
1767
1768 // We only checks for named modules here. The header like modules is skipped.
1769 // FIXME: This is not right if we import the header like modules in the module
1770 // purview.
1771 //
1772 // For example, assuming "header.h" provides definition for `D`.
1773 // ```C++
1774 // //--- M.cppm
1775 // export module M;
1776 // import "header.h"; // or #include "header.h" but import it by clang modules
1777 // actually.
1778 //
1779 // //--- Use.cpp
1780 // import M;
1781 // import "header.h"; // or uses clang modules.
1782 // ```
1783 //
1784 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1785 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1786 // reject it. But the current implementation couldn't detect the case since we
1787 // don't record the information about the importee modules.
1788 //
1789 // But this might not be painful in practice. Since the design of C++20 Named
1790 // Modules suggests us to use headers in global module fragment instead of
1791 // module purview.
1792 if (NewM && NewM->isHeaderLikeModule())
1793 NewM = nullptr;
1794 if (OldM && OldM->isHeaderLikeModule())
1795 OldM = nullptr;
1796
1797 if (!NewM && !OldM)
1798 return true;
1799
1800 // [basic.def.odr]p14.3
1801 // Each such definition shall not be attached to a named module
1802 // ([module.unit]).
1803 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1804 return true;
1805
1806 // Then New and Old lives in the same TU if their share one same module unit.
1807 if (NewM)
1808 NewM = NewM->getTopLevelModule();
1809 if (OldM)
1810 OldM = OldM->getTopLevelModule();
1811 return OldM == NewM;
1812}
1813
1815 if (D->getDeclContext()->isFileContext())
1816 return false;
1817
1818 return isa<UsingShadowDecl>(D) ||
1819 isa<UnresolvedUsingTypenameDecl>(D) ||
1820 isa<UnresolvedUsingValueDecl>(D);
1821}
1822
1823/// Removes using shadow declarations not at class scope from the lookup
1824/// results.
1827 while (F.hasNext())
1829 F.erase();
1830
1831 F.done();
1832}
1833
1834/// Check for this common pattern:
1835/// @code
1836/// class S {
1837/// S(const S&); // DO NOT IMPLEMENT
1838/// void operator=(const S&); // DO NOT IMPLEMENT
1839/// };
1840/// @endcode
1842 // FIXME: Should check for private access too but access is set after we get
1843 // the decl here.
1845 return false;
1846
1847 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1848 return CD->isCopyConstructor();
1849 return D->isCopyAssignmentOperator();
1850}
1851
1852// We need this to handle
1853//
1854// typedef struct {
1855// void *foo() { return 0; }
1856// } A;
1857//
1858// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1859// for example. If 'A', foo will have external linkage. If we have '*A',
1860// foo will have no linkage. Since we can't know until we get to the end
1861// of the typedef, this function finds out if D might have non-external linkage.
1862// Callers should verify at the end of the TU if it D has external linkage or
1863// not.
1864bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1865 const DeclContext *DC = D->getDeclContext();
1866 while (!DC->isTranslationUnit()) {
1867 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1868 if (!RD->hasNameForLinkage())
1869 return true;
1870 }
1871 DC = DC->getParent();
1872 }
1873
1874 return !D->isExternallyVisible();
1875}
1876
1877// FIXME: This needs to be refactored; some other isInMainFile users want
1878// these semantics.
1879static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1881 return false;
1882 return S.SourceMgr.isInMainFile(Loc);
1883}
1884
1886 assert(D);
1887
1888 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1889 return false;
1890
1891 // Ignore all entities declared within templates, and out-of-line definitions
1892 // of members of class templates.
1893 if (D->getDeclContext()->isDependentContext() ||
1895 return false;
1896
1897 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1898 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1899 return false;
1900 // A non-out-of-line declaration of a member specialization was implicitly
1901 // instantiated; it's the out-of-line declaration that we're interested in.
1902 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1903 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1904 return false;
1905
1906 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1907 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1908 return false;
1909 } else {
1910 // 'static inline' functions are defined in headers; don't warn.
1911 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1912 return false;
1913 }
1914
1915 if (FD->doesThisDeclarationHaveABody() &&
1917 return false;
1918 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1919 // Constants and utility variables are defined in headers with internal
1920 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1921 // like "inline".)
1922 if (!isMainFileLoc(*this, VD->getLocation()))
1923 return false;
1924
1925 if (Context.DeclMustBeEmitted(VD))
1926 return false;
1927
1928 if (VD->isStaticDataMember() &&
1929 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1930 return false;
1931 if (VD->isStaticDataMember() &&
1932 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1933 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1934 return false;
1935
1936 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1937 return false;
1938 } else {
1939 return false;
1940 }
1941
1942 // Only warn for unused decls internal to the translation unit.
1943 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1944 // for inline functions defined in the main source file, for instance.
1945 return mightHaveNonExternalLinkage(D);
1946}
1947
1949 if (!D)
1950 return;
1951
1952 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1953 const FunctionDecl *First = FD->getFirstDecl();
1955 return; // First should already be in the vector.
1956 }
1957
1958 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1959 const VarDecl *First = VD->getFirstDecl();
1961 return; // First should already be in the vector.
1962 }
1963
1966}
1967
1968static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1969 const NamedDecl *D) {
1970 if (D->isInvalidDecl())
1971 return false;
1972
1973 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1974 // For a decomposition declaration, warn if none of the bindings are
1975 // referenced, instead of if the variable itself is referenced (which
1976 // it is, by the bindings' expressions).
1977 bool IsAllPlaceholders = true;
1978 for (const auto *BD : DD->bindings()) {
1979 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1980 return false;
1981 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1982 }
1983 if (IsAllPlaceholders)
1984 return false;
1985 } else if (!D->getDeclName()) {
1986 return false;
1987 } else if (D->isReferenced() || D->isUsed()) {
1988 return false;
1989 }
1990
1991 if (D->isPlaceholderVar(LangOpts))
1992 return false;
1993
1994 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1995 D->hasAttr<CleanupAttr>())
1996 return false;
1997
1998 if (isa<LabelDecl>(D))
1999 return true;
2000
2001 // Except for labels, we only care about unused decls that are local to
2002 // functions.
2003 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2004 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2005 // For dependent types, the diagnostic is deferred.
2006 WithinFunction =
2007 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2008 if (!WithinFunction)
2009 return false;
2010
2011 if (isa<TypedefNameDecl>(D))
2012 return true;
2013
2014 // White-list anything that isn't a local variable.
2015 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2016 return false;
2017
2018 // Types of valid local variables should be complete, so this should succeed.
2019 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2020
2021 const Expr *Init = VD->getInit();
2022 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2023 Init = Cleanups->getSubExpr();
2024
2025 const auto *Ty = VD->getType().getTypePtr();
2026
2027 // Only look at the outermost level of typedef.
2028 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2029 // Allow anything marked with __attribute__((unused)).
2030 if (TT->getDecl()->hasAttr<UnusedAttr>())
2031 return false;
2032 }
2033
2034 // Warn for reference variables whose initializtion performs lifetime
2035 // extension.
2036 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2037 MTE && MTE->getExtendingDecl()) {
2038 Ty = VD->getType().getNonReferenceType().getTypePtr();
2039 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2040 }
2041
2042 // If we failed to complete the type for some reason, or if the type is
2043 // dependent, don't diagnose the variable.
2044 if (Ty->isIncompleteType() || Ty->isDependentType())
2045 return false;
2046
2047 // Look at the element type to ensure that the warning behaviour is
2048 // consistent for both scalars and arrays.
2049 Ty = Ty->getBaseElementTypeUnsafe();
2050
2051 if (const TagType *TT = Ty->getAs<TagType>()) {
2052 const TagDecl *Tag = TT->getDecl();
2053 if (Tag->hasAttr<UnusedAttr>())
2054 return false;
2055
2056 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2057 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2058 return false;
2059
2060 if (Init) {
2061 const auto *Construct =
2062 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2063 if (Construct && !Construct->isElidable()) {
2064 const CXXConstructorDecl *CD = Construct->getConstructor();
2065 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2066 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2067 return false;
2068 }
2069
2070 // Suppress the warning if we don't know how this is constructed, and
2071 // it could possibly be non-trivial constructor.
2072 if (Init->isTypeDependent()) {
2073 for (const CXXConstructorDecl *Ctor : RD->ctors())
2074 if (!Ctor->isTrivial())
2075 return false;
2076 }
2077
2078 // Suppress the warning if the constructor is unresolved because
2079 // its arguments are dependent.
2080 if (isa<CXXUnresolvedConstructExpr>(Init))
2081 return false;
2082 }
2083 }
2084 }
2085
2086 // TODO: __attribute__((unused)) templates?
2087 }
2088
2089 return true;
2090}
2091
2093 FixItHint &Hint) {
2094 if (isa<LabelDecl>(D)) {
2096 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2097 /*SkipTrailingWhitespaceAndNewline=*/false);
2098 if (AfterColon.isInvalid())
2099 return;
2101 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2102 }
2103}
2104
2107 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2108}
2109
2111 DiagReceiverTy DiagReceiver) {
2112 if (D->getTypeForDecl()->isDependentType())
2113 return;
2114
2115 for (auto *TmpD : D->decls()) {
2116 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2117 DiagnoseUnusedDecl(T, DiagReceiver);
2118 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2119 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2120 }
2121}
2122
2125 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2126}
2127
2128/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2129/// unless they are marked attr(unused).
2132 return;
2133
2134 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2135 // typedefs can be referenced later on, so the diagnostics are emitted
2136 // at end-of-translation-unit.
2138 return;
2139 }
2140
2141 FixItHint Hint;
2143
2144 unsigned DiagID;
2145 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2146 DiagID = diag::warn_unused_exception_param;
2147 else if (isa<LabelDecl>(D))
2148 DiagID = diag::warn_unused_label;
2149 else
2150 DiagID = diag::warn_unused_variable;
2151
2152 SourceLocation DiagLoc = D->getLocation();
2153 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2154}
2155
2157 DiagReceiverTy DiagReceiver) {
2158 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2159 // it's not really unused.
2160 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2161 return;
2162
2163 // In C++, `_` variables behave as if they were maybe_unused
2164 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2165 return;
2166
2167 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2168
2169 if (Ty->isReferenceType() || Ty->isDependentType())
2170 return;
2171
2172 if (const TagType *TT = Ty->getAs<TagType>()) {
2173 const TagDecl *Tag = TT->getDecl();
2174 if (Tag->hasAttr<UnusedAttr>())
2175 return;
2176 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2177 // mimic gcc's behavior.
2178 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2179 RD && !RD->hasAttr<WarnUnusedAttr>())
2180 return;
2181 }
2182
2183 // Don't warn about __block Objective-C pointer variables, as they might
2184 // be assigned in the block but not used elsewhere for the purpose of lifetime
2185 // extension.
2186 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2187 return;
2188
2189 // Don't warn about Objective-C pointer variables with precise lifetime
2190 // semantics; they can be used to ensure ARC releases the object at a known
2191 // time, which may mean assignment but no other references.
2192 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2193 return;
2194
2195 auto iter = RefsMinusAssignments.find(VD);
2196 if (iter == RefsMinusAssignments.end())
2197 return;
2198
2199 assert(iter->getSecond() >= 0 &&
2200 "Found a negative number of references to a VarDecl");
2201 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2202 // Assume the given VarDecl is "used" if its ref count stored in
2203 // `RefMinusAssignments` is positive, with one exception.
2204 //
2205 // For a C++ variable whose decl (with initializer) entirely consist the
2206 // condition expression of a if/while/for construct,
2207 // Clang creates a DeclRefExpr for the condition expression rather than a
2208 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2209 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2210 // used in the body of the if/while/for construct.
2211 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2212 if (!UnusedCXXCondDecl)
2213 return;
2214 }
2215
2216 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2217 : diag::warn_unused_but_set_variable;
2218 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2219}
2220
2222 Sema::DiagReceiverTy DiagReceiver) {
2223 // Verify that we have no forward references left. If so, there was a goto
2224 // or address of a label taken, but no definition of it. Label fwd
2225 // definitions are indicated with a null substmt which is also not a resolved
2226 // MS inline assembly label name.
2227 bool Diagnose = false;
2228 if (L->isMSAsmLabel())
2229 Diagnose = !L->isResolvedMSAsmLabel();
2230 else
2231 Diagnose = L->getStmt() == nullptr;
2232 if (Diagnose)
2233 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2234 << L);
2235}
2236
2238 S->applyNRVO();
2239
2240 if (S->decl_empty()) return;
2241 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2242 "Scope shouldn't contain decls!");
2243
2244 /// We visit the decls in non-deterministic order, but we want diagnostics
2245 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2246 /// and sort the diagnostics before emitting them, after we visited all decls.
2247 struct LocAndDiag {
2249 std::optional<SourceLocation> PreviousDeclLoc;
2251 };
2253 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2254 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2255 };
2256 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2257 SourceLocation PreviousDeclLoc,
2258 PartialDiagnostic PD) {
2259 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2260 };
2261
2262 for (auto *TmpD : S->decls()) {
2263 assert(TmpD && "This decl didn't get pushed??");
2264
2265 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2266 NamedDecl *D = cast<NamedDecl>(TmpD);
2267
2268 // Diagnose unused variables in this scope.
2269 if (!S->hasUnrecoverableErrorOccurred()) {
2270 DiagnoseUnusedDecl(D, addDiag);
2271 if (const auto *RD = dyn_cast<RecordDecl>(D))
2272 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2273 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2274 DiagnoseUnusedButSetDecl(VD, addDiag);
2275 RefsMinusAssignments.erase(VD);
2276 }
2277 }
2278
2279 if (!D->getDeclName()) continue;
2280
2281 // If this was a forward reference to a label, verify it was defined.
2282 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2283 CheckPoppedLabel(LD, *this, addDiag);
2284
2285 // Remove this name from our lexical scope, and warn on it if we haven't
2286 // already.
2288 auto ShadowI = ShadowingDecls.find(D);
2289 if (ShadowI != ShadowingDecls.end()) {
2290 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2291 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2292 PDiag(diag::warn_ctor_parm_shadows_field)
2293 << D << FD << FD->getParent());
2294 }
2295 ShadowingDecls.erase(ShadowI);
2296 }
2297 }
2298
2299 llvm::sort(DeclDiags,
2300 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2301 // The particular order for diagnostics is not important, as long
2302 // as the order is deterministic. Using the raw location is going
2303 // to generally be in source order unless there are macro
2304 // expansions involved.
2305 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2306 });
2307 for (const LocAndDiag &D : DeclDiags) {
2308 Diag(D.Loc, D.PD);
2309 if (D.PreviousDeclLoc)
2310 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2311 }
2312}
2313
2314/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2315/// from S, where a non-field would be declared. This routine copes
2316/// with the difference between C and C++ scoping rules in structs and
2317/// unions. For example, the following code is well-formed in C but
2318/// ill-formed in C++:
2319/// @code
2320/// struct S6 {
2321/// enum { BAR } e;
2322/// };
2323///
2324/// void test_S6() {
2325/// struct S6 a;
2326/// a.e = BAR;
2327/// }
2328/// @endcode
2329/// For the declaration of BAR, this routine will return a different
2330/// scope. The scope S will be the scope of the unnamed enumeration
2331/// within S6. In C++, this routine will return the scope associated
2332/// with S6, because the enumeration's scope is a transparent
2333/// context but structures can contain non-field names. In C, this
2334/// routine will return the translation unit scope, since the
2335/// enumeration's scope is a transparent context and structures cannot
2336/// contain non-field names.
2338 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2339 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2340 (S->isClassScope() && !getLangOpts().CPlusPlus))
2341 S = S->getParent();
2342 return S;
2343}
2344
2345static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2347 switch (Error) {
2349 return "";
2351 return BuiltinInfo.getHeaderName(ID);
2353 return "stdio.h";
2355 return "setjmp.h";
2357 return "ucontext.h";
2358 }
2359 llvm_unreachable("unhandled error kind");
2360}
2361
2363 unsigned ID, SourceLocation Loc) {
2365
2366 if (getLangOpts().CPlusPlus) {
2369 CLinkageDecl->setImplicit();
2370 Parent->addDecl(CLinkageDecl);
2371 Parent = CLinkageDecl;
2372 }
2373
2375 /*TInfo=*/nullptr, SC_Extern,
2376 getCurFPFeatures().isFPConstrained(),
2377 false, Type->isFunctionProtoType());
2378 New->setImplicit();
2379 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2380
2381 // Create Decl objects for each parameter, adding them to the
2382 // FunctionDecl.
2383 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2385 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2387 Context, New, SourceLocation(), SourceLocation(), nullptr,
2388 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2389 parm->setScopeInfo(0, i);
2390 Params.push_back(parm);
2391 }
2392 New->setParams(Params);
2393 }
2394
2396 return New;
2397}
2398
2399/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2400/// file scope. lazily create a decl for it. ForRedeclaration is true
2401/// if we're creating this built-in in anticipation of redeclaring the
2402/// built-in.
2404 Scope *S, bool ForRedeclaration,
2407
2409 QualType R = Context.GetBuiltinType(ID, Error);
2410 if (Error) {
2411 if (!ForRedeclaration)
2412 return nullptr;
2413
2414 // If we have a builtin without an associated type we should not emit a
2415 // warning when we were not able to find a type for it.
2416 if (Error == ASTContext::GE_Missing_type ||
2418 return nullptr;
2419
2420 // If we could not find a type for setjmp it is because the jmp_buf type was
2421 // not defined prior to the setjmp declaration.
2422 if (Error == ASTContext::GE_Missing_setjmp) {
2423 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2425 return nullptr;
2426 }
2427
2428 // Generally, we emit a warning that the declaration requires the
2429 // appropriate header.
2430 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2431 << getHeaderName(Context.BuiltinInfo, ID, Error)
2433 return nullptr;
2434 }
2435
2436 if (!ForRedeclaration &&
2439 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2440 : diag::ext_implicit_lib_function_decl)
2441 << Context.BuiltinInfo.getName(ID) << R;
2442 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2443 Diag(Loc, diag::note_include_header_or_declare)
2444 << Header << Context.BuiltinInfo.getName(ID);
2445 }
2446
2447 if (R.isNull())
2448 return nullptr;
2449
2450 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2452
2453 // TUScope is the translation-unit scope to insert this function into.
2454 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2455 // relate Scopes to DeclContexts, and probably eliminate CurContext
2456 // entirely, but we're not there yet.
2457 DeclContext *SavedContext = CurContext;
2458 CurContext = New->getDeclContext();
2460 CurContext = SavedContext;
2461 return New;
2462}
2463
2464/// Typedef declarations don't have linkage, but they still denote the same
2465/// entity if their types are the same.
2466/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2467/// isSameEntity.
2468static void
2471 // This is only interesting when modules are enabled.
2472 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2473 return;
2474
2475 // Empty sets are uninteresting.
2476 if (Previous.empty())
2477 return;
2478
2479 LookupResult::Filter Filter = Previous.makeFilter();
2480 while (Filter.hasNext()) {
2481 NamedDecl *Old = Filter.next();
2482
2483 // Non-hidden declarations are never ignored.
2484 if (S.isVisible(Old))
2485 continue;
2486
2487 // Declarations of the same entity are not ignored, even if they have
2488 // different linkages.
2489 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2490 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2491 Decl->getUnderlyingType()))
2492 continue;
2493
2494 // If both declarations give a tag declaration a typedef name for linkage
2495 // purposes, then they declare the same entity.
2496 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2497 Decl->getAnonDeclWithTypedefName())
2498 continue;
2499 }
2500
2501 Filter.erase();
2502 }
2503
2504 Filter.done();
2505}
2506
2508 QualType OldType;
2509 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2510 OldType = OldTypedef->getUnderlyingType();
2511 else
2512 OldType = Context.getTypeDeclType(Old);
2513 QualType NewType = New->getUnderlyingType();
2514
2515 if (NewType->isVariablyModifiedType()) {
2516 // Must not redefine a typedef with a variably-modified type.
2517 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2518 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2519 << Kind << NewType;
2520 if (Old->getLocation().isValid())
2522 New->setInvalidDecl();
2523 return true;
2524 }
2525
2526 if (OldType != NewType &&
2527 !OldType->isDependentType() &&
2528 !NewType->isDependentType() &&
2529 !Context.hasSameType(OldType, NewType)) {
2530 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2531 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2532 << Kind << NewType << OldType;
2533 if (Old->getLocation().isValid())
2535 New->setInvalidDecl();
2536 return true;
2537 }
2538 return false;
2539}
2540
2541/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2542/// same name and scope as a previous declaration 'Old'. Figure out
2543/// how to resolve this situation, merging decls or emitting
2544/// diagnostics as appropriate. If there was an error, set New to be invalid.
2545///
2547 LookupResult &OldDecls) {
2548 // If the new decl is known invalid already, don't bother doing any
2549 // merging checks.
2550 if (New->isInvalidDecl()) return;
2551
2552 // Allow multiple definitions for ObjC built-in typedefs.
2553 // FIXME: Verify the underlying types are equivalent!
2554 if (getLangOpts().ObjC) {
2555 const IdentifierInfo *TypeID = New->getIdentifier();
2556 switch (TypeID->getLength()) {
2557 default: break;
2558 case 2:
2559 {
2560 if (!TypeID->isStr("id"))
2561 break;
2562 QualType T = New->getUnderlyingType();
2563 if (!T->isPointerType())
2564 break;
2565 if (!T->isVoidPointerType()) {
2566 QualType PT = T->castAs<PointerType>()->getPointeeType();
2567 if (!PT->isStructureType())
2568 break;
2569 }
2571 // Install the built-in type for 'id', ignoring the current definition.
2573 return;
2574 }
2575 case 5:
2576 if (!TypeID->isStr("Class"))
2577 break;
2579 // Install the built-in type for 'Class', ignoring the current definition.
2581 return;
2582 case 3:
2583 if (!TypeID->isStr("SEL"))
2584 break;
2586 // Install the built-in type for 'SEL', ignoring the current definition.
2588 return;
2589 }
2590 // Fall through - the typedef name was not a builtin type.
2591 }
2592
2593 // Verify the old decl was also a type.
2594 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2595 if (!Old) {
2596 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2597 << New->getDeclName();
2598
2599 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2600 if (OldD->getLocation().isValid())
2601 notePreviousDefinition(OldD, New->getLocation());
2602
2603 return New->setInvalidDecl();
2604 }
2605
2606 // If the old declaration is invalid, just give up here.
2607 if (Old->isInvalidDecl())
2608 return New->setInvalidDecl();
2609
2610 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2611 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2612 auto *NewTag = New->getAnonDeclWithTypedefName();
2613 NamedDecl *Hidden = nullptr;
2614 if (OldTag && NewTag &&
2615 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2616 !hasVisibleDefinition(OldTag, &Hidden)) {
2617 // There is a definition of this tag, but it is not visible. Use it
2618 // instead of our tag.
2619 New->setTypeForDecl(OldTD->getTypeForDecl());
2620 if (OldTD->isModed())
2621 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2622 OldTD->getUnderlyingType());
2623 else
2624 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2625
2626 // Make the old tag definition visible.
2628
2629 // If this was an unscoped enumeration, yank all of its enumerators
2630 // out of the scope.
2631 if (isa<EnumDecl>(NewTag)) {
2632 Scope *EnumScope = getNonFieldDeclScope(S);
2633 for (auto *D : NewTag->decls()) {
2634 auto *ED = cast<EnumConstantDecl>(D);
2635 assert(EnumScope->isDeclScope(ED));
2636 EnumScope->RemoveDecl(ED);
2638 ED->getLexicalDeclContext()->removeDecl(ED);
2639 }
2640 }
2641 }
2642 }
2643
2644 // If the typedef types are not identical, reject them in all languages and
2645 // with any extensions enabled.
2646 if (isIncompatibleTypedef(Old, New))
2647 return;
2648
2649 // The types match. Link up the redeclaration chain and merge attributes if
2650 // the old declaration was a typedef.
2651 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2652 New->setPreviousDecl(Typedef);
2653 mergeDeclAttributes(New, Old);
2654 }
2655
2656 if (getLangOpts().MicrosoftExt)
2657 return;
2658
2659 if (getLangOpts().CPlusPlus) {
2660 // C++ [dcl.typedef]p2:
2661 // In a given non-class scope, a typedef specifier can be used to
2662 // redefine the name of any type declared in that scope to refer
2663 // to the type to which it already refers.
2664 if (!isa<CXXRecordDecl>(CurContext))
2665 return;
2666
2667 // C++0x [dcl.typedef]p4:
2668 // In a given class scope, a typedef specifier can be used to redefine
2669 // any class-name declared in that scope that is not also a typedef-name
2670 // to refer to the type to which it already refers.
2671 //
2672 // This wording came in via DR424, which was a correction to the
2673 // wording in DR56, which accidentally banned code like:
2674 //
2675 // struct S {
2676 // typedef struct A { } A;
2677 // };
2678 //
2679 // in the C++03 standard. We implement the C++0x semantics, which
2680 // allow the above but disallow
2681 //
2682 // struct S {
2683 // typedef int I;
2684 // typedef int I;
2685 // };
2686 //
2687 // since that was the intent of DR56.
2688 if (!isa<TypedefNameDecl>(Old))
2689 return;
2690
2691 Diag(New->getLocation(), diag::err_redefinition)
2692 << New->getDeclName();
2694 return New->setInvalidDecl();
2695 }
2696
2697 // Modules always permit redefinition of typedefs, as does C11.
2698 if (getLangOpts().Modules || getLangOpts().C11)
2699 return;
2700
2701 // If we have a redefinition of a typedef in C, emit a warning. This warning
2702 // is normally mapped to an error, but can be controlled with
2703 // -Wtypedef-redefinition. If either the original or the redefinition is
2704 // in a system header, don't emit this for compatibility with GCC.
2705 if (getDiagnostics().getSuppressSystemWarnings() &&
2706 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2707 (Old->isImplicit() ||
2710 return;
2711
2712 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2713 << New->getDeclName();
2715}
2716
2717/// DeclhasAttr - returns true if decl Declaration already has the target
2718/// attribute.
2719static bool DeclHasAttr(const Decl *D, const Attr *A) {
2720 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2721 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2722 for (const auto *i : D->attrs())
2723 if (i->getKind() == A->getKind()) {
2724 if (Ann) {
2725 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2726 return true;
2727 continue;
2728 }
2729 // FIXME: Don't hardcode this check
2730 if (OA && isa<OwnershipAttr>(i))
2731 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2732 return true;
2733 }
2734
2735 return false;
2736}
2737
2739 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2740 return VD->isThisDeclarationADefinition();
2741 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2742 return TD->isCompleteDefinition() || TD->isBeingDefined();
2743 return true;
2744}
2745
2746/// Merge alignment attributes from \p Old to \p New, taking into account the
2747/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2748///
2749/// \return \c true if any attributes were added to \p New.
2750static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2751 // Look for alignas attributes on Old, and pick out whichever attribute
2752 // specifies the strictest alignment requirement.
2753 AlignedAttr *OldAlignasAttr = nullptr;
2754 AlignedAttr *OldStrictestAlignAttr = nullptr;
2755 unsigned OldAlign = 0;
2756 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2757 // FIXME: We have no way of representing inherited dependent alignments
2758 // in a case like:
2759 // template<int A, int B> struct alignas(A) X;
2760 // template<int A, int B> struct alignas(B) X {};
2761 // For now, we just ignore any alignas attributes which are not on the
2762 // definition in such a case.
2763 if (I->isAlignmentDependent())
2764 return false;
2765
2766 if (I->isAlignas())
2767 OldAlignasAttr = I;
2768
2769 unsigned Align = I->getAlignment(S.Context);
2770 if (Align > OldAlign) {
2771 OldAlign = Align;
2772 OldStrictestAlignAttr = I;
2773 }
2774 }
2775
2776 // Look for alignas attributes on New.
2777 AlignedAttr *NewAlignasAttr = nullptr;
2778 unsigned NewAlign = 0;
2779 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2780 if (I->isAlignmentDependent())
2781 return false;
2782
2783 if (I->isAlignas())
2784 NewAlignasAttr = I;
2785
2786 unsigned Align = I->getAlignment(S.Context);
2787 if (Align > NewAlign)
2788 NewAlign = Align;
2789 }
2790
2791 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2792 // Both declarations have 'alignas' attributes. We require them to match.
2793 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2794 // fall short. (If two declarations both have alignas, they must both match
2795 // every definition, and so must match each other if there is a definition.)
2796
2797 // If either declaration only contains 'alignas(0)' specifiers, then it
2798 // specifies the natural alignment for the type.
2799 if (OldAlign == 0 || NewAlign == 0) {
2800 QualType Ty;
2801 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2802 Ty = VD->getType();
2803 else
2804 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2805
2806 if (OldAlign == 0)
2807 OldAlign = S.Context.getTypeAlign(Ty);
2808 if (NewAlign == 0)
2809 NewAlign = S.Context.getTypeAlign(Ty);
2810 }
2811
2812 if (OldAlign != NewAlign) {
2813 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2816 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2817 }
2818 }
2819
2820 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2821 // C++11 [dcl.align]p6:
2822 // if any declaration of an entity has an alignment-specifier,
2823 // every defining declaration of that entity shall specify an
2824 // equivalent alignment.
2825 // C11 6.7.5/7:
2826 // If the definition of an object does not have an alignment
2827 // specifier, any other declaration of that object shall also
2828 // have no alignment specifier.
2829 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2830 << OldAlignasAttr;
2831 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2832 << OldAlignasAttr;
2833 }
2834
2835 bool AnyAdded = false;
2836
2837 // Ensure we have an attribute representing the strictest alignment.
2838 if (OldAlign > NewAlign) {
2839 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2840 Clone->setInherited(true);
2841 New->addAttr(Clone);
2842 AnyAdded = true;
2843 }
2844
2845 // Ensure we have an alignas attribute if the old declaration had one.
2846 if (OldAlignasAttr && !NewAlignasAttr &&
2847 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2848 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2849 Clone->setInherited(true);
2850 New->addAttr(Clone);
2851 AnyAdded = true;
2852 }
2853
2854 return AnyAdded;
2855}
2856
2857#define WANT_DECL_MERGE_LOGIC
2858#include "clang/Sema/AttrParsedAttrImpl.inc"
2859#undef WANT_DECL_MERGE_LOGIC
2860
2862 const InheritableAttr *Attr,
2864 // Diagnose any mutual exclusions between the attribute that we want to add
2865 // and attributes that already exist on the declaration.
2866 if (!DiagnoseMutualExclusions(S, D, Attr))
2867 return false;
2868
2869 // This function copies an attribute Attr from a previous declaration to the
2870 // new declaration D if the new declaration doesn't itself have that attribute
2871 // yet or if that attribute allows duplicates.
2872 // If you're adding a new attribute that requires logic different from
2873 // "use explicit attribute on decl if present, else use attribute from
2874 // previous decl", for example if the attribute needs to be consistent
2875 // between redeclarations, you need to call a custom merge function here.
2876 InheritableAttr *NewAttr = nullptr;
2877 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2878 NewAttr = S.mergeAvailabilityAttr(
2879 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2880 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2881 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2882 AA->getPriority(), AA->getEnvironment());
2883 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2884 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2885 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2886 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2887 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2888 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2889 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2890 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2891 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2892 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2893 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2894 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2895 FA->getFirstArg());
2896 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2897 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2898 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2899 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2900 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2901 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2902 IA->getInheritanceModel());
2903 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2904 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2905 &S.Context.Idents.get(AA->getSpelling()));
2906 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2907 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2908 isa<CUDAGlobalAttr>(Attr))) {
2909 // CUDA target attributes are part of function signature for
2910 // overloading purposes and must not be merged.
2911 return false;
2912 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2913 NewAttr = S.mergeMinSizeAttr(D, *MA);
2914 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2915 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2916 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2917 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2918 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2919 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2920 else if (isa<AlignedAttr>(Attr))
2921 // AlignedAttrs are handled separately, because we need to handle all
2922 // such attributes on a declaration at the same time.
2923 NewAttr = nullptr;
2924 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2925 (AMK == Sema::AMK_Override ||
2928 NewAttr = nullptr;
2929 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2930 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2931 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2932 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2933 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2934 NewAttr = S.mergeImportNameAttr(D, *INA);
2935 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2936 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2937 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2938 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2939 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2940 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2941 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2942 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2943 NT->getZ());
2944 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2945 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2946 else if (isa<SuppressAttr>(Attr))
2947 // Do nothing. Each redeclaration should be suppressed separately.
2948 NewAttr = nullptr;
2949 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2950 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2951
2952 if (NewAttr) {
2953 NewAttr->setInherited(true);
2954 D->addAttr(NewAttr);
2955 if (isa<MSInheritanceAttr>(NewAttr))
2956 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2957 return true;
2958 }
2959
2960 return false;
2961}
2962
2963static const NamedDecl *getDefinition(const Decl *D) {
2964 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2965 return TD->getDefinition();
2966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2967 const VarDecl *Def = VD->getDefinition();
2968 if (Def)
2969 return Def;
2970 return VD->getActingDefinition();
2971 }
2972 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2973 const FunctionDecl *Def = nullptr;
2974 if (FD->isDefined(Def, true))
2975 return Def;
2976 }
2977 return nullptr;
2978}
2979
2980static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2981 for (const auto *Attribute : D->attrs())
2982 if (Attribute->getKind() == Kind)
2983 return true;
2984 return false;
2985}
2986
2987/// checkNewAttributesAfterDef - If we already have a definition, check that
2988/// there are no new attributes in this declaration.
2989static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2990 if (!New->hasAttrs())
2991 return;
2992
2993 const NamedDecl *Def = getDefinition(Old);
2994 if (!Def || Def == New)
2995 return;
2996
2997 AttrVec &NewAttributes = New->getAttrs();
2998 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2999 const Attr *NewAttribute = NewAttributes[I];
3000
3001 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3002 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3003 SkipBodyInfo SkipBody;
3004 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3005
3006 // If we're skipping this definition, drop the "alias" attribute.
3007 if (SkipBody.ShouldSkip) {
3008 NewAttributes.erase(NewAttributes.begin() + I);
3009 --E;
3010 continue;
3011 }
3012 } else {
3013 VarDecl *VD = cast<VarDecl>(New);
3014 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3016 ? diag::err_alias_after_tentative
3017 : diag::err_redefinition;
3018 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3019 if (Diag == diag::err_redefinition)
3020 S.notePreviousDefinition(Def, VD->getLocation());
3021 else
3022 S.Diag(Def->getLocation(), diag::note_previous_definition);
3023 VD->setInvalidDecl();
3024 }
3025 ++I;
3026 continue;
3027 }
3028
3029 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3030 // Tentative definitions are only interesting for the alias check above.
3031 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3032 ++I;
3033 continue;
3034 }
3035 }
3036
3037 if (hasAttribute(Def, NewAttribute->getKind())) {
3038 ++I;
3039 continue; // regular attr merging will take care of validating this.
3040 }
3041
3042 if (isa<C11NoReturnAttr>(NewAttribute)) {
3043 // C's _Noreturn is allowed to be added to a function after it is defined.
3044 ++I;
3045 continue;
3046 } else if (isa<UuidAttr>(NewAttribute)) {
3047 // msvc will allow a subsequent definition to add an uuid to a class
3048 ++I;
3049 continue;
3050 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3051 if (AA->isAlignas()) {
3052 // C++11 [dcl.align]p6:
3053 // if any declaration of an entity has an alignment-specifier,
3054 // every defining declaration of that entity shall specify an
3055 // equivalent alignment.
3056 // C11 6.7.5/7:
3057 // If the definition of an object does not have an alignment
3058 // specifier, any other declaration of that object shall also
3059 // have no alignment specifier.
3060 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3061 << AA;
3062 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3063 << AA;
3064 NewAttributes.erase(NewAttributes.begin() + I);
3065 --E;
3066 continue;
3067 }
3068 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3069 // If there is a C definition followed by a redeclaration with this
3070 // attribute then there are two different definitions. In C++, prefer the
3071 // standard diagnostics.
3072 if (!S.getLangOpts().CPlusPlus) {
3073 S.Diag(NewAttribute->getLocation(),
3074 diag::err_loader_uninitialized_redeclaration);
3075 S.Diag(Def->getLocation(), diag::note_previous_definition);
3076 NewAttributes.erase(NewAttributes.begin() + I);
3077 --E;
3078 continue;
3079 }
3080 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3081 cast<VarDecl>(New)->isInline() &&
3082 !cast<VarDecl>(New)->isInlineSpecified()) {
3083 // Don't warn about applying selectany to implicitly inline variables.
3084 // Older compilers and language modes would require the use of selectany
3085 // to make such variables inline, and it would have no effect if we
3086 // honored it.
3087 ++I;
3088 continue;
3089 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3090 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3091 // declarations after definitions.
3092 ++I;
3093 continue;
3094 }
3095
3096 S.Diag(NewAttribute->getLocation(),
3097 diag::warn_attribute_precede_definition);
3098 S.Diag(Def->getLocation(), diag::note_previous_definition);
3099 NewAttributes.erase(NewAttributes.begin() + I);
3100 --E;
3101 }
3102}
3103
3104static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3105 const ConstInitAttr *CIAttr,
3106 bool AttrBeforeInit) {
3107 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3108
3109 // Figure out a good way to write this specifier on the old declaration.
3110 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3111 // enough of the attribute list spelling information to extract that without
3112 // heroics.
3113 std::string SuitableSpelling;
3114 if (S.getLangOpts().CPlusPlus20)
3115 SuitableSpelling = std::string(
3116 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3117 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3118 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3119 InsertLoc, {tok::l_square, tok::l_square,
3120 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3121 S.PP.getIdentifierInfo("require_constant_initialization"),
3122 tok::r_square, tok::r_square}));
3123 if (SuitableSpelling.empty())
3124 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3125 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3126 S.PP.getIdentifierInfo("require_constant_initialization"),
3127 tok::r_paren, tok::r_paren}));
3128 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3129 SuitableSpelling = "constinit";
3130 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3131 SuitableSpelling = "[[clang::require_constant_initialization]]";
3132 if (SuitableSpelling.empty())
3133 SuitableSpelling = "__attribute__((require_constant_initialization))";
3134 SuitableSpelling += " ";
3135
3136 if (AttrBeforeInit) {
3137 // extern constinit int a;
3138 // int a = 0; // error (missing 'constinit'), accepted as extension
3139 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3140 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3141 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3142 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3143 } else {
3144 // int a = 0;
3145 // constinit extern int a; // error (missing 'constinit')
3146 S.Diag(CIAttr->getLocation(),
3147 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3148 : diag::warn_require_const_init_added_too_late)
3149 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3150 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3151 << CIAttr->isConstinit()
3152 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3153 }
3154}
3155
3156/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3159 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3160 UsedAttr *NewAttr = OldAttr->clone(Context);
3161 NewAttr->setInherited(true);
3162 New->addAttr(NewAttr);
3163 }
3164 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3165 RetainAttr *NewAttr = OldAttr->clone(Context);
3166 NewAttr->setInherited(true);
3167 New->addAttr(NewAttr);
3168 }
3169
3170 if (!Old->hasAttrs() && !New->hasAttrs())
3171 return;
3172
3173 // [dcl.constinit]p1:
3174 // If the [constinit] specifier is applied to any declaration of a
3175 // variable, it shall be applied to the initializing declaration.
3176 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3177 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3178 if (bool(OldConstInit) != bool(NewConstInit)) {
3179 const auto *OldVD = cast<VarDecl>(Old);
3180 auto *NewVD = cast<VarDecl>(New);
3181
3182 // Find the initializing declaration. Note that we might not have linked
3183 // the new declaration into the redeclaration chain yet.
3184 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3185 if (!InitDecl &&
3186 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3187 InitDecl = NewVD;
3188
3189 if (InitDecl == NewVD) {
3190 // This is the initializing declaration. If it would inherit 'constinit',
3191 // that's ill-formed. (Note that we do not apply this to the attribute
3192 // form).
3193 if (OldConstInit && OldConstInit->isConstinit())
3194 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3195 /*AttrBeforeInit=*/true);
3196 } else if (NewConstInit) {
3197 // This is the first time we've been told that this declaration should
3198 // have a constant initializer. If we already saw the initializing
3199 // declaration, this is too late.
3200 if (InitDecl && InitDecl != NewVD) {
3201 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3202 /*AttrBeforeInit=*/false);
3203 NewVD->dropAttr<ConstInitAttr>();
3204 }
3205 }
3206 }
3207
3208 // Attributes declared post-definition are currently ignored.
3209 checkNewAttributesAfterDef(*this, New, Old);
3210
3211 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3212 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3213 if (!OldA->isEquivalent(NewA)) {
3214 // This redeclaration changes __asm__ label.
3215 Diag(New->getLocation(), diag::err_different_asm_label);
3216 Diag(OldA->getLocation(), diag::note_previous_declaration);
3217 }
3218 } else if (Old->isUsed()) {
3219 // This redeclaration adds an __asm__ label to a declaration that has
3220 // already been ODR-used.
3221 Diag(New->getLocation(), diag::err_late_asm_label_name)
3222 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3223 }
3224 }
3225
3226 // Re-declaration cannot add abi_tag's.
3227 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3228 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3229 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3230 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3231 Diag(NewAbiTagAttr->getLocation(),
3232 diag::err_new_abi_tag_on_redeclaration)
3233 << NewTag;
3234 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3235 }
3236 }
3237 } else {
3238 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3239 Diag(Old->getLocation(), diag::note_previous_declaration);
3240 }
3241 }
3242
3243 // This redeclaration adds a section attribute.
3244 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3245 if (auto *VD = dyn_cast<VarDecl>(New)) {
3246 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3247 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3248 Diag(Old->getLocation(), diag::note_previous_declaration);
3249 }
3250 }
3251 }
3252
3253 // Redeclaration adds code-seg attribute.
3254 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3255 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3256 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3257 Diag(New->getLocation(), diag::warn_mismatched_section)
3258 << 0 /*codeseg*/;
3259 Diag(Old->getLocation(), diag::note_previous_declaration);
3260 }
3261
3262 if (!Old->hasAttrs())
3263 return;
3264
3265 bool foundAny = New->hasAttrs();
3266
3267 // Ensure that any moving of objects within the allocated map is done before
3268 // we process them.
3269 if (!foundAny) New->setAttrs(AttrVec());
3270
3271 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3272 // Ignore deprecated/unavailable/availability attributes if requested.
3274 if (isa<DeprecatedAttr>(I) ||
3275 isa<UnavailableAttr>(I) ||
3276 isa<AvailabilityAttr>(I)) {
3277 switch (AMK) {
3278 case AMK_None:
3279 continue;
3280
3281 case AMK_Redeclaration:
3282 case AMK_Override:
3285 LocalAMK = AMK;
3286 break;
3287 }
3288 }
3289
3290 // Already handled.
3291 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3292 continue;
3293
3294 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3295 foundAny = true;
3296 }
3297
3298 if (mergeAlignedAttrs(*this, New, Old))
3299 foundAny = true;
3300
3301 if (!foundAny) New->dropAttrs();
3302}
3303
3304/// mergeParamDeclAttributes - Copy attributes from the old parameter
3305/// to the new one.
3307 const ParmVarDecl *oldDecl,
3308 Sema &S) {
3309 // C++11 [dcl.attr.depend]p2:
3310 // The first declaration of a function shall specify the
3311 // carries_dependency attribute for its declarator-id if any declaration
3312 // of the function specifies the carries_dependency attribute.
3313 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3314 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3315 S.Diag(CDA->getLocation(),
3316 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3317 // Find the first declaration of the parameter.
3318 // FIXME: Should we build redeclaration chains for function parameters?
3319 const FunctionDecl *FirstFD =
3320 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3321 const ParmVarDecl *FirstVD =
3322 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3323 S.Diag(FirstVD->getLocation(),
3324 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3325 }
3326
3327 // HLSL parameter declarations for inout and out must match between
3328 // declarations. In HLSL inout and out are ambiguous at the call site, but
3329 // have different calling behavior, so you cannot overload a method based on a
3330 // difference between inout and out annotations.
3331 if (S.getLangOpts().HLSL) {
3332 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3333 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3334 // We don't need to cover the case where one declaration doesn't have an
3335 // attribute. The only possible case there is if one declaration has an `in`
3336 // attribute and the other declaration has no attribute. This case is
3337 // allowed since parameters are `in` by default.
3338 if (NDAttr && ODAttr &&
3339 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3340 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3341 << NDAttr << newDecl;
3342 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3343 << ODAttr;
3344 }
3345 }
3346
3347 if (!oldDecl->hasAttrs())
3348 return;
3349
3350 bool foundAny = newDecl->hasAttrs();
3351
3352 // Ensure that any moving of objects within the allocated map is
3353 // done before we process them.
3354 if (!foundAny) newDecl->setAttrs(AttrVec());
3355
3356 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3357 if (!DeclHasAttr(newDecl, I)) {
3358 InheritableAttr *newAttr =
3359 cast<InheritableParamAttr>(I->clone(S.Context));
3360 newAttr->setInherited(true);
3361 newDecl->addAttr(newAttr);
3362 foundAny = true;
3363 }
3364 }
3365
3366 if (!foundAny) newDecl->dropAttrs();
3367}
3368
3370 const ASTContext &Ctx) {
3371
3372 auto NoSizeInfo = [&Ctx](QualType Ty) {
3373 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3374 return true;
3375 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3376 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3377 return false;
3378 };
3379
3380 // `type[]` is equivalent to `type *` and `type[*]`.
3381 if (NoSizeInfo(Old) && NoSizeInfo(New))
3382 return true;
3383
3384 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3385 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3386 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3387 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3388 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3389 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3390 return false;
3391 return true;
3392 }
3393
3394 // Only compare size, ignore Size modifiers and CVR.
3395 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3396 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3397 Ctx.getAsConstantArrayType(New)->getSize();
3398 }
3399
3400 // Don't try to compare dependent sized array
3402 return true;
3403 }
3404
3405 return Old == New;
3406}
3407
3408static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3409 const ParmVarDecl *OldParam,
3410 Sema &S) {
3411 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3412 if (auto Newnullability = NewParam->getType()->getNullability()) {
3413 if (*Oldnullability != *Newnullability) {
3414 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3416 *Newnullability,
3418 != 0))
3420 *Oldnullability,
3422 != 0));
3423 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3424 }
3425 } else {
3426 QualType NewT = NewParam->getType();
3427 NewT = S.Context.getAttributedType(
3429 NewT, NewT);
3430 NewParam->setType(NewT);
3431 }
3432 }
3433 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3434 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3435 if (OldParamDT && NewParamDT &&
3436 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3437 QualType OldParamOT = OldParamDT->getOriginalType();
3438 QualType NewParamOT = NewParamDT->getOriginalType();
3439 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3440 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3441 << NewParam << NewParamOT;
3442 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3443 << OldParamOT;
3444 }
3445 }
3446}
3447
3448namespace {
3449
3450/// Used in MergeFunctionDecl to keep track of function parameters in
3451/// C.
3452struct GNUCompatibleParamWarning {
3453 ParmVarDecl *OldParm;
3454 ParmVarDecl *NewParm;
3455 QualType PromotedType;
3456};
3457
3458} // end anonymous namespace
3459
3460// Determine whether the previous declaration was a definition, implicit
3461// declaration, or a declaration.
3462template <typename T>
3463static std::pair<diag::kind, SourceLocation>
3464getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3465 diag::kind PrevDiag;
3466 SourceLocation OldLocation = Old->getLocation();
3467 if (Old->isThisDeclarationADefinition())
3468 PrevDiag = diag::note_previous_definition;
3469 else if (Old->isImplicit()) {
3470 PrevDiag = diag::note_previous_implicit_declaration;
3471 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3472 if (FD->getBuiltinID())
3473 PrevDiag = diag::note_previous_builtin_declaration;
3474 }
3475 if (OldLocation.isInvalid())
3476 OldLocation = New->getLocation();
3477 } else
3478 PrevDiag = diag::note_previous_declaration;
3479 return std::make_pair(PrevDiag, OldLocation);
3480}
3481
3482/// canRedefineFunction - checks if a function can be redefined. Currently,
3483/// only extern inline functions can be redefined, and even then only in
3484/// GNU89 mode.
3485static bool canRedefineFunction(const FunctionDecl *FD,
3486 const LangOptions& LangOpts) {
3487 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3488 !LangOpts.CPlusPlus &&
3489 FD->isInlineSpecified() &&
3490 FD->getStorageClass() == SC_Extern);
3491}
3492
3494 const AttributedType *AT = T->getAs<AttributedType>();
3495 while (AT && !AT->isCallingConv())
3496 AT = AT->getModifiedType()->getAs<AttributedType>();
3497 return AT;
3498}
3499
3500template <typename T>
3501static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3502 const DeclContext *DC = Old->getDeclContext();
3503 if (DC->isRecord())
3504 return false;
3505
3506 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3507 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3508 return true;
3509 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3510 return true;
3511 return false;
3512}
3513
3514template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3515static bool isExternC(VarTemplateDecl *) { return false; }
3516static bool isExternC(FunctionTemplateDecl *) { return false; }
3517
3518/// Check whether a redeclaration of an entity introduced by a
3519/// using-declaration is valid, given that we know it's not an overload
3520/// (nor a hidden tag declaration).
3521template<typename ExpectedDecl>
3523 ExpectedDecl *New) {
3524 // C++11 [basic.scope.declarative]p4:
3525 // Given a set of declarations in a single declarative region, each of
3526 // which specifies the same unqualified name,
3527 // -- they shall all refer to the same entity, or all refer to functions
3528 // and function templates; or
3529 // -- exactly one declaration shall declare a class name or enumeration
3530 // name that is not a typedef name and the other declarations shall all
3531 // refer to the same variable or enumerator, or all refer to functions
3532 // and function templates; in this case the class name or enumeration
3533 // name is hidden (3.3.10).
3534
3535 // C++11 [namespace.udecl]p14:
3536 // If a function declaration in namespace scope or block scope has the
3537 // same name and the same parameter-type-list as a function introduced
3538 // by a using-declaration, and the declarations do not declare the same
3539 // function, the program is ill-formed.
3540
3541 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3542 if (Old &&
3543 !Old->getDeclContext()->getRedeclContext()->Equals(
3544 New->getDeclContext()->getRedeclContext()) &&
3545 !(isExternC(Old) && isExternC(New)))
3546 Old = nullptr;
3547
3548 if (!Old) {
3549 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3550 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3551 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3552 return true;
3553 }
3554 return false;
3555}
3556
3558 const FunctionDecl *B) {
3559 assert(A->getNumParams() == B->getNumParams());
3560
3561 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3562 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3563 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3564 if (AttrA == AttrB)
3565 return true;
3566 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3567 AttrA->isDynamic() == AttrB->isDynamic();
3568 };
3569
3570 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3571}
3572
3573/// If necessary, adjust the semantic declaration context for a qualified
3574/// declaration to name the correct inline namespace within the qualifier.
3576 DeclaratorDecl *OldD) {
3577 // The only case where we need to update the DeclContext is when
3578 // redeclaration lookup for a qualified name finds a declaration
3579 // in an inline namespace within the context named by the qualifier:
3580 //
3581 // inline namespace N { int f(); }
3582 // int ::f(); // Sema DC needs adjusting from :: to N::.
3583 //
3584 // For unqualified declarations, the semantic context *can* change
3585 // along the redeclaration chain (for local extern declarations,
3586 // extern "C" declarations, and friend declarations in particular).
3587 if (!NewD->getQualifier())
3588 return;
3589
3590 // NewD is probably already in the right context.
3591 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3592 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3593 if (NamedDC->Equals(SemaDC))
3594 return;
3595
3596 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3597 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3598 "unexpected context for redeclaration");
3599
3600 auto *LexDC = NewD->getLexicalDeclContext();
3601 auto FixSemaDC = [=](NamedDecl *D) {
3602 if (!D)
3603 return;
3604 D->setDeclContext(SemaDC);
3605 D->setLexicalDeclContext(LexDC);
3606 };
3607
3608 FixSemaDC(NewD);
3609 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3610 FixSemaDC(FD->getDescribedFunctionTemplate());
3611 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3612 FixSemaDC(VD->getDescribedVarTemplate());
3613}
3614
3615/// MergeFunctionDecl - We just parsed a function 'New' from
3616/// declarator D which has the same name and scope as a previous
3617/// declaration 'Old'. Figure out how to resolve this situation,
3618/// merging decls or emitting diagnostics as appropriate.
3619///
3620/// In C++, New and Old must be declarations that are not
3621/// overloaded. Use IsOverload to determine whether New and Old are
3622/// overloaded, and to select the Old declaration that New should be
3623/// merged with.
3624///
3625/// Returns true if there was an error, false otherwise.
3627 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3628 // Verify the old decl was also a function.
3629 FunctionDecl *Old = OldD->getAsFunction();
3630 if (!Old) {
3631 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3632 if (New->getFriendObjectKind()) {
3633 Diag(New->getLocation(), diag::err_using_decl_friend);
3634 Diag(Shadow->getTargetDecl()->getLocation(),
3635 diag::note_using_decl_target);
3636 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3637 << 0;
3638 return true;
3639 }
3640
3641 // Check whether the two declarations might declare the same function or
3642 // function template.
3643 if (FunctionTemplateDecl *NewTemplate =
3645 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3646 NewTemplate))
3647 return true;
3648 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3649 ->getAsFunction();
3650 } else {
3651 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3652 return true;
3653 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3654 }
3655 } else {
3656 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3657 << New->getDeclName();
3658 notePreviousDefinition(OldD, New->getLocation());
3659 return true;
3660 }
3661 }
3662
3663 // If the old declaration was found in an inline namespace and the new
3664 // declaration was qualified, update the DeclContext to match.
3666
3667 // If the old declaration is invalid, just give up here.
3668 if (Old->isInvalidDecl())
3669 return true;
3670
3671 // Disallow redeclaration of some builtins.
3672 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3673 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3674 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3675 << Old << Old->getType();
3676 return true;
3677 }
3678
3679 diag::kind PrevDiag;
3680 SourceLocation OldLocation;
3681 std::tie(PrevDiag, OldLocation) =
3683
3684 // Don't complain about this if we're in GNU89 mode and the old function
3685 // is an extern inline function.
3686 // Don't complain about specializations. They are not supposed to have
3687 // storage classes.
3688 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3689 New->getStorageClass() == SC_Static &&
3690 Old->hasExternalFormalLinkage() &&
3693 if (getLangOpts().MicrosoftExt) {
3694 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3695 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3696 } else {
3697 Diag(New->getLocation(), diag::err_static_non_static) << New;
3698 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3699 return true;
3700 }
3701 }
3702
3703 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3704 if (!Old->hasAttr<InternalLinkageAttr>()) {
3705 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3706 << ILA;
3707 Diag(Old->getLocation(), diag::note_previous_declaration);
3708 New->dropAttr<InternalLinkageAttr>();
3709 }
3710
3711 if (auto *EA = New->getAttr<ErrorAttr>()) {
3712 if (!Old->hasAttr<ErrorAttr>()) {
3713 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3714 Diag(Old->getLocation(), diag::note_previous_declaration);
3715 New->dropAttr<ErrorAttr>();
3716 }
3717 }
3718
3719 if (CheckRedeclarationInModule(New, Old))
3720 return true;
3721
3722 if (!getLangOpts().CPlusPlus) {
3723 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3724 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3725 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3726 << New << OldOvl;
3727
3728 // Try our best to find a decl that actually has the overloadable
3729 // attribute for the note. In most cases (e.g. programs with only one
3730 // broken declaration/definition), this won't matter.
3731 //
3732 // FIXME: We could do this if we juggled some extra state in
3733 // OverloadableAttr, rather than just removing it.
3734 const Decl *DiagOld = Old;
3735 if (OldOvl) {
3736 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3737 const auto *A = D->getAttr<OverloadableAttr>();
3738 return A && !A->isImplicit();
3739 });
3740 // If we've implicitly added *all* of the overloadable attrs to this
3741 // chain, emitting a "previous redecl" note is pointless.
3742 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3743 }
3744
3745 if (DiagOld)
3746 Diag(DiagOld->getLocation(),
3747 diag::note_attribute_overloadable_prev_overload)
3748 << OldOvl;
3749
3750 if (OldOvl)
3751 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3752 else
3753 New->dropAttr<OverloadableAttr>();
3754 }
3755 }
3756
3757 // It is not permitted to redeclare an SME function with different SME
3758 // attributes.
3759 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3760 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3761 << New->getType() << Old->getType();
3762 Diag(OldLocation, diag::note_previous_declaration);
3763 return true;
3764 }
3765
3766 // If a function is first declared with a calling convention, but is later
3767 // declared or defined without one, all following decls assume the calling
3768 // convention of the first.
3769 //
3770 // It's OK if a function is first declared without a calling convention,
3771 // but is later declared or defined with the default calling convention.
3772 //
3773 // To test if either decl has an explicit calling convention, we look for
3774 // AttributedType sugar nodes on the type as written. If they are missing or
3775 // were canonicalized away, we assume the calling convention was implicit.
3776 //
3777 // Note also that we DO NOT return at this point, because we still have
3778 // other tests to run.
3779 QualType OldQType = Context.getCanonicalType(Old->getType());
3780 QualType NewQType = Context.getCanonicalType(New->getType());
3781 const FunctionType *OldType = cast<FunctionType>(OldQType);
3782 const FunctionType *NewType = cast<FunctionType>(NewQType);
3783 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3784 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3785 bool RequiresAdjustment = false;
3786
3787 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3789 const FunctionType *FT =
3790 First->getType().getCanonicalType()->castAs<FunctionType>();
3792 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3793 if (!NewCCExplicit) {
3794 // Inherit the CC from the previous declaration if it was specified
3795 // there but not here.
3796 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3797 RequiresAdjustment = true;
3798 } else if (Old->getBuiltinID()) {
3799 // Builtin attribute isn't propagated to the new one yet at this point,
3800 // so we check if the old one is a builtin.
3801
3802 // Calling Conventions on a Builtin aren't really useful and setting a
3803 // default calling convention and cdecl'ing some builtin redeclarations is
3804 // common, so warn and ignore the calling convention on the redeclaration.
3805 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3806 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3808 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3809 RequiresAdjustment = true;
3810 } else {
3811 // Calling conventions aren't compatible, so complain.
3812 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3813 Diag(New->getLocation(), diag::err_cconv_change)
3814 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3815 << !FirstCCExplicit
3816 << (!FirstCCExplicit ? "" :
3818
3819 // Put the note on the first decl, since it is the one that matters.
3820 Diag(First->getLocation(), diag::note_previous_declaration);
3821 return true;
3822 }
3823 }
3824
3825 // FIXME: diagnose the other way around?
3826 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3827 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3828 RequiresAdjustment = true;
3829 }
3830
3831 // Merge regparm attribute.
3832 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3833 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3834 if (NewTypeInfo.getHasRegParm()) {
3835 Diag(New->getLocation(), diag::err_regparm_mismatch)
3836 << NewType->getRegParmType()
3837 << OldType->getRegParmType();
3838 Diag(OldLocation, diag::note_previous_declaration);
3839 return true;
3840 }
3841
3842 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3843 RequiresAdjustment = true;
3844 }
3845
3846 // Merge ns_returns_retained attribute.
3847 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3848 if (NewTypeInfo.getProducesResult()) {
3849 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3850 << "'ns_returns_retained'";
3851 Diag(OldLocation, diag::note_previous_declaration);
3852 return true;
3853 }
3854
3855 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3856 RequiresAdjustment = true;
3857 }
3858
3859 if (OldTypeInfo.getNoCallerSavedRegs() !=
3860 NewTypeInfo.getNoCallerSavedRegs()) {
3861 if (NewTypeInfo.getNoCallerSavedRegs()) {
3862 AnyX86NoCallerSavedRegistersAttr *Attr =
3863 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3864 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3865 Diag(OldLocation, diag::note_previous_declaration);
3866 return true;
3867 }
3868
3869 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3870 RequiresAdjustment = true;
3871 }
3872
3873 if (RequiresAdjustment) {
3876 New->setType(QualType(AdjustedType, 0));
3877 NewQType = Context.getCanonicalType(New->getType());
3878 }
3879
3880 // If this redeclaration makes the function inline, we may need to add it to
3881 // UndefinedButUsed.
3882 if (!Old->isInlined() && New->isInlined() &&
3883 !New->hasAttr<GNUInlineAttr>() &&
3884 !getLangOpts().GNUInline &&
3885 Old->isUsed(false) &&
3886 !Old->isDefined() && !New->isThisDeclarationADefinition())
3887 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3888 SourceLocation()));
3889
3890 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3891 // about it.
3892 if (New->hasAttr<GNUInlineAttr>() &&
3893 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3894 UndefinedButUsed.erase(Old->getCanonicalDecl());
3895 }
3896
3897 // If pass_object_size params don't match up perfectly, this isn't a valid
3898 // redeclaration.
3899 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3901 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3902 << New->getDeclName();
3903 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3904 return true;
3905 }
3906
3907 if (getLangOpts().CPlusPlus) {
3908 OldQType = Context.getCanonicalType(Old->getType());
3909 NewQType = Context.getCanonicalType(New->getType());
3910
3911 // Go back to the type source info to compare the declared return types,
3912 // per C++1y [dcl.type.auto]p13:
3913 // Redeclarations or specializations of a function or function template
3914 // with a declared return type that uses a placeholder type shall also
3915 // use that placeholder, not a deduced type.
3916 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3917 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3918 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3919 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3920 OldDeclaredReturnType)) {
3921 QualType ResQT;
3922 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3923 OldDeclaredReturnType->isObjCObjectPointerType())
3924 // FIXME: This does the wrong thing for a deduced return type.
3925 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3926 if (ResQT.isNull()) {
3927 if (New->isCXXClassMember() && New->isOutOfLine())
3928 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3929 << New << New->getReturnTypeSourceRange();
3930 else
3931 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3932 << New->getReturnTypeSourceRange();
3933 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3934 << Old->getReturnTypeSourceRange();
3935 return true;
3936 }
3937 else
3938 NewQType = ResQT;
3939 }
3940
3941 QualType OldReturnType = OldType->getReturnType();
3942 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3943 if (OldReturnType != NewReturnType) {
3944 // If this function has a deduced return type and has already been
3945 // defined, copy the deduced value from the old declaration.
3946 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3947 if (OldAT && OldAT->isDeduced()) {
3948 QualType DT = OldAT->getDeducedType();
3949 if (DT.isNull()) {
3951 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3952 } else {
3953 New->setType(SubstAutoType(New->getType(), DT));
3954 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3955 }
3956 }
3957 }
3958
3959 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3960 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3961 if (OldMethod && NewMethod) {
3962 // Preserve triviality.
3963 NewMethod->setTrivial(OldMethod->isTrivial());
3964
3965 // MSVC allows explicit template specialization at class scope:
3966 // 2 CXXMethodDecls referring to the same function will be injected.
3967 // We don't want a redeclaration error.
3968 bool IsClassScopeExplicitSpecialization =
3969 OldMethod->isFunctionTemplateSpecialization() &&
3971 bool isFriend = NewMethod->getFriendObjectKind();
3972
3973 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3974 !IsClassScopeExplicitSpecialization) {
3975 // -- Member function declarations with the same name and the
3976 // same parameter types cannot be overloaded if any of them
3977 // is a static member function declaration.
3978 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3979 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3980 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3981 return true;
3982 }
3983
3984 // C++ [class.mem]p1:
3985 // [...] A member shall not be declared twice in the
3986 // member-specification, except that a nested class or member
3987 // class template can be declared and then later defined.
3988 if (!inTemplateInstantiation()) {
3989 unsigned NewDiag;
3990 if (isa<CXXConstructorDecl>(OldMethod))
3991 NewDiag = diag::err_constructor_redeclared;
3992 else if (isa<CXXDestructorDecl>(NewMethod))
3993 NewDiag = diag::err_destructor_redeclared;
3994 else if (isa<CXXConversionDecl>(NewMethod))
3995 NewDiag = diag::err_conv_function_redeclared;
3996 else
3997 NewDiag = diag::err_member_redeclared;
3998
3999 Diag(New->getLocation(), NewDiag);
4000 } else {
4001 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4002 << New << New->getType();
4003 }
4004 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4005 return true;
4006
4007 // Complain if this is an explicit declaration of a special
4008 // member that was initially declared implicitly.
4009 //
4010 // As an exception, it's okay to befriend such methods in order
4011 // to permit the implicit constructor/destructor/operator calls.
4012 } else if (OldMethod->isImplicit()) {
4013 if (isFriend) {
4014 NewMethod->setImplicit();
4015 } else {
4016 Diag(NewMethod->getLocation(),
4017 diag::err_definition_of_implicitly_declared_member)
4018 << New << llvm::to_underlying(getSpecialMember(OldMethod));
4019 return true;
4020 }
4021 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4022 Diag(NewMethod->getLocation(),
4023 diag::err_definition_of_explicitly_defaulted_member)
4024 << llvm::to_underlying(getSpecialMember(OldMethod));
4025 return true;
4026 }
4027 }
4028
4029 // C++1z [over.load]p2
4030 // Certain function declarations cannot be overloaded:
4031 // -- Function declarations that differ only in the return type,
4032 // the exception specification, or both cannot be overloaded.
4033
4034 // Check the exception specifications match. This may recompute the type of
4035 // both Old and New if it resolved exception specifications, so grab the
4036 // types again after this. Because this updates the type, we do this before
4037 // any of the other checks below, which may update the "de facto" NewQType
4038 // but do not necessarily update the type of New.
4039 if (CheckEquivalentExceptionSpec(Old, New))
4040 return true;
4041
4042 // C++11 [dcl.attr.noreturn]p1:
4043 // The first declaration of a function shall specify the noreturn
4044 // attribute if any declaration of that function specifies the noreturn
4045 // attribute.
4046 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4047 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4048 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4049 << NRA;
4050 Diag(Old->getLocation(), diag::note_previous_declaration);
4051 }
4052
4053 // C++11 [dcl.attr.depend]p2:
4054 // The first declaration of a function shall specify the
4055 // carries_dependency attribute for its declarator-id if any declaration
4056 // of the function specifies the carries_dependency attribute.
4057 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4058 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4059 Diag(CDA->getLocation(),
4060 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4061 Diag(Old->getFirstDecl()->getLocation(),
4062 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4063 }
4064
4065 // (C++98 8.3.5p3):
4066 // All declarations for a function shall agree exactly in both the
4067 // return type and the parameter-type-list.
4068 // We also want to respect all the extended bits except noreturn.
4069
4070 // noreturn should now match unless the old type info didn't have it.
4071 QualType OldQTypeForComparison = OldQType;
4072 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4073 auto *OldType = OldQType->castAs<FunctionProtoType>();
4074 const FunctionType *OldTypeForComparison
4075 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4076 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4077 assert(OldQTypeForComparison.isCanonical());
4078 }
4079
4080 if (haveIncompatibleLanguageLinkages(Old, New)) {
4081 // As a special case, retain the language linkage from previous
4082 // declarations of a friend function as an extension.
4083 //
4084 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4085 // and is useful because there's otherwise no way to specify language
4086 // linkage within class scope.
4087 //
4088 // Check cautiously as the friend object kind isn't yet complete.
4089 if (New->getFriendObjectKind() != Decl::FOK_None) {
4090 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4091 Diag(OldLocation, PrevDiag);
4092 } else {
4093 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4094 Diag(OldLocation, PrevDiag);
4095 return true;
4096 }
4097 }
4098
4099 // If the function types are compatible, merge the declarations. Ignore the
4100 // exception specifier because it was already checked above in
4101 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4102 // about incompatible types under -fms-compatibility.
4103 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4104 NewQType))
4105 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4106
4107 // If the types are imprecise (due to dependent constructs in friends or
4108 // local extern declarations), it's OK if they differ. We'll check again
4109 // during instantiation.
4110 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4111 return false;
4112
4113 // Fall through for conflicting redeclarations and redefinitions.
4114 }
4115
4116 // C: Function types need to be compatible, not identical. This handles
4117 // duplicate function decls like "void f(int); void f(enum X);" properly.
4118 if (!getLangOpts().CPlusPlus) {
4119 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4120 // type is specified by a function definition that contains a (possibly
4121 // empty) identifier list, both shall agree in the number of parameters
4122 // and the type of each parameter shall be compatible with the type that
4123 // results from the application of default argument promotions to the
4124 // type of the corresponding identifier. ...
4125 // This cannot be handled by ASTContext::typesAreCompatible() because that
4126 // doesn't know whether the function type is for a definition or not when
4127 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4128 // we need to cover here is that the number of arguments agree as the
4129 // default argument promotion rules were already checked by
4130 // ASTContext::typesAreCompatible().
4131 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4132 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4133 if (Old->hasInheritedPrototype())
4134 Old = Old->getCanonicalDecl();
4135 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4136 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4137 return true;
4138 }
4139
4140 // If we are merging two functions where only one of them has a prototype,
4141 // we may have enough information to decide to issue a diagnostic that the
4142 // function without a protoype will change behavior in C23. This handles
4143 // cases like:
4144 // void i(); void i(int j);
4145 // void i(int j); void i();
4146 // void i(); void i(int j) {}
4147 // See ActOnFinishFunctionBody() for other cases of the behavior change
4148 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4149 // type without a prototype.
4150 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4151 !New->isImplicit() && !Old->isImplicit()) {
4152 const FunctionDecl *WithProto, *WithoutProto;
4153 if (New->hasWrittenPrototype()) {
4154 WithProto = New;
4155 WithoutProto = Old;
4156 } else {
4157 WithProto = Old;
4158 WithoutProto = New;
4159 }
4160
4161 if (WithProto->getNumParams() != 0) {
4162 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4163 // The one without the prototype will be changing behavior in C23, so
4164 // warn about that one so long as it's a user-visible declaration.
4165 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4166 if (WithoutProto == New)
4167 IsWithoutProtoADef = NewDeclIsDefn;
4168 else
4169 IsWithProtoADef = NewDeclIsDefn;
4170 Diag(WithoutProto->getLocation(),
4171 diag::warn_non_prototype_changes_behavior)
4172 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4173 << (WithoutProto == Old) << IsWithProtoADef;
4174
4175 // The reason the one without the prototype will be changing behavior
4176 // is because of the one with the prototype, so note that so long as
4177 // it's a user-visible declaration. There is one exception to this:
4178 // when the new declaration is a definition without a prototype, the
4179 // old declaration with a prototype is not the cause of the issue,
4180 // and that does not need to be noted because the one with a
4181 // prototype will not change behavior in C23.
4182 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4183 !IsWithoutProtoADef)
4184 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4185 }
4186 }
4187 }
4188
4189 if (Context.typesAreCompatible(OldQType, NewQType)) {
4190 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4191 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4192 const FunctionProtoType *OldProto = nullptr;
4193 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4194 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4195 // The old declaration provided a function prototype, but the
4196 // new declaration does not. Merge in the prototype.
4197 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4198 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4199 OldProto->getParamTypes(),
4200 OldProto->getExtProtoInfo());
4201 New->setType(NewQType);
4203
4204 // Synthesize parameters with the same types.
4206 for (const auto &ParamType : OldProto->param_types()) {
4208 Context, New, SourceLocation(), SourceLocation(), nullptr,
4209 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4210 Param->setScopeInfo(0, Params.size());
4211 Param->setImplicit();
4212 Params.push_back(Param);
4213 }
4214
4215 New->setParams(Params);
4216 }
4217
4218 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4219 }
4220 }
4221
4222 // Check if the function types are compatible when pointer size address
4223 // spaces are ignored.
4224 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4225 return false;
4226
4227 // GNU C permits a K&R definition to follow a prototype declaration
4228 // if the declared types of the parameters in the K&R definition
4229 // match the types in the prototype declaration, even when the
4230 // promoted types of the parameters from the K&R definition differ
4231 // from the types in the prototype. GCC then keeps the types from
4232 // the prototype.
4233 //
4234 // If a variadic prototype is followed by a non-variadic K&R definition,
4235 // the K&R definition becomes variadic. This is sort of an edge case, but
4236 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4237 // C99 6.9.1p8.
4238 if (!getLangOpts().CPlusPlus &&
4239 Old->hasPrototype() && !New->hasPrototype() &&
4240 New->getType()->getAs<FunctionProtoType>() &&
4241 Old->getNumParams() == New->getNumParams()) {
4244 const FunctionProtoType *OldProto
4245 = Old->getType()->getAs<FunctionProtoType>();
4246 const FunctionProtoType *NewProto
4247 = New->getType()->getAs<FunctionProtoType>();
4248
4249 // Determine whether this is the GNU C extension.
4250 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4251 NewProto->getReturnType());
4252 bool LooseCompatible = !MergedReturn.isNull();
4253 for (unsigned Idx = 0, End = Old->getNumParams();
4254 LooseCompatible && Idx != End; ++Idx) {
4255 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4256 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4257 if (Context.typesAreCompatible(OldParm->getType(),
4258 NewProto->getParamType(Idx))) {
4259 ArgTypes.push_back(NewParm->getType());
4260 } else if (Context.typesAreCompatible(OldParm->getType(),
4261 NewParm->getType(),
4262 /*CompareUnqualified=*/true)) {
4263 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4264 NewProto->getParamType(Idx) };
4265 Warnings.push_back(Warn);
4266 ArgTypes.push_back(NewParm->getType());
4267 } else
4268 LooseCompatible = false;
4269 }
4270
4271 if (LooseCompatible) {
4272 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4273 Diag(Warnings[Warn].NewParm->getLocation(),
4274 diag::ext_param_promoted_not_compatible_with_prototype)
4275 << Warnings[Warn].PromotedType
4276 << Warnings[Warn].OldParm->getType();
4277 if (Warnings[Warn].OldParm->getLocation().isValid())
4278 Diag(Warnings[Warn].OldParm->getLocation(),
4279 diag::note_previous_declaration);
4280 }
4281
4282 if (MergeTypeWithOld)
4283 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4284 OldProto->getExtProtoInfo()));
4285 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4286 }
4287
4288 // Fall through to diagnose conflicting types.
4289 }
4290
4291 // A function that has already been declared has been redeclared or
4292 // defined with a different type; show an appropriate diagnostic.
4293
4294 // If the previous declaration was an implicitly-generated builtin
4295 // declaration, then at the very least we should use a specialized note.
4296 unsigned BuiltinID;
4297 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4298 // If it's actually a library-defined builtin function like 'malloc'
4299 // or 'printf', just warn about the incompatible redeclaration.
4301 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4302 Diag(OldLocation, diag::note_previous_builtin_declaration)
4303 << Old << Old->getType();
4304 return false;
4305 }
4306
4307 PrevDiag = diag::note_previous_builtin_declaration;
4308 }
4309
4310 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4311 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4312 return true;
4313}
4314
4315/// Completes the merge of two function declarations that are
4316/// known to be compatible.
4317///
4318/// This routine handles the merging of attributes and other
4319/// properties of function declarations from the old declaration to
4320/// the new declaration, once we know that New is in fact a
4321/// redeclaration of Old.
4322///
4323/// \returns false
4325 Scope *S, bool MergeTypeWithOld) {
4326 // Merge the attributes
4327 mergeDeclAttributes(New, Old);
4328
4329 // Merge "pure" flag.
4330 if (Old->isPureVirtual())
4331 New->setIsPureVirtual();
4332
4333 // Merge "used" flag.
4334 if (Old->getMostRecentDecl()->isUsed(false))
4335 New->setIsUsed();
4336
4337 // Merge attributes from the parameters. These can mismatch with K&R
4338 // declarations.
4339 if (New->getNumParams() == Old->getNumParams())
4340 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4341 ParmVarDecl *NewParam = New->getParamDecl(i);
4342 ParmVarDecl *OldParam = Old->getParamDecl(i);
4343 mergeParamDeclAttributes(NewParam, OldParam, *this);
4344 mergeParamDeclTypes(NewParam, OldParam, *this);
4345 }
4346
4347 if (getLangOpts().CPlusPlus)
4348 return MergeCXXFunctionDecl(New, Old, S);
4349
4350 // Merge the function types so the we get the composite types for the return
4351 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4352 // was visible.
4353 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4354 if (!Merged.isNull() && MergeTypeWithOld)
4355 New->setType(Merged);
4356
4357 return false;
4358}
4359
4361 ObjCMethodDecl *oldMethod) {
4362 // Merge the attributes, including deprecated/unavailable
4363 AvailabilityMergeKind MergeKind =
4364 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4367 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4368 : AMK_Override;
4369
4370 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4371
4372 // Merge attributes from the parameters.
4374 oe = oldMethod->param_end();
4376 ni = newMethod->param_begin(), ne = newMethod->param_end();
4377 ni != ne && oi != oe; ++ni, ++oi)
4378 mergeParamDeclAttributes(*ni, *oi, *this);
4379
4380 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4381}
4382
4384 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4385
4387 ? diag::err_redefinition_different_type
4388 : diag::err_redeclaration_different_type)
4389 << New->getDeclName() << New->getType() << Old->getType();
4390
4391 diag::kind PrevDiag;
4392 SourceLocation OldLocation;
4393 std::tie(PrevDiag, OldLocation)
4395 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4396 New->setInvalidDecl();
4397}
4398
4399/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4400/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4401/// emitting diagnostics as appropriate.
4402///
4403/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4404/// to here in AddInitializerToDecl. We can't check them before the initializer
4405/// is attached.
4407 bool MergeTypeWithOld) {
4408 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4409 return;
4410
4411 QualType MergedT;
4412 if (getLangOpts().CPlusPlus) {
4413 if (New->getType()->isUndeducedType()) {
4414 // We don't know what the new type is until the initializer is attached.
4415 return;
4416 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4417 // These could still be something that needs exception specs checked.
4418 return MergeVarDeclExceptionSpecs(New, Old);
4419 }
4420 // C++ [basic.link]p10:
4421 // [...] the types specified by all declarations referring to a given
4422 // object or function shall be identical, except that declarations for an
4423 // array object can specify array types that differ by the presence or
4424 // absence of a major array bound (8.3.4).
4425 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4426 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4427 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4428
4429 // We are merging a variable declaration New into Old. If it has an array
4430 // bound, and that bound differs from Old's bound, we should diagnose the
4431 // mismatch.
4432 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4433 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4434 PrevVD = PrevVD->getPreviousDecl()) {
4435 QualType PrevVDTy = PrevVD->getType();
4436 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4437 continue;
4438
4439 if (!Context.hasSameType(New->getType(), PrevVDTy))
4440 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4441 }
4442 }
4443
4444 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4445 if (Context.hasSameType(OldArray->getElementType(),
4446 NewArray->getElementType()))
4447 MergedT = New->getType();
4448 }
4449 // FIXME: Check visibility. New is hidden but has a complete type. If New
4450 // has no array bound, it should not inherit one from Old, if Old is not
4451 // visible.
4452 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4453 if (Context.hasSameType(OldArray->getElementType(),
4454 NewArray->getElementType()))
4455 MergedT = Old->getType();
4456 }
4457 }
4458 else if (New->getType()->isObjCObjectPointerType() &&
4459 Old->getType()->isObjCObjectPointerType()) {
4460 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4461 Old->getType());
4462 }
4463 } else {
4464 // C 6.2.7p2:
4465 // All declarations that refer to the same object or function shall have
4466 // compatible type.
4467 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4468 }
4469 if (MergedT.isNull()) {
4470 // It's OK if we couldn't merge types if either type is dependent, for a
4471 // block-scope variable. In other cases (static data members of class
4472 // templates, variable templates, ...), we require the types to be
4473 // equivalent.
4474 // FIXME: The C++ standard doesn't say anything about this.
4475 if ((New->getType()->isDependentType() ||
4476 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4477 // If the old type was dependent, we can't merge with it, so the new type
4478 // becomes dependent for now. We'll reproduce the original type when we
4479 // instantiate the TypeSourceInfo for the variable.
4480 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4482 return;
4483 }
4484 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4485 }
4486
4487 // Don't actually update the type on the new declaration if the old
4488 // declaration was an extern declaration in a different scope.
4489 if (MergeTypeWithOld)
4490 New->setType(MergedT);
4491}
4492
4493static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4495 // C11 6.2.7p4:
4496 // For an identifier with internal or external linkage declared
4497 // in a scope in which a prior declaration of that identifier is
4498 // visible, if the prior declaration specifies internal or
4499 // external linkage, the type of the identifier at the later
4500 // declaration becomes the composite type.
4501 //
4502 // If the variable isn't visible, we do not merge with its type.
4503 if (Previous.isShadowed())
4504 return false;
4505
4506 if (S.getLangOpts().CPlusPlus) {
4507 // C++11 [dcl.array]p3:
4508 // If there is a preceding declaration of the entity in the same
4509 // scope in which the bound was specified, an omitted array bound
4510 // is taken to be the same as in that earlier declaration.
4511 return NewVD->isPreviousDeclInSameBlockScope() ||
4514 } else {
4515 // If the old declaration was function-local, don't merge with its
4516 // type unless we're in the same function.
4517 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4518 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4519 }
4520}
4521
4522/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4523/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4524/// situation, merging decls or emitting diagnostics as appropriate.
4525///
4526/// Tentative definition rules (C99 6.9.2p2) are checked by
4527/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4528/// definitions here, since the initializer hasn't been attached.
4529///
4531 // If the new decl is already invalid, don't do any other checking.
4532 if (New->isInvalidDecl())
4533 return;
4534
4535 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4536 return;
4537
4538 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4539
4540 // Verify the old decl was also a variable or variable template.
4541 VarDecl *Old = nullptr;
4542 VarTemplateDecl *OldTemplate = nullptr;
4543 if (Previous.isSingleResult()) {
4544 if (NewTemplate) {
4545 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4546 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4547
4548 if (auto *Shadow =
4549 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4550 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4551 return New->setInvalidDecl();
4552 } else {
4553 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4554
4555 if (auto *Shadow =
4556 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4557 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4558 return New->setInvalidDecl();
4559 }
4560 }
4561 if (!Old) {
4562 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4563 << New->getDeclName();
4564 notePreviousDefinition(Previous.getRepresentativeDecl(),
4565 New->getLocation());
4566 return New->setInvalidDecl();
4567 }
4568
4569 // If the old declaration was found in an inline namespace and the new
4570 // declaration was qualified, update the DeclContext to match.
4572
4573 // Ensure the template parameters are compatible.
4574 if (NewTemplate &&
4576 OldTemplate->getTemplateParameters(),
4577 /*Complain=*/true, TPL_TemplateMatch))
4578 return New->setInvalidDecl();
4579
4580 // C++ [class.mem]p1:
4581 // A member shall not be declared twice in the member-specification [...]
4582 //
4583 // Here, we need only consider static data members.
4584 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4585 Diag(New->getLocation(), diag::err_duplicate_member)
4586 << New->getIdentifier();
4587 Diag(Old->getLocation(), diag::note_previous_declaration);
4588 New->setInvalidDecl();
4589 }
4590
4591 mergeDeclAttributes(New, Old);
4592 // Warn if an already-declared variable is made a weak_import in a subsequent
4593 // declaration
4594 if (New->hasAttr<WeakImportAttr>() &&
4595 Old->getStorageClass() == SC_None &&
4596 !Old->hasAttr<WeakImportAttr>()) {
4597 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4598 Diag(Old->getLocation(), diag::note_previous_declaration);
4599 // Remove weak_import attribute on new declaration.
4600 New->dropAttr<WeakImportAttr>();
4601 }
4602
4603 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4604 if (!Old->hasAttr<InternalLinkageAttr>()) {
4605 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4606 << ILA;
4607 Diag(Old->getLocation(), diag::note_previous_declaration);
4608 New->dropAttr<InternalLinkageAttr>();
4609 }
4610
4611 // Merge the types.
4612 VarDecl *MostRecent = Old->getMostRecentDecl();
4613 if (MostRecent != Old) {
4614 MergeVarDeclTypes(New, MostRecent,
4615 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4616 if (New->isInvalidDecl())
4617 return;
4618 }
4619
4620 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4621 if (New->isInvalidDecl())
4622 return;
4623
4624 diag::kind PrevDiag;
4625 SourceLocation OldLocation;
4626 std::tie(PrevDiag, OldLocation) =
4628
4629 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4630 if (New->getStorageClass() == SC_Static &&
4631 !New->isStaticDataMember() &&
4632 Old->hasExternalFormalLinkage()) {
4633 if (getLangOpts().MicrosoftExt) {
4634 Diag(New->getLocation(), diag::ext_static_non_static)
4635 << New->getDeclName();
4636 Diag(OldLocation, PrevDiag);
4637 } else {
4638 Diag(New->getLocation(), diag::err_static_non_static)
4639 << New->getDeclName();
4640 Diag(OldLocation, PrevDiag);
4641 return New->setInvalidDecl();
4642 }
4643 }
4644 // C99 6.2.2p4:
4645 // For an identifier declared with the storage-class specifier
4646 // extern in a scope in which a prior declaration of that
4647 // identifier is visible,23) if the prior declaration specifies
4648 // internal or external linkage, the linkage of the identifier at
4649 // the later declaration is the same as the linkage specified at
4650 // the prior declaration. If no prior declaration is visible, or
4651 // if the prior declaration specifies no linkage, then the
4652 // identifier has external linkage.
4653 if (New->hasExternalStorage() && Old->hasLinkage())
4654 /* Okay */;
4655 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4656 !New->isStaticDataMember() &&
4658 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4659 Diag(OldLocation, PrevDiag);
4660 return New->setInvalidDecl();
4661 }
4662
4663 // Check if extern is followed by non-extern and vice-versa.
4664 if (New->hasExternalStorage() &&
4665 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4666 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4667 Diag(OldLocation, PrevDiag);
4668 return New->setInvalidDecl();
4669 }
4670 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4671 !New->hasExternalStorage()) {
4672 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4673 Diag(OldLocation, PrevDiag);
4674 return New->setInvalidDecl();
4675 }
4676
4677 if (CheckRedeclarationInModule(New, Old))
4678 return;
4679
4680 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4681
4682 // FIXME: The test for external storage here seems wrong? We still
4683 // need to check for mismatches.
4684 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4685 // Don't complain about out-of-line definitions of static members.
4686 !(Old->getLexicalDeclContext()->isRecord() &&
4687 !New->getLexicalDeclContext()->isRecord())) {
4688 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4689 Diag(OldLocation, PrevDiag);
4690 return New->setInvalidDecl();
4691 }
4692
4693 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4694 if (VarDecl *Def = Old->getDefinition()) {
4695 // C++1z [dcl.fcn.spec]p4:
4696 // If the definition of a variable appears in a translation unit before
4697 // its first declaration as inline, the program is ill-formed.
4698 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4699 Diag(Def->getLocation(), diag::note_previous_definition);
4700 }
4701 }
4702
4703 // If this redeclaration makes the variable inline, we may need to add it to
4704 // UndefinedButUsed.
4705 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4707 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4708 SourceLocation()));
4709
4710 if (New->getTLSKind() != Old->getTLSKind()) {
4711 if (!Old->getTLSKind()) {
4712 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4713 Diag(OldLocation, PrevDiag);
4714 } else if (!New->getTLSKind()) {
4715 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4716 Diag(OldLocation, PrevDiag);
4717 } else {
4718 // Do not allow redeclaration to change the variable between requiring
4719 // static and dynamic initialization.
4720 // FIXME: GCC allows this, but uses the TLS keyword on the first
4721 // declaration to determine the kind. Do we need to be compatible here?
4722 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4723 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4724 Diag(OldLocation, PrevDiag);
4725 }
4726 }
4727
4728 // C++ doesn't have tentative definitions, so go right ahead and check here.
4729 if (getLangOpts().CPlusPlus) {
4730 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4731 Old->getCanonicalDecl()->isConstexpr()) {
4732 // This definition won't be a definition any more once it's been merged.
4733 Diag(New->getLocation(),
4734 diag::warn_deprecated_redundant_constexpr_static_def);
4736 VarDecl *Def = Old->getDefinition();
4737 if (Def && checkVarDeclRedefinition(Def, New))
4738 return;
4739 }
4740 }
4741
4742 if (haveIncompatibleLanguageLinkages(Old, New)) {
4743 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4744 Diag(OldLocation, PrevDiag);
4745 New->setInvalidDecl();
4746 return;
4747 }
4748
4749 // Merge "used" flag.
4750 if (Old->getMostRecentDecl()->isUsed(false))
4751 New->setIsUsed();
4752
4753 // Keep a chain of previous declarations.
4754 New->setPreviousDecl(Old);
4755 if (NewTemplate)
4756 NewTemplate->setPreviousDecl(OldTemplate);
4757
4758 // Inherit access appropriately.
4759 New->setAccess(Old->getAccess());
4760 if (NewTemplate)
4761 NewTemplate->setAccess(New->getAccess());
4762
4763 if (Old->isInline())
4764 New->setImplicitlyInline();
4765}
4766
4768 SourceManager &SrcMgr = getSourceManager();
4769 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4770 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4771 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4772 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4773 auto &HSI = PP.getHeaderSearchInfo();
4774 StringRef HdrFilename =
4775 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4776
4777 auto noteFromModuleOrInclude = [&](Module *Mod,
4778 SourceLocation IncLoc) -> bool {
4779 // Redefinition errors with modules are common with non modular mapped
4780 // headers, example: a non-modular header H in module A that also gets
4781 // included directly in a TU. Pointing twice to the same header/definition
4782 // is confusing, try to get better diagnostics when modules is on.
4783 if (IncLoc.isValid()) {
4784 if (Mod) {
4785 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4786 << HdrFilename.str() << Mod->getFullModuleName();
4787 if (!Mod->DefinitionLoc.isInvalid())
4788 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4789 << Mod->getFullModuleName();
4790 } else {
4791 Diag(IncLoc, diag::note_redefinition_include_same_file)
4792 << HdrFilename.str();
4793 }
4794 return true;
4795 }
4796
4797 return false;
4798 };
4799
4800 // Is it the same file and same offset? Provide more information on why
4801 // this leads to a redefinition error.
4802 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4803 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4804 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4805 bool EmittedDiag =
4806 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4807 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4808
4809 // If the header has no guards, emit a note suggesting one.
4810 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4811 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4812
4813 if (EmittedDiag)
4814 return;
4815 }
4816
4817 // Redefinition coming from different files or couldn't do better above.
4818 if (Old->getLocation().isValid())
4819 Diag(Old->getLocation(), diag::note_previous_definition);
4820}
4821
4822/// We've just determined that \p Old and \p New both appear to be definitions
4823/// of the same variable. Either diagnose or fix the problem.
4825 if (!hasVisibleDefinition(Old) &&
4826 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4827 isa<VarTemplateSpecializationDecl>(New) ||
4830 // The previous definition is hidden, and multiple definitions are
4831 // permitted (in separate TUs). Demote this to a declaration.
4833
4834 // Make the canonical definition visible.
4835 if (auto *OldTD = Old->getDescribedVarTemplate())
4838 return false;
4839 } else {
4840 Diag(New->getLocation(), diag::err_redefinition) << New;
4842 New->setInvalidDecl();
4843 return true;
4844 }
4845}
4846
4847/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4848/// no declarator (e.g. "struct foo;") is parsed.
4850 DeclSpec &DS,
4851 const ParsedAttributesView &DeclAttrs,
4852 RecordDecl *&AnonRecord) {
4854 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4855}
4856
4857// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4858// disambiguate entities defined in different scopes.
4859// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4860// compatibility.
4861// We will pick our mangling number depending on which version of MSVC is being
4862// targeted.
4863static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4865 ? S->getMSCurManglingNumber()
4866 : S->getMSLastManglingNumber();
4867}
4868
4869void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4870 if (!Context.getLangOpts().CPlusPlus)
4871 return;
4872
4873 if (isa<CXXRecordDecl>(Tag->getParent())) {
4874 // If this tag is the direct child of a class, number it if
4875 // it is anonymous.
4876 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4877 return;
4881 Tag, MCtx.getManglingNumber(
4882 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4883 return;
4884 }
4885
4886 // If this tag isn't a direct child of a class, number it if it is local.
4888 Decl *ManglingContextDecl;
4889 std::tie(MCtx, ManglingContextDecl) =
4891 if (MCtx) {
4893 Tag, MCtx->getManglingNumber(
4894 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4895 }
4896}
4897
4898namespace {
4899struct NonCLikeKind {
4900 enum {
4901 None,
4902 BaseClass,
4903 DefaultMemberInit,
4904 Lambda,
4905 Friend,
4906 OtherMember,
4907 Invalid,
4908 } Kind = None;
4910
4911 explicit operator bool() { return Kind != None; }
4912};
4913}
4914
4915/// Determine whether a class is C-like, according to the rules of C++
4916/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4917static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4918 if (RD->isInvalidDecl())
4919 return {NonCLikeKind::Invalid, {}};
4920
4921 // C++ [dcl.typedef]p9: [P1766R1]
4922 // An unnamed class with a typedef name for linkage purposes shall not
4923 //
4924 // -- have any base classes
4925 if (RD->getNumBases())
4926 return {NonCLikeKind::BaseClass,
4928 RD->bases_end()[-1].getEndLoc())};
4929 bool Invalid = false;
4930 for (Decl *D : RD->decls()) {
4931 // Don't complain about things we already diagnosed.
4932 if (D->isInvalidDecl()) {
4933 Invalid = true;
4934 continue;
4935 }
4936
4937 // -- have any [...] default member initializers
4938 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4939 if (FD->hasInClassInitializer()) {
4940 auto *Init = FD->getInClassInitializer();
4941 return {NonCLikeKind::DefaultMemberInit,
4942 Init ? Init->getSourceRange() : D->getSourceRange()};
4943 }
4944 continue;
4945 }
4946
4947 // FIXME: We don't allow friend declarations. This violates the wording of
4948 // P1766, but not the intent.
4949 if (isa<FriendDecl>(D))
4950 return {NonCLikeKind::Friend, D->getSourceRange()};
4951
4952 // -- declare any members other than non-static data members, member
4953 // enumerations, or member classes,
4954 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4955 isa<EnumDecl>(D))
4956 continue;
4957 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4958 if (!MemberRD) {
4959 if (D->isImplicit())
4960 continue;
4961 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4962 }
4963
4964 // -- contain a lambda-expression,
4965 if (MemberRD->isLambda())
4966 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4967
4968 // and all member classes shall also satisfy these requirements
4969 // (recursively).
4970 if (MemberRD->isThisDeclarationADefinition()) {
4971 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4972 return Kind;
4973 }
4974 }
4975
4976 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4977}
4978
4980 TypedefNameDecl *NewTD) {
4981 if (TagFromDeclSpec->isInvalidDecl())
4982 return;
4983
4984 // Do nothing if the tag already has a name for linkage purposes.
4985 if (TagFromDeclSpec->hasNameForLinkage())
4986 return;
4987
4988 // A well-formed anonymous tag must always be a TUK_Definition.
4989 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4990
4991 // The type must match the tag exactly; no qualifiers allowed.
4993 Context.getTagDeclType(TagFromDeclSpec))) {
4994 if (getLangOpts().CPlusPlus)
4995 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4996 return;
4997 }
4998
4999 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5000 // An unnamed class with a typedef name for linkage purposes shall [be
5001 // C-like].
5002 //
5003 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5004 // shouldn't happen, but there are constructs that the language rule doesn't
5005 // disallow for which we can't reasonably avoid computing linkage early.
5006 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5007 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5008 : NonCLikeKind();
5009 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5010 if (NonCLike || ChangesLinkage) {
5011 if (NonCLike.Kind == NonCLikeKind::Invalid)
5012 return;
5013
5014 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5015 if (ChangesLinkage) {
5016 // If the linkage changes, we can't accept this as an extension.
5017 if (NonCLike.Kind == NonCLikeKind::None)
5018 DiagID = diag::err_typedef_changes_linkage;
5019 else
5020 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5021 }
5022
5023 SourceLocation FixitLoc =
5024 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5025 llvm::SmallString<40> TextToInsert;
5026 TextToInsert += ' ';
5027 TextToInsert += NewTD->getIdentifier()->getName();
5028
5029 Diag(FixitLoc, DiagID)
5030 << isa<TypeAliasDecl>(NewTD)
5031 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5032 if (NonCLike.Kind != NonCLikeKind::None) {
5033 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5034 << NonCLike.Kind - 1 << NonCLike.Range;
5035 }
5036 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5037 << NewTD << isa<TypeAliasDecl>(NewTD);
5038
5039 if (ChangesLinkage)
5040 return;
5041 }
5042
5043 // Otherwise, set this as the anon-decl typedef for the tag.
5044 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5045}
5046
5047static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5049 switch (T) {
5051 return 0;
5053 return 1;
5055 return 2;
5057 return 3;
5058 case DeclSpec::TST_enum:
5059 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5060 if (ED->isScopedUsingClassTag())
5061 return 5;
5062 if (ED->isScoped())
5063 return 6;
5064 }
5065 return 4;
5066 default:
5067 llvm_unreachable("unexpected type specifier");
5068 }
5069}
5070/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5071/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5072/// parameters to cope with template friend declarations.
5074 DeclSpec &DS,
5075 const ParsedAttributesView &DeclAttrs,
5076 MultiTemplateParamsArg TemplateParams,
5077 bool IsExplicitInstantiation,
5078 RecordDecl *&AnonRecord) {
5079 Decl *TagD = nullptr;
5080 TagDecl *Tag = nullptr;
5086 TagD = DS.getRepAsDecl();
5087
5088 if (!TagD) // We probably had an error
5089 return nullptr;
5090
5091 // Note that the above type specs guarantee that the
5092 // type rep is a Decl, whereas in many of the others
5093 // it's a Type.
5094 if (isa<TagDecl>(TagD))
5095 Tag = cast<TagDecl>(TagD);
5096 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5097 Tag = CTD->getTemplatedDecl();
5098 }
5099
5100 if (Tag) {
5101 handleTagNumbering(Tag, S);
5102 Tag->setFreeStanding();
5103 if (Tag->isInvalidDecl())
5104 return Tag;
5105 }
5106
5107 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5108 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5109 // or incomplete types shall not be restrict-qualified."
5110 if (TypeQuals & DeclSpec::TQ_restrict)
5112 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5113 << DS.getSourceRange();
5114 }
5115
5116 if (DS.isInlineSpecified())
5117 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5118 << getLangOpts().CPlusPlus17;
5119
5120 if (DS.hasConstexprSpecifier()) {
5121 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5122 // and definitions of functions and variables.
5123 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5124 // the declaration of a function or function template
5125 if (Tag)
5126 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5128 << static_cast<int>(DS.getConstexprSpecifier());
5129 else if (getLangOpts().C23)
5130 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5131 else
5132 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5133 << static_cast<int>(DS.getConstexprSpecifier());
5134 // Don't emit warnings after this error.
5135 return TagD;
5136 }
5137
5139
5140 if (DS.isFriendSpecified()) {
5141 // If we're dealing with a decl but not a TagDecl, assume that
5142 // whatever routines created it handled the friendship aspect.
5143 if (TagD && !Tag)
5144 return nullptr;
5145 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5146 }
5147
5148 // Track whether this decl-specifier declares anything.
5149 bool DeclaresAnything = true;
5150
5151 // Handle anonymous struct definitions.
5152 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5153 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5155 if (getLangOpts().CPlusPlus ||
5156 Record->getDeclContext()->isRecord()) {
5157 // If CurContext is a DeclContext that can contain statements,
5158 // RecursiveASTVisitor won't visit the decls that
5159 // BuildAnonymousStructOrUnion() will put into CurContext.
5160 // Also store them here so that they can be part of the
5161 // DeclStmt that gets created in this case.
5162 // FIXME: Also return the IndirectFieldDecls created by
5163 // BuildAnonymousStructOr union, for the same reason?
5165 AnonRecord = Record;
5166 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5168 }
5169
5170 DeclaresAnything = false;
5171 }
5172 }
5173
5174 // C11 6.7.2.1p2:
5175 // A struct-declaration that does not declare an anonymous structure or
5176 // anonymous union shall contain a struct-declarator-list.
5177 //
5178 // This rule also existed in C89 and C99; the grammar for struct-declaration
5179 // did not permit a struct-declaration without a struct-declarator-list.
5182 // Check for Microsoft C extension: anonymous struct/union member.
5183 // Handle 2 kinds of anonymous struct/union:
5184 // struct STRUCT;
5185 // union UNION;
5186 // and
5187 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5188 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5189 if ((Tag && Tag->getDeclName()) ||
5191 RecordDecl *Record = nullptr;
5192 if (Tag)
5193 Record = dyn_cast<RecordDecl>(Tag);
5194 else if (const RecordType *RT =
5196 Record = RT->getDecl();
5197 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5198 Record = UT->getDecl();
5199
5200 if (Record && getLangOpts().MicrosoftExt) {
5201 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5202 << Record->isUnion() << DS.getSourceRange();
5204 }
5205
5206 DeclaresAnything = false;
5207 }
5208 }
5209
5210 // Skip all the checks below if we have a type error.
5212 (TagD && TagD->isInvalidDecl()))
5213 return TagD;
5214
5215 if (getLangOpts().CPlusPlus &&
5217 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5218 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5219 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5220 DeclaresAnything = false;
5221
5222 if (!DS.isMissingDeclaratorOk()) {
5223 // Customize diagnostic for a typedef missing a name.
5225 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5226 << DS.getSourceRange();
5227 else
5228 DeclaresAnything = false;
5229 }
5230
5231 if (DS.isModulePrivateSpecified() &&
5232 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5233 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5234 << llvm::to_underlying(Tag->getTagKind())
5236
5238
5239 // C 6.7/2:
5240 // A declaration [...] shall declare at least a declarator [...], a tag,
5241 // or the members of an enumeration.
5242 // C++ [dcl.dcl]p3:
5243 // [If there are no declarators], and except for the declaration of an
5244 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5245 // names into the program, or shall redeclare a name introduced by a
5246 // previous declaration.
5247 if (!DeclaresAnything) {
5248 // In C, we allow this as a (popular) extension / bug. Don't bother
5249 // producing further diagnostics for redundant qualifiers after this.
5250 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5251 ? diag::err_no_declarators
5252 : diag::ext_no_declarators)
5253 << DS.getSourceRange();
5254 return TagD;
5255 }
5256
5257 // C++ [dcl.stc]p1:
5258 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5259 // init-declarator-list of the declaration shall not be empty.
5260 // C++ [dcl.fct.spec]p1:
5261 // If a cv-qualifier appears in a decl-specifier-seq, the
5262 // init-declarator-list of the declaration shall not be empty.
5263 //
5264 // Spurious qualifiers here appear to be valid in C.
5265 unsigned DiagID = diag::warn_standalone_specifier;
5266 if (getLangOpts().CPlusPlus)
5267 DiagID = diag::ext_standalone_specifier;
5268
5269 // Note that a linkage-specification sets a storage class, but
5270 // 'extern "C" struct foo;' is actually valid and not theoretically
5271 // useless.
5272 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5273 if (SCS == DeclSpec::SCS_mutable)
5274 // Since mutable is not a viable storage class specifier in C, there is
5275 // no reason to treat it as an extension. Instead, diagnose as an error.
5276 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5277 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5278 Diag(DS.getStorageClassSpecLoc(), DiagID)
5280 }
5281
5285 if (DS.getTypeQualifiers()) {
5287 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5289 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5290 // Restrict is covered above.
5292 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5294 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5295 }
5296
5297 // Warn about ignored type attributes, for example:
5298 // __attribute__((aligned)) struct A;
5299 // Attributes should be placed after tag to apply to type declaration.
5300 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5301 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5302 if (TypeSpecType == DeclSpec::TST_class ||
5303 TypeSpecType == DeclSpec::TST_struct ||
5304 TypeSpecType == DeclSpec::TST_interface ||
5305 TypeSpecType == DeclSpec::TST_union ||
5306 TypeSpecType == DeclSpec::TST_enum) {
5307
5308 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5309 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5310 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5311 DiagnosticId = diag::warn_attribute_ignored;
5312 else if (AL.isRegularKeywordAttribute())
5313 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5314 else
5315 DiagnosticId = diag::warn_declspec_attribute_ignored;
5316 Diag(AL.getLoc(), DiagnosticId)
5317 << AL << GetDiagnosticTypeSpecifierID(DS);
5318 };
5319
5320 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5321 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5322 }
5323 }
5324
5325 return TagD;
5326}
5327
5328/// We are trying to inject an anonymous member into the given scope;
5329/// check if there's an existing declaration that can't be overloaded.
5330///
5331/// \return true if this is a forbidden redeclaration
5332static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5333 DeclContext *Owner,
5334 DeclarationName Name,
5335 SourceLocation NameLoc, bool IsUnion,
5336 StorageClass SC) {
5337 LookupResult R(SemaRef, Name, NameLoc,
5340 RedeclarationKind::ForVisibleRedeclaration);
5341 if (!SemaRef.LookupName(R, S)) return false;
5342
5343 // Pick a representative declaration.
5345 assert(PrevDecl && "Expected a non-null Decl");
5346
5347 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5348 return false;
5349
5350 if (SC == StorageClass::SC_None &&
5351 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5352 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5353 if (!Owner->isRecord())
5354 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5355 return false;
5356 }
5357
5358 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5359 << IsUnion << Name;
5360 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5361
5362 return true;
5363}
5364
5366 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5368}
5369
5370/// Emit diagnostic warnings for placeholder members.
5371/// We can only do that after the class is fully constructed,
5372/// as anonymous union/structs can insert placeholders
5373/// in their parent scope (which might be a Record).
5375 if (!getLangOpts().CPlusPlus)
5376 return;
5377
5378 // This function can be parsed before we have validated the
5379 // structure as an anonymous struct
5380 if (Record->isAnonymousStructOrUnion())
5381 return;
5382
5383 const NamedDecl *First = 0;
5384 for (const Decl *D : Record->decls()) {
5385 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5386 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5387 continue;
5388 if (!First)
5389 First = ND;
5390 else
5392 }
5393}
5394
5395/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5396/// anonymous struct or union AnonRecord into the owning context Owner
5397/// and scope S. This routine will be invoked just after we realize
5398/// that an unnamed union or struct is actually an anonymous union or
5399/// struct, e.g.,
5400///
5401/// @code
5402/// union {
5403/// int i;
5404/// float f;
5405/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5406/// // f into the surrounding scope.x
5407/// @endcode
5408///
5409/// This routine is recursive, injecting the names of nested anonymous
5410/// structs/unions into the owning context and scope as well.
5411static bool
5413 RecordDecl *AnonRecord, AccessSpecifier AS,
5414 StorageClass SC,
5415 SmallVectorImpl<NamedDecl *> &Chaining) {
5416 bool Invalid = false;
5417
5418 // Look every FieldDecl and IndirectFieldDecl with a name.
5419 for (auto *D : AnonRecord->decls()) {
5420 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5421 cast<NamedDecl>(D)->getDeclName()) {
5422 ValueDecl *VD = cast<ValueDecl>(D);
5423 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5424 VD->getLocation(), AnonRecord->isUnion(),
5425 SC)) {
5426 // C++ [class.union]p2:
5427 // The names of the members of an anonymous union shall be
5428 // distinct from the names of any other entity in the
5429 // scope in which the anonymous union is declared.
5430 Invalid = true;
5431 } else {
5432 // C++ [class.union]p2:
5433 // For the purpose of name lookup, after the anonymous union
5434 // definition, the members of the anonymous union are
5435 // considered to have been defined in the scope in which the
5436 // anonymous union is declared.
5437 unsigned OldChainingSize = Chaining.size();
5438 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5439 Chaining.append(IF->chain_begin(), IF->chain_end());
5440 else
5441 Chaining.push_back(VD);
5442
5443 assert(Chaining.size() >= 2);
5444 NamedDecl **NamedChain =
5445 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5446 for (unsigned i = 0; i < Chaining.size(); i++)
5447 NamedChain[i] = Chaining[i];
5448
5450 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5451 VD->getType(), {NamedChain, Chaining.size()});
5452
5453 for (const auto *Attr : VD->attrs())
5454 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5455
5456 IndirectField->setAccess(AS);
5457 IndirectField->setImplicit();
5458 SemaRef.PushOnScopeChains(IndirectField, S);
5459
5460 // That includes picking up the appropriate access specifier.
5461 if (AS != AS_none) IndirectField->setAccess(AS);
5462
5463 Chaining.resize(OldChainingSize);
5464 }
5465 }
5466 }
5467
5468 return Invalid;
5469}
5470
5471/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5472/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5473/// illegal input values are mapped to SC_None.
5474static StorageClass
5476 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5477 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5478 "Parser allowed 'typedef' as storage class VarDecl.");
5479 switch (StorageClassSpec) {
5482 if (DS.isExternInLinkageSpec())
5483 return SC_None;
5484 return SC_Extern;
5485 case DeclSpec::SCS_static: return SC_Static;
5486 case DeclSpec::SCS_auto: return SC_Auto;
5489 // Illegal SCSs map to None: error reporting is up to the caller.
5490 case DeclSpec::SCS_mutable: // Fall through.
5491 case DeclSpec::SCS_typedef: return SC_None;
5492 }
5493 llvm_unreachable("unknown storage class specifier");
5494}
5495
5497 assert(Record->hasInClassInitializer());
5498
5499 for (const auto *I : Record->decls()) {
5500 const auto *FD = dyn_cast<FieldDecl>(I);
5501 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5502 FD = IFD->getAnonField();
5503 if (FD && FD->hasInClassInitializer())
5504 return FD->getLocation();
5505 }
5506
5507 llvm_unreachable("couldn't find in-class initializer");
5508}
5509
5511 SourceLocation DefaultInitLoc) {
5512 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5513 return;
5514
5515 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5516 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5517}
5518
5520 CXXRecordDecl *AnonUnion) {
5521 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5522 return;
5523
5525}
5526
5527/// BuildAnonymousStructOrUnion - Handle the declaration of an
5528/// anonymous structure or union. Anonymous unions are a C++ feature
5529/// (C++ [class.union]) and a C11 feature; anonymous structures
5530/// are a C11 feature and GNU C++ extension.
5532 AccessSpecifier AS,
5534 const PrintingPolicy &Policy) {
5535 DeclContext *Owner = Record->getDeclContext();
5536
5537 // Diagnose whether this anonymous struct/union is an extension.
5538 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5539 Diag(Record->getLocation(), diag::ext_anonymous_union);
5540 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5541 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5542 else if (!Record->isUnion() && !getLangOpts().C11)
5543 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5544
5545 // C and C++ require different kinds of checks for anonymous
5546 // structs/unions.
5547 bool Invalid = false;
5548 if (getLangOpts().CPlusPlus) {
5549 const char *PrevSpec = nullptr;
5550 if (Record->isUnion()) {
5551 // C++ [class.union]p6:
5552 // C++17 [class.union.anon]p2:
5553 // Anonymous unions declared in a named namespace or in the
5554 // global namespace shall be declared static.
5555 unsigned DiagID;
5556 DeclContext *OwnerScope = Owner->getRedeclContext();
5558 (OwnerScope->isTranslationUnit() ||
5559 (OwnerScope->isNamespace() &&
5560 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5561 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5562 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5563
5564 // Recover by adding 'static'.
5566 PrevSpec, DiagID, Policy);
5567 }
5568 // C++ [class.union]p6:
5569 // A storage class is not allowed in a declaration of an
5570 // anonymous union in a class scope.
5572 isa<RecordDecl>(Owner)) {
5574 diag::err_anonymous_union_with_storage_spec)
5576
5577 // Recover by removing the storage specifier.
5580 PrevSpec, DiagID, Context.getPrintingPolicy());
5581 }
5582 }
5583
5584 // Ignore const/volatile/restrict qualifiers.
5585 if (DS.getTypeQualifiers()) {
5587 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5588 << Record->isUnion() << "const"
5592 diag::ext_anonymous_struct_union_qualified)
5593 << Record->isUnion() << "volatile"
5597 diag::ext_anonymous_struct_union_qualified)
5598 << Record->isUnion() << "restrict"
5602 diag::ext_anonymous_struct_union_qualified)
5603 << Record->isUnion() << "_Atomic"
5607 diag::ext_anonymous_struct_union_qualified)
5608 << Record->isUnion() << "__unaligned"
5610
5612 }
5613
5614 // C++ [class.union]p2:
5615 // The member-specification of an anonymous union shall only
5616 // define non-static data members. [Note: nested types and
5617 // functions cannot be declared within an anonymous union. ]
5618 for (auto *Mem : Record->decls()) {
5619 // Ignore invalid declarations; we already diagnosed them.
5620 if (Mem->isInvalidDecl())
5621 continue;
5622
5623 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5624 // C++ [class.union]p3:
5625 // An anonymous union shall not have private or protected
5626 // members (clause 11).
5627 assert(FD->getAccess() != AS_none);
5628 if (FD->getAccess() != AS_public) {
5629 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5630 << Record->isUnion() << (FD->getAccess() == AS_protected);
5631 Invalid = true;
5632 }
5633
5634 // C++ [class.union]p1
5635 // An object of a class with a non-trivial constructor, a non-trivial
5636 // copy constructor, a non-trivial destructor, or a non-trivial copy
5637 // assignment operator cannot be a member of a union, nor can an
5638 // array of such objects.
5639 if (CheckNontrivialField(FD))
5640 Invalid = true;
5641 } else if (Mem->isImplicit()) {
5642 // Any implicit members are fine.
5643 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5644 // This is a type that showed up in an
5645 // elaborated-type-specifier inside the anonymous struct or
5646 // union, but which actually declares a type outside of the
5647 // anonymous struct or union. It's okay.
5648 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5649 if (!MemRecord->isAnonymousStructOrUnion() &&
5650 MemRecord->getDeclName()) {
5651 // Visual C++ allows type definition in anonymous struct or union.
5652 if (getLangOpts().MicrosoftExt)
5653 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5654 << Record->isUnion();
5655 else {
5656 // This is a nested type declaration.
5657 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5658 << Record->isUnion();
5659 Invalid = true;
5660 }
5661 } else {
5662 // This is an anonymous type definition within another anonymous type.
5663 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5664 // not part of standard C++.
5665 Diag(MemRecord->getLocation(),
5666 diag::ext_anonymous_record_with_anonymous_type)
5667 << Record->isUnion();
5668 }
5669 } else if (isa<AccessSpecDecl>(Mem)) {
5670 // Any access specifier is fine.
5671 } else if (isa<StaticAssertDecl>(Mem)) {
5672 // In C++1z, static_assert declarations are also fine.
5673 } else {
5674 // We have something that isn't a non-static data
5675 // member. Complain about it.
5676 unsigned DK = diag::err_anonymous_record_bad_member;
5677 if (isa<TypeDecl>(Mem))
5678 DK = diag::err_anonymous_record_with_type;
5679 else if (isa<FunctionDecl>(Mem))
5680 DK = diag::err_anonymous_record_with_function;
5681 else if (isa<VarDecl>(Mem))
5682 DK = diag::err_anonymous_record_with_static;
5683
5684 // Visual C++ allows type definition in anonymous struct or union.
5685 if (getLangOpts().MicrosoftExt &&
5686 DK == diag::err_anonymous_record_with_type)
5687 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5688 << Record->isUnion();
5689 else {
5690 Diag(Mem->getLocation(), DK) << Record->isUnion();
5691 Invalid = true;
5692 }
5693 }
5694 }
5695
5696 // C++11 [class.union]p8 (DR1460):
5697 // At most one variant member of a union may have a
5698 // brace-or-equal-initializer.
5699 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5700 Owner->isRecord())
5701 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5702 cast<CXXRecordDecl>(Record));
5703 }
5704
5705 if (!Record->isUnion() && !Owner->isRecord()) {
5706 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5707 << getLangOpts().CPlusPlus;
5708 Invalid = true;
5709 }
5710
5711 // C++ [dcl.dcl]p3:
5712 // [If there are no declarators], and except for the declaration of an
5713 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5714 // names into the program
5715 // C++ [class.mem]p2:
5716 // each such member-declaration shall either declare at least one member
5717 // name of the class or declare at least one unnamed bit-field
5718 //
5719 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5720 if (getLangOpts().CPlusPlus && Record->field_empty())
5721 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5722
5723 // Mock up a declarator.
5727 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5728
5729 // Create a declaration for this anonymous struct/union.
5730 NamedDecl *Anon = nullptr;
5731 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5732 Anon = FieldDecl::Create(
5733 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5734 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5735 /*BitWidth=*/nullptr, /*Mutable=*/false,
5736 /*InitStyle=*/ICIS_NoInit);
5737 Anon->setAccess(AS);
5738 ProcessDeclAttributes(S, Anon, Dc);
5739
5740 if (getLangOpts().CPlusPlus)
5741 FieldCollector->Add(cast<FieldDecl>(Anon));
5742 } else {
5743 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5744 if (SCSpec == DeclSpec::SCS_mutable) {
5745 // mutable can only appear on non-static class members, so it's always
5746 // an error here
5747 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5748 Invalid = true;
5749 SC = SC_None;
5750 }
5751
5752 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5753 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5754 Context.getTypeDeclType(Record), TInfo, SC);
5755 if (Invalid)
5756 Anon->setInvalidDecl();
5757
5758 ProcessDeclAttributes(S, Anon, Dc);
5759
5760 // Default-initialize the implicit variable. This initialization will be
5761 // trivial in almost all cases, except if a union member has an in-class
5762 // initializer:
5763 // union { int n = 0; };
5765 }
5766 Anon->setImplicit();
5767
5768 // Mark this as an anonymous struct/union type.
5769 Record->setAnonymousStructOrUnion(true);
5770
5771 // Add the anonymous struct/union object to the current
5772 // context. We'll be referencing this object when we refer to one of
5773 // its members.
5774 Owner->addDecl(Anon);
5775
5776 // Inject the members of the anonymous struct/union into the owning
5777 // context and into the identifier resolver chain for name lookup
5778 // purposes.
5780 Chain.push_back(Anon);
5781
5782 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5783 Chain))
5784 Invalid = true;
5785
5786 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5787 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5789 Decl *ManglingContextDecl;
5790 std::tie(MCtx, ManglingContextDecl) =
5791 getCurrentMangleNumberContext(NewVD->getDeclContext());
5792 if (MCtx) {
5794 NewVD, MCtx->getManglingNumber(
5795 NewVD, getMSManglingNumber(getLangOpts(), S)));
5797 }
5798 }
5799 }
5800
5801 if (Invalid)
5802 Anon->setInvalidDecl();
5803
5804 return Anon;
5805}
5806
5807/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5808/// Microsoft C anonymous structure.
5809/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5810/// Example:
5811///
5812/// struct A { int a; };
5813/// struct B { struct A; int b; };
5814///
5815/// void foo() {
5816/// B var;
5817/// var.a = 3;
5818/// }
5819///
5821 RecordDecl *Record) {
5822 assert(Record && "expected a record!");
5823
5824 // Mock up a declarator.
5827 assert(TInfo && "couldn't build declarator info for anonymous struct");
5828
5829 auto *ParentDecl = cast<RecordDecl>(CurContext);
5831
5832 // Create a declaration for this anonymous struct.
5833 NamedDecl *Anon =
5834 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5835 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5836 /*BitWidth=*/nullptr, /*Mutable=*/false,
5837 /*InitStyle=*/ICIS_NoInit);
5838 Anon->setImplicit();
5839
5840 // Add the anonymous struct object to the current context.
5841 CurContext->addDecl(Anon);
5842
5843 // Inject the members of the anonymous struct into the current
5844 // context and into the identifier resolver chain for name lookup
5845 // purposes.
5847 Chain.push_back(Anon);
5848
5849 RecordDecl *RecordDef = Record->getDefinition();
5850 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5851 diag::err_field_incomplete_or_sizeless) ||
5853 *this, S, CurContext, RecordDef, AS_none,
5855 Anon->setInvalidDecl();
5856 ParentDecl->setInvalidDecl();
5857 }
5858
5859 return Anon;
5860}
5861
5862/// GetNameForDeclarator - Determine the full declaration name for the
5863/// given Declarator.
5866}
5867
5868/// Retrieves the declaration name from a parsed unqualified-id.
5871 DeclarationNameInfo NameInfo;
5872 NameInfo.setLoc(Name.StartLocation);
5873
5874 switch (Name.getKind()) {
5875
5878 NameInfo.setName(Name.Identifier);
5879 return NameInfo;
5880
5882 // C++ [temp.deduct.guide]p3:
5883 // The simple-template-id shall name a class template specialization.
5884 // The template-name shall be the same identifier as the template-name
5885 // of the simple-template-id.
5886 // These together intend to imply that the template-name shall name a
5887 // class template.
5888 // FIXME: template<typename T> struct X {};
5889 // template<typename T> using Y = X<T>;
5890 // Y(int) -> Y<int>;
5891 // satisfies these rules but does not name a class template.
5892 TemplateName TN = Name.TemplateName.get().get();
5893 auto *Template = TN.getAsTemplateDecl();
5894 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5895 Diag(Name.StartLocation,
5896 diag::err_deduction_guide_name_not_class_template)
5898 if (Template)
5899 NoteTemplateLocation(*Template);
5900 return DeclarationNameInfo();
5901 }
5902
5903 NameInfo.setName(
5905 return NameInfo;
5906 }
5907
5910 Name.OperatorFunctionId.Operator));
5912 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5913 return NameInfo;
5914
5917 Name.Identifier));
5918 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5919 return NameInfo;
5920
5922 TypeSourceInfo *TInfo;
5923 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5924 if (Ty.isNull())
5925 return DeclarationNameInfo();
5928 NameInfo.setNamedTypeInfo(TInfo);
5929 return NameInfo;
5930 }
5931
5933 TypeSourceInfo *TInfo;
5934 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5935 if (Ty.isNull())
5936 return DeclarationNameInfo();
5939 NameInfo.setNamedTypeInfo(TInfo);
5940 return NameInfo;
5941 }
5942
5944 // In well-formed code, we can only have a constructor
5945 // template-id that refers to the current context, so go there
5946 // to find the actual type being constructed.
5947 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5948 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5949 return DeclarationNameInfo();
5950
5951 // Determine the type of the class being constructed.
5952 QualType CurClassType = Context.getTypeDeclType(CurClass);
5953
5954 // FIXME: Check two things: that the template-id names the same type as
5955 // CurClassType, and that the template-id does not occur when the name
5956 // was qualified.
5957
5959 Context.getCanonicalType(CurClassType)));
5960 // FIXME: should we retrieve TypeSourceInfo?
5961 NameInfo.setNamedTypeInfo(nullptr);
5962 return NameInfo;
5963 }
5964
5966 TypeSourceInfo *TInfo;
5967 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5968 if (Ty.isNull())
5969 return DeclarationNameInfo();
5972 NameInfo.setNamedTypeInfo(TInfo);
5973 return NameInfo;
5974 }
5975
5977 TemplateName TName = Name.TemplateId->Template.get();
5978 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5979 return Context.getNameForTemplate(TName, TNameLoc);
5980 }
5981
5982 } // switch (Name.getKind())
5983
5984 llvm_unreachable("Unknown name kind");
5985}
5986
5988 do {
5989 if (Ty->isPointerType() || Ty->isReferenceType())
5990 Ty = Ty->getPointeeType();
5991 else if (Ty->isArrayType())
5993 else
5994 return Ty.withoutLocalFastQualifiers();
5995 } while (true);
5996}
5997
5998/// hasSimilarParameters - Determine whether the C++ functions Declaration
5999/// and Definition have "nearly" matching parameters. This heuristic is
6000/// used to improve diagnostics in the case where an out-of-line function
6001/// definition doesn't match any declaration within the class or namespace.
6002/// Also sets Params to the list of indices to the parameters that differ
6003/// between the declaration and the definition. If hasSimilarParameters
6004/// returns true and Params is empty, then all of the parameters match.
6008 SmallVectorImpl<unsigned> &Params) {
6009 Params.clear();
6010 if (Declaration->param_size() != Definition->param_size())
6011 return false;
6012 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6013 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6014 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6015
6016 // The parameter types are identical
6017 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6018 continue;
6019
6020 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6021 QualType DefParamBaseTy = getCoreType(DefParamTy);
6022 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6023 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6024
6025 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6026 (DeclTyName && DeclTyName == DefTyName))
6027 Params.push_back(Idx);
6028 else // The two parameters aren't even close
6029 return false;
6030 }
6031
6032 return true;
6033}
6034
6035/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6036/// declarator needs to be rebuilt in the current instantiation.
6037/// Any bits of declarator which appear before the name are valid for
6038/// consideration here. That's specifically the type in the decl spec
6039/// and the base type in any member-pointer chunks.
6041 DeclarationName Name) {
6042 // The types we specifically need to rebuild are:
6043 // - typenames, typeofs, and decltypes
6044 // - types which will become injected class names
6045 // Of course, we also need to rebuild any type referencing such a
6046 // type. It's safest to just say "dependent", but we call out a
6047 // few cases here.
6048
6049 DeclSpec &DS = D.getMutableDeclSpec();
6050 switch (DS.getTypeSpecType()) {
6054#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6055#include "clang/Basic/TransformTypeTraits.def"
6056 case DeclSpec::TST_atomic: {
6057 // Grab the type from the parser.
6058 TypeSourceInfo *TSI = nullptr;
6059 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6060 if (T.isNull() || !T->isInstantiationDependentType()) break;
6061
6062 // Make sure there's a type source info. This isn't really much
6063 // of a waste; most dependent types should have type source info
6064 // attached already.
6065 if (!TSI)
6067
6068 // Rebuild the type in the current instantiation.
6070 if (!TSI) return true;
6071
6072 // Store the new type back in the decl spec.
6073 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6074 DS.UpdateTypeRep(LocType);
6075 break;
6076 }
6077
6081 Expr *E = DS.getRepAsExpr();
6083 if (Result.isInvalid()) return true;
6084 DS.UpdateExprRep(Result.get());
6085 break;
6086 }
6087
6088 default:
6089 // Nothing to do for these decl specs.
6090 break;
6091 }
6092
6093 // It doesn't matter what order we do this in.
6094 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6095 DeclaratorChunk &Chunk = D.getTypeObject(I);
6096
6097 // The only type information in the declarator which can come
6098 // before the declaration name is the base type of a member
6099 // pointer.
6101 continue;
6102
6103 // Rebuild the scope specifier in-place.
6104 CXXScopeSpec &SS = Chunk.Mem.Scope();
6106 return true;
6107 }
6108
6109 return false;
6110}
6111
6112/// Returns true if the declaration is declared in a system header or from a
6113/// system macro.
6114static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6115 return SM.isInSystemHeader(D->getLocation()) ||
6116 SM.isInSystemMacro(D->getLocation());
6117}
6118
6120 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6121 // of system decl.
6122 if (D->getPreviousDecl() || D->isImplicit())
6123 return;
6127 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6128 << D << static_cast<int>(Status);
6129 }
6130}
6131
6134
6135 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6136 // declaration only if the `bind_to_declaration` extension is set.
6138 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6139 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6140 llvm::omp::TraitProperty::
6141 implementation_extension_bind_to_declaration))
6143 S, D, MultiTemplateParamsArg(), Bases);
6144
6146
6148 Dcl && Dcl->getDeclContext()->isFileContext())
6150
6151 if (!Bases.empty())
6153 Bases);
6154
6155 return Dcl;
6156}
6157
6158/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6159/// If T is the name of a class, then each of the following shall have a
6160/// name different from T:
6161/// - every static data member of class T;
6162/// - every member function of class T
6163/// - every member of class T that is itself a type;
6164/// \returns true if the declaration name violates these rules.
6166 DeclarationNameInfo NameInfo) {
6167 DeclarationName Name = NameInfo.getName();
6168
6169 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6170 while (Record && Record->isAnonymousStructOrUnion())
6171 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6172 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6173 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6174 return true;
6175 }
6176
6177 return false;
6178}
6179
6180/// Diagnose a declaration whose declarator-id has the given
6181/// nested-name-specifier.
6182///
6183/// \param SS The nested-name-specifier of the declarator-id.
6184///
6185/// \param DC The declaration context to which the nested-name-specifier
6186/// resolves.
6187///
6188/// \param Name The name of the entity being declared.
6189///
6190/// \param Loc The location of the name of the entity being declared.
6191///
6192/// \param IsMemberSpecialization Whether we are declaring a member
6193/// specialization.
6194///
6195/// \param TemplateId The template-id, if any.
6196///
6197/// \returns true if we cannot safely recover from this error, false otherwise.
6199 DeclarationName Name,
6201 TemplateIdAnnotation *TemplateId,
6202 bool IsMemberSpecialization) {
6203 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6204 "without nested-name-specifier");
6205 DeclContext *Cur = CurContext;
6206 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6207 Cur = Cur->getParent();
6208
6209 // If the user provided a superfluous scope specifier that refers back to the
6210 // class in which the entity is already declared, diagnose and ignore it.
6211 //
6212 // class X {
6213 // void X::f();
6214 // };
6215 //
6216 // Note, it was once ill-formed to give redundant qualification in all
6217 // contexts, but that rule was removed by DR482.
6218 if (Cur->Equals(DC)) {
6219 if (Cur->isRecord()) {
6220 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6221 : diag::err_member_extra_qualification)
6222 << Name << FixItHint::CreateRemoval(SS.getRange());
6223 SS.clear();
6224 } else {
6225 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6226 }
6227 return false;
6228 }
6229
6230 // Check whether the qualifying scope encloses the scope of the original
6231 // declaration. For a template-id, we perform the checks in
6232 // CheckTemplateSpecializationScope.
6233 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6234 if (Cur->isRecord())
6235 Diag(Loc, diag::err_member_qualification)
6236 << Name << SS.getRange();
6237 else if (isa<TranslationUnitDecl>(DC))
6238 Diag(Loc, diag::err_invalid_declarator_global_scope)
6239 << Name << SS.getRange();
6240 else if (isa<FunctionDecl>(Cur))
6241 Diag(Loc, diag::err_invalid_declarator_in_function)
6242 << Name << SS.getRange();
6243 else if (isa<BlockDecl>(Cur))
6244 Diag(Loc, diag::err_invalid_declarator_in_block)
6245 << Name << SS.getRange();
6246 else if (isa<ExportDecl>(Cur)) {
6247 if (!isa<NamespaceDecl>(DC))
6248 Diag(Loc, diag::err_export_non_namespace_scope_name)
6249 << Name << SS.getRange();
6250 else
6251 // The cases that DC is not NamespaceDecl should be handled in
6252 // CheckRedeclarationExported.
6253 return false;
6254 } else
6255 Diag(Loc, diag::err_invalid_declarator_scope)
6256 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6257
6258 return true;
6259 }
6260
6261 if (Cur->isRecord()) {
6262 // Cannot qualify members within a class.
6263 Diag(Loc, diag::err_member_qualification)
6264 << Name << SS.getRange();
6265 SS.clear();
6266
6267 // C++ constructors and destructors with incorrect scopes can break
6268 // our AST invariants by having the wrong underlying types. If
6269 // that's the case, then drop this declaration entirely.
6270 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6271 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6272 !Context.hasSameType(Name.getCXXNameType(),
6273 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6274 return true;
6275
6276 return false;
6277 }
6278
6279 // C++23 [temp.names]p5:
6280 // The keyword template shall not appear immediately after a declarative
6281 // nested-name-specifier.
6282 //
6283 // First check the template-id (if any), and then check each component of the
6284 // nested-name-specifier in reverse order.
6285 //
6286 // FIXME: nested-name-specifiers in friend declarations are declarative,
6287 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6288 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6289 Diag(Loc, diag::ext_template_after_declarative_nns)
6291
6293 do {
6294 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6296 Diag(Loc, diag::ext_template_after_declarative_nns)
6298 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6299
6300 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6301 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6302 // C++23 [expr.prim.id.qual]p3:
6303 // [...] If a nested-name-specifier N is declarative and has a
6304 // simple-template-id with a template argument list A that involves a
6305 // template parameter, let T be the template nominated by N without A.
6306 // T shall be a class template.
6307 if (TST->isDependentType() && TST->isTypeAlias())
6308 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6309 << SpecLoc.getLocalSourceRange();
6310 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6311 // C++23 [expr.prim.id.qual]p2:
6312 // [...] A declarative nested-name-specifier shall not have a
6313 // computed-type-specifier.
6314 //
6315 // CWG2858 changed this from 'decltype-specifier' to
6316 // 'computed-type-specifier'.
6317 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6318 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6319 }
6320 }
6321 } while ((SpecLoc = SpecLoc.getPrefix()));
6322
6323 return false;
6324}
6325
6327 MultiTemplateParamsArg TemplateParamLists) {
6328 // TODO: consider using NameInfo for diagnostic.
6330 DeclarationName Name = NameInfo.getName();
6331
6332 // All of these full declarators require an identifier. If it doesn't have
6333 // one, the ParsedFreeStandingDeclSpec action should be used.
6334 if (D.isDecompositionDeclarator()) {
6335 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6336 } else if (!Name) {
6337 if (!D.isInvalidType()) // Reject this if we think it is valid.
6338 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6340 return nullptr;
6342 return nullptr;
6343
6344 DeclContext *DC = CurContext;
6345 if (D.getCXXScopeSpec().isInvalid())
6346 D.setInvalidType();
6347 else if (D.getCXXScopeSpec().isSet()) {
6350 return nullptr;
6351
6352 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6353 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6354 if (!DC || isa<EnumDecl>(DC)) {
6355 // If we could not compute the declaration context, it's because the
6356 // declaration context is dependent but does not refer to a class,
6357 // class template, or class template partial specialization. Complain
6358 // and return early, to avoid the coming semantic disaster.
6360 diag::err_template_qualified_declarator_no_match)
6362 << D.getCXXScopeSpec().getRange();
6363 return nullptr;
6364 }
6365 bool IsDependentContext = DC->isDependentContext();
6366
6367 if (!IsDependentContext &&
6369 return nullptr;
6370
6371 // If a class is incomplete, do not parse entities inside it.
6372 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6374 diag::err_member_def_undefined_record)
6375 << Name << DC << D.getCXXScopeSpec().getRange();
6376 return nullptr;
6377 }
6378 if (!D.getDeclSpec().isFriendSpecified()) {
6379 TemplateIdAnnotation *TemplateId =
6381 ? D.getName().TemplateId
6382 : nullptr;
6384 D.getIdentifierLoc(), TemplateId,
6385 /*IsMemberSpecialization=*/false)) {
6386 if (DC->isRecord())
6387 return nullptr;
6388
6389 D.setInvalidType();
6390 }
6391 }
6392
6393 // Check whether we need to rebuild the type of the given
6394 // declaration in the current instantiation.
6395 if (EnteringContext && IsDependentContext &&
6396 TemplateParamLists.size() != 0) {
6397 ContextRAII SavedContext(*this, DC);
6398 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6399 D.setInvalidType();
6400 }
6401 }
6402
6404 QualType R = TInfo->getType();
6405
6408 D.setInvalidType();
6409
6410 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6412
6413 // See if this is a redefinition of a variable in the same scope.
6414 if (!D.getCXXScopeSpec().isSet()) {
6415 bool IsLinkageLookup = false;
6416 bool CreateBuiltins = false;
6417
6418 // If the declaration we're planning to build will be a function
6419 // or object with linkage, then look for another declaration with
6420 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6421 //
6422 // If the declaration we're planning to build will be declared with
6423 // external linkage in the translation unit, create any builtin with
6424 // the same name.
6426 /* Do nothing*/;
6427 else if (CurContext->isFunctionOrMethod() &&
6429 R->isFunctionType())) {
6430 IsLinkageLookup = true;
6431 CreateBuiltins =
6435 CreateBuiltins = true;
6436
6437 if (IsLinkageLookup) {
6439 Previous.setRedeclarationKind(
6440 RedeclarationKind::ForExternalRedeclaration);
6441 }
6442
6443 LookupName(Previous, S, CreateBuiltins);
6444 } else { // Something like "int foo::x;"
6446
6447 // C++ [dcl.meaning]p1:
6448 // When the declarator-id is qualified, the declaration shall refer to a
6449 // previously declared member of the class or namespace to which the
6450 // qualifier refers (or, in the case of a namespace, of an element of the
6451 // inline namespace set of that namespace (7.3.1)) or to a specialization
6452 // thereof; [...]
6453 //
6454 // Note that we already checked the context above, and that we do not have
6455 // enough information to make sure that Previous contains the declaration
6456 // we want to match. For example, given:
6457 //
6458 // class X {
6459 // void f();
6460 // void f(float);
6461 // };
6462 //
6463 // void X::f(int) { } // ill-formed
6464 //
6465 // In this case, Previous will point to the overload set
6466 // containing the two f's declared in X, but neither of them
6467 // matches.
6468
6470 }
6471
6472 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6473 TPD && TPD->isTemplateParameter()) {
6474 // Older versions of clang allowed the names of function/variable templates
6475 // to shadow the names of their template parameters. For the compatibility
6476 // purposes we detect such cases and issue a default-to-error warning that
6477 // can be disabled with -Wno-strict-primary-template-shadow.
6478 if (!D.isInvalidType()) {
6479 bool AllowForCompatibility = false;
6480 if (Scope *DeclParent = S->getDeclParent();
6481 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6482 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6483 TemplateParamParent->isDeclScope(TPD);
6484 }
6486 AllowForCompatibility);
6487 }
6488
6489 // Just pretend that we didn't see the previous declaration.
6490 Previous.clear();
6491 }
6492
6493 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6494 // Forget that the previous declaration is the injected-class-name.
6495 Previous.clear();
6496
6497 // In C++, the previous declaration we find might be a tag type
6498 // (class or enum). In this case, the new declaration will hide the
6499 // tag type. Note that this applies to functions, function templates, and
6500 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6501 if (Previous.isSingleTagDecl() &&
6503 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6504 Previous.clear();
6505
6506 // Check that there are no default arguments other than in the parameters
6507 // of a function declaration (C++ only).
6508 if (getLangOpts().CPlusPlus)
6510
6511 /// Get the innermost enclosing declaration scope.
6512 S = S->getDeclParent();
6513
6514 NamedDecl *New;
6515
6516 bool AddToScope = true;
6518 if (TemplateParamLists.size()) {
6519 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6520 return nullptr;
6521 }
6522
6523 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6524 } else if (R->isFunctionType()) {
6525 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6526 TemplateParamLists,
6527 AddToScope);
6528 } else {
6529 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6530 AddToScope);
6531 }
6532
6533 if (!New)
6534 return nullptr;
6535
6536 // If this has an identifier and is not a function template specialization,
6537 // add it to the scope stack.
6538 if (New->getDeclName() && AddToScope)
6539 PushOnScopeChains(New, S);
6540
6541 if (OpenMP().isInOpenMPDeclareTargetContext())
6543
6544 return New;
6545}
6546
6547/// Helper method to turn variable array types into constant array
6548/// types in certain situations which would otherwise be errors (for
6549/// GCC compatibility).
6551 ASTContext &Context,
6552 bool &SizeIsNegative,
6553 llvm::APSInt &Oversized) {
6554 // This method tries to turn a variable array into a constant
6555 // array even when the size isn't an ICE. This is necessary
6556 // for compatibility with code that depends on gcc's buggy
6557 // constant expression folding, like struct {char x[(int)(char*)2];}
6558 SizeIsNegative = false;
6559 Oversized = 0;
6560
6561 if (T->isDependentType())
6562 return QualType();
6563
6565 const Type *Ty = Qs.strip(T);
6566
6567 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6568 QualType Pointee = PTy->getPointeeType();
6569 QualType FixedType =
6570 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6571 Oversized);
6572 if (FixedType.isNull()) return FixedType;
6573 FixedType = Context.getPointerType(FixedType);
6574 return Qs.apply(Context, FixedType);
6575 }
6576 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6577 QualType Inner = PTy->getInnerType();
6578 QualType FixedType =
6579 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6580 Oversized);
6581 if (FixedType.isNull()) return FixedType;
6582 FixedType = Context.getParenType(FixedType);
6583 return Qs.apply(Context, FixedType);
6584 }
6585
6586 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6587 if (!VLATy)
6588 return QualType();
6589
6590 QualType ElemTy = VLATy->getElementType();
6591 if (ElemTy->isVariablyModifiedType()) {
6592 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6593 SizeIsNegative, Oversized);
6594 if (ElemTy.isNull())
6595 return QualType();
6596 }
6597
6599 if (!VLATy->getSizeExpr() ||
6600 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6601 return QualType();
6602
6603 llvm::APSInt Res = Result.Val.getInt();
6604
6605 // Check whether the array size is negative.
6606 if (Res.isSigned() && Res.isNegative()) {
6607 SizeIsNegative = true;
6608 return QualType();
6609 }
6610
6611 // Check whether the array is too large to be addressed.
6612 unsigned ActiveSizeBits =
6613 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6614 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6615 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6616 : Res.getActiveBits();
6617 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6618 Oversized = Res;
6619 return QualType();
6620 }
6621
6622 QualType FoldedArrayType = Context.getConstantArrayType(
6623 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6624 return Qs.apply(Context, FoldedArrayType);
6625}
6626
6627static void
6629 SrcTL = SrcTL.getUnqualifiedLoc();
6630 DstTL = DstTL.getUnqualifiedLoc();
6631 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6632 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6633 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6634 DstPTL.getPointeeLoc());
6635 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6636 return;
6637 }
6638 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6639 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6640 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6641 DstPTL.getInnerLoc());
6642 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6643 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6644 return;
6645 }
6646 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6647 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6648 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6649 TypeLoc DstElemTL = DstATL.getElementLoc();
6650 if (VariableArrayTypeLoc SrcElemATL =
6651 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6652 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6653 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6654 } else {
6655 DstElemTL.initializeFullCopy(SrcElemTL);
6656 }
6657 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6658 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6659 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6660}
6661
6662/// Helper method to turn variable array types into constant array
6663/// types in certain situations which would otherwise be errors (for
6664/// GCC compatibility).
6665static TypeSourceInfo*
6667 ASTContext &Context,
6668 bool &SizeIsNegative,
6669 llvm::APSInt &Oversized) {
6670 QualType FixedTy
6671 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6672 SizeIsNegative, Oversized);
6673 if (FixedTy.isNull())
6674 return nullptr;
6675 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6677 FixedTInfo->getTypeLoc());
6678 return FixedTInfo;
6679}
6680
6681/// Attempt to fold a variable-sized type to a constant-sized type, returning
6682/// true if we were successful.
6685 unsigned FailedFoldDiagID) {
6686 bool SizeIsNegative;
6687 llvm::APSInt Oversized;
6689 TInfo, Context, SizeIsNegative, Oversized);
6690 if (FixedTInfo) {
6691 Diag(Loc, diag::ext_vla_folded_to_constant);
6692 TInfo = FixedTInfo;
6693 T = FixedTInfo->getType();
6694 return true;
6695 }
6696
6697 if (SizeIsNegative)
6698 Diag(Loc, diag::err_typecheck_negative_array_size);
6699 else if (Oversized.getBoolValue())
6700 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6701 else if (FailedFoldDiagID)
6702 Diag(Loc, FailedFoldDiagID);
6703 return false;
6704}
6705
6706/// Register the given locally-scoped extern "C" declaration so
6707/// that it can be found later for redeclarations. We include any extern "C"
6708/// declaration that is not visible in the translation unit here, not just
6709/// function-scope declarations.
6710void
6712 if (!getLangOpts().CPlusPlus &&
6714 // Don't need to track declarations in the TU in C.
6715 return;
6716
6717 // Note that we have a locally-scoped external with this name.
6719}
6720
6722 // FIXME: We can have multiple results via __attribute__((overloadable)).
6724 return Result.empty() ? nullptr : *Result.begin();
6725}
6726
6727/// Diagnose function specifiers on a declaration of an identifier that
6728/// does not identify a function.
6730 // FIXME: We should probably indicate the identifier in question to avoid
6731 // confusion for constructs like "virtual int a(), b;"
6732 if (DS.isVirtualSpecified())
6734 diag::err_virtual_non_function);
6735
6736 if (DS.hasExplicitSpecifier())
6738 diag::err_explicit_non_function);
6739
6740 if (DS.isNoreturnSpecified())
6742 diag::err_noreturn_non_function);
6743}
6744
6745NamedDecl*
6748 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6749 if (D.getCXXScopeSpec().isSet()) {
6750 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6751 << D.getCXXScopeSpec().getRange();
6752 D.setInvalidType();
6753 // Pretend we didn't see the scope specifier.
6754 DC = CurContext;
6755 Previous.clear();
6756 }
6757
6759
6761 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6762 << getLangOpts().CPlusPlus17;
6764 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6765 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6766
6770 diag::err_deduction_guide_invalid_specifier)
6771 << "typedef";
6772 else
6773 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6774 << D.getName().getSourceRange();
6775 return nullptr;
6776 }
6777
6778 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6779 if (!NewTD) return nullptr;
6780
6781 // Handle attributes prior to checking for duplicates in MergeVarDecl
6782 ProcessDeclAttributes(S, NewTD, D);
6783
6785
6786 bool Redeclaration = D.isRedeclaration();
6787 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6788 D.setRedeclaration(Redeclaration);
6789 return ND;
6790}
6791
6792void
6794 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6795 // then it shall have block scope.
6796 // Note that variably modified types must be fixed before merging the decl so
6797 // that redeclarations will match.
6798 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6799 QualType T = TInfo->getType();
6800 if (T->isVariablyModifiedType()) {
6802
6803 if (S->getFnParent() == nullptr) {
6804 bool SizeIsNegative;
6805 llvm::APSInt Oversized;
6806 TypeSourceInfo *FixedTInfo =
6808 SizeIsNegative,
6809 Oversized);
6810 if (FixedTInfo) {
6811 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6812 NewTD->setTypeSourceInfo(FixedTInfo);
6813 } else {
6814 if (SizeIsNegative)
6815 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6816 else if (T->isVariableArrayType())
6817 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6818 else if (Oversized.getBoolValue())
6819 Diag(NewTD->getLocation(), diag::err_array_too_large)
6820 << toString(Oversized, 10);
6821 else
6822 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6823 NewTD->setInvalidDecl();
6824 }
6825 }
6826 }
6827}
6828
6829/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6830/// declares a typedef-name, either using the 'typedef' type specifier or via
6831/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6832NamedDecl*
6834 LookupResult &Previous, bool &Redeclaration) {
6835
6836 // Find the shadowed declaration before filtering for scope.
6837 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6838
6839 // Merge the decl with the existing one if appropriate. If the decl is
6840 // in an outer scope, it isn't the same thing.
6841 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6842 /*AllowInlineNamespace*/false);
6844 if (!Previous.empty()) {
6845 Redeclaration = true;
6846 MergeTypedefNameDecl(S, NewTD, Previous);
6847 } else {
6849 }
6850
6851 if (ShadowedDecl && !Redeclaration)
6852 CheckShadow(NewTD, ShadowedDecl, Previous);
6853
6854 // If this is the C FILE type, notify the AST context.
6855 if (IdentifierInfo *II = NewTD->getIdentifier())
6856 if (!NewTD->isInvalidDecl() &&
6858 switch (II->getNotableIdentifierID()) {
6859 case tok::NotableIdentifierKind::FILE:
6860 Context.setFILEDecl(NewTD);
6861 break;
6862 case tok::NotableIdentifierKind::jmp_buf:
6863 Context.setjmp_bufDecl(NewTD);
6864 break;
6865 case tok::NotableIdentifierKind::sigjmp_buf:
6867 break;
6868 case tok::NotableIdentifierKind::ucontext_t:
6870 break;
6871 case tok::NotableIdentifierKind::float_t:
6872 case tok::NotableIdentifierKind::double_t:
6873 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6874 break;
6875 default:
6876 break;
6877 }
6878 }
6879
6880 return NewTD;
6881}
6882
6883/// Determines whether the given declaration is an out-of-scope
6884/// previous declaration.
6885///
6886/// This routine should be invoked when name lookup has found a
6887/// previous declaration (PrevDecl) that is not in the scope where a
6888/// new declaration by the same name is being introduced. If the new
6889/// declaration occurs in a local scope, previous declarations with
6890/// linkage may still be considered previous declarations (C99
6891/// 6.2.2p4-5, C++ [basic.link]p6).
6892///
6893/// \param PrevDecl the previous declaration found by name
6894/// lookup
6895///
6896/// \param DC the context in which the new declaration is being
6897/// declared.
6898///
6899/// \returns true if PrevDecl is an out-of-scope previous declaration
6900/// for a new delcaration with the same name.
6901static bool
6903 ASTContext &Context) {
6904 if (!PrevDecl)
6905 return false;
6906
6907 if (!PrevDecl->hasLinkage())
6908 return false;
6909
6910 if (Context.getLangOpts().CPlusPlus) {
6911 // C++ [basic.link]p6:
6912 // If there is a visible declaration of an entity with linkage
6913 // having the same name and type, ignoring entities declared
6914 // outside the innermost enclosing namespace scope, the block
6915 // scope declaration declares that same entity and receives the
6916 // linkage of the previous declaration.
6917 DeclContext *OuterContext = DC->getRedeclContext();
6918 if (!OuterContext->isFunctionOrMethod())
6919 // This rule only applies to block-scope declarations.
6920 return false;
6921
6922 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6923 if (PrevOuterContext->isRecord())
6924 // We found a member function: ignore it.
6925 return false;
6926
6927 // Find the innermost enclosing namespace for the new and
6928 // previous declarations.
6929 OuterContext = OuterContext->getEnclosingNamespaceContext();
6930 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6931
6932 // The previous declaration is in a different namespace, so it
6933 // isn't the same function.
6934 if (!OuterContext->Equals(PrevOuterContext))
6935 return false;
6936 }
6937
6938 return true;
6939}
6940
6942 CXXScopeSpec &SS = D.getCXXScopeSpec();
6943 if (!SS.isSet()) return;
6945}
6946
6948 if (Decl->getType().hasAddressSpace())
6949 return;
6950 if (Decl->getType()->isDependentType())
6951 return;
6952 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6953 QualType Type = Var->getType();
6954 if (Type->isSamplerT() || Type->isVoidType())
6955 return;
6957 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6958 // __opencl_c_program_scope_global_variables feature, the address space
6959 // for a variable at program scope or a static or extern variable inside
6960 // a function are inferred to be __global.
6961 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6962 Var->hasGlobalStorage())
6963 ImplAS = LangAS::opencl_global;
6964 // If the original type from a decayed type is an array type and that array
6965 // type has no address space yet, deduce it now.
6966 if (auto DT = dyn_cast<DecayedType>(Type)) {
6967 auto OrigTy = DT->getOriginalType();
6968 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6969 // Add the address space to the original array type and then propagate
6970 // that to the element type through `getAsArrayType`.
6971 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6972 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6973 // Re-generate the decayed type.
6974 Type = Context.getDecayedType(OrigTy);
6975 }
6976 }
6978 // Apply any qualifiers (including address space) from the array type to
6979 // the element type. This implements C99 6.7.3p8: "If the specification of
6980 // an array type includes any type qualifiers, the element type is so
6981 // qualified, not the array type."
6982 if (Type->isArrayType())
6984 Decl->setType(Type);
6985 }
6986}
6987
6989 // Ensure that an auto decl is deduced otherwise the checks below might cache
6990 // the wrong linkage.
6991 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6992
6993 // 'weak' only applies to declarations with external linkage.
6994 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6995 if (!ND.isExternallyVisible()) {
6996 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6997 ND.dropAttr<WeakAttr>();
6998 }
6999 }
7000 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7001 if (ND.isExternallyVisible()) {
7002 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7003 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7004 }
7005 }
7006
7007 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7008 if (VD->hasInit()) {
7009 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7010 assert(VD->isThisDeclarationADefinition() &&
7011 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7012 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7013 VD->dropAttr<AliasAttr>();
7014 }
7015 }
7016 }
7017
7018 // 'selectany' only applies to externally visible variable declarations.
7019 // It does not apply to functions.
7020 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7021 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7022 S.Diag(Attr->getLocation(),
7023 diag::err_attribute_selectany_non_extern_data);
7024 ND.dropAttr<SelectAnyAttr>();
7025 }
7026 }
7027
7028 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7029 auto *VD = dyn_cast<VarDecl>(&ND);
7030 bool IsAnonymousNS = false;
7031 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7032 if (VD) {
7033 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7034 while (NS && !IsAnonymousNS) {
7035 IsAnonymousNS = NS->isAnonymousNamespace();
7036 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7037 }
7038 }
7039 // dll attributes require external linkage. Static locals may have external
7040 // linkage but still cannot be explicitly imported or exported.
7041 // In Microsoft mode, a variable defined in anonymous namespace must have
7042 // external linkage in order to be exported.
7043 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7044 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7045 (!AnonNSInMicrosoftMode &&
7046 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7047 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7048 << &ND << Attr;
7049 ND.setInvalidDecl();
7050 }
7051 }
7052
7053 // Check the attributes on the function type, if any.
7054 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7055 // Don't declare this variable in the second operand of the for-statement;
7056 // GCC miscompiles that by ending its lifetime before evaluating the
7057 // third operand. See gcc.gnu.org/PR86769.
7059 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7060 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7061 TL = ATL.getModifiedLoc()) {
7062 // The [[lifetimebound]] attribute can be applied to the implicit object
7063 // parameter of a non-static member function (other than a ctor or dtor)
7064 // by applying it to the function type.
7065 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7066 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7067 if (!MD || MD->isStatic()) {
7068 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7069 << !MD << A->getRange();
7070 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7071 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7072 << isa<CXXDestructorDecl>(MD) << A->getRange();
7073 }
7074 }
7075 }
7076 }
7077}
7078
7080 NamedDecl *NewDecl,
7081 bool IsSpecialization,
7082 bool IsDefinition) {
7083 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7084 return;
7085
7086 bool IsTemplate = false;
7087 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7088 OldDecl = OldTD->getTemplatedDecl();
7089 IsTemplate = true;
7090 if (!IsSpecialization)
7091 IsDefinition = false;
7092 }
7093 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7094 NewDecl = NewTD->getTemplatedDecl();
7095 IsTemplate = true;
7096 }
7097
7098 if (!OldDecl || !NewDecl)
7099 return;
7100
7101 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7102 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7103 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7104 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7105
7106 // dllimport and dllexport are inheritable attributes so we have to exclude
7107 // inherited attribute instances.
7108 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7109 (NewExportAttr && !NewExportAttr->isInherited());
7110
7111 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7112 // the only exception being explicit specializations.
7113 // Implicitly generated declarations are also excluded for now because there
7114 // is no other way to switch these to use dllimport or dllexport.
7115 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7116
7117 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7118 // Allow with a warning for free functions and global variables.
7119 bool JustWarn = false;
7120 if (!OldDecl->isCXXClassMember()) {
7121 auto *VD = dyn_cast<VarDecl>(OldDecl);
7122 if (VD && !VD->getDescribedVarTemplate())
7123 JustWarn = true;
7124 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7125 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7126 JustWarn = true;
7127 }
7128
7129 // We cannot change a declaration that's been used because IR has already
7130 // been emitted. Dllimported functions will still work though (modulo
7131 // address equality) as they can use the thunk.
7132 if (OldDecl->isUsed())
7133 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7134 JustWarn = false;
7135
7136 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7137 : diag::err_attribute_dll_redeclaration;
7138 S.Diag(NewDecl->getLocation(), DiagID)
7139 << NewDecl
7140 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7141 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7142 if (!JustWarn) {
7143 NewDecl->setInvalidDecl();
7144 return;
7145 }
7146 }
7147
7148 // A redeclaration is not allowed to drop a dllimport attribute, the only
7149 // exceptions being inline function definitions (except for function
7150 // templates), local extern declarations, qualified friend declarations or
7151 // special MSVC extension: in the last case, the declaration is treated as if
7152 // it were marked dllexport.
7153 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7154 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7155 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7156 // Ignore static data because out-of-line definitions are diagnosed
7157 // separately.
7158 IsStaticDataMember = VD->isStaticDataMember();
7159 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7161 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7162 IsInline = FD->isInlined();
7163 IsQualifiedFriend = FD->getQualifier() &&
7164 FD->getFriendObjectKind() == Decl::FOK_Declared;
7165 }
7166
7167 if (OldImportAttr && !HasNewAttr &&
7168 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7169 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7170 if (IsMicrosoftABI && IsDefinition) {
7171 if (IsSpecialization) {
7172 S.Diag(
7173 NewDecl->getLocation(),
7174 diag::err_attribute_dllimport_function_specialization_definition);
7175 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7176 NewDecl->dropAttr<DLLImportAttr>();
7177 } else {
7178 S.Diag(NewDecl->getLocation(),
7179 diag::warn_redeclaration_without_import_attribute)
7180 << NewDecl;
7181 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7182 NewDecl->dropAttr<DLLImportAttr>();
7183 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7184 S.Context, NewImportAttr->getRange()));
7185 }
7186 } else if (IsMicrosoftABI && IsSpecialization) {
7187 assert(!IsDefinition);
7188 // MSVC allows this. Keep the inherited attribute.
7189 } else {
7190 S.Diag(NewDecl->getLocation(),
7191 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7192 << NewDecl << OldImportAttr;
7193 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7194 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7195 OldDecl->dropAttr<DLLImportAttr>();
7196 NewDecl->dropAttr<DLLImportAttr>();
7197 }
7198 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7199 // In MinGW, seeing a function declared inline drops the dllimport
7200 // attribute.
7201 OldDecl->dropAttr<DLLImportAttr>();
7202 NewDecl->dropAttr<DLLImportAttr>();
7203 S.Diag(NewDecl->getLocation(),
7204 diag::warn_dllimport_dropped_from_inline_function)
7205 << NewDecl << OldImportAttr;
7206 }
7207
7208 // A specialization of a class template member function is processed here
7209 // since it's a redeclaration. If the parent class is dllexport, the
7210 // specialization inherits that attribute. This doesn't happen automatically
7211 // since the parent class isn't instantiated until later.
7212 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7213 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7214 !NewImportAttr && !NewExportAttr) {
7215 if (const DLLExportAttr *ParentExportAttr =
7216 MD->getParent()->getAttr<DLLExportAttr>()) {
7217 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7218 NewAttr->setInherited(true);
7219 NewDecl->addAttr(NewAttr);
7220 }
7221 }
7222 }
7223}
7224
7225/// Given that we are within the definition of the given function,
7226/// will that definition behave like C99's 'inline', where the
7227/// definition is discarded except for optimization purposes?
7229 // Try to avoid calling GetGVALinkageForFunction.
7230
7231 // All cases of this require the 'inline' keyword.
7232 if (!FD->isInlined()) return false;
7233
7234 // This is only possible in C++ with the gnu_inline attribute.
7235 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7236 return false;
7237
7238 // Okay, go ahead and call the relatively-more-expensive function.
7240}
7241
7242/// Determine whether a variable is extern "C" prior to attaching
7243/// an initializer. We can't just call isExternC() here, because that
7244/// will also compute and cache whether the declaration is externally
7245/// visible, which might change when we attach the initializer.
7246///
7247/// This can only be used if the declaration is known to not be a
7248/// redeclaration of an internal linkage declaration.
7249///
7250/// For instance:
7251///
7252/// auto x = []{};
7253///
7254/// Attaching the initializer here makes this declaration not externally
7255/// visible, because its type has internal linkage.
7256///
7257/// FIXME: This is a hack.
7258template<typename T>
7259static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7260 if (S.getLangOpts().CPlusPlus) {
7261 // In C++, the overloadable attribute negates the effects of extern "C".
7262 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7263 return false;
7264
7265 // So do CUDA's host/device attributes.
7266 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7267 D->template hasAttr<CUDAHostAttr>()))
7268 return false;
7269 }
7270 return D->isExternC();
7271}
7272
7273static bool shouldConsiderLinkage(const VarDecl *VD) {
7274 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7275 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7276 isa<OMPDeclareMapperDecl>(DC))
7277 return VD->hasExternalStorage();
7278 if (DC->isFileContext())
7279 return true;
7280 if (DC->isRecord())
7281 return false;
7282 if (DC->getDeclKind() == Decl::HLSLBuffer)
7283 return false;
7284
7285 if (isa<RequiresExprBodyDecl>(DC))
7286 return false;
7287 llvm_unreachable("Unexpected context");
7288}
7289
7290static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7291 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7292 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7293 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7294 return true;
7295 if (DC->isRecord())
7296 return false;
7297 llvm_unreachable("Unexpected context");
7298}
7299
7300static bool hasParsedAttr(Scope *S, const Declarator &PD,
7301 ParsedAttr::Kind Kind) {
7302 // Check decl attributes on the DeclSpec.
7303 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7304 return true;
7305
7306 // Walk the declarator structure, checking decl attributes that were in a type
7307 // position to the decl itself.
7308 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7309 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7310 return true;
7311 }
7312
7313 // Finally, check attributes on the decl itself.
7314 return PD.getAttributes().hasAttribute(Kind) ||
7316}
7317
7318/// Adjust the \c DeclContext for a function or variable that might be a
7319/// function-local external declaration.
7321 if (!DC->isFunctionOrMethod())
7322 return false;
7323
7324 // If this is a local extern function or variable declared within a function
7325 // template, don't add it into the enclosing namespace scope until it is
7326 // instantiated; it might have a dependent type right now.
7327 if (DC->isDependentContext())
7328 return true;
7329
7330 // C++11 [basic.link]p7:
7331 // When a block scope declaration of an entity with linkage is not found to
7332 // refer to some other declaration, then that entity is a member of the
7333 // innermost enclosing namespace.
7334 //
7335 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7336 // semantically-enclosing namespace, not a lexically-enclosing one.
7337 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7338 DC = DC->getParent();
7339 return true;
7340}
7341
7342/// Returns true if given declaration has external C language linkage.
7343static bool isDeclExternC(const Decl *D) {
7344 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7345 return FD->isExternC();
7346 if (const auto *VD = dyn_cast<VarDecl>(D))
7347 return VD->isExternC();
7348
7349 llvm_unreachable("Unknown type of decl!");
7350}
7351
7352/// Returns true if there hasn't been any invalid type diagnosed.
7353static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7354 DeclContext *DC = NewVD->getDeclContext();
7355 QualType R = NewVD->getType();
7356
7357 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7358 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7359 // argument.
7360 if (R->isImageType() || R->isPipeType()) {
7361 Se.Diag(NewVD->getLocation(),
7362 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7363 << R;
7364 NewVD->setInvalidDecl();
7365 return false;
7366 }
7367
7368 // OpenCL v1.2 s6.9.r:
7369 // The event type cannot be used to declare a program scope variable.
7370 // OpenCL v2.0 s6.9.q:
7371 // The clk_event_t and reserve_id_t types cannot be declared in program
7372 // scope.
7373 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7374 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7375 Se.Diag(NewVD->getLocation(),
7376 diag::err_invalid_type_for_program_scope_var)
7377 << R;
7378 NewVD->setInvalidDecl();
7379 return false;
7380 }
7381 }
7382
7383 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7384 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7385 Se.getLangOpts())) {
7386 QualType NR = R.getCanonicalType();
7387 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7388 NR->isReferenceType()) {
7391 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7392 << NR->isReferenceType();
7393 NewVD->setInvalidDecl();
7394 return false;
7395 }
7396 NR = NR->getPointeeType();
7397 }
7398 }
7399
7400 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7401 Se.getLangOpts())) {
7402 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7403 // half array type (unless the cl_khr_fp16 extension is enabled).
7404 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7405 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7406 NewVD->setInvalidDecl();
7407 return false;
7408 }
7409 }
7410
7411 // OpenCL v1.2 s6.9.r:
7412 // The event type cannot be used with the __local, __constant and __global
7413 // address space qualifiers.
7414 if (R->isEventT()) {
7416 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7417 NewVD->setInvalidDecl();
7418 return false;
7419 }
7420 }
7421
7422 if (R->isSamplerT()) {
7423 // OpenCL v1.2 s6.9.b p4:
7424 // The sampler type cannot be used with the __local and __global address
7425 // space qualifiers.
7428 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7429 NewVD->setInvalidDecl();
7430 }
7431
7432 // OpenCL v1.2 s6.12.14.1:
7433 // A global sampler must be declared with either the constant address
7434 // space qualifier or with the const qualifier.
7435 if (DC->isTranslationUnit() &&
7437 R.isConstQualified())) {
7438 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7439 NewVD->setInvalidDecl();
7440 }
7441 if (NewVD->isInvalidDecl())
7442 return false;
7443 }
7444
7445 return true;
7446}
7447
7448template <typename AttrTy>
7449static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7450 const TypedefNameDecl *TND = TT->getDecl();
7451 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7452 AttrTy *Clone = Attribute->clone(S.Context);
7453 Clone->setInherited(true);
7454 D->addAttr(Clone);
7455 }
7456}
7457
7458// This function emits warning and a corresponding note based on the
7459// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7460// declarations of an annotated type must be const qualified.
7462 QualType VarType = VD->getType().getCanonicalType();
7463
7464 // Ignore local declarations (for now) and those with const qualification.
7465 // TODO: Local variables should not be allowed if their type declaration has
7466 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7467 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7468 return;
7469
7470 if (VarType->isArrayType()) {
7471 // Retrieve element type for array declarations.
7472 VarType = S.getASTContext().getBaseElementType(VarType);
7473 }
7474
7475 const RecordDecl *RD = VarType->getAsRecordDecl();
7476
7477 // Check if the record declaration is present and if it has any attributes.
7478 if (RD == nullptr)
7479 return;
7480
7481 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7482 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7483 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7484 return;
7485 }
7486}
7487
7489 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7490 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7491 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7492 QualType R = TInfo->getType();
7494
7495 IdentifierInfo *II = Name.getAsIdentifierInfo();
7496 bool IsPlaceholderVariable = false;
7497
7498 if (D.isDecompositionDeclarator()) {
7499 // Take the name of the first declarator as our name for diagnostic
7500 // purposes.
7501 auto &Decomp = D.getDecompositionDeclarator();
7502 if (!Decomp.bindings().empty()) {
7503 II = Decomp.bindings()[0].Name;
7504 Name = II;
7505 }
7506 } else if (!II) {
7507 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7508 return nullptr;
7509 }
7510
7511
7514
7515 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7516 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7517 IsPlaceholderVariable = true;
7518 if (!Previous.empty()) {
7519 NamedDecl *PrevDecl = *Previous.begin();
7520 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7521 DC->getRedeclContext());
7522 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7524 }
7525 }
7526
7527 // dllimport globals without explicit storage class are treated as extern. We
7528 // have to change the storage class this early to get the right DeclContext.
7529 if (SC == SC_None && !DC->isRecord() &&
7530 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7531 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7532 SC = SC_Extern;
7533
7534 DeclContext *OriginalDC = DC;
7535 bool IsLocalExternDecl = SC == SC_Extern &&
7537
7538 if (SCSpec == DeclSpec::SCS_mutable) {
7539 // mutable can only appear on non-static class members, so it's always
7540 // an error here
7541 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7542 D.setInvalidType();
7543 SC = SC_None;
7544 }
7545
7546 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7547 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7549 // In C++11, the 'register' storage class specifier is deprecated.
7550 // Suppress the warning in system macros, it's used in macros in some
7551 // popular C system headers, such as in glibc's htonl() macro.
7553 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7554 : diag::warn_deprecated_register)
7556 }
7557
7559
7560 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7561 // C99 6.9p2: The storage-class specifiers auto and register shall not
7562 // appear in the declaration specifiers in an external declaration.
7563 // Global Register+Asm is a GNU extension we support.
7564 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7565 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7566 D.setInvalidType();
7567 }
7568 }
7569
7570 // If this variable has a VLA type and an initializer, try to
7571 // fold to a constant-sized type. This is otherwise invalid.
7572 if (D.hasInitializer() && R->isVariableArrayType())
7574 /*DiagID=*/0);
7575
7576 if (const AutoType *AutoT = R->getAs<AutoType>())
7578 AutoT,
7580
7581 bool IsMemberSpecialization = false;
7582 bool IsVariableTemplateSpecialization = false;
7583 bool IsPartialSpecialization = false;
7584 bool IsVariableTemplate = false;
7585 VarDecl *NewVD = nullptr;
7586 VarTemplateDecl *NewTemplate = nullptr;
7587 TemplateParameterList *TemplateParams = nullptr;
7588 if (!getLangOpts().CPlusPlus) {
7590 II, R, TInfo, SC);
7591
7592 if (R->getContainedDeducedType())
7593 ParsingInitForAutoVars.insert(NewVD);
7594
7595 if (D.isInvalidType())
7596 NewVD->setInvalidDecl();
7597
7599 NewVD->hasLocalStorage())
7600 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7602 } else {
7603 bool Invalid = false;
7604
7605 if (DC->isRecord() && !CurContext->isRecord()) {
7606 // This is an out-of-line definition of a static data member.
7607 switch (SC) {
7608 case SC_None:
7609 break;
7610 case SC_Static:
7612 diag::err_static_out_of_line)
7614 break;
7615 case SC_Auto:
7616 case SC_Register:
7617 case SC_Extern:
7618 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7619 // to names of variables declared in a block or to function parameters.
7620 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7621 // of class members
7622
7624 diag::err_storage_class_for_static_member)
7626 break;
7627 case SC_PrivateExtern:
7628 llvm_unreachable("C storage class in c++!");
7629 }
7630 }
7631
7632 if (SC == SC_Static && CurContext->isRecord()) {
7633 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7634 // Walk up the enclosing DeclContexts to check for any that are
7635 // incompatible with static data members.
7636 const DeclContext *FunctionOrMethod = nullptr;
7637 const CXXRecordDecl *AnonStruct = nullptr;
7638 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7639 if (Ctxt->isFunctionOrMethod()) {
7640 FunctionOrMethod = Ctxt;
7641 break;
7642 }
7643 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7644 if (ParentDecl && !ParentDecl->getDeclName()) {
7645 AnonStruct = ParentDecl;
7646 break;
7647 }
7648 }
7649 if (FunctionOrMethod) {
7650 // C++ [class.static.data]p5: A local class shall not have static data
7651 // members.
7653 diag::err_static_data_member_not_allowed_in_local_class)
7654 << Name << RD->getDeclName()
7655 << llvm::to_underlying(RD->getTagKind());
7656 } else if (AnonStruct) {
7657 // C++ [class.static.data]p4: Unnamed classes and classes contained
7658 // directly or indirectly within unnamed classes shall not contain
7659 // static data members.
7661 diag::err_static_data_member_not_allowed_in_anon_struct)
7662 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7663 Invalid = true;
7664 } else if (RD->isUnion()) {
7665 // C++98 [class.union]p1: If a union contains a static data member,
7666 // the program is ill-formed. C++11 drops this restriction.
7669 ? diag::warn_cxx98_compat_static_data_member_in_union
7670 : diag::ext_static_data_member_in_union) << Name;
7671 }
7672 }
7673 }
7674
7675 // Match up the template parameter lists with the scope specifier, then
7676 // determine whether we have a template or a template specialization.
7677 bool InvalidScope = false;
7680 D.getCXXScopeSpec(),
7682 ? D.getName().TemplateId
7683 : nullptr,
7684 TemplateParamLists,
7685 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7686 Invalid |= InvalidScope;
7687
7688 if (TemplateParams) {
7689 if (!TemplateParams->size() &&
7691 // There is an extraneous 'template<>' for this variable. Complain
7692 // about it, but allow the declaration of the variable.
7693 Diag(TemplateParams->getTemplateLoc(),
7694 diag::err_template_variable_noparams)
7695 << II
7696 << SourceRange(TemplateParams->getTemplateLoc(),
7697 TemplateParams->getRAngleLoc());
7698 TemplateParams = nullptr;
7699 } else {
7700 // Check that we can declare a template here.
7701 if (CheckTemplateDeclScope(S, TemplateParams))
7702 return nullptr;
7703
7705 // This is an explicit specialization or a partial specialization.
7706 IsVariableTemplateSpecialization = true;
7707 IsPartialSpecialization = TemplateParams->size() > 0;
7708 } else { // if (TemplateParams->size() > 0)
7709 // This is a template declaration.
7710 IsVariableTemplate = true;
7711
7712 // Only C++1y supports variable templates (N3651).
7715 ? diag::warn_cxx11_compat_variable_template
7716 : diag::ext_variable_template);
7717 }
7718 }
7719 } else {
7720 // Check that we can declare a member specialization here.
7721 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7722 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7723 return nullptr;
7724 assert((Invalid ||
7726 "should have a 'template<>' for this decl");
7727 }
7728
7729 if (IsVariableTemplateSpecialization) {
7730 SourceLocation TemplateKWLoc =
7731 TemplateParamLists.size() > 0
7732 ? TemplateParamLists[0]->getTemplateLoc()
7733 : SourceLocation();
7735 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7737 if (Res.isInvalid())
7738 return nullptr;
7739 NewVD = cast<VarDecl>(Res.get());
7740 AddToScope = false;
7741 } else if (D.isDecompositionDeclarator()) {
7743 D.getIdentifierLoc(), R, TInfo, SC,
7744 Bindings);
7745 } else
7746 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7747 D.getIdentifierLoc(), II, R, TInfo, SC);
7748
7749 // If this is supposed to be a variable template, create it as such.
7750 if (IsVariableTemplate) {
7751 NewTemplate =
7753 TemplateParams, NewVD);
7754 NewVD->setDescribedVarTemplate(NewTemplate);
7755 }
7756
7757 // If this decl has an auto type in need of deduction, make a note of the
7758 // Decl so we can diagnose uses of it in its own initializer.
7759 if (R->getContainedDeducedType())
7760 ParsingInitForAutoVars.insert(NewVD);
7761
7762 if (D.isInvalidType() || Invalid) {
7763 NewVD->setInvalidDecl();
7764 if (NewTemplate)
7765 NewTemplate->setInvalidDecl();
7766 }
7767
7768 SetNestedNameSpecifier(*this, NewVD, D);
7769
7770 // If we have any template parameter lists that don't directly belong to
7771 // the variable (matching the scope specifier), store them.
7772 // An explicit variable template specialization does not own any template
7773 // parameter lists.
7774 bool IsExplicitSpecialization =
7775 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7776 unsigned VDTemplateParamLists =
7777 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7778 if (TemplateParamLists.size() > VDTemplateParamLists)
7780 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7781 }
7782
7783 if (D.getDeclSpec().isInlineSpecified()) {
7784 if (!getLangOpts().CPlusPlus) {
7785 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7786 << 0;
7787 } else if (CurContext->isFunctionOrMethod()) {
7788 // 'inline' is not allowed on block scope variable declaration.
7790 diag::err_inline_declaration_block_scope) << Name
7792 } else {
7794 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7795 : diag::ext_inline_variable);
7796 NewVD->setInlineSpecified();
7797 }
7798 }
7799
7800 // Set the lexical context. If the declarator has a C++ scope specifier, the
7801 // lexical context will be different from the semantic context.
7803 if (NewTemplate)
7804 NewTemplate->setLexicalDeclContext(CurContext);
7805
7806 if (IsLocalExternDecl) {
7808 for (auto *B : Bindings)
7809 B->setLocalExternDecl();
7810 else
7811 NewVD->setLocalExternDecl();
7812 }
7813
7814 bool EmitTLSUnsupportedError = false;
7816 // C++11 [dcl.stc]p4:
7817 // When thread_local is applied to a variable of block scope the
7818 // storage-class-specifier static is implied if it does not appear
7819 // explicitly.
7820 // Core issue: 'static' is not implied if the variable is declared
7821 // 'extern'.
7822 if (NewVD->hasLocalStorage() &&
7823 (SCSpec != DeclSpec::SCS_unspecified ||
7825 !DC->isFunctionOrMethod()))
7827 diag::err_thread_non_global)
7829 else if (!Context.getTargetInfo().isTLSSupported()) {
7830 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7831 getLangOpts().SYCLIsDevice) {
7832 // Postpone error emission until we've collected attributes required to
7833 // figure out whether it's a host or device variable and whether the
7834 // error should be ignored.
7835 EmitTLSUnsupportedError = true;
7836 // We still need to mark the variable as TLS so it shows up in AST with
7837 // proper storage class for other tools to use even if we're not going
7838 // to emit any code for it.
7839 NewVD->setTSCSpec(TSCS);
7840 } else
7842 diag::err_thread_unsupported);
7843 } else
7844 NewVD->setTSCSpec(TSCS);
7845 }
7846
7847 switch (D.getDeclSpec().getConstexprSpecifier()) {
7849 break;
7850
7853 diag::err_constexpr_wrong_decl_kind)
7854 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7855 [[fallthrough]];
7856
7858 NewVD->setConstexpr(true);
7859 // C++1z [dcl.spec.constexpr]p1:
7860 // A static data member declared with the constexpr specifier is
7861 // implicitly an inline variable.
7862 if (NewVD->isStaticDataMember() &&
7863 (getLangOpts().CPlusPlus17 ||
7865 NewVD->setImplicitlyInline();
7866 break;
7867
7869 if (!NewVD->hasGlobalStorage())
7871 diag::err_constinit_local_variable);
7872 else
7873 NewVD->addAttr(
7874 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7875 ConstInitAttr::Keyword_constinit));
7876 break;
7877 }
7878
7879 // C99 6.7.4p3
7880 // An inline definition of a function with external linkage shall
7881 // not contain a definition of a modifiable object with static or
7882 // thread storage duration...
7883 // We only apply this when the function is required to be defined
7884 // elsewhere, i.e. when the function is not 'extern inline'. Note
7885 // that a local variable with thread storage duration still has to
7886 // be marked 'static'. Also note that it's possible to get these
7887 // semantics in C++ using __attribute__((gnu_inline)).
7888 if (SC == SC_Static && S->getFnParent() != nullptr &&
7889 !NewVD->getType().isConstQualified()) {
7891 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7893 diag::warn_static_local_in_extern_inline);
7895 }
7896 }
7897
7899 if (IsVariableTemplateSpecialization)
7900 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7901 << (IsPartialSpecialization ? 1 : 0)
7904 else if (IsMemberSpecialization)
7905 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7906 << 2
7908 else if (NewVD->hasLocalStorage())
7909 Diag(NewVD->getLocation(), diag::err_module_private_local)
7910 << 0 << NewVD
7914 else {
7915 NewVD->setModulePrivate();
7916 if (NewTemplate)
7917 NewTemplate->setModulePrivate();
7918 for (auto *B : Bindings)
7919 B->setModulePrivate();
7920 }
7921 }
7922
7923 if (getLangOpts().OpenCL) {
7925
7927 if (TSC != TSCS_unspecified) {
7929 diag::err_opencl_unknown_type_specifier)
7931 << DeclSpec::getSpecifierName(TSC) << 1;
7932 NewVD->setInvalidDecl();
7933 }
7934 }
7935
7936 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7937 // address space if the table has local storage (semantic checks elsewhere
7938 // will produce an error anyway).
7939 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7940 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7941 !NewVD->hasLocalStorage()) {
7944 NewVD->setType(Type);
7945 }
7946 }
7947
7948 // Handle attributes prior to checking for duplicates in MergeVarDecl
7949 ProcessDeclAttributes(S, NewVD, D);
7950
7951 // FIXME: This is probably the wrong location to be doing this and we should
7952 // probably be doing this for more attributes (especially for function
7953 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7954 // the code to copy attributes would be generated by TableGen.
7955 if (R->isFunctionPointerType())
7956 if (const auto *TT = R->getAs<TypedefType>())
7957 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7958
7959 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7960 getLangOpts().SYCLIsDevice) {
7961 if (EmitTLSUnsupportedError &&
7963 (getLangOpts().OpenMPIsTargetDevice &&
7964 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7966 diag::err_thread_unsupported);
7967
7968 if (EmitTLSUnsupportedError &&
7969 (LangOpts.SYCLIsDevice ||
7970 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7971 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7972 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7973 // storage [duration]."
7974 if (SC == SC_None && S->getFnParent() != nullptr &&
7975 (NewVD->hasAttr<CUDASharedAttr>() ||
7976 NewVD->hasAttr<CUDAConstantAttr>())) {
7977 NewVD->setStorageClass(SC_Static);
7978 }
7979 }
7980
7981 // Ensure that dllimport globals without explicit storage class are treated as
7982 // extern. The storage class is set above using parsed attributes. Now we can
7983 // check the VarDecl itself.
7984 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7985 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7986 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7987
7988 // In auto-retain/release, infer strong retension for variables of
7989 // retainable type.
7990 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7991 NewVD->setInvalidDecl();
7992
7993 // Handle GNU asm-label extension (encoded as an attribute).
7994 if (Expr *E = (Expr*)D.getAsmLabel()) {
7995 // The parser guarantees this is a string.
7996 StringLiteral *SE = cast<StringLiteral>(E);
7997 StringRef Label = SE->getString();
7998 if (S->getFnParent() != nullptr) {
7999 switch (SC) {
8000 case SC_None:
8001 case SC_Auto:
8002 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8003 break;
8004 case SC_Register:
8005 // Local Named register
8008 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8009 break;
8010 case SC_Static:
8011 case SC_Extern:
8012 case SC_PrivateExtern:
8013 break;
8014 }
8015 } else if (SC == SC_Register) {
8016 // Global Named register
8017 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8018 const auto &TI = Context.getTargetInfo();
8019 bool HasSizeMismatch;
8020
8021 if (!TI.isValidGCCRegisterName(Label))
8022 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8023 else if (!TI.validateGlobalRegisterVariable(Label,
8025 HasSizeMismatch))
8026 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8027 else if (HasSizeMismatch)
8028 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8029 }
8030
8031 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8032 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8033 NewVD->setInvalidDecl(true);
8034 }
8035 }
8036
8037 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8038 /*IsLiteralLabel=*/true,
8039 SE->getStrTokenLoc(0)));
8040 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8041 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8043 if (I != ExtnameUndeclaredIdentifiers.end()) {
8044 if (isDeclExternC(NewVD)) {
8045 NewVD->addAttr(I->second);
8047 } else
8048 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8049 << /*Variable*/1 << NewVD;
8050 }
8051 }
8052
8053 // Find the shadowed declaration before filtering for scope.
8054 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8056 : nullptr;
8057
8058 // Don't consider existing declarations that are in a different
8059 // scope and are out-of-semantic-context declarations (if the new
8060 // declaration has linkage).
8063 IsMemberSpecialization ||
8064 IsVariableTemplateSpecialization);
8065
8066 // Check whether the previous declaration is in the same block scope. This
8067 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8068 if (getLangOpts().CPlusPlus &&
8069 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8071 Previous.isSingleResult() && !Previous.isShadowed() &&
8072 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8073
8074 if (!getLangOpts().CPlusPlus) {
8076 } else {
8077 // If this is an explicit specialization of a static data member, check it.
8078 if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
8080 NewVD->setInvalidDecl();
8081
8082 // Merge the decl with the existing one if appropriate.
8083 if (!Previous.empty()) {
8084 if (Previous.isSingleResult() &&
8085 isa<FieldDecl>(Previous.getFoundDecl()) &&
8086 D.getCXXScopeSpec().isSet()) {
8087 // The user tried to define a non-static data member
8088 // out-of-line (C++ [dcl.meaning]p1).
8089 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8090 << D.getCXXScopeSpec().getRange();
8091 Previous.clear();
8092 NewVD->setInvalidDecl();
8093 }
8094 } else if (D.getCXXScopeSpec().isSet() &&
8095 !IsVariableTemplateSpecialization) {
8096 // No previous declaration in the qualifying scope.
8097 Diag(D.getIdentifierLoc(), diag::err_no_member)
8098 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8099 << D.getCXXScopeSpec().getRange();
8100 NewVD->setInvalidDecl();
8101 }
8102
8103 if (!IsPlaceholderVariable)
8105
8106 // CheckVariableDeclaration will set NewVD as invalid if something is in
8107 // error like WebAssembly tables being declared as arrays with a non-zero
8108 // size, but then parsing continues and emits further errors on that line.
8109 // To avoid that we check here if it happened and return nullptr.
8110 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8111 return nullptr;
8112
8113 if (NewTemplate) {
8114 VarTemplateDecl *PrevVarTemplate =
8115 NewVD->getPreviousDecl()
8117 : nullptr;
8118
8119 // Check the template parameter list of this declaration, possibly
8120 // merging in the template parameter list from the previous variable
8121 // template declaration.
8123 TemplateParams,
8124 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8125 : nullptr,
8126 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8127 DC->isDependentContext())
8129 : TPC_VarTemplate))
8130 NewVD->setInvalidDecl();
8131
8132 // If we are providing an explicit specialization of a static variable
8133 // template, make a note of that.
8134 if (PrevVarTemplate &&
8135 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8136 PrevVarTemplate->setMemberSpecialization();
8137 }
8138 }
8139
8140 // Diagnose shadowed variables iff this isn't a redeclaration.
8141 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8142 CheckShadow(NewVD, ShadowedDecl, Previous);
8143
8144 ProcessPragmaWeak(S, NewVD);
8145
8146 // If this is the first declaration of an extern C variable, update
8147 // the map of such variables.
8148 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8149 isIncompleteDeclExternC(*this, NewVD))
8151
8152 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8154 Decl *ManglingContextDecl;
8155 std::tie(MCtx, ManglingContextDecl) =
8157 if (MCtx) {
8159 NewVD, MCtx->getManglingNumber(
8160 NewVD, getMSManglingNumber(getLangOpts(), S)));
8162 }
8163 }
8164
8165 // Special handling of variable named 'main'.
8166 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8168 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8169
8170 // C++ [basic.start.main]p3
8171 // A program that declares a variable main at global scope is ill-formed.
8172 if (getLangOpts().CPlusPlus)
8173 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8174
8175 // In C, and external-linkage variable named main results in undefined
8176 // behavior.
8177 else if (NewVD->hasExternalFormalLinkage())
8178 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8179 }
8180
8181 if (D.isRedeclaration() && !Previous.empty()) {
8182 NamedDecl *Prev = Previous.getRepresentativeDecl();
8183 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8185 }
8186
8187 if (NewTemplate) {
8188 if (NewVD->isInvalidDecl())
8189 NewTemplate->setInvalidDecl();
8190 ActOnDocumentableDecl(NewTemplate);
8191 return NewTemplate;
8192 }
8193
8194 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8196
8198
8199 return NewVD;
8200}
8201
8202/// Enum describing the %select options in diag::warn_decl_shadow.
8212
8213/// Determine what kind of declaration we're shadowing.
8215 const DeclContext *OldDC) {
8216 if (isa<TypeAliasDecl>(ShadowedDecl))
8217 return SDK_Using;
8218 else if (isa<TypedefDecl>(ShadowedDecl))
8219 return SDK_Typedef;
8220 else if (isa<BindingDecl>(ShadowedDecl))
8221 return SDK_StructuredBinding;
8222 else if (isa<RecordDecl>(OldDC))
8223 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8224
8225 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8226}
8227
8228/// Return the location of the capture if the given lambda captures the given
8229/// variable \p VD, or an invalid source location otherwise.
8231 const VarDecl *VD) {
8232 for (const Capture &Capture : LSI->Captures) {
8234 return Capture.getLocation();
8235 }
8236 return SourceLocation();
8237}
8238
8240 const LookupResult &R) {
8241 // Only diagnose if we're shadowing an unambiguous field or variable.
8243 return false;
8244
8245 // Return false if warning is ignored.
8246 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8247}
8248
8249/// Return the declaration shadowed by the given variable \p D, or null
8250/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8252 const LookupResult &R) {
8254 return nullptr;
8255
8256 // Don't diagnose declarations at file scope.
8257 if (D->hasGlobalStorage() && !D->isStaticLocal())
8258 return nullptr;
8259
8260 NamedDecl *ShadowedDecl = R.getFoundDecl();
8261 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8262 : nullptr;
8263}
8264
8265/// Return the declaration shadowed by the given typedef \p D, or null
8266/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8268 const LookupResult &R) {
8269 // Don't warn if typedef declaration is part of a class
8270 if (D->getDeclContext()->isRecord())
8271 return nullptr;
8272
8274 return nullptr;
8275
8276 NamedDecl *ShadowedDecl = R.getFoundDecl();
8277 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8278}
8279
8280/// Return the declaration shadowed by the given variable \p D, or null
8281/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8283 const LookupResult &R) {
8285 return nullptr;
8286
8287 NamedDecl *ShadowedDecl = R.getFoundDecl();
8288 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8289 : nullptr;
8290}
8291
8292/// Diagnose variable or built-in function shadowing. Implements
8293/// -Wshadow.
8294///
8295/// This method is called whenever a VarDecl is added to a "useful"
8296/// scope.
8297///
8298/// \param ShadowedDecl the declaration that is shadowed by the given variable
8299/// \param R the lookup of the name
8300///
8302 const LookupResult &R) {
8303 DeclContext *NewDC = D->getDeclContext();
8304
8305 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8306 // Fields are not shadowed by variables in C++ static methods.
8307 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8308 if (MD->isStatic())
8309 return;
8310
8311 // Fields shadowed by constructor parameters are a special case. Usually
8312 // the constructor initializes the field with the parameter.
8313 if (isa<CXXConstructorDecl>(NewDC))
8314 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8315 // Remember that this was shadowed so we can either warn about its
8316 // modification or its existence depending on warning settings.
8317 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8318 return;
8319 }
8320 }
8321
8322 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8323 if (shadowedVar->isExternC()) {
8324 // For shadowing external vars, make sure that we point to the global
8325 // declaration, not a locally scoped extern declaration.
8326 for (auto *I : shadowedVar->redecls())
8327 if (I->isFileVarDecl()) {
8328 ShadowedDecl = I;
8329 break;
8330 }
8331 }
8332
8333 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8334
8335 unsigned WarningDiag = diag::warn_decl_shadow;
8336 SourceLocation CaptureLoc;
8337 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8338 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8339 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8340 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8341 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8342 if (RD->getLambdaCaptureDefault() == LCD_None) {
8343 // Try to avoid warnings for lambdas with an explicit capture
8344 // list. Warn only when the lambda captures the shadowed decl
8345 // explicitly.
8346 CaptureLoc = getCaptureLocation(LSI, VD);
8347 if (CaptureLoc.isInvalid())
8348 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8349 } else {
8350 // Remember that this was shadowed so we can avoid the warning if
8351 // the shadowed decl isn't captured and the warning settings allow
8352 // it.
8353 cast<LambdaScopeInfo>(getCurFunction())
8354 ->ShadowingDecls.push_back({D, VD});
8355 return;
8356 }
8357 }
8358 if (isa<FieldDecl>(ShadowedDecl)) {
8359 // If lambda can capture this, then emit default shadowing warning,
8360 // Otherwise it is not really a shadowing case since field is not
8361 // available in lambda's body.
8362 // At this point we don't know that lambda can capture this, so
8363 // remember that this was shadowed and delay until we know.
8364 cast<LambdaScopeInfo>(getCurFunction())
8365 ->ShadowingDecls.push_back({D, ShadowedDecl});
8366 return;
8367 }
8368 }
8369 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8370 VD && VD->hasLocalStorage()) {
8371 // A variable can't shadow a local variable in an enclosing scope, if
8372 // they are separated by a non-capturing declaration context.
8373 for (DeclContext *ParentDC = NewDC;
8374 ParentDC && !ParentDC->Equals(OldDC);
8375 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8376 // Only block literals, captured statements, and lambda expressions
8377 // can capture; other scopes don't.
8378 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8379 !isLambdaCallOperator(ParentDC)) {
8380 return;
8381 }
8382 }
8383 }
8384 }
8385 }
8386
8387 // Never warn about shadowing a placeholder variable.
8388 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8389 return;
8390
8391 // Only warn about certain kinds of shadowing for class members.
8392 if (NewDC && NewDC->isRecord()) {
8393 // In particular, don't warn about shadowing non-class members.
8394 if (!OldDC->isRecord())
8395 return;
8396
8397 // TODO: should we warn about static data members shadowing
8398 // static data members from base classes?
8399
8400 // TODO: don't diagnose for inaccessible shadowed members.
8401 // This is hard to do perfectly because we might friend the
8402 // shadowing context, but that's just a false negative.
8403 }
8404
8405
8406 DeclarationName Name = R.getLookupName();
8407
8408 // Emit warning and note.
8409 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8410 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8411 if (!CaptureLoc.isInvalid())
8412 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8413 << Name << /*explicitly*/ 1;
8414 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8415}
8416
8417/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8418/// when these variables are captured by the lambda.
8420 for (const auto &Shadow : LSI->ShadowingDecls) {
8421 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8422 // Try to avoid the warning when the shadowed decl isn't captured.
8423 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8424 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8425 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8426 Diag(Shadow.VD->getLocation(),
8427 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8428 : diag::warn_decl_shadow)
8429 << Shadow.VD->getDeclName()
8430 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8431 if (CaptureLoc.isValid())
8432 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8433 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8434 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8435 } else if (isa<FieldDecl>(ShadowedDecl)) {
8436 Diag(Shadow.VD->getLocation(),
8437 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8438 : diag::warn_decl_shadow_uncaptured_local)
8439 << Shadow.VD->getDeclName()
8440 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8441 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8442 }
8443 }
8444}
8445
8446/// Check -Wshadow without the advantage of a previous lookup.
8448 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8449 return;
8450
8451 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8453 RedeclarationKind::ForVisibleRedeclaration);
8454 LookupName(R, S);
8455 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8456 CheckShadow(D, ShadowedDecl, R);
8457}
8458
8459/// Check if 'E', which is an expression that is about to be modified, refers
8460/// to a constructor parameter that shadows a field.
8462 // Quickly ignore expressions that can't be shadowing ctor parameters.
8463 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8464 return;
8465 E = E->IgnoreParenImpCasts();
8466 auto *DRE = dyn_cast<DeclRefExpr>(E);
8467 if (!DRE)
8468 return;
8469 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8470 auto I = ShadowingDecls.find(D);
8471 if (I == ShadowingDecls.end())
8472 return;
8473 const NamedDecl *ShadowedDecl = I->second;
8474 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8475 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8476 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8477 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8478
8479 // Avoid issuing multiple warnings about the same decl.
8480 ShadowingDecls.erase(I);
8481}
8482
8483/// Check for conflict between this global or extern "C" declaration and
8484/// previous global or extern "C" declarations. This is only used in C++.
8485template<typename T>
8487 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8488 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8489 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8490
8491 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8492 // The common case: this global doesn't conflict with any extern "C"
8493 // declaration.
8494 return false;
8495 }
8496
8497 if (Prev) {
8498 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8499 // Both the old and new declarations have C language linkage. This is a
8500 // redeclaration.
8501 Previous.clear();
8502 Previous.addDecl(Prev);
8503 return true;
8504 }
8505
8506 // This is a global, non-extern "C" declaration, and there is a previous
8507 // non-global extern "C" declaration. Diagnose if this is a variable
8508 // declaration.
8509 if (!isa<VarDecl>(ND))
8510 return false;
8511 } else {
8512 // The declaration is extern "C". Check for any declaration in the
8513 // translation unit which might conflict.
8514 if (IsGlobal) {
8515 // We have already performed the lookup into the translation unit.
8516 IsGlobal = false;
8517 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8518 I != E; ++I) {
8519 if (isa<VarDecl>(*I)) {
8520 Prev = *I;
8521 break;
8522 }
8523 }
8524 } else {
8526 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8527 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8528 I != E; ++I) {
8529 if (isa<VarDecl>(*I)) {
8530 Prev = *I;
8531 break;
8532 }
8533 // FIXME: If we have any other entity with this name in global scope,
8534 // the declaration is ill-formed, but that is a defect: it breaks the
8535 // 'stat' hack, for instance. Only variables can have mangled name
8536 // clashes with extern "C" declarations, so only they deserve a
8537 // diagnostic.
8538 }
8539 }
8540
8541 if (!Prev)
8542 return false;
8543 }
8544
8545 // Use the first declaration's location to ensure we point at something which
8546 // is lexically inside an extern "C" linkage-spec.
8547 assert(Prev && "should have found a previous declaration to diagnose");
8548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8549 Prev = FD->getFirstDecl();
8550 else
8551 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8552
8553 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8554 << IsGlobal << ND;
8555 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8556 << IsGlobal;
8557 return false;
8558}
8559
8560/// Apply special rules for handling extern "C" declarations. Returns \c true
8561/// if we have found that this is a redeclaration of some prior entity.
8562///
8563/// Per C++ [dcl.link]p6:
8564/// Two declarations [for a function or variable] with C language linkage
8565/// with the same name that appear in different scopes refer to the same
8566/// [entity]. An entity with C language linkage shall not be declared with
8567/// the same name as an entity in global scope.
8568template<typename T>
8571 if (!S.getLangOpts().CPlusPlus) {
8572 // In C, when declaring a global variable, look for a corresponding 'extern'
8573 // variable declared in function scope. We don't need this in C++, because
8574 // we find local extern decls in the surrounding file-scope DeclContext.
8575 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8576 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8577 Previous.clear();
8578 Previous.addDecl(Prev);
8579 return true;
8580 }
8581 }
8582 return false;
8583 }
8584
8585 // A declaration in the translation unit can conflict with an extern "C"
8586 // declaration.
8587 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8588 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8589
8590 // An extern "C" declaration can conflict with a declaration in the
8591 // translation unit or can be a redeclaration of an extern "C" declaration
8592 // in another scope.
8593 if (isIncompleteDeclExternC(S,ND))
8594 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8595
8596 // Neither global nor extern "C": nothing to do.
8597 return false;
8598}
8599
8600static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8601 QualType T) {
8602 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8603 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8604 // any of its members, even recursively, shall not have an atomic type, or a
8605 // variably modified type, or a type that is volatile or restrict qualified.
8606 if (CanonT->isVariablyModifiedType()) {
8607 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8608 return true;
8609 }
8610
8611 // Arrays are qualified by their element type, so get the base type (this
8612 // works on non-arrays as well).
8613 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8614
8615 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8616 CanonT.isRestrictQualified()) {
8617 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8618 return true;
8619 }
8620
8621 if (CanonT->isRecordType()) {
8622 const RecordDecl *RD = CanonT->getAsRecordDecl();
8623 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8624 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8625 }))
8626 return true;
8627 }
8628
8629 return false;
8630}
8631
8633 // If the decl is already known invalid, don't check it.
8634 if (NewVD->isInvalidDecl())
8635 return;
8636
8637 QualType T = NewVD->getType();
8638
8639 // Defer checking an 'auto' type until its initializer is attached.
8640 if (T->isUndeducedType())
8641 return;
8642
8643 if (NewVD->hasAttrs())
8645
8646 if (T->isObjCObjectType()) {
8647 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8648 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8650 NewVD->setType(T);
8651 }
8652
8653 // Emit an error if an address space was applied to decl with local storage.
8654 // This includes arrays of objects with address space qualifiers, but not
8655 // automatic variables that point to other address spaces.
8656 // ISO/IEC TR 18037 S5.1.2
8657 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8658 T.getAddressSpace() != LangAS::Default) {
8659 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8660 NewVD->setInvalidDecl();
8661 return;
8662 }
8663
8664 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8665 // scope.
8666 if (getLangOpts().OpenCLVersion == 120 &&
8667 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8668 getLangOpts()) &&
8669 NewVD->isStaticLocal()) {
8670 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8671 NewVD->setInvalidDecl();
8672 return;
8673 }
8674
8675 if (getLangOpts().OpenCL) {
8676 if (!diagnoseOpenCLTypes(*this, NewVD))
8677 return;
8678
8679 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8680 if (NewVD->hasAttr<BlocksAttr>()) {
8681 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8682 return;
8683 }
8684
8685 if (T->isBlockPointerType()) {
8686 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8687 // can't use 'extern' storage class.
8688 if (!T.isConstQualified()) {
8689 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8690 << 0 /*const*/;
8691 NewVD->setInvalidDecl();
8692 return;
8693 }
8694 if (NewVD->hasExternalStorage()) {
8695 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8696 NewVD->setInvalidDecl();
8697 return;
8698 }
8699 }
8700
8701 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8702 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8703 NewVD->hasExternalStorage()) {
8704 if (!T->isSamplerT() && !T->isDependentType() &&
8705 !(T.getAddressSpace() == LangAS::opencl_constant ||
8706 (T.getAddressSpace() == LangAS::opencl_global &&
8707 getOpenCLOptions().areProgramScopeVariablesSupported(
8708 getLangOpts())))) {
8709 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8710 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8711 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8712 << Scope << "global or constant";
8713 else
8714 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8715 << Scope << "constant";
8716 NewVD->setInvalidDecl();
8717 return;
8718 }
8719 } else {
8720 if (T.getAddressSpace() == LangAS::opencl_global) {
8721 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8722 << 1 /*is any function*/ << "global";
8723 NewVD->setInvalidDecl();
8724 return;
8725 }
8726 if (T.getAddressSpace() == LangAS::opencl_constant ||
8727 T.getAddressSpace() == LangAS::opencl_local) {
8729 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8730 // in functions.
8731 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8732 if (T.getAddressSpace() == LangAS::opencl_constant)
8733 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8734 << 0 /*non-kernel only*/ << "constant";
8735 else
8736 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8737 << 0 /*non-kernel only*/ << "local";
8738 NewVD->setInvalidDecl();
8739 return;
8740 }
8741 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8742 // in the outermost scope of a kernel function.
8743 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8744 if (!getCurScope()->isFunctionScope()) {
8745 if (T.getAddressSpace() == LangAS::opencl_constant)
8746 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8747 << "constant";
8748 else
8749 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8750 << "local";
8751 NewVD->setInvalidDecl();
8752 return;
8753 }
8754 }
8755 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8756 // If we are parsing a template we didn't deduce an addr
8757 // space yet.
8758 T.getAddressSpace() != LangAS::Default) {
8759 // Do not allow other address spaces on automatic variable.
8760 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8761 NewVD->setInvalidDecl();
8762 return;
8763 }
8764 }
8765 }
8766
8767 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8768 && !NewVD->hasAttr<BlocksAttr>()) {
8769 if (getLangOpts().getGC() != LangOptions::NonGC)
8770 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8771 else {
8772 assert(!getLangOpts().ObjCAutoRefCount);
8773 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8774 }
8775 }
8776
8777 // WebAssembly tables must be static with a zero length and can't be
8778 // declared within functions.
8779 if (T->isWebAssemblyTableType()) {
8780 if (getCurScope()->getParent()) { // Parent is null at top-level
8781 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8782 NewVD->setInvalidDecl();
8783 return;
8784 }
8785 if (NewVD->getStorageClass() != SC_Static) {
8786 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8787 NewVD->setInvalidDecl();
8788 return;
8789 }
8790 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8791 if (!ATy || ATy->getZExtSize() != 0) {
8792 Diag(NewVD->getLocation(),
8793 diag::err_typecheck_wasm_table_must_have_zero_length);
8794 NewVD->setInvalidDecl();
8795 return;
8796 }
8797 }
8798
8799 bool isVM = T->isVariablyModifiedType();
8800 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8801 NewVD->hasAttr<BlocksAttr>())
8803
8804 if ((isVM && NewVD->hasLinkage()) ||
8805 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8806 bool SizeIsNegative;
8807 llvm::APSInt Oversized;
8809 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8810 QualType FixedT;
8811 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8812 FixedT = FixedTInfo->getType();
8813 else if (FixedTInfo) {
8814 // Type and type-as-written are canonically different. We need to fix up
8815 // both types separately.
8816 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8817 Oversized);
8818 }
8819 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8821 // FIXME: This won't give the correct result for
8822 // int a[10][n];
8823 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8824
8825 if (NewVD->isFileVarDecl())
8826 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8827 << SizeRange;
8828 else if (NewVD->isStaticLocal())
8829 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8830 << SizeRange;
8831 else
8832 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8833 << SizeRange;
8834 NewVD->setInvalidDecl();
8835 return;
8836 }
8837
8838 if (!FixedTInfo) {
8839 if (NewVD->isFileVarDecl())
8840 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8841 else
8842 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8843 NewVD->setInvalidDecl();
8844 return;
8845 }
8846
8847 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8848 NewVD->setType(FixedT);
8849 NewVD->setTypeSourceInfo(FixedTInfo);
8850 }
8851
8852 if (T->isVoidType()) {
8853 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8854 // of objects and functions.
8856 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8857 << T;
8858 NewVD->setInvalidDecl();
8859 return;
8860 }
8861 }
8862
8863 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8864 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8865 NewVD->setInvalidDecl();
8866 return;
8867 }
8868
8869 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8870 !T.isWebAssemblyReferenceType()) {
8871 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8872 NewVD->setInvalidDecl();
8873 return;
8874 }
8875
8876 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8877 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8878 NewVD->setInvalidDecl();
8879 return;
8880 }
8881
8882 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8883 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8884 NewVD->setInvalidDecl();
8885 return;
8886 }
8887
8888 if (NewVD->isConstexpr() && !T->isDependentType() &&
8890 diag::err_constexpr_var_non_literal)) {
8891 NewVD->setInvalidDecl();
8892 return;
8893 }
8894
8895 // PPC MMA non-pointer types are not allowed as non-local variable types.
8896 if (Context.getTargetInfo().getTriple().isPPC64() &&
8897 !NewVD->isLocalVarDecl() &&
8898 CheckPPCMMAType(T, NewVD->getLocation())) {
8899 NewVD->setInvalidDecl();
8900 return;
8901 }
8902
8903 // Check that SVE types are only used in functions with SVE available.
8904 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8905 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8906 llvm::StringMap<bool> CallerFeatureMap;
8907 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8908
8909 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8910 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8911 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8912 NewVD->setInvalidDecl();
8913 return;
8914 } else if (!IsArmStreamingFunction(FD,
8915 /*IncludeLocallyStreaming=*/true)) {
8916 Diag(NewVD->getLocation(),
8917 diag::err_sve_vector_in_non_streaming_function)
8918 << T;
8919 NewVD->setInvalidDecl();
8920 return;
8921 }
8922 }
8923 }
8924
8925 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8926 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8927 llvm::StringMap<bool> CallerFeatureMap;
8928 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8929 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8930 CallerFeatureMap);
8931 }
8932}
8933
8934/// Perform semantic checking on a newly-created variable
8935/// declaration.
8936///
8937/// This routine performs all of the type-checking required for a
8938/// variable declaration once it has been built. It is used both to
8939/// check variables after they have been parsed and their declarators
8940/// have been translated into a declaration, and to check variables
8941/// that have been instantiated from a template.
8942///
8943/// Sets NewVD->isInvalidDecl() if an error was encountered.
8944///
8945/// Returns true if the variable declaration is a redeclaration.
8948
8949 // If the decl is already known invalid, don't check it.
8950 if (NewVD->isInvalidDecl())
8951 return false;
8952
8953 // If we did not find anything by this name, look for a non-visible
8954 // extern "C" declaration with the same name.
8955 if (Previous.empty() &&
8957 Previous.setShadowed();
8958
8959 if (!Previous.empty()) {
8960 MergeVarDecl(NewVD, Previous);
8961 return true;
8962 }
8963 return false;
8964}
8965
8966/// AddOverriddenMethods - See if a method overrides any in the base classes,
8967/// and if so, check that it's a valid override and remember it.
8970
8971 // Look for methods in base classes that this method might override.
8972 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8973 /*DetectVirtual=*/false);
8974 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8975 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8976 DeclarationName Name = MD->getDeclName();
8977
8978 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8979 // We really want to find the base class destructor here.
8980 QualType T = Context.getTypeDeclType(BaseRecord);
8983 }
8984
8985 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8986 CXXMethodDecl *BaseMD =
8987 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8988 if (!BaseMD || !BaseMD->isVirtual() ||
8989 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8990 /*ConsiderCudaAttrs=*/true))
8991 continue;
8992 if (!CheckExplicitObjectOverride(MD, BaseMD))
8993 continue;
8994 if (Overridden.insert(BaseMD).second) {
8995 MD->addOverriddenMethod(BaseMD);
9000 }
9001
9002 // A method can only override one function from each base class. We
9003 // don't track indirectly overridden methods from bases of bases.
9004 return true;
9005 }
9006
9007 return false;
9008 };
9009
9010 DC->lookupInBases(VisitBase, Paths);
9011 return !Overridden.empty();
9012}
9013
9014namespace {
9015 // Struct for holding all of the extra arguments needed by
9016 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9017 struct ActOnFDArgs {
9018 Scope *S;
9019 Declarator &D;
9020 MultiTemplateParamsArg TemplateParamLists;
9021 bool AddToScope;
9022 };
9023} // end anonymous namespace
9024
9025namespace {
9026
9027// Callback to only accept typo corrections that have a non-zero edit distance.
9028// Also only accept corrections that have the same parent decl.
9029class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9030 public:
9031 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9033 : Context(Context), OriginalFD(TypoFD),
9034 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9035
9036 bool ValidateCandidate(const TypoCorrection &candidate) override {
9037 if (candidate.getEditDistance() == 0)
9038 return false;
9039
9040 SmallVector<unsigned, 1> MismatchedParams;
9041 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9042 CDeclEnd = candidate.end();
9043 CDecl != CDeclEnd; ++CDecl) {
9044 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9045
9046 if (FD && !FD->hasBody() &&
9047 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9048 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9049 CXXRecordDecl *Parent = MD->getParent();
9050 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9051 return true;
9052 } else if (!ExpectedParent) {
9053 return true;
9054 }
9055 }
9056 }
9057
9058 return false;
9059 }
9060
9061 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9062 return std::make_unique<DifferentNameValidatorCCC>(*this);
9063 }
9064
9065 private:
9066 ASTContext &Context;
9067 FunctionDecl *OriginalFD;
9068 CXXRecordDecl *ExpectedParent;
9069};
9070
9071} // end anonymous namespace
9072
9075}
9076
9077/// Generate diagnostics for an invalid function redeclaration.
9078///
9079/// This routine handles generating the diagnostic messages for an invalid
9080/// function redeclaration, including finding possible similar declarations
9081/// or performing typo correction if there are no previous declarations with
9082/// the same name.
9083///
9084/// Returns a NamedDecl iff typo correction was performed and substituting in
9085/// the new declaration name does not cause new errors.
9087 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9088 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9089 DeclarationName Name = NewFD->getDeclName();
9090 DeclContext *NewDC = NewFD->getDeclContext();
9091 SmallVector<unsigned, 1> MismatchedParams;
9093 TypoCorrection Correction;
9094 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9095 unsigned DiagMsg =
9096 IsLocalFriend ? diag::err_no_matching_local_friend :
9097 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9098 diag::err_member_decl_does_not_match;
9099 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9100 IsLocalFriend ? Sema::LookupLocalFriendName
9102 RedeclarationKind::ForVisibleRedeclaration);
9103
9104 NewFD->setInvalidDecl();
9105 if (IsLocalFriend)
9106 SemaRef.LookupName(Prev, S);
9107 else
9108 SemaRef.LookupQualifiedName(Prev, NewDC);
9109 assert(!Prev.isAmbiguous() &&
9110 "Cannot have an ambiguity in previous-declaration lookup");
9111 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9112 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9113 MD ? MD->getParent() : nullptr);
9114 if (!Prev.empty()) {
9115 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9116 Func != FuncEnd; ++Func) {
9117 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9118 if (FD &&
9119 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9120 // Add 1 to the index so that 0 can mean the mismatch didn't
9121 // involve a parameter
9122 unsigned ParamNum =
9123 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9124 NearMatches.push_back(std::make_pair(FD, ParamNum));
9125 }
9126 }
9127 // If the qualified name lookup yielded nothing, try typo correction
9128 } else if ((Correction = SemaRef.CorrectTypo(
9129 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9130 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9131 IsLocalFriend ? nullptr : NewDC))) {
9132 // Set up everything for the call to ActOnFunctionDeclarator
9133 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9134 ExtraArgs.D.getIdentifierLoc());
9135 Previous.clear();
9136 Previous.setLookupName(Correction.getCorrection());
9137 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9138 CDeclEnd = Correction.end();
9139 CDecl != CDeclEnd; ++CDecl) {
9140 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9141 if (FD && !FD->hasBody() &&
9142 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9143 Previous.addDecl(FD);
9144 }
9145 }
9146 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9147
9149 // Retry building the function declaration with the new previous
9150 // declarations, and with errors suppressed.
9151 {
9152 // Trap errors.
9153 Sema::SFINAETrap Trap(SemaRef);
9154
9155 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9156 // pieces need to verify the typo-corrected C++ declaration and hopefully
9157 // eliminate the need for the parameter pack ExtraArgs.
9159 ExtraArgs.S, ExtraArgs.D,
9160 Correction.getCorrectionDecl()->getDeclContext(),
9161 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9162 ExtraArgs.AddToScope);
9163
9164 if (Trap.hasErrorOccurred())
9165 Result = nullptr;
9166 }
9167
9168 if (Result) {
9169 // Determine which correction we picked.
9170 Decl *Canonical = Result->getCanonicalDecl();
9171 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9172 I != E; ++I)
9173 if ((*I)->getCanonicalDecl() == Canonical)
9174 Correction.setCorrectionDecl(*I);
9175
9176 // Let Sema know about the correction.
9178 SemaRef.diagnoseTypo(
9179 Correction,
9180 SemaRef.PDiag(IsLocalFriend
9181 ? diag::err_no_matching_local_friend_suggest
9182 : diag::err_member_decl_does_not_match_suggest)
9183 << Name << NewDC << IsDefinition);
9184 return Result;
9185 }
9186
9187 // Pretend the typo correction never occurred
9188 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9189 ExtraArgs.D.getIdentifierLoc());
9190 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9191 Previous.clear();
9192 Previous.setLookupName(Name);
9193 }
9194
9195 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9196 << Name << NewDC << IsDefinition << NewFD->getLocation();
9197
9198 bool NewFDisConst = false;
9199 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9200 NewFDisConst = NewMD->isConst();
9201
9202 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9203 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9204 NearMatch != NearMatchEnd; ++NearMatch) {
9205 FunctionDecl *FD = NearMatch->first;
9206 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9207 bool FDisConst = MD && MD->isConst();
9208 bool IsMember = MD || !IsLocalFriend;
9209
9210 // FIXME: These notes are poorly worded for the local friend case.
9211 if (unsigned Idx = NearMatch->second) {
9212 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9214 if (Loc.isInvalid()) Loc = FD->getLocation();
9215 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9216 : diag::note_local_decl_close_param_match)
9217 << Idx << FDParam->getType()
9218 << NewFD->getParamDecl(Idx - 1)->getType();
9219 } else if (FDisConst != NewFDisConst) {
9220 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9221 << NewFDisConst << FD->getSourceRange().getEnd()
9222 << (NewFDisConst
9223 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9224 .getConstQualifierLoc())
9225 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9226 .getRParenLoc()
9227 .getLocWithOffset(1),
9228 " const"));
9229 } else
9230 SemaRef.Diag(FD->getLocation(),
9231 IsMember ? diag::note_member_def_close_match
9232 : diag::note_local_decl_close_match);
9233 }
9234 return nullptr;
9235}
9236
9238 switch (D.getDeclSpec().getStorageClassSpec()) {
9239 default: llvm_unreachable("Unknown storage class!");
9240 case DeclSpec::SCS_auto:
9244 diag::err_typecheck_sclass_func);
9246 D.setInvalidType();
9247 break;
9248 case DeclSpec::SCS_unspecified: break;
9251 return SC_None;
9252 return SC_Extern;
9253 case DeclSpec::SCS_static: {
9255 // C99 6.7.1p5:
9256 // The declaration of an identifier for a function that has
9257 // block scope shall have no explicit storage-class specifier
9258 // other than extern
9259 // See also (C++ [dcl.stc]p4).
9261 diag::err_static_block_func);
9262 break;
9263 } else
9264 return SC_Static;
9265 }
9267 }
9268
9269 // No explicit storage class has already been returned
9270 return SC_None;
9271}
9272
9274 DeclContext *DC, QualType &R,
9275 TypeSourceInfo *TInfo,
9276 StorageClass SC,
9277 bool &IsVirtualOkay) {
9278 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9279 DeclarationName Name = NameInfo.getName();
9280
9281 FunctionDecl *NewFD = nullptr;
9282 bool isInline = D.getDeclSpec().isInlineSpecified();
9283
9285 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9286 (SemaRef.getLangOpts().C23 &&
9287 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9288
9289 if (SemaRef.getLangOpts().C23)
9290 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9291 diag::err_c23_constexpr_not_variable);
9292 else
9293 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9294 diag::err_constexpr_wrong_decl_kind)
9295 << static_cast<int>(ConstexprKind);
9296 ConstexprKind = ConstexprSpecKind::Unspecified;
9298 }
9299
9300 if (!SemaRef.getLangOpts().CPlusPlus) {
9301 // Determine whether the function was written with a prototype. This is
9302 // true when:
9303 // - there is a prototype in the declarator, or
9304 // - the type R of the function is some kind of typedef or other non-
9305 // attributed reference to a type name (which eventually refers to a
9306 // function type). Note, we can't always look at the adjusted type to
9307 // check this case because attributes may cause a non-function
9308 // declarator to still have a function type. e.g.,
9309 // typedef void func(int a);
9310 // __attribute__((noreturn)) func other_func; // This has a prototype
9311 bool HasPrototype =
9313 (D.getDeclSpec().isTypeRep() &&
9314 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9315 ->isFunctionProtoType()) ||
9317 assert(
9318 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9319 "Strict prototypes are required");
9320
9321 NewFD = FunctionDecl::Create(
9322 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9323 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9325 /*TrailingRequiresClause=*/nullptr);
9326 if (D.isInvalidType())
9327 NewFD->setInvalidDecl();
9328
9329 return NewFD;
9330 }
9331
9333 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9334
9335 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9336
9337 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9338 // This is a C++ constructor declaration.
9339 assert(DC->isRecord() &&
9340 "Constructors can only be declared in a member context");
9341
9342 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9344 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9346 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9347 InheritedConstructor(), TrailingRequiresClause);
9348
9349 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9350 // This is a C++ destructor declaration.
9351 if (DC->isRecord()) {
9352 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9353 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9355 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9356 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9357 /*isImplicitlyDeclared=*/false, ConstexprKind,
9358 TrailingRequiresClause);
9359 // User defined destructors start as not selected if the class definition is still
9360 // not done.
9361 if (Record->isBeingDefined())
9362 NewDD->setIneligibleOrNotSelected(true);
9363
9364 // If the destructor needs an implicit exception specification, set it
9365 // now. FIXME: It'd be nice to be able to create the right type to start
9366 // with, but the type needs to reference the destructor declaration.
9367 if (SemaRef.getLangOpts().CPlusPlus11)
9368 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9369
9370 IsVirtualOkay = true;
9371 return NewDD;
9372
9373 } else {
9374 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9375 D.setInvalidType();
9376
9377 // Create a FunctionDecl to satisfy the function definition parsing
9378 // code path.
9379 return FunctionDecl::Create(
9380 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9381 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9382 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9383 }
9384
9385 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9386 if (!DC->isRecord()) {
9387 SemaRef.Diag(D.getIdentifierLoc(),
9388 diag::err_conv_function_not_member);
9389 return nullptr;
9390 }
9391
9392 SemaRef.CheckConversionDeclarator(D, R, SC);
9393 if (D.isInvalidType())
9394 return nullptr;
9395
9396 IsVirtualOkay = true;
9398 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9399 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9400 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9401 TrailingRequiresClause);
9402
9403 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9404 if (TrailingRequiresClause)
9405 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9406 diag::err_trailing_requires_clause_on_deduction_guide)
9407 << TrailingRequiresClause->getSourceRange();
9408 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9409 return nullptr;
9410 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9411 ExplicitSpecifier, NameInfo, R, TInfo,
9412 D.getEndLoc());
9413 } else if (DC->isRecord()) {
9414 // If the name of the function is the same as the name of the record,
9415 // then this must be an invalid constructor that has a return type.
9416 // (The parser checks for a return type and makes the declarator a
9417 // constructor if it has no return type).
9418 if (Name.getAsIdentifierInfo() &&
9419 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9420 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9423 return nullptr;
9424 }
9425
9426 // This is a C++ method declaration.
9428 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9429 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9430 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9431 IsVirtualOkay = !Ret->isStatic();
9432 return Ret;
9433 } else {
9434 bool isFriend =
9435 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9436 if (!isFriend && SemaRef.CurContext->isRecord())
9437 return nullptr;
9438
9439 // Determine whether the function was written with a
9440 // prototype. This true when:
9441 // - we're in C++ (where every function has a prototype),
9442 return FunctionDecl::Create(
9443 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9444 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9445 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9446 }
9447}
9448
9457
9459 // Size dependent types are just typedefs to normal integer types
9460 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9461 // integers other than by their names.
9462 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9463
9464 // Remove typedefs one by one until we reach a typedef
9465 // for a size dependent type.
9466 QualType DesugaredTy = Ty;
9467 do {
9468 ArrayRef<StringRef> Names(SizeTypeNames);
9469 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9470 if (Names.end() != Match)
9471 return true;
9472
9473 Ty = DesugaredTy;
9474 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9475 } while (DesugaredTy != Ty);
9476
9477 return false;
9478}
9479
9481 if (PT->isDependentType())
9482 return InvalidKernelParam;
9483
9484 if (PT->isPointerType() || PT->isReferenceType()) {
9485 QualType PointeeType = PT->getPointeeType();
9486 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9487 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9488 PointeeType.getAddressSpace() == LangAS::Default)
9490
9491 if (PointeeType->isPointerType()) {
9492 // This is a pointer to pointer parameter.
9493 // Recursively check inner type.
9494 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9495 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9496 ParamKind == InvalidKernelParam)
9497 return ParamKind;
9498
9499 // OpenCL v3.0 s6.11.a:
9500 // A restriction to pass pointers to pointers only applies to OpenCL C
9501 // v1.2 or below.
9503 return ValidKernelParam;
9504
9505 return PtrPtrKernelParam;
9506 }
9507
9508 // C++ for OpenCL v1.0 s2.4:
9509 // Moreover the types used in parameters of the kernel functions must be:
9510 // Standard layout types for pointer parameters. The same applies to
9511 // reference if an implementation supports them in kernel parameters.
9512 if (S.getLangOpts().OpenCLCPlusPlus &&
9514 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9515 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9516 bool IsStandardLayoutType = true;
9517 if (CXXRec) {
9518 // If template type is not ODR-used its definition is only available
9519 // in the template definition not its instantiation.
9520 // FIXME: This logic doesn't work for types that depend on template
9521 // parameter (PR58590).
9522 if (!CXXRec->hasDefinition())
9523 CXXRec = CXXRec->getTemplateInstantiationPattern();
9524 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9525 IsStandardLayoutType = false;
9526 }
9527 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9528 !IsStandardLayoutType)
9529 return InvalidKernelParam;
9530 }
9531
9532 // OpenCL v1.2 s6.9.p:
9533 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9535 return ValidKernelParam;
9536
9537 return PtrKernelParam;
9538 }
9539
9540 // OpenCL v1.2 s6.9.k:
9541 // Arguments to kernel functions in a program cannot be declared with the
9542 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9543 // uintptr_t or a struct and/or union that contain fields declared to be one
9544 // of these built-in scalar types.
9546 return InvalidKernelParam;
9547
9548 if (PT->isImageType())
9549 return PtrKernelParam;
9550
9551 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9552 return InvalidKernelParam;
9553
9554 // OpenCL extension spec v1.2 s9.5:
9555 // This extension adds support for half scalar and vector types as built-in
9556 // types that can be used for arithmetic operations, conversions etc.
9557 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9558 PT->isHalfType())
9559 return InvalidKernelParam;
9560
9561 // Look into an array argument to check if it has a forbidden type.
9562 if (PT->isArrayType()) {
9563 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9564 // Call ourself to check an underlying type of an array. Since the
9565 // getPointeeOrArrayElementType returns an innermost type which is not an
9566 // array, this recursive call only happens once.
9567 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9568 }
9569
9570 // C++ for OpenCL v1.0 s2.4:
9571 // Moreover the types used in parameters of the kernel functions must be:
9572 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9573 // types) for parameters passed by value;
9574 if (S.getLangOpts().OpenCLCPlusPlus &&
9576 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9577 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9578 return InvalidKernelParam;
9579
9580 if (PT->isRecordType())
9581 return RecordKernelParam;
9582
9583 return ValidKernelParam;
9584}
9585
9587 Sema &S,
9588 Declarator &D,
9589 ParmVarDecl *Param,
9590 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9591 QualType PT = Param->getType();
9592
9593 // Cache the valid types we encounter to avoid rechecking structs that are
9594 // used again
9595 if (ValidTypes.count(PT.getTypePtr()))
9596 return;
9597
9598 switch (getOpenCLKernelParameterType(S, PT)) {
9599 case PtrPtrKernelParam:
9600 // OpenCL v3.0 s6.11.a:
9601 // A kernel function argument cannot be declared as a pointer to a pointer
9602 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9603 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9604 D.setInvalidType();
9605 return;
9606
9608 // OpenCL v1.0 s6.5:
9609 // __kernel function arguments declared to be a pointer of a type can point
9610 // to one of the following address spaces only : __global, __local or
9611 // __constant.
9612 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9613 D.setInvalidType();
9614 return;
9615
9616 // OpenCL v1.2 s6.9.k:
9617 // Arguments to kernel functions in a program cannot be declared with the
9618 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9619 // uintptr_t or a struct and/or union that contain fields declared to be
9620 // one of these built-in scalar types.
9621
9622 case InvalidKernelParam:
9623 // OpenCL v1.2 s6.8 n:
9624 // A kernel function argument cannot be declared
9625 // of event_t type.
9626 // Do not diagnose half type since it is diagnosed as invalid argument
9627 // type for any function elsewhere.
9628 if (!PT->isHalfType()) {
9629 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9630
9631 // Explain what typedefs are involved.
9632 const TypedefType *Typedef = nullptr;
9633 while ((Typedef = PT->getAs<TypedefType>())) {
9634 SourceLocation Loc = Typedef->getDecl()->getLocation();
9635 // SourceLocation may be invalid for a built-in type.
9636 if (Loc.isValid())
9637 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9638 PT = Typedef->desugar();
9639 }
9640 }
9641
9642 D.setInvalidType();
9643 return;
9644
9645 case PtrKernelParam:
9646 case ValidKernelParam:
9647 ValidTypes.insert(PT.getTypePtr());
9648 return;
9649
9650 case RecordKernelParam:
9651 break;
9652 }
9653
9654 // Track nested structs we will inspect
9656
9657 // Track where we are in the nested structs. Items will migrate from
9658 // VisitStack to HistoryStack as we do the DFS for bad field.
9660 HistoryStack.push_back(nullptr);
9661
9662 // At this point we already handled everything except of a RecordType or
9663 // an ArrayType of a RecordType.
9664 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9665 const RecordType *RecTy =
9667 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9668
9669 VisitStack.push_back(RecTy->getDecl());
9670 assert(VisitStack.back() && "First decl null?");
9671
9672 do {
9673 const Decl *Next = VisitStack.pop_back_val();
9674 if (!Next) {
9675 assert(!HistoryStack.empty());
9676 // Found a marker, we have gone up a level
9677 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9678 ValidTypes.insert(Hist->getType().getTypePtr());
9679
9680 continue;
9681 }
9682
9683 // Adds everything except the original parameter declaration (which is not a
9684 // field itself) to the history stack.
9685 const RecordDecl *RD;
9686 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9687 HistoryStack.push_back(Field);
9688
9689 QualType FieldTy = Field->getType();
9690 // Other field types (known to be valid or invalid) are handled while we
9691 // walk around RecordDecl::fields().
9692 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9693 "Unexpected type.");
9694 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9695
9696 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9697 } else {
9698 RD = cast<RecordDecl>(Next);
9699 }
9700
9701 // Add a null marker so we know when we've gone back up a level
9702 VisitStack.push_back(nullptr);
9703
9704 for (const auto *FD : RD->fields()) {
9705 QualType QT = FD->getType();
9706
9707 if (ValidTypes.count(QT.getTypePtr()))
9708 continue;
9709
9711 if (ParamType == ValidKernelParam)
9712 continue;
9713
9714 if (ParamType == RecordKernelParam) {
9715 VisitStack.push_back(FD);
9716 continue;
9717 }
9718
9719 // OpenCL v1.2 s6.9.p:
9720 // Arguments to kernel functions that are declared to be a struct or union
9721 // do not allow OpenCL objects to be passed as elements of the struct or
9722 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9723 // of SVM.
9724 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9725 ParamType == InvalidAddrSpacePtrKernelParam) {
9726 S.Diag(Param->getLocation(),
9727 diag::err_record_with_pointers_kernel_param)
9728 << PT->isUnionType()
9729 << PT;
9730 } else {
9731 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9732 }
9733
9734 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9735 << OrigRecDecl->getDeclName();
9736
9737 // We have an error, now let's go back up through history and show where
9738 // the offending field came from
9740 I = HistoryStack.begin() + 1,
9741 E = HistoryStack.end();
9742 I != E; ++I) {
9743 const FieldDecl *OuterField = *I;
9744 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9745 << OuterField->getType();
9746 }
9747
9748 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9749 << QT->isPointerType()
9750 << QT;
9751 D.setInvalidType();
9752 return;
9753 }
9754 } while (!VisitStack.empty());
9755}
9756
9757/// Find the DeclContext in which a tag is implicitly declared if we see an
9758/// elaborated type specifier in the specified context, and lookup finds
9759/// nothing.
9761 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9762 DC = DC->getParent();
9763 return DC;
9764}
9765
9766/// Find the Scope in which a tag is implicitly declared if we see an
9767/// elaborated type specifier in the specified context, and lookup finds
9768/// nothing.
9769static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9770 while (S->isClassScope() ||
9771 (LangOpts.CPlusPlus &&
9772 S->isFunctionPrototypeScope()) ||
9773 ((S->getFlags() & Scope::DeclScope) == 0) ||
9774 (S->getEntity() && S->getEntity()->isTransparentContext()))
9775 S = S->getParent();
9776 return S;
9777}
9778
9779/// Determine whether a declaration matches a known function in namespace std.
9781 unsigned BuiltinID) {
9782 switch (BuiltinID) {
9783 case Builtin::BI__GetExceptionInfo:
9784 // No type checking whatsoever.
9785 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9786
9787 case Builtin::BIaddressof:
9788 case Builtin::BI__addressof:
9789 case Builtin::BIforward:
9790 case Builtin::BIforward_like:
9791 case Builtin::BImove:
9792 case Builtin::BImove_if_noexcept:
9793 case Builtin::BIas_const: {
9794 // Ensure that we don't treat the algorithm
9795 // OutputIt std::move(InputIt, InputIt, OutputIt)
9796 // as the builtin std::move.
9797 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9798 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9799 }
9800
9801 default:
9802 return false;
9803 }
9804}
9805
9806NamedDecl*
9809 MultiTemplateParamsArg TemplateParamListsRef,
9810 bool &AddToScope) {
9811 QualType R = TInfo->getType();
9812
9813 assert(R->isFunctionType());
9815 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9816
9817 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9818 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9820 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9821 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9822 TemplateParamLists.back() = Invented;
9823 else
9824 TemplateParamLists.push_back(Invented);
9825 }
9826
9827 // TODO: consider using NameInfo for diagnostic.
9829 DeclarationName Name = NameInfo.getName();
9831
9834 diag::err_invalid_thread)
9836
9841
9842 bool isFriend = false;
9844 bool isMemberSpecialization = false;
9845 bool isFunctionTemplateSpecialization = false;
9846
9847 bool HasExplicitTemplateArgs = false;
9848 TemplateArgumentListInfo TemplateArgs;
9849
9850 bool isVirtualOkay = false;
9851
9852 DeclContext *OriginalDC = DC;
9853 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9854
9855 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9856 isVirtualOkay);
9857 if (!NewFD) return nullptr;
9858
9861
9862 // Set the lexical context. If this is a function-scope declaration, or has a
9863 // C++ scope specifier, or is the object of a friend declaration, the lexical
9864 // context will be different from the semantic context.
9866
9867 if (IsLocalExternDecl)
9868 NewFD->setLocalExternDecl();
9869
9870 if (getLangOpts().CPlusPlus) {
9871 // The rules for implicit inlines changed in C++20 for methods and friends
9872 // with an in-class definition (when such a definition is not attached to
9873 // the global module). User-specified 'inline' overrides this (set when
9874 // the function decl is created above).
9875 // FIXME: We need a better way to separate C++ standard and clang modules.
9876 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9877 !NewFD->getOwningModule() ||
9878 NewFD->isFromExplicitGlobalModule() ||
9880 bool isInline = D.getDeclSpec().isInlineSpecified();
9881 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9882 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9883 isFriend = D.getDeclSpec().isFriendSpecified();
9884 if (isFriend && !isInline && D.isFunctionDefinition()) {
9885 // Pre-C++20 [class.friend]p5
9886 // A function can be defined in a friend declaration of a
9887 // class . . . . Such a function is implicitly inline.
9888 // Post C++20 [class.friend]p7
9889 // Such a function is implicitly an inline function if it is attached
9890 // to the global module.
9891 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9892 }
9893
9894 // If this is a method defined in an __interface, and is not a constructor
9895 // or an overloaded operator, then set the pure flag (isVirtual will already
9896 // return true).
9897 if (const CXXRecordDecl *Parent =
9898 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9899 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9900 NewFD->setIsPureVirtual(true);
9901
9902 // C++ [class.union]p2
9903 // A union can have member functions, but not virtual functions.
9904 if (isVirtual && Parent->isUnion()) {
9905 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9906 NewFD->setInvalidDecl();
9907 }
9908 if ((Parent->isClass() || Parent->isStruct()) &&
9909 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9910 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9911 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9912 if (auto *Def = Parent->getDefinition())
9913 Def->setInitMethod(true);
9914 }
9915 }
9916
9917 SetNestedNameSpecifier(*this, NewFD, D);
9918 isMemberSpecialization = false;
9919 isFunctionTemplateSpecialization = false;
9920 if (D.isInvalidType())
9921 NewFD->setInvalidDecl();
9922
9923 // Match up the template parameter lists with the scope specifier, then
9924 // determine whether we have a template or a template specialization.
9925 bool Invalid = false;
9926 TemplateIdAnnotation *TemplateId =
9928 ? D.getName().TemplateId
9929 : nullptr;
9930 TemplateParameterList *TemplateParams =
9933 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9934 isMemberSpecialization, Invalid);
9935 if (TemplateParams) {
9936 // Check that we can declare a template here.
9937 if (CheckTemplateDeclScope(S, TemplateParams))
9938 NewFD->setInvalidDecl();
9939
9940 if (TemplateParams->size() > 0) {
9941 // This is a function template
9942
9943 // A destructor cannot be a template.
9944 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9945 Diag(NewFD->getLocation(), diag::err_destructor_template);
9946 NewFD->setInvalidDecl();
9947 // Function template with explicit template arguments.
9948 } else if (TemplateId) {
9949 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9950 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9951 NewFD->setInvalidDecl();
9952 }
9953
9954 // If we're adding a template to a dependent context, we may need to
9955 // rebuilding some of the types used within the template parameter list,
9956 // now that we know what the current instantiation is.
9957 if (DC->isDependentContext()) {
9958 ContextRAII SavedContext(*this, DC);
9960 Invalid = true;
9961 }
9962
9964 NewFD->getLocation(),
9965 Name, TemplateParams,
9966 NewFD);
9967 FunctionTemplate->setLexicalDeclContext(CurContext);
9969
9970 // For source fidelity, store the other template param lists.
9971 if (TemplateParamLists.size() > 1) {
9973 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9974 .drop_back(1));
9975 }
9976 } else {
9977 // This is a function template specialization.
9978 isFunctionTemplateSpecialization = true;
9979 // For source fidelity, store all the template param lists.
9980 if (TemplateParamLists.size() > 0)
9981 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9982
9983 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9984 if (isFriend) {
9985 // We want to remove the "template<>", found here.
9986 SourceRange RemoveRange = TemplateParams->getSourceRange();
9987
9988 // If we remove the template<> and the name is not a
9989 // template-id, we're actually silently creating a problem:
9990 // the friend declaration will refer to an untemplated decl,
9991 // and clearly the user wants a template specialization. So
9992 // we need to insert '<>' after the name.
9993 SourceLocation InsertLoc;
9995 InsertLoc = D.getName().getSourceRange().getEnd();
9996 InsertLoc = getLocForEndOfToken(InsertLoc);
9997 }
9998
9999 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10000 << Name << RemoveRange
10001 << FixItHint::CreateRemoval(RemoveRange)
10002 << FixItHint::CreateInsertion(InsertLoc, "<>");
10003 Invalid = true;
10004
10005 // Recover by faking up an empty template argument list.
10006 HasExplicitTemplateArgs = true;
10007 TemplateArgs.setLAngleLoc(InsertLoc);
10008 TemplateArgs.setRAngleLoc(InsertLoc);
10009 }
10010 }
10011 } else {
10012 // Check that we can declare a template here.
10013 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10014 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10015 NewFD->setInvalidDecl();
10016
10017 // All template param lists were matched against the scope specifier:
10018 // this is NOT (an explicit specialization of) a template.
10019 if (TemplateParamLists.size() > 0)
10020 // For source fidelity, store all the template param lists.
10021 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10022
10023 // "friend void foo<>(int);" is an implicit specialization decl.
10024 if (isFriend && TemplateId)
10025 isFunctionTemplateSpecialization = true;
10026 }
10027
10028 // If this is a function template specialization and the unqualified-id of
10029 // the declarator-id is a template-id, convert the template argument list
10030 // into our AST format and check for unexpanded packs.
10031 if (isFunctionTemplateSpecialization && TemplateId) {
10032 HasExplicitTemplateArgs = true;
10033
10034 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10035 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10036 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10037 TemplateId->NumArgs);
10038 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10039
10040 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10041 // declaration of a function template partial specialization? Should we
10042 // consider the unexpanded pack context to be a partial specialization?
10043 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10045 ArgLoc, isFriend ? UPPC_FriendDeclaration
10047 NewFD->setInvalidDecl();
10048 }
10049 }
10050
10051 if (Invalid) {
10052 NewFD->setInvalidDecl();
10053 if (FunctionTemplate)
10054 FunctionTemplate->setInvalidDecl();
10055 }
10056
10057 // C++ [dcl.fct.spec]p5:
10058 // The virtual specifier shall only be used in declarations of
10059 // nonstatic class member functions that appear within a
10060 // member-specification of a class declaration; see 10.3.
10061 //
10062 if (isVirtual && !NewFD->isInvalidDecl()) {
10063 if (!isVirtualOkay) {
10065 diag::err_virtual_non_function);
10066 } else if (!CurContext->isRecord()) {
10067 // 'virtual' was specified outside of the class.
10069 diag::err_virtual_out_of_class)
10071 } else if (NewFD->getDescribedFunctionTemplate()) {
10072 // C++ [temp.mem]p3:
10073 // A member function template shall not be virtual.
10075 diag::err_virtual_member_function_template)
10077 } else {
10078 // Okay: Add virtual to the method.
10079 NewFD->setVirtualAsWritten(true);
10080 }
10081
10082 if (getLangOpts().CPlusPlus14 &&
10083 NewFD->getReturnType()->isUndeducedType())
10084 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10085 }
10086
10087 // C++ [dcl.fct.spec]p3:
10088 // The inline specifier shall not appear on a block scope function
10089 // declaration.
10090 if (isInline && !NewFD->isInvalidDecl()) {
10092 // 'inline' is not allowed on block scope function declaration.
10094 diag::err_inline_declaration_block_scope) << Name
10096 }
10097 }
10098
10099 // C++ [dcl.fct.spec]p6:
10100 // The explicit specifier shall be used only in the declaration of a
10101 // constructor or conversion function within its class definition;
10102 // see 12.3.1 and 12.3.2.
10103 if (hasExplicit && !NewFD->isInvalidDecl() &&
10104 !isa<CXXDeductionGuideDecl>(NewFD)) {
10105 if (!CurContext->isRecord()) {
10106 // 'explicit' was specified outside of the class.
10108 diag::err_explicit_out_of_class)
10110 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10111 !isa<CXXConversionDecl>(NewFD)) {
10112 // 'explicit' was specified on a function that wasn't a constructor
10113 // or conversion function.
10115 diag::err_explicit_non_ctor_or_conv_function)
10117 }
10118 }
10119
10121 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10122 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10123 // are implicitly inline.
10124 NewFD->setImplicitlyInline();
10125
10126 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10127 // be either constructors or to return a literal type. Therefore,
10128 // destructors cannot be declared constexpr.
10129 if (isa<CXXDestructorDecl>(NewFD) &&
10131 ConstexprKind == ConstexprSpecKind::Consteval)) {
10132 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10133 << static_cast<int>(ConstexprKind);
10134 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10137 }
10138 // C++20 [dcl.constexpr]p2: An allocation function, or a
10139 // deallocation function shall not be declared with the consteval
10140 // specifier.
10141 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10142 (NewFD->getOverloadedOperator() == OO_New ||
10143 NewFD->getOverloadedOperator() == OO_Array_New ||
10144 NewFD->getOverloadedOperator() == OO_Delete ||
10145 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10147 diag::err_invalid_consteval_decl_kind)
10148 << NewFD;
10150 }
10151 }
10152
10153 // If __module_private__ was specified, mark the function accordingly.
10155 if (isFunctionTemplateSpecialization) {
10156 SourceLocation ModulePrivateLoc
10158 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10159 << 0
10160 << FixItHint::CreateRemoval(ModulePrivateLoc);
10161 } else {
10162 NewFD->setModulePrivate();
10163 if (FunctionTemplate)
10164 FunctionTemplate->setModulePrivate();
10165 }
10166 }
10167
10168 if (isFriend) {
10169 if (FunctionTemplate) {
10170 FunctionTemplate->setObjectOfFriendDecl();
10171 FunctionTemplate->setAccess(AS_public);
10172 }
10173 NewFD->setObjectOfFriendDecl();
10174 NewFD->setAccess(AS_public);
10175 }
10176
10177 // If a function is defined as defaulted or deleted, mark it as such now.
10178 // We'll do the relevant checks on defaulted / deleted functions later.
10179 switch (D.getFunctionDefinitionKind()) {
10182 break;
10183
10185 NewFD->setDefaulted();
10186 break;
10187
10189 NewFD->setDeletedAsWritten();
10190 break;
10191 }
10192
10193 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10194 D.isFunctionDefinition() && !isInline) {
10195 // Pre C++20 [class.mfct]p2:
10196 // A member function may be defined (8.4) in its class definition, in
10197 // which case it is an inline member function (7.1.2)
10198 // Post C++20 [class.mfct]p1:
10199 // If a member function is attached to the global module and is defined
10200 // in its class definition, it is inline.
10201 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10202 }
10203
10204 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10205 !CurContext->isRecord()) {
10206 // C++ [class.static]p1:
10207 // A data or function member of a class may be declared static
10208 // in a class definition, in which case it is a static member of
10209 // the class.
10210
10211 // Complain about the 'static' specifier if it's on an out-of-line
10212 // member function definition.
10213
10214 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10215 // member function template declaration and class member template
10216 // declaration (MSVC versions before 2015), warn about this.
10218 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10219 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10220 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10221 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10223 }
10224
10225 // C++11 [except.spec]p15:
10226 // A deallocation function with no exception-specification is treated
10227 // as if it were specified with noexcept(true).
10228 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10229 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10230 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10231 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10233 FPT->getReturnType(), FPT->getParamTypes(),
10235
10236 // C++20 [dcl.inline]/7
10237 // If an inline function or variable that is attached to a named module
10238 // is declared in a definition domain, it shall be defined in that
10239 // domain.
10240 // So, if the current declaration does not have a definition, we must
10241 // check at the end of the TU (or when the PMF starts) to see that we
10242 // have a definition at that point.
10243 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10244 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10245 PendingInlineFuncDecls.insert(NewFD);
10246 }
10247 }
10248
10249 // Filter out previous declarations that don't match the scope.
10252 isMemberSpecialization ||
10253 isFunctionTemplateSpecialization);
10254
10255 // Handle GNU asm-label extension (encoded as an attribute).
10256 if (Expr *E = (Expr*) D.getAsmLabel()) {
10257 // The parser guarantees this is a string.
10258 StringLiteral *SE = cast<StringLiteral>(E);
10259 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10260 /*IsLiteralLabel=*/true,
10261 SE->getStrTokenLoc(0)));
10262 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10263 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10265 if (I != ExtnameUndeclaredIdentifiers.end()) {
10266 if (isDeclExternC(NewFD)) {
10267 NewFD->addAttr(I->second);
10269 } else
10270 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10271 << /*Variable*/0 << NewFD;
10272 }
10273 }
10274
10275 // Copy the parameter declarations from the declarator D to the function
10276 // declaration NewFD, if they are available. First scavenge them into Params.
10278 unsigned FTIIdx;
10279 if (D.isFunctionDeclarator(FTIIdx)) {
10281
10282 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10283 // function that takes no arguments, not a function that takes a
10284 // single void argument.
10285 // We let through "const void" here because Sema::GetTypeForDeclarator
10286 // already checks for that case.
10287 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10288 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10289 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10290 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10291 Param->setDeclContext(NewFD);
10292 Params.push_back(Param);
10293
10294 if (Param->isInvalidDecl())
10295 NewFD->setInvalidDecl();
10296 }
10297 }
10298
10299 if (!getLangOpts().CPlusPlus) {
10300 // In C, find all the tag declarations from the prototype and move them
10301 // into the function DeclContext. Remove them from the surrounding tag
10302 // injection context of the function, which is typically but not always
10303 // the TU.
10304 DeclContext *PrototypeTagContext =
10306 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10307 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10308
10309 // We don't want to reparent enumerators. Look at their parent enum
10310 // instead.
10311 if (!TD) {
10312 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10313 TD = cast<EnumDecl>(ECD->getDeclContext());
10314 }
10315 if (!TD)
10316 continue;
10317 DeclContext *TagDC = TD->getLexicalDeclContext();
10318 if (!TagDC->containsDecl(TD))
10319 continue;
10320 TagDC->removeDecl(TD);
10321 TD->setDeclContext(NewFD);
10322 NewFD->addDecl(TD);
10323
10324 // Preserve the lexical DeclContext if it is not the surrounding tag
10325 // injection context of the FD. In this example, the semantic context of
10326 // E will be f and the lexical context will be S, while both the
10327 // semantic and lexical contexts of S will be f:
10328 // void f(struct S { enum E { a } f; } s);
10329 if (TagDC != PrototypeTagContext)
10330 TD->setLexicalDeclContext(TagDC);
10331 }
10332 }
10333 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10334 // When we're declaring a function with a typedef, typeof, etc as in the
10335 // following example, we'll need to synthesize (unnamed)
10336 // parameters for use in the declaration.
10337 //
10338 // @code
10339 // typedef void fn(int);
10340 // fn f;
10341 // @endcode
10342
10343 // Synthesize a parameter for each argument type.
10344 for (const auto &AI : FT->param_types()) {
10345 ParmVarDecl *Param =
10347 Param->setScopeInfo(0, Params.size());
10348 Params.push_back(Param);
10349 }
10350 } else {
10351 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10352 "Should not need args for typedef of non-prototype fn");
10353 }
10354
10355 // Finally, we know we have the right number of parameters, install them.
10356 NewFD->setParams(Params);
10357
10359 NewFD->addAttr(
10360 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10361
10362 // Functions returning a variably modified type violate C99 6.7.5.2p2
10363 // because all functions have linkage.
10364 if (!NewFD->isInvalidDecl() &&
10366 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10367 NewFD->setInvalidDecl();
10368 }
10369
10370 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10372 !NewFD->hasAttr<SectionAttr>())
10373 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10376
10377 // Apply an implicit SectionAttr if #pragma code_seg is active.
10378 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10379 !NewFD->hasAttr<SectionAttr>()) {
10380 NewFD->addAttr(SectionAttr::CreateImplicit(
10381 Context, CodeSegStack.CurrentValue->getString(),
10382 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10383 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10386 NewFD))
10387 NewFD->dropAttr<SectionAttr>();
10388 }
10389
10390 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10391 // active.
10393 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10394 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10396
10397 // Apply an implicit CodeSegAttr from class declspec or
10398 // apply an implicit SectionAttr from #pragma code_seg if active.
10399 if (!NewFD->hasAttr<CodeSegAttr>()) {
10401 D.isFunctionDefinition())) {
10402 NewFD->addAttr(SAttr);
10403 }
10404 }
10405
10406 // Handle attributes.
10407 ProcessDeclAttributes(S, NewFD, D);
10408 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10409 if (NewTVA && !NewTVA->isDefaultVersion() &&
10410 !Context.getTargetInfo().hasFeature("fmv")) {
10411 // Don't add to scope fmv functions declarations if fmv disabled
10412 AddToScope = false;
10413 return NewFD;
10414 }
10415
10416 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10417 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10418 // type.
10419 //
10420 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10421 // type declaration will generate a compilation error.
10422 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10423 if (AddressSpace != LangAS::Default) {
10424 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10425 NewFD->setInvalidDecl();
10426 }
10427 }
10428
10429 if (!getLangOpts().CPlusPlus) {
10430 // Perform semantic checking on the function declaration.
10431 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10432 CheckMain(NewFD, D.getDeclSpec());
10433
10434 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10435 CheckMSVCRTEntryPoint(NewFD);
10436
10437 if (!NewFD->isInvalidDecl())
10439 isMemberSpecialization,
10441 else if (!Previous.empty())
10442 // Recover gracefully from an invalid redeclaration.
10443 D.setRedeclaration(true);
10444 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10445 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10446 "previous declaration set still overloaded");
10447
10448 // Diagnose no-prototype function declarations with calling conventions that
10449 // don't support variadic calls. Only do this in C and do it after merging
10450 // possibly prototyped redeclarations.
10451 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10452 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10453 CallingConv CC = FT->getExtInfo().getCC();
10454 if (!supportsVariadicCall(CC)) {
10455 // Windows system headers sometimes accidentally use stdcall without
10456 // (void) parameters, so we relax this to a warning.
10457 int DiagID =
10458 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10459 Diag(NewFD->getLocation(), DiagID)
10461 }
10462 }
10463
10469 } else {
10470 // C++11 [replacement.functions]p3:
10471 // The program's definitions shall not be specified as inline.
10472 //
10473 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10474 //
10475 // Suppress the diagnostic if the function is __attribute__((used)), since
10476 // that forces an external definition to be emitted.
10477 if (D.getDeclSpec().isInlineSpecified() &&
10479 !NewFD->hasAttr<UsedAttr>())
10481 diag::ext_operator_new_delete_declared_inline)
10482 << NewFD->getDeclName();
10483
10484 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10485 // C++20 [dcl.decl.general]p4:
10486 // The optional requires-clause in an init-declarator or
10487 // member-declarator shall be present only if the declarator declares a
10488 // templated function.
10489 //
10490 // C++20 [temp.pre]p8:
10491 // An entity is templated if it is
10492 // - a template,
10493 // - an entity defined or created in a templated entity,
10494 // - a member of a templated entity,
10495 // - an enumerator for an enumeration that is a templated entity, or
10496 // - the closure type of a lambda-expression appearing in the
10497 // declaration of a templated entity.
10498 //
10499 // [Note 6: A local class, a local or block variable, or a friend
10500 // function defined in a templated entity is a templated entity.
10501 // — end note]
10502 //
10503 // A templated function is a function template or a function that is
10504 // templated. A templated class is a class template or a class that is
10505 // templated. A templated variable is a variable template or a variable
10506 // that is templated.
10507 if (!FunctionTemplate) {
10508 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10509 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10510 // An explicit specialization shall not have a trailing
10511 // requires-clause unless it declares a function template.
10512 //
10513 // Since a friend function template specialization cannot be
10514 // definition, and since a non-template friend declaration with a
10515 // trailing requires-clause must be a definition, we diagnose
10516 // friend function template specializations with trailing
10517 // requires-clauses on the same path as explicit specializations
10518 // even though they aren't necessarily prohibited by the same
10519 // language rule.
10520 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10521 << isFriend;
10522 } else if (isFriend && NewFD->isTemplated() &&
10523 !D.isFunctionDefinition()) {
10524 // C++ [temp.friend]p9:
10525 // A non-template friend declaration with a requires-clause shall be
10526 // a definition.
10527 Diag(NewFD->getBeginLoc(),
10528 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10529 NewFD->setInvalidDecl();
10530 } else if (!NewFD->isTemplated() ||
10531 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10532 Diag(TRC->getBeginLoc(),
10533 diag::err_constrained_non_templated_function);
10534 }
10535 }
10536 }
10537
10538 // We do not add HD attributes to specializations here because
10539 // they may have different constexpr-ness compared to their
10540 // templates and, after maybeAddHostDeviceAttrs() is applied,
10541 // may end up with different effective targets. Instead, a
10542 // specialization inherits its target attributes from its template
10543 // in the CheckFunctionTemplateSpecialization() call below.
10544 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10546
10547 // Handle explict specializations of function templates
10548 // and friend function declarations with an explicit
10549 // template argument list.
10550 if (isFunctionTemplateSpecialization) {
10551 bool isDependentSpecialization = false;
10552 if (isFriend) {
10553 // For friend function specializations, this is a dependent
10554 // specialization if its semantic context is dependent, its
10555 // type is dependent, or if its template-id is dependent.
10556 isDependentSpecialization =
10557 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10558 (HasExplicitTemplateArgs &&
10561 TemplateArgs.arguments()));
10562 assert((!isDependentSpecialization ||
10563 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10564 "dependent friend function specialization without template "
10565 "args");
10566 } else {
10567 // For class-scope explicit specializations of function templates,
10568 // if the lexical context is dependent, then the specialization
10569 // is dependent.
10570 isDependentSpecialization =
10572 }
10573
10574 TemplateArgumentListInfo *ExplicitTemplateArgs =
10575 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10576 if (isDependentSpecialization) {
10577 // If it's a dependent specialization, it may not be possible
10578 // to determine the primary template (for explicit specializations)
10579 // or befriended declaration (for friends) until the enclosing
10580 // template is instantiated. In such cases, we store the declarations
10581 // found by name lookup and defer resolution until instantiation.
10583 NewFD, ExplicitTemplateArgs, Previous))
10584 NewFD->setInvalidDecl();
10585 } else if (!NewFD->isInvalidDecl()) {
10586 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10587 Previous))
10588 NewFD->setInvalidDecl();
10589 }
10590
10591 // C++ [dcl.stc]p1:
10592 // A storage-class-specifier shall not be specified in an explicit
10593 // specialization (14.7.3)
10594 // FIXME: We should be checking this for dependent specializations.
10597 if (Info && SC != SC_None) {
10598 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10599 Diag(NewFD->getLocation(),
10600 diag::err_explicit_specialization_inconsistent_storage_class)
10601 << SC
10604
10605 else
10606 Diag(NewFD->getLocation(),
10607 diag::ext_explicit_specialization_storage_class)
10610 }
10611 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10613 NewFD->setInvalidDecl();
10614 }
10615
10616 // Perform semantic checking on the function declaration.
10617 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10618 CheckMain(NewFD, D.getDeclSpec());
10619
10620 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10621 CheckMSVCRTEntryPoint(NewFD);
10622
10623 if (!NewFD->isInvalidDecl())
10625 isMemberSpecialization,
10627 else if (!Previous.empty())
10628 // Recover gracefully from an invalid redeclaration.
10629 D.setRedeclaration(true);
10630
10631 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10632 !D.isRedeclaration() ||
10633 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10634 "previous declaration set still overloaded");
10635
10636 NamedDecl *PrincipalDecl = (FunctionTemplate
10637 ? cast<NamedDecl>(FunctionTemplate)
10638 : NewFD);
10639
10640 if (isFriend && NewFD->getPreviousDecl()) {
10641 AccessSpecifier Access = AS_public;
10642 if (!NewFD->isInvalidDecl())
10643 Access = NewFD->getPreviousDecl()->getAccess();
10644
10645 NewFD->setAccess(Access);
10646 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10647 }
10648
10649 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10651 PrincipalDecl->setNonMemberOperator();
10652
10653 // If we have a function template, check the template parameter
10654 // list. This will check and merge default template arguments.
10655 if (FunctionTemplate) {
10656 FunctionTemplateDecl *PrevTemplate =
10657 FunctionTemplate->getPreviousDecl();
10658 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10659 PrevTemplate ? PrevTemplate->getTemplateParameters()
10660 : nullptr,
10665 : (D.getCXXScopeSpec().isSet() &&
10666 DC && DC->isRecord() &&
10667 DC->isDependentContext())
10670 }
10671
10672 if (NewFD->isInvalidDecl()) {
10673 // Ignore all the rest of this.
10674 } else if (!D.isRedeclaration()) {
10675 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10676 AddToScope };
10677 // Fake up an access specifier if it's supposed to be a class member.
10678 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10679 NewFD->setAccess(AS_public);
10680
10681 // Qualified decls generally require a previous declaration.
10682 if (D.getCXXScopeSpec().isSet()) {
10683 // ...with the major exception of templated-scope or
10684 // dependent-scope friend declarations.
10685
10686 // TODO: we currently also suppress this check in dependent
10687 // contexts because (1) the parameter depth will be off when
10688 // matching friend templates and (2) we might actually be
10689 // selecting a friend based on a dependent factor. But there
10690 // are situations where these conditions don't apply and we
10691 // can actually do this check immediately.
10692 //
10693 // Unless the scope is dependent, it's always an error if qualified
10694 // redeclaration lookup found nothing at all. Diagnose that now;
10695 // nothing will diagnose that error later.
10696 if (isFriend &&
10698 (!Previous.empty() && CurContext->isDependentContext()))) {
10699 // ignore these
10700 } else if (NewFD->isCPUDispatchMultiVersion() ||
10701 NewFD->isCPUSpecificMultiVersion()) {
10702 // ignore this, we allow the redeclaration behavior here to create new
10703 // versions of the function.
10704 } else {
10705 // The user tried to provide an out-of-line definition for a
10706 // function that is a member of a class or namespace, but there
10707 // was no such member function declared (C++ [class.mfct]p2,
10708 // C++ [namespace.memdef]p2). For example:
10709 //
10710 // class X {
10711 // void f() const;
10712 // };
10713 //
10714 // void X::f() { } // ill-formed
10715 //
10716 // Complain about this problem, and attempt to suggest close
10717 // matches (e.g., those that differ only in cv-qualifiers and
10718 // whether the parameter types are references).
10719
10721 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10722 AddToScope = ExtraArgs.AddToScope;
10723 return Result;
10724 }
10725 }
10726
10727 // Unqualified local friend declarations are required to resolve
10728 // to something.
10729 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10731 *this, Previous, NewFD, ExtraArgs, true, S)) {
10732 AddToScope = ExtraArgs.AddToScope;
10733 return Result;
10734 }
10735 }
10736 } else if (!D.isFunctionDefinition() &&
10737 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10738 !isFriend && !isFunctionTemplateSpecialization &&
10739 !isMemberSpecialization) {
10740 // An out-of-line member function declaration must also be a
10741 // definition (C++ [class.mfct]p2).
10742 // Note that this is not the case for explicit specializations of
10743 // function templates or member functions of class templates, per
10744 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10745 // extension for compatibility with old SWIG code which likes to
10746 // generate them.
10747 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10748 << D.getCXXScopeSpec().getRange();
10749 }
10750 }
10751
10752 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10753 // Any top level function could potentially be specified as an entry.
10754 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10755 HLSL().ActOnTopLevelFunction(NewFD);
10756
10757 if (NewFD->hasAttr<HLSLShaderAttr>())
10758 HLSL().CheckEntryPoint(NewFD);
10759 }
10760
10761 // If this is the first declaration of a library builtin function, add
10762 // attributes as appropriate.
10763 if (!D.isRedeclaration()) {
10764 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10765 if (unsigned BuiltinID = II->getBuiltinID()) {
10766 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10767 if (!InStdNamespace &&
10769 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10770 // Validate the type matches unless this builtin is specified as
10771 // matching regardless of its declared type.
10772 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10773 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10774 } else {
10776 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10777 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10778
10779 if (!Error && !BuiltinType.isNull() &&
10781 NewFD->getType(), BuiltinType))
10782 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10783 }
10784 }
10785 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10786 isStdBuiltin(Context, NewFD, BuiltinID)) {
10787 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10788 }
10789 }
10790 }
10791 }
10792
10793 ProcessPragmaWeak(S, NewFD);
10794 checkAttributesAfterMerging(*this, *NewFD);
10795
10797
10798 if (NewFD->hasAttr<OverloadableAttr>() &&
10799 !NewFD->getType()->getAs<FunctionProtoType>()) {
10800 Diag(NewFD->getLocation(),
10801 diag::err_attribute_overloadable_no_prototype)
10802 << NewFD;
10803 NewFD->dropAttr<OverloadableAttr>();
10804 }
10805
10806 // If there's a #pragma GCC visibility in scope, and this isn't a class
10807 // member, set the visibility of this function.
10808 if (!DC->isRecord() && NewFD->isExternallyVisible())
10810
10811 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10812 // marking the function.
10813 ObjC().AddCFAuditedAttribute(NewFD);
10814
10815 // If this is a function definition, check if we have to apply any
10816 // attributes (i.e. optnone and no_builtin) due to a pragma.
10817 if (D.isFunctionDefinition()) {
10818 AddRangeBasedOptnone(NewFD);
10820 AddSectionMSAllocText(NewFD);
10822 }
10823
10824 // If this is the first declaration of an extern C variable, update
10825 // the map of such variables.
10826 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10827 isIncompleteDeclExternC(*this, NewFD))
10829
10830 // Set this FunctionDecl's range up to the right paren.
10831 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10832
10833 if (D.isRedeclaration() && !Previous.empty()) {
10834 NamedDecl *Prev = Previous.getRepresentativeDecl();
10835 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10836 isMemberSpecialization ||
10837 isFunctionTemplateSpecialization,
10839 }
10840
10841 if (getLangOpts().CUDA) {
10842 IdentifierInfo *II = NewFD->getIdentifier();
10843 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10844 !NewFD->isInvalidDecl() &&
10847 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10850 }
10851
10852 // Variadic functions, other than a *declaration* of printf, are not allowed
10853 // in device-side CUDA code, unless someone passed
10854 // -fcuda-allow-variadic-functions.
10855 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10856 (NewFD->hasAttr<CUDADeviceAttr>() ||
10857 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10858 !(II && II->isStr("printf") && NewFD->isExternC() &&
10859 !D.isFunctionDefinition())) {
10860 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10861 }
10862 }
10863
10865
10866
10867
10868 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10869 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10870 if (SC == SC_Static) {
10871 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10872 D.setInvalidType();
10873 }
10874
10875 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10876 if (!NewFD->getReturnType()->isVoidType()) {
10877 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10878 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10879 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10880 : FixItHint());
10881 D.setInvalidType();
10882 }
10883
10885 for (auto *Param : NewFD->parameters())
10886 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10887
10888 if (getLangOpts().OpenCLCPlusPlus) {
10889 if (DC->isRecord()) {
10890 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10891 D.setInvalidType();
10892 }
10893 if (FunctionTemplate) {
10894 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10895 D.setInvalidType();
10896 }
10897 }
10898 }
10899
10900 if (getLangOpts().CPlusPlus) {
10901 // Precalculate whether this is a friend function template with a constraint
10902 // that depends on an enclosing template, per [temp.friend]p9.
10903 if (isFriend && FunctionTemplate &&
10906
10907 // C++ [temp.friend]p9:
10908 // A friend function template with a constraint that depends on a
10909 // template parameter from an enclosing template shall be a definition.
10910 if (!D.isFunctionDefinition()) {
10911 Diag(NewFD->getBeginLoc(),
10912 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10913 NewFD->setInvalidDecl();
10914 }
10915 }
10916
10917 if (FunctionTemplate) {
10918 if (NewFD->isInvalidDecl())
10919 FunctionTemplate->setInvalidDecl();
10920 return FunctionTemplate;
10921 }
10922
10923 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10925 }
10926
10927 for (const ParmVarDecl *Param : NewFD->parameters()) {
10928 QualType PT = Param->getType();
10929
10930 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10931 // types.
10932 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10933 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10934 QualType ElemTy = PipeTy->getElementType();
10935 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10936 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10937 D.setInvalidType();
10938 }
10939 }
10940 }
10941 // WebAssembly tables can't be used as function parameters.
10942 if (Context.getTargetInfo().getTriple().isWasm()) {
10944 Diag(Param->getTypeSpecStartLoc(),
10945 diag::err_wasm_table_as_function_parameter);
10946 D.setInvalidType();
10947 }
10948 }
10949 }
10950
10951 // Diagnose availability attributes. Availability cannot be used on functions
10952 // that are run during load/unload.
10953 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10954 if (NewFD->hasAttr<ConstructorAttr>()) {
10955 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10956 << 1;
10957 NewFD->dropAttr<AvailabilityAttr>();
10958 }
10959 if (NewFD->hasAttr<DestructorAttr>()) {
10960 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10961 << 2;
10962 NewFD->dropAttr<AvailabilityAttr>();
10963 }
10964 }
10965
10966 // Diagnose no_builtin attribute on function declaration that are not a
10967 // definition.
10968 // FIXME: We should really be doing this in
10969 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10970 // the FunctionDecl and at this point of the code
10971 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10972 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10973 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10974 switch (D.getFunctionDefinitionKind()) {
10977 Diag(NBA->getLocation(),
10978 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10979 << NBA->getSpelling();
10980 break;
10982 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10983 << NBA->getSpelling();
10984 break;
10986 break;
10987 }
10988
10989 return NewFD;
10990}
10991
10992/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10993/// when __declspec(code_seg) "is applied to a class, all member functions of
10994/// the class and nested classes -- this includes compiler-generated special
10995/// member functions -- are put in the specified segment."
10996/// The actual behavior is a little more complicated. The Microsoft compiler
10997/// won't check outer classes if there is an active value from #pragma code_seg.
10998/// The CodeSeg is always applied from the direct parent but only from outer
10999/// classes when the #pragma code_seg stack is empty. See:
11000/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11001/// available since MS has removed the page.
11003 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11004 if (!Method)
11005 return nullptr;
11006 const CXXRecordDecl *Parent = Method->getParent();
11007 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11008 Attr *NewAttr = SAttr->clone(S.getASTContext());
11009 NewAttr->setImplicit(true);
11010 return NewAttr;
11011 }
11012
11013 // The Microsoft compiler won't check outer classes for the CodeSeg
11014 // when the #pragma code_seg stack is active.
11015 if (S.CodeSegStack.CurrentValue)
11016 return nullptr;
11017
11018 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11019 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11020 Attr *NewAttr = SAttr->clone(S.getASTContext());
11021 NewAttr->setImplicit(true);
11022 return NewAttr;
11023 }
11024 }
11025 return nullptr;
11026}
11027
11028/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
11029/// containing class. Otherwise it will return implicit SectionAttr if the
11030/// function is a definition and there is an active value on CodeSegStack
11031/// (from the current #pragma code-seg value).
11032///
11033/// \param FD Function being declared.
11034/// \param IsDefinition Whether it is a definition or just a declaration.
11035/// \returns A CodeSegAttr or SectionAttr to apply to the function or
11036/// nullptr if no attribute should be added.
11038 bool IsDefinition) {
11039 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11040 return A;
11041 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11042 CodeSegStack.CurrentValue)
11043 return SectionAttr::CreateImplicit(
11044 getASTContext(), CodeSegStack.CurrentValue->getString(),
11045 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11046 return nullptr;
11047}
11048
11049/// Determines if we can perform a correct type check for \p D as a
11050/// redeclaration of \p PrevDecl. If not, we can generally still perform a
11051/// best-effort check.
11052///
11053/// \param NewD The new declaration.
11054/// \param OldD The old declaration.
11055/// \param NewT The portion of the type of the new declaration to check.
11056/// \param OldT The portion of the type of the old declaration to check.
11058 QualType NewT, QualType OldT) {
11060 return true;
11061
11062 // For dependently-typed local extern declarations and friends, we can't
11063 // perform a correct type check in general until instantiation:
11064 //
11065 // int f();
11066 // template<typename T> void g() { T f(); }
11067 //
11068 // (valid if g() is only instantiated with T = int).
11069 if (NewT->isDependentType() &&
11070 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11071 return false;
11072
11073 // Similarly, if the previous declaration was a dependent local extern
11074 // declaration, we don't really know its type yet.
11075 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11076 return false;
11077
11078 return true;
11079}
11080
11081/// Checks if the new declaration declared in dependent context must be
11082/// put in the same redeclaration chain as the specified declaration.
11083///
11084/// \param D Declaration that is checked.
11085/// \param PrevDecl Previous declaration found with proper lookup method for the
11086/// same declaration name.
11087/// \returns True if D must be added to the redeclaration chain which PrevDecl
11088/// belongs to.
11089///
11092 return true;
11093
11094 // Don't chain dependent friend function definitions until instantiation, to
11095 // permit cases like
11096 //
11097 // void func();
11098 // template<typename T> class C1 { friend void func() {} };
11099 // template<typename T> class C2 { friend void func() {} };
11100 //
11101 // ... which is valid if only one of C1 and C2 is ever instantiated.
11102 //
11103 // FIXME: This need only apply to function definitions. For now, we proxy
11104 // this by checking for a file-scope function. We do not want this to apply
11105 // to friend declarations nominating member functions, because that gets in
11106 // the way of access checks.
11108 return false;
11109
11110 auto *VD = dyn_cast<ValueDecl>(D);
11111 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11112 return !VD || !PrevVD ||
11113 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11114 PrevVD->getType());
11115}
11116
11117/// Check the target or target_version attribute of the function for
11118/// MultiVersion validity.
11119///
11120/// Returns true if there was an error, false otherwise.
11121static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11122 const auto *TA = FD->getAttr<TargetAttr>();
11123 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11124 assert(
11125 (TA || TVA) &&
11126 "MultiVersion candidate requires a target or target_version attribute");
11128 enum ErrType { Feature = 0, Architecture = 1 };
11129
11130 if (TA) {
11131 ParsedTargetAttr ParseInfo =
11132 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11133 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11134 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11135 << Architecture << ParseInfo.CPU;
11136 return true;
11137 }
11138 for (const auto &Feat : ParseInfo.Features) {
11139 auto BareFeat = StringRef{Feat}.substr(1);
11140 if (Feat[0] == '-') {
11141 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11142 << Feature << ("no-" + BareFeat).str();
11143 return true;
11144 }
11145
11146 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11147 !TargetInfo.isValidFeatureName(BareFeat)) {
11148 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11149 << Feature << BareFeat;
11150 return true;
11151 }
11152 }
11153 }
11154
11155 if (TVA) {
11157 TVA->getFeatures(Feats);
11158 for (const auto &Feat : Feats) {
11159 if (!TargetInfo.validateCpuSupports(Feat)) {
11160 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11161 << Feature << Feat;
11162 return true;
11163 }
11164 }
11165 }
11166 return false;
11167}
11168
11169// Provide a white-list of attributes that are allowed to be combined with
11170// multiversion functions.
11172 MultiVersionKind MVKind) {
11173 // Note: this list/diagnosis must match the list in
11174 // checkMultiversionAttributesAllSame.
11175 switch (Kind) {
11176 default:
11177 return false;
11178 case attr::Used:
11179 return MVKind == MultiVersionKind::Target;
11180 case attr::NonNull:
11181 case attr::NoThrow:
11182 return true;
11183 }
11184}
11185
11187 const FunctionDecl *FD,
11188 const FunctionDecl *CausedFD,
11189 MultiVersionKind MVKind) {
11190 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11191 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11192 << static_cast<unsigned>(MVKind) << A;
11193 if (CausedFD)
11194 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11195 return true;
11196 };
11197
11198 for (const Attr *A : FD->attrs()) {
11199 switch (A->getKind()) {
11200 case attr::CPUDispatch:
11201 case attr::CPUSpecific:
11202 if (MVKind != MultiVersionKind::CPUDispatch &&
11204 return Diagnose(S, A);
11205 break;
11206 case attr::Target:
11207 if (MVKind != MultiVersionKind::Target)
11208 return Diagnose(S, A);
11209 break;
11210 case attr::TargetVersion:
11211 if (MVKind != MultiVersionKind::TargetVersion &&
11213 return Diagnose(S, A);
11214 break;
11215 case attr::TargetClones:
11216 if (MVKind != MultiVersionKind::TargetClones &&
11218 return Diagnose(S, A);
11219 break;
11220 default:
11221 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11222 return Diagnose(S, A);
11223 break;
11224 }
11225 }
11226 return false;
11227}
11228
11230 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11231 const PartialDiagnostic &NoProtoDiagID,
11232 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11233 const PartialDiagnosticAt &NoSupportDiagIDAt,
11234 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11235 bool ConstexprSupported, bool CLinkageMayDiffer) {
11236 enum DoesntSupport {
11237 FuncTemplates = 0,
11238 VirtFuncs = 1,
11239 DeducedReturn = 2,
11240 Constructors = 3,
11241 Destructors = 4,
11242 DeletedFuncs = 5,
11243 DefaultedFuncs = 6,
11244 ConstexprFuncs = 7,
11245 ConstevalFuncs = 8,
11246 Lambda = 9,
11247 };
11248 enum Different {
11249 CallingConv = 0,
11250 ReturnType = 1,
11251 ConstexprSpec = 2,
11252 InlineSpec = 3,
11253 Linkage = 4,
11254 LanguageLinkage = 5,
11255 };
11256
11257 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11258 !OldFD->getType()->getAs<FunctionProtoType>()) {
11259 Diag(OldFD->getLocation(), NoProtoDiagID);
11260 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11261 return true;
11262 }
11263
11264 if (NoProtoDiagID.getDiagID() != 0 &&
11265 !NewFD->getType()->getAs<FunctionProtoType>())
11266 return Diag(NewFD->getLocation(), NoProtoDiagID);
11267
11268 if (!TemplatesSupported &&
11270 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11271 << FuncTemplates;
11272
11273 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11274 if (NewCXXFD->isVirtual())
11275 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11276 << VirtFuncs;
11277
11278 if (isa<CXXConstructorDecl>(NewCXXFD))
11279 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11280 << Constructors;
11281
11282 if (isa<CXXDestructorDecl>(NewCXXFD))
11283 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11284 << Destructors;
11285 }
11286
11287 if (NewFD->isDeleted())
11288 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11289 << DeletedFuncs;
11290
11291 if (NewFD->isDefaulted())
11292 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11293 << DefaultedFuncs;
11294
11295 if (!ConstexprSupported && NewFD->isConstexpr())
11296 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11297 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11298
11299 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11300 const auto *NewType = cast<FunctionType>(NewQType);
11301 QualType NewReturnType = NewType->getReturnType();
11302
11303 if (NewReturnType->isUndeducedType())
11304 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11305 << DeducedReturn;
11306
11307 // Ensure the return type is identical.
11308 if (OldFD) {
11309 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11310 const auto *OldType = cast<FunctionType>(OldQType);
11311 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11312 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11313
11314 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11315 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11316
11317 QualType OldReturnType = OldType->getReturnType();
11318
11319 if (OldReturnType != NewReturnType)
11320 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11321
11322 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11323 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11324
11325 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11326 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11327
11328 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11329 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11330
11331 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11332 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11333
11335 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11336 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11337 return true;
11338 }
11339 return false;
11340}
11341
11343 const FunctionDecl *NewFD,
11344 bool CausesMV,
11345 MultiVersionKind MVKind) {
11347 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11348 if (OldFD)
11349 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11350 return true;
11351 }
11352
11353 bool IsCPUSpecificCPUDispatchMVKind =
11356
11357 if (CausesMV && OldFD &&
11358 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11359 return true;
11360
11361 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11362 return true;
11363
11364 // Only allow transition to MultiVersion if it hasn't been used.
11365 if (OldFD && CausesMV && OldFD->isUsed(false))
11366 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11367
11369 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11371 S.PDiag(diag::note_multiversioning_caused_here)),
11373 S.PDiag(diag::err_multiversion_doesnt_support)
11374 << static_cast<unsigned>(MVKind)),
11376 S.PDiag(diag::err_multiversion_diff)),
11377 /*TemplatesSupported=*/false,
11378 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11379 /*CLinkageMayDiffer=*/false);
11380}
11381
11382/// Check the validity of a multiversion function declaration that is the
11383/// first of its kind. Also sets the multiversion'ness' of the function itself.
11384///
11385/// This sets NewFD->isInvalidDecl() to true if there was an error.
11386///
11387/// Returns true if there was an error, false otherwise.
11390 assert(MVKind != MultiVersionKind::None &&
11391 "Function lacks multiversion attribute");
11392 const auto *TA = FD->getAttr<TargetAttr>();
11393 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11394 // The target attribute only causes MV if this declaration is the default,
11395 // otherwise it is treated as a normal function.
11396 if (TA && !TA->isDefaultVersion())
11397 return false;
11398
11399 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11400 FD->setInvalidDecl();
11401 return true;
11402 }
11403
11404 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11405 FD->setInvalidDecl();
11406 return true;
11407 }
11408
11409 FD->setIsMultiVersion();
11410 return false;
11411}
11412
11414 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11416 return true;
11417 }
11418
11419 return false;
11420}
11421
11423 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11424 return;
11425
11426 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11427 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11428
11429 if (MVKindTo == MultiVersionKind::None &&
11430 (MVKindFrom == MultiVersionKind::TargetVersion ||
11431 MVKindFrom == MultiVersionKind::TargetClones)) {
11432 To->setIsMultiVersion();
11433 To->addAttr(TargetVersionAttr::CreateImplicit(
11434 To->getASTContext(), "default", To->getSourceRange()));
11435 }
11436}
11437
11439 FunctionDecl *NewFD,
11440 bool &Redeclaration,
11441 NamedDecl *&OldDecl,
11443 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11444
11445 // The definitions should be allowed in any order. If we have discovered
11446 // a new target version and the preceeding was the default, then add the
11447 // corresponding attribute to it.
11448 patchDefaultTargetVersion(NewFD, OldFD);
11449
11450 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11451 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11452 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11453 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11454 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11455 // to change, this is a simple redeclaration.
11456 if ((NewTA && !NewTA->isDefaultVersion() &&
11457 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11458 (NewTVA && !NewTVA->isDefaultVersion() &&
11459 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11460 return false;
11461
11462 // Otherwise, this decl causes MultiVersioning.
11463 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11466 NewFD->setInvalidDecl();
11467 return true;
11468 }
11469
11470 if (CheckMultiVersionValue(S, NewFD)) {
11471 NewFD->setInvalidDecl();
11472 return true;
11473 }
11474
11475 // If this is 'default', permit the forward declaration.
11476 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11477 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11478 Redeclaration = true;
11479 OldDecl = OldFD;
11480 OldFD->setIsMultiVersion();
11481 NewFD->setIsMultiVersion();
11482 return false;
11483 }
11484
11485 if (CheckMultiVersionValue(S, OldFD)) {
11486 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11487 NewFD->setInvalidDecl();
11488 return true;
11489 }
11490
11491 if (NewTA) {
11492 ParsedTargetAttr OldParsed =
11494 OldTA->getFeaturesStr());
11495 llvm::sort(OldParsed.Features);
11496 ParsedTargetAttr NewParsed =
11498 NewTA->getFeaturesStr());
11499 // Sort order doesn't matter, it just needs to be consistent.
11500 llvm::sort(NewParsed.Features);
11501 if (OldParsed == NewParsed) {
11502 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11503 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11504 NewFD->setInvalidDecl();
11505 return true;
11506 }
11507 }
11508
11509 if (NewTVA) {
11511 OldTVA->getFeatures(Feats);
11512 llvm::sort(Feats);
11514 NewTVA->getFeatures(NewFeats);
11515 llvm::sort(NewFeats);
11516
11517 if (Feats == NewFeats) {
11518 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11519 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11520 NewFD->setInvalidDecl();
11521 return true;
11522 }
11523 }
11524
11525 for (const auto *FD : OldFD->redecls()) {
11526 const auto *CurTA = FD->getAttr<TargetAttr>();
11527 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11528 // We allow forward declarations before ANY multiversioning attributes, but
11529 // nothing after the fact.
11531 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11532 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11533 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11534 << (NewTA ? 0 : 2);
11535 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11536 NewFD->setInvalidDecl();
11537 return true;
11538 }
11539 }
11540
11541 OldFD->setIsMultiVersion();
11542 NewFD->setIsMultiVersion();
11543 Redeclaration = false;
11544 OldDecl = nullptr;
11545 Previous.clear();
11546 return false;
11547}
11548
11550 MultiVersionKind OldKind = Old->getMultiVersionKind();
11551 MultiVersionKind NewKind = New->getMultiVersionKind();
11552
11553 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11554 NewKind == MultiVersionKind::None)
11555 return true;
11556
11557 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11558 switch (OldKind) {
11560 return NewKind == MultiVersionKind::TargetClones;
11562 return NewKind == MultiVersionKind::TargetVersion;
11563 default:
11564 return false;
11565 }
11566 } else {
11567 switch (OldKind) {
11569 return NewKind == MultiVersionKind::CPUSpecific;
11571 return NewKind == MultiVersionKind::CPUDispatch;
11572 default:
11573 return false;
11574 }
11575 }
11576}
11577
11578/// Check the validity of a new function declaration being added to an existing
11579/// multiversioned declaration collection.
11581 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11582 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11583 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11585
11586 // Disallow mixing of multiversioning types.
11587 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11588 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11589 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11590 NewFD->setInvalidDecl();
11591 return true;
11592 }
11593
11594 // Add the default target_version attribute if it's missing.
11595 patchDefaultTargetVersion(OldFD, NewFD);
11596 patchDefaultTargetVersion(NewFD, OldFD);
11597
11598 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11599 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11600 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11601 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11602
11603 ParsedTargetAttr NewParsed;
11604 if (NewTA) {
11606 NewTA->getFeaturesStr());
11607 llvm::sort(NewParsed.Features);
11608 }
11610 if (NewTVA) {
11611 NewTVA->getFeatures(NewFeats);
11612 llvm::sort(NewFeats);
11613 }
11614
11615 bool UseMemberUsingDeclRules =
11616 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11617
11618 bool MayNeedOverloadableChecks =
11620
11621 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11622 // of a previous member of the MultiVersion set.
11623 for (NamedDecl *ND : Previous) {
11624 FunctionDecl *CurFD = ND->getAsFunction();
11625 if (!CurFD || CurFD->isInvalidDecl())
11626 continue;
11627 if (MayNeedOverloadableChecks &&
11628 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11629 continue;
11630
11631 switch (NewMVKind) {
11633 assert(OldMVKind == MultiVersionKind::TargetClones &&
11634 "Only target_clones can be omitted in subsequent declarations");
11635 break;
11637 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11638 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11639 NewFD->setIsMultiVersion();
11640 Redeclaration = true;
11641 OldDecl = ND;
11642 return false;
11643 }
11644
11645 ParsedTargetAttr CurParsed =
11647 CurTA->getFeaturesStr());
11648 llvm::sort(CurParsed.Features);
11649 if (CurParsed == NewParsed) {
11650 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11651 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11652 NewFD->setInvalidDecl();
11653 return true;
11654 }
11655 break;
11656 }
11658 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11659 if (CurTVA->getName() == NewTVA->getName()) {
11660 NewFD->setIsMultiVersion();
11661 Redeclaration = true;
11662 OldDecl = ND;
11663 return false;
11664 }
11666 CurTVA->getFeatures(CurFeats);
11667 llvm::sort(CurFeats);
11668
11669 if (CurFeats == NewFeats) {
11670 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11671 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11672 NewFD->setInvalidDecl();
11673 return true;
11674 }
11675 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11676 // Default
11677 if (NewFeats.empty())
11678 break;
11679
11680 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11682 CurClones->getFeatures(CurFeats, I);
11683 llvm::sort(CurFeats);
11684
11685 if (CurFeats == NewFeats) {
11686 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11687 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11688 NewFD->setInvalidDecl();
11689 return true;
11690 }
11691 }
11692 }
11693 break;
11694 }
11696 assert(NewClones && "MultiVersionKind does not match attribute type");
11697 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11698 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11699 !std::equal(CurClones->featuresStrs_begin(),
11700 CurClones->featuresStrs_end(),
11701 NewClones->featuresStrs_begin())) {
11702 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11703 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11704 NewFD->setInvalidDecl();
11705 return true;
11706 }
11707 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11709 CurTVA->getFeatures(CurFeats);
11710 llvm::sort(CurFeats);
11711
11712 // Default
11713 if (CurFeats.empty())
11714 break;
11715
11716 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11717 NewFeats.clear();
11718 NewClones->getFeatures(NewFeats, I);
11719 llvm::sort(NewFeats);
11720
11721 if (CurFeats == NewFeats) {
11722 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11723 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11724 NewFD->setInvalidDecl();
11725 return true;
11726 }
11727 }
11728 break;
11729 }
11730 Redeclaration = true;
11731 OldDecl = CurFD;
11732 NewFD->setIsMultiVersion();
11733 return false;
11734 }
11737 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11738 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11739 // Handle CPUDispatch/CPUSpecific versions.
11740 // Only 1 CPUDispatch function is allowed, this will make it go through
11741 // the redeclaration errors.
11742 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11743 CurFD->hasAttr<CPUDispatchAttr>()) {
11744 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11745 std::equal(
11746 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11747 NewCPUDisp->cpus_begin(),
11748 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11749 return Cur->getName() == New->getName();
11750 })) {
11751 NewFD->setIsMultiVersion();
11752 Redeclaration = true;
11753 OldDecl = ND;
11754 return false;
11755 }
11756
11757 // If the declarations don't match, this is an error condition.
11758 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11759 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11760 NewFD->setInvalidDecl();
11761 return true;
11762 }
11763 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11764 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11765 std::equal(
11766 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11767 NewCPUSpec->cpus_begin(),
11768 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11769 return Cur->getName() == New->getName();
11770 })) {
11771 NewFD->setIsMultiVersion();
11772 Redeclaration = true;
11773 OldDecl = ND;
11774 return false;
11775 }
11776
11777 // Only 1 version of CPUSpecific is allowed for each CPU.
11778 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11779 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11780 if (CurII == NewII) {
11781 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11782 << NewII;
11783 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11784 NewFD->setInvalidDecl();
11785 return true;
11786 }
11787 }
11788 }
11789 }
11790 break;
11791 }
11792 }
11793 }
11794
11795 // Else, this is simply a non-redecl case. Checking the 'value' is only
11796 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11797 // handled in the attribute adding step.
11798 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11799 NewMVKind == MultiVersionKind::Target) &&
11800 CheckMultiVersionValue(S, NewFD)) {
11801 NewFD->setInvalidDecl();
11802 return true;
11803 }
11804
11805 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11806 !OldFD->isMultiVersion(), NewMVKind)) {
11807 NewFD->setInvalidDecl();
11808 return true;
11809 }
11810
11811 // Permit forward declarations in the case where these two are compatible.
11812 if (!OldFD->isMultiVersion()) {
11813 OldFD->setIsMultiVersion();
11814 NewFD->setIsMultiVersion();
11815 Redeclaration = true;
11816 OldDecl = OldFD;
11817 return false;
11818 }
11819
11820 NewFD->setIsMultiVersion();
11821 Redeclaration = false;
11822 OldDecl = nullptr;
11823 Previous.clear();
11824 return false;
11825}
11826
11827/// Check the validity of a mulitversion function declaration.
11828/// Also sets the multiversion'ness' of the function itself.
11829///
11830/// This sets NewFD->isInvalidDecl() to true if there was an error.
11831///
11832/// Returns true if there was an error, false otherwise.
11834 bool &Redeclaration, NamedDecl *&OldDecl,
11836 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11837 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11838 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11839 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11840 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11841 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11842
11843 // Main isn't allowed to become a multiversion function, however it IS
11844 // permitted to have 'main' be marked with the 'target' optimization hint,
11845 // for 'target_version' only default is allowed.
11846 if (NewFD->isMain()) {
11847 if (MVKind != MultiVersionKind::None &&
11848 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11849 !(MVKind == MultiVersionKind::TargetVersion &&
11850 NewTVA->isDefaultVersion())) {
11851 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11852 NewFD->setInvalidDecl();
11853 return true;
11854 }
11855 return false;
11856 }
11857
11858 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11859
11860 // Target attribute on AArch64 is not used for multiversioning
11861 if (NewTA && T.isAArch64())
11862 return false;
11863
11864 // Target attribute on RISCV is not used for multiversioning
11865 if (NewTA && T.isRISCV())
11866 return false;
11867
11868 if (!OldDecl || !OldDecl->getAsFunction() ||
11869 OldDecl->getDeclContext()->getRedeclContext() !=
11870 NewFD->getDeclContext()->getRedeclContext()) {
11871 // If there's no previous declaration, AND this isn't attempting to cause
11872 // multiversioning, this isn't an error condition.
11873 if (MVKind == MultiVersionKind::None)
11874 return false;
11875 return CheckMultiVersionFirstFunction(S, NewFD);
11876 }
11877
11878 FunctionDecl *OldFD = OldDecl->getAsFunction();
11879
11880 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11881 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11882 return false;
11883 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11884 // Multiversion declaration doesn't have prototype.
11885 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11886 NewFD->setInvalidDecl();
11887 } else {
11888 // No "target_version" attribute is equivalent to "default" attribute.
11889 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11890 S.Context, "default", NewFD->getSourceRange()));
11891 NewFD->setIsMultiVersion();
11892 OldFD->setIsMultiVersion();
11893 OldDecl = OldFD;
11894 Redeclaration = true;
11895 }
11896 return true;
11897 }
11898
11899 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11900 // for target_clones and target_version.
11901 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11904 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11906 NewFD->setInvalidDecl();
11907 return true;
11908 }
11909
11910 if (!OldFD->isMultiVersion()) {
11911 switch (MVKind) {
11914 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11915 OldDecl, Previous);
11917 if (OldFD->isUsed(false)) {
11918 NewFD->setInvalidDecl();
11919 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11920 }
11921 OldFD->setIsMultiVersion();
11922 break;
11923
11927 break;
11928 }
11929 }
11930
11931 // At this point, we have a multiversion function decl (in OldFD) AND an
11932 // appropriate attribute in the current function decl. Resolve that these are
11933 // still compatible with previous declarations.
11934 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11935 NewCPUSpec, NewClones, Redeclaration,
11936 OldDecl, Previous);
11937}
11938
11940 bool IsPure = NewFD->hasAttr<PureAttr>();
11941 bool IsConst = NewFD->hasAttr<ConstAttr>();
11942
11943 // If there are no pure or const attributes, there's nothing to check.
11944 if (!IsPure && !IsConst)
11945 return;
11946
11947 // If the function is marked both pure and const, we retain the const
11948 // attribute because it makes stronger guarantees than the pure attribute, and
11949 // we drop the pure attribute explicitly to prevent later confusion about
11950 // semantics.
11951 if (IsPure && IsConst) {
11952 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11953 NewFD->dropAttrs<PureAttr>();
11954 }
11955
11956 // Constructors and destructors are functions which return void, so are
11957 // handled here as well.
11958 if (NewFD->getReturnType()->isVoidType()) {
11959 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11960 << IsConst;
11961 NewFD->dropAttrs<PureAttr, ConstAttr>();
11962 }
11963}
11964
11965/// Perform semantic checking of a new function declaration.
11966///
11967/// Performs semantic analysis of the new function declaration
11968/// NewFD. This routine performs all semantic checking that does not
11969/// require the actual declarator involved in the declaration, and is
11970/// used both for the declaration of functions as they are parsed
11971/// (called via ActOnDeclarator) and for the declaration of functions
11972/// that have been instantiated via C++ template instantiation (called
11973/// via InstantiateDecl).
11974///
11975/// \param IsMemberSpecialization whether this new function declaration is
11976/// a member specialization (that replaces any definition provided by the
11977/// previous declaration).
11978///
11979/// This sets NewFD->isInvalidDecl() to true if there was an error.
11980///
11981/// \returns true if the function declaration is a redeclaration.
11984 bool IsMemberSpecialization,
11985 bool DeclIsDefn) {
11986 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11987 "Variably modified return types are not handled here");
11988
11989 // Determine whether the type of this function should be merged with
11990 // a previous visible declaration. This never happens for functions in C++,
11991 // and always happens in C if the previous declaration was visible.
11992 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11993 !Previous.isShadowed();
11994
11995 bool Redeclaration = false;
11996 NamedDecl *OldDecl = nullptr;
11997 bool MayNeedOverloadableChecks = false;
11998
11999 // Merge or overload the declaration with an existing declaration of
12000 // the same name, if appropriate.
12001 if (!Previous.empty()) {
12002 // Determine whether NewFD is an overload of PrevDecl or
12003 // a declaration that requires merging. If it's an overload,
12004 // there's no more work to do here; we'll just add the new
12005 // function to the scope.
12007 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12008 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12009 Redeclaration = true;
12010 OldDecl = Candidate;
12011 }
12012 } else {
12013 MayNeedOverloadableChecks = true;
12014 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12015 /*NewIsUsingDecl*/ false)) {
12016 case Ovl_Match:
12017 Redeclaration = true;
12018 break;
12019
12020 case Ovl_NonFunction:
12021 Redeclaration = true;
12022 break;
12023
12024 case Ovl_Overload:
12025 Redeclaration = false;
12026 break;
12027 }
12028 }
12029 }
12030
12031 // Check for a previous extern "C" declaration with this name.
12032 if (!Redeclaration &&
12034 if (!Previous.empty()) {
12035 // This is an extern "C" declaration with the same name as a previous
12036 // declaration, and thus redeclares that entity...
12037 Redeclaration = true;
12038 OldDecl = Previous.getFoundDecl();
12039 MergeTypeWithPrevious = false;
12040
12041 // ... except in the presence of __attribute__((overloadable)).
12042 if (OldDecl->hasAttr<OverloadableAttr>() ||
12043 NewFD->hasAttr<OverloadableAttr>()) {
12044 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12045 MayNeedOverloadableChecks = true;
12046 Redeclaration = false;
12047 OldDecl = nullptr;
12048 }
12049 }
12050 }
12051 }
12052
12053 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12054 return Redeclaration;
12055
12056 // PPC MMA non-pointer types are not allowed as function return types.
12057 if (Context.getTargetInfo().getTriple().isPPC64() &&
12058 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12059 NewFD->setInvalidDecl();
12060 }
12061
12062 CheckConstPureAttributesUsage(*this, NewFD);
12063
12064 // C++ [dcl.spec.auto.general]p12:
12065 // Return type deduction for a templated function with a placeholder in its
12066 // declared type occurs when the definition is instantiated even if the
12067 // function body contains a return statement with a non-type-dependent
12068 // operand.
12069 //
12070 // C++ [temp.dep.expr]p3:
12071 // An id-expression is type-dependent if it is a template-id that is not a
12072 // concept-id and is dependent; or if its terminal name is:
12073 // - [...]
12074 // - associated by name lookup with one or more declarations of member
12075 // functions of a class that is the current instantiation declared with a
12076 // return type that contains a placeholder type,
12077 // - [...]
12078 //
12079 // If this is a templated function with a placeholder in its return type,
12080 // make the placeholder type dependent since it won't be deduced until the
12081 // definition is instantiated. We do this here because it needs to happen
12082 // for implicitly instantiated member functions/member function templates.
12083 if (getLangOpts().CPlusPlus14 &&
12084 (NewFD->isDependentContext() &&
12085 NewFD->getReturnType()->isUndeducedType())) {
12086 const FunctionProtoType *FPT =
12087 NewFD->getType()->castAs<FunctionProtoType>();
12088 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12089 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12090 FPT->getExtProtoInfo()));
12091 }
12092
12093 // C++11 [dcl.constexpr]p8:
12094 // A constexpr specifier for a non-static member function that is not
12095 // a constructor declares that member function to be const.
12096 //
12097 // This needs to be delayed until we know whether this is an out-of-line
12098 // definition of a static member function.
12099 //
12100 // This rule is not present in C++1y, so we produce a backwards
12101 // compatibility warning whenever it happens in C++11.
12102 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12103 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12104 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12105 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12106 CXXMethodDecl *OldMD = nullptr;
12107 if (OldDecl)
12108 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12109 if (!OldMD || !OldMD->isStatic()) {
12110 const FunctionProtoType *FPT =
12113 EPI.TypeQuals.addConst();
12115 FPT->getParamTypes(), EPI));
12116
12117 // Warn that we did this, if we're not performing template instantiation.
12118 // In that case, we'll have warned already when the template was defined.
12119 if (!inTemplateInstantiation()) {
12120 SourceLocation AddConstLoc;
12123 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12124
12125 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12126 << FixItHint::CreateInsertion(AddConstLoc, " const");
12127 }
12128 }
12129 }
12130
12131 if (Redeclaration) {
12132 // NewFD and OldDecl represent declarations that need to be
12133 // merged.
12134 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12135 DeclIsDefn)) {
12136 NewFD->setInvalidDecl();
12137 return Redeclaration;
12138 }
12139
12140 Previous.clear();
12141 Previous.addDecl(OldDecl);
12142
12143 if (FunctionTemplateDecl *OldTemplateDecl =
12144 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12145 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12146 FunctionTemplateDecl *NewTemplateDecl
12148 assert(NewTemplateDecl && "Template/non-template mismatch");
12149
12150 // The call to MergeFunctionDecl above may have created some state in
12151 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12152 // can add it as a redeclaration.
12153 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12154
12155 NewFD->setPreviousDeclaration(OldFD);
12156 if (NewFD->isCXXClassMember()) {
12157 NewFD->setAccess(OldTemplateDecl->getAccess());
12158 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12159 }
12160
12161 // If this is an explicit specialization of a member that is a function
12162 // template, mark it as a member specialization.
12163 if (IsMemberSpecialization &&
12164 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12165 NewTemplateDecl->setMemberSpecialization();
12166 assert(OldTemplateDecl->isMemberSpecialization());
12167 // Explicit specializations of a member template do not inherit deleted
12168 // status from the parent member template that they are specializing.
12169 if (OldFD->isDeleted()) {
12170 // FIXME: This assert will not hold in the presence of modules.
12171 assert(OldFD->getCanonicalDecl() == OldFD);
12172 // FIXME: We need an update record for this AST mutation.
12173 OldFD->setDeletedAsWritten(false);
12174 }
12175 }
12176
12177 } else {
12178 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12179 auto *OldFD = cast<FunctionDecl>(OldDecl);
12180 // This needs to happen first so that 'inline' propagates.
12181 NewFD->setPreviousDeclaration(OldFD);
12182 if (NewFD->isCXXClassMember())
12183 NewFD->setAccess(OldFD->getAccess());
12184 }
12185 }
12186 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12187 !NewFD->getAttr<OverloadableAttr>()) {
12188 assert((Previous.empty() ||
12189 llvm::any_of(Previous,
12190 [](const NamedDecl *ND) {
12191 return ND->hasAttr<OverloadableAttr>();
12192 })) &&
12193 "Non-redecls shouldn't happen without overloadable present");
12194
12195 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12196 const auto *FD = dyn_cast<FunctionDecl>(ND);
12197 return FD && !FD->hasAttr<OverloadableAttr>();
12198 });
12199
12200 if (OtherUnmarkedIter != Previous.end()) {
12201 Diag(NewFD->getLocation(),
12202 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12203 Diag((*OtherUnmarkedIter)->getLocation(),
12204 diag::note_attribute_overloadable_prev_overload)
12205 << false;
12206
12207 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12208 }
12209 }
12210
12211 if (LangOpts.OpenMP)
12213
12214 // Semantic checking for this function declaration (in isolation).
12215
12216 if (getLangOpts().CPlusPlus) {
12217 // C++-specific checks.
12218 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12219 CheckConstructor(Constructor);
12220 } else if (CXXDestructorDecl *Destructor =
12221 dyn_cast<CXXDestructorDecl>(NewFD)) {
12222 // We check here for invalid destructor names.
12223 // If we have a friend destructor declaration that is dependent, we can't
12224 // diagnose right away because cases like this are still valid:
12225 // template <class T> struct A { friend T::X::~Y(); };
12226 // struct B { struct Y { ~Y(); }; using X = Y; };
12227 // template struct A<B>;
12229 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12230 CXXRecordDecl *Record = Destructor->getParent();
12232
12234 Context.getCanonicalType(ClassType));
12235 if (NewFD->getDeclName() != Name) {
12236 Diag(NewFD->getLocation(), diag::err_destructor_name);
12237 NewFD->setInvalidDecl();
12238 return Redeclaration;
12239 }
12240 }
12241 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12242 if (auto *TD = Guide->getDescribedFunctionTemplate())
12244
12245 // A deduction guide is not on the list of entities that can be
12246 // explicitly specialized.
12247 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12248 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12249 << /*explicit specialization*/ 1;
12250 }
12251
12252 // Find any virtual functions that this function overrides.
12253 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12254 if (!Method->isFunctionTemplateSpecialization() &&
12255 !Method->getDescribedFunctionTemplate() &&
12256 Method->isCanonicalDecl()) {
12257 AddOverriddenMethods(Method->getParent(), Method);
12258 }
12259 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12260 // C++2a [class.virtual]p6
12261 // A virtual method shall not have a requires-clause.
12263 diag::err_constrained_virtual_method);
12264
12265 if (Method->isStatic())
12267 }
12268
12269 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12270 ActOnConversionDeclarator(Conversion);
12271
12272 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12273 if (NewFD->isOverloadedOperator() &&
12275 NewFD->setInvalidDecl();
12276 return Redeclaration;
12277 }
12278
12279 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12280 if (NewFD->getLiteralIdentifier() &&
12282 NewFD->setInvalidDecl();
12283 return Redeclaration;
12284 }
12285
12286 // In C++, check default arguments now that we have merged decls. Unless
12287 // the lexical context is the class, because in this case this is done
12288 // during delayed parsing anyway.
12289 if (!CurContext->isRecord())
12291
12292 // If this function is declared as being extern "C", then check to see if
12293 // the function returns a UDT (class, struct, or union type) that is not C
12294 // compatible, and if it does, warn the user.
12295 // But, issue any diagnostic on the first declaration only.
12296 if (Previous.empty() && NewFD->isExternC()) {
12297 QualType R = NewFD->getReturnType();
12298 if (R->isIncompleteType() && !R->isVoidType())
12299 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12300 << NewFD << R;
12301 else if (!R.isPODType(Context) && !R->isVoidType() &&
12303 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12304 }
12305
12306 // C++1z [dcl.fct]p6:
12307 // [...] whether the function has a non-throwing exception-specification
12308 // [is] part of the function type
12309 //
12310 // This results in an ABI break between C++14 and C++17 for functions whose
12311 // declared type includes an exception-specification in a parameter or
12312 // return type. (Exception specifications on the function itself are OK in
12313 // most cases, and exception specifications are not permitted in most other
12314 // contexts where they could make it into a mangling.)
12315 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12316 auto HasNoexcept = [&](QualType T) -> bool {
12317 // Strip off declarator chunks that could be between us and a function
12318 // type. We don't need to look far, exception specifications are very
12319 // restricted prior to C++17.
12320 if (auto *RT = T->getAs<ReferenceType>())
12321 T = RT->getPointeeType();
12322 else if (T->isAnyPointerType())
12323 T = T->getPointeeType();
12324 else if (auto *MPT = T->getAs<MemberPointerType>())
12325 T = MPT->getPointeeType();
12326 if (auto *FPT = T->getAs<FunctionProtoType>())
12327 if (FPT->isNothrow())
12328 return true;
12329 return false;
12330 };
12331
12332 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12333 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12334 for (QualType T : FPT->param_types())
12335 AnyNoexcept |= HasNoexcept(T);
12336 if (AnyNoexcept)
12337 Diag(NewFD->getLocation(),
12338 diag::warn_cxx17_compat_exception_spec_in_signature)
12339 << NewFD;
12340 }
12341
12342 if (!Redeclaration && LangOpts.CUDA)
12344 }
12345
12346 // Check if the function definition uses any AArch64 SME features without
12347 // having the '+sme' feature enabled and warn user if sme locally streaming
12348 // function returns or uses arguments with VL-based types.
12349 if (DeclIsDefn) {
12350 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12351 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12352 bool UsesZA = Attr && Attr->isNewZA();
12353 bool UsesZT0 = Attr && Attr->isNewZT0();
12354
12355 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12356 if (NewFD->getReturnType()->isSizelessVectorType())
12357 Diag(NewFD->getLocation(),
12358 diag::warn_sme_locally_streaming_has_vl_args_returns)
12359 << /*IsArg=*/false;
12360 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12361 return P->getOriginalType()->isSizelessVectorType();
12362 }))
12363 Diag(NewFD->getLocation(),
12364 diag::warn_sme_locally_streaming_has_vl_args_returns)
12365 << /*IsArg=*/true;
12366 }
12367 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12368 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12369 UsesSM |=
12375 }
12376
12377 if (UsesSM || UsesZA) {
12378 llvm::StringMap<bool> FeatureMap;
12379 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12380 if (!FeatureMap.contains("sme")) {
12381 if (UsesSM)
12382 Diag(NewFD->getLocation(),
12383 diag::err_sme_definition_using_sm_in_non_sme_target);
12384 else
12385 Diag(NewFD->getLocation(),
12386 diag::err_sme_definition_using_za_in_non_sme_target);
12387 }
12388 }
12389 if (UsesZT0) {
12390 llvm::StringMap<bool> FeatureMap;
12391 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12392 if (!FeatureMap.contains("sme2")) {
12393 Diag(NewFD->getLocation(),
12394 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12395 }
12396 }
12397 }
12398
12399 return Redeclaration;
12400}
12401
12403 // C++11 [basic.start.main]p3:
12404 // A program that [...] declares main to be inline, static or
12405 // constexpr is ill-formed.
12406 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12407 // appear in a declaration of main.
12408 // static main is not an error under C99, but we should warn about it.
12409 // We accept _Noreturn main as an extension.
12410 if (FD->getStorageClass() == SC_Static)
12412 ? diag::err_static_main : diag::warn_static_main)
12414 if (FD->isInlineSpecified())
12415 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12417 if (DS.isNoreturnSpecified()) {
12418 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12419 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12420 Diag(NoreturnLoc, diag::ext_noreturn_main);
12421 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12422 << FixItHint::CreateRemoval(NoreturnRange);
12423 }
12424 if (FD->isConstexpr()) {
12425 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12426 << FD->isConsteval()
12429 }
12430
12431 if (getLangOpts().OpenCL) {
12432 Diag(FD->getLocation(), diag::err_opencl_no_main)
12433 << FD->hasAttr<OpenCLKernelAttr>();
12434 FD->setInvalidDecl();
12435 return;
12436 }
12437
12438 // Functions named main in hlsl are default entries, but don't have specific
12439 // signatures they are required to conform to.
12440 if (getLangOpts().HLSL)
12441 return;
12442
12443 QualType T = FD->getType();
12444 assert(T->isFunctionType() && "function decl is not of function type");
12445 const FunctionType* FT = T->castAs<FunctionType>();
12446
12447 // Set default calling convention for main()
12448 if (FT->getCallConv() != CC_C) {
12450 FD->setType(QualType(FT, 0));
12452 }
12453
12454 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12455 // In C with GNU extensions we allow main() to have non-integer return
12456 // type, but we should warn about the extension, and we disable the
12457 // implicit-return-zero rule.
12458
12459 // GCC in C mode accepts qualified 'int'.
12461 FD->setHasImplicitReturnZero(true);
12462 else {
12463 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12464 SourceRange RTRange = FD->getReturnTypeSourceRange();
12465 if (RTRange.isValid())
12466 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12467 << FixItHint::CreateReplacement(RTRange, "int");
12468 }
12469 } else {
12470 // In C and C++, main magically returns 0 if you fall off the end;
12471 // set the flag which tells us that.
12472 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12473
12474 // All the standards say that main() should return 'int'.
12476 FD->setHasImplicitReturnZero(true);
12477 else {
12478 // Otherwise, this is just a flat-out error.
12479 SourceRange RTRange = FD->getReturnTypeSourceRange();
12480 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12481 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12482 : FixItHint());
12483 FD->setInvalidDecl(true);
12484 }
12485 }
12486
12487 // Treat protoless main() as nullary.
12488 if (isa<FunctionNoProtoType>(FT)) return;
12489
12490 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12491 unsigned nparams = FTP->getNumParams();
12492 assert(FD->getNumParams() == nparams);
12493
12494 bool HasExtraParameters = (nparams > 3);
12495
12496 if (FTP->isVariadic()) {
12497 Diag(FD->getLocation(), diag::ext_variadic_main);
12498 // FIXME: if we had information about the location of the ellipsis, we
12499 // could add a FixIt hint to remove it as a parameter.
12500 }
12501
12502 // Darwin passes an undocumented fourth argument of type char**. If
12503 // other platforms start sprouting these, the logic below will start
12504 // getting shifty.
12505 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12506 HasExtraParameters = false;
12507
12508 if (HasExtraParameters) {
12509 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12510 FD->setInvalidDecl(true);
12511 nparams = 3;
12512 }
12513
12514 // FIXME: a lot of the following diagnostics would be improved
12515 // if we had some location information about types.
12516
12517 QualType CharPP =
12519 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12520
12521 for (unsigned i = 0; i < nparams; ++i) {
12522 QualType AT = FTP->getParamType(i);
12523
12524 bool mismatch = true;
12525
12527 mismatch = false;
12528 else if (Expected[i] == CharPP) {
12529 // As an extension, the following forms are okay:
12530 // char const **
12531 // char const * const *
12532 // char * const *
12533
12535 const PointerType* PT;
12536 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12537 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12539 Context.CharTy)) {
12540 qs.removeConst();
12541 mismatch = !qs.empty();
12542 }
12543 }
12544
12545 if (mismatch) {
12546 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12547 // TODO: suggest replacing given type with expected type
12548 FD->setInvalidDecl(true);
12549 }
12550 }
12551
12552 if (nparams == 1 && !FD->isInvalidDecl()) {
12553 Diag(FD->getLocation(), diag::warn_main_one_arg);
12554 }
12555
12556 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12557 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12558 FD->setInvalidDecl();
12559 }
12560}
12561
12562static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12563
12564 // Default calling convention for main and wmain is __cdecl
12565 if (FD->getName() == "main" || FD->getName() == "wmain")
12566 return false;
12567
12568 // Default calling convention for MinGW is __cdecl
12569 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12570 if (T.isWindowsGNUEnvironment())
12571 return false;
12572
12573 // Default calling convention for WinMain, wWinMain and DllMain
12574 // is __stdcall on 32 bit Windows
12575 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12576 return true;
12577
12578 return false;
12579}
12580
12582 QualType T = FD->getType();
12583 assert(T->isFunctionType() && "function decl is not of function type");
12584 const FunctionType *FT = T->castAs<FunctionType>();
12585
12586 // Set an implicit return of 'zero' if the function can return some integral,
12587 // enumeration, pointer or nullptr type.
12591 // DllMain is exempt because a return value of zero means it failed.
12592 if (FD->getName() != "DllMain")
12593 FD->setHasImplicitReturnZero(true);
12594
12595 // Explicity specified calling conventions are applied to MSVC entry points
12596 if (!hasExplicitCallingConv(T)) {
12597 if (isDefaultStdCall(FD, *this)) {
12598 if (FT->getCallConv() != CC_X86StdCall) {
12601 FD->setType(QualType(FT, 0));
12602 }
12603 } else if (FT->getCallConv() != CC_C) {
12606 FD->setType(QualType(FT, 0));
12607 }
12608 }
12609
12610 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12611 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12612 FD->setInvalidDecl();
12613 }
12614}
12615
12617 // FIXME: Need strict checking. In C89, we need to check for
12618 // any assignment, increment, decrement, function-calls, or
12619 // commas outside of a sizeof. In C99, it's the same list,
12620 // except that the aforementioned are allowed in unevaluated
12621 // expressions. Everything else falls under the
12622 // "may accept other forms of constant expressions" exception.
12623 //
12624 // Regular C++ code will not end up here (exceptions: language extensions,
12625 // OpenCL C++ etc), so the constant expression rules there don't matter.
12626 if (Init->isValueDependent()) {
12627 assert(Init->containsErrors() &&
12628 "Dependent code should only occur in error-recovery path.");
12629 return true;
12630 }
12631 const Expr *Culprit;
12632 if (Init->isConstantInitializer(Context, false, &Culprit))
12633 return false;
12634 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12635 return true;
12636}
12637
12638namespace {
12639 // Visits an initialization expression to see if OrigDecl is evaluated in
12640 // its own initialization and throws a warning if it does.
12641 class SelfReferenceChecker
12642 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12643 Sema &S;
12644 Decl *OrigDecl;
12645 bool isRecordType;
12646 bool isPODType;
12647 bool isReferenceType;
12648
12649 bool isInitList;
12650 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12651
12652 public:
12654
12655 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12656 S(S), OrigDecl(OrigDecl) {
12657 isPODType = false;
12658 isRecordType = false;
12659 isReferenceType = false;
12660 isInitList = false;
12661 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12662 isPODType = VD->getType().isPODType(S.Context);
12663 isRecordType = VD->getType()->isRecordType();
12664 isReferenceType = VD->getType()->isReferenceType();
12665 }
12666 }
12667
12668 // For most expressions, just call the visitor. For initializer lists,
12669 // track the index of the field being initialized since fields are
12670 // initialized in order allowing use of previously initialized fields.
12671 void CheckExpr(Expr *E) {
12672 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12673 if (!InitList) {
12674 Visit(E);
12675 return;
12676 }
12677
12678 // Track and increment the index here.
12679 isInitList = true;
12680 InitFieldIndex.push_back(0);
12681 for (auto *Child : InitList->children()) {
12682 CheckExpr(cast<Expr>(Child));
12683 ++InitFieldIndex.back();
12684 }
12685 InitFieldIndex.pop_back();
12686 }
12687
12688 // Returns true if MemberExpr is checked and no further checking is needed.
12689 // Returns false if additional checking is required.
12690 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12692 Expr *Base = E;
12693 bool ReferenceField = false;
12694
12695 // Get the field members used.
12696 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12697 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12698 if (!FD)
12699 return false;
12700 Fields.push_back(FD);
12701 if (FD->getType()->isReferenceType())
12702 ReferenceField = true;
12703 Base = ME->getBase()->IgnoreParenImpCasts();
12704 }
12705
12706 // Keep checking only if the base Decl is the same.
12707 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12708 if (!DRE || DRE->getDecl() != OrigDecl)
12709 return false;
12710
12711 // A reference field can be bound to an unininitialized field.
12712 if (CheckReference && !ReferenceField)
12713 return true;
12714
12715 // Convert FieldDecls to their index number.
12716 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12717 for (const FieldDecl *I : llvm::reverse(Fields))
12718 UsedFieldIndex.push_back(I->getFieldIndex());
12719
12720 // See if a warning is needed by checking the first difference in index
12721 // numbers. If field being used has index less than the field being
12722 // initialized, then the use is safe.
12723 for (auto UsedIter = UsedFieldIndex.begin(),
12724 UsedEnd = UsedFieldIndex.end(),
12725 OrigIter = InitFieldIndex.begin(),
12726 OrigEnd = InitFieldIndex.end();
12727 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12728 if (*UsedIter < *OrigIter)
12729 return true;
12730 if (*UsedIter > *OrigIter)
12731 break;
12732 }
12733
12734 // TODO: Add a different warning which will print the field names.
12735 HandleDeclRefExpr(DRE);
12736 return true;
12737 }
12738
12739 // For most expressions, the cast is directly above the DeclRefExpr.
12740 // For conditional operators, the cast can be outside the conditional
12741 // operator if both expressions are DeclRefExpr's.
12742 void HandleValue(Expr *E) {
12743 E = E->IgnoreParens();
12744 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12745 HandleDeclRefExpr(DRE);
12746 return;
12747 }
12748
12749 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12750 Visit(CO->getCond());
12751 HandleValue(CO->getTrueExpr());
12752 HandleValue(CO->getFalseExpr());
12753 return;
12754 }
12755
12756 if (BinaryConditionalOperator *BCO =
12757 dyn_cast<BinaryConditionalOperator>(E)) {
12758 Visit(BCO->getCond());
12759 HandleValue(BCO->getFalseExpr());
12760 return;
12761 }
12762
12763 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12764 if (Expr *SE = OVE->getSourceExpr())
12765 HandleValue(SE);
12766 return;
12767 }
12768
12769 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12770 if (BO->getOpcode() == BO_Comma) {
12771 Visit(BO->getLHS());
12772 HandleValue(BO->getRHS());
12773 return;
12774 }
12775 }
12776
12777 if (isa<MemberExpr>(E)) {
12778 if (isInitList) {
12779 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12780 false /*CheckReference*/))
12781 return;
12782 }
12783
12785 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12786 // Check for static member variables and don't warn on them.
12787 if (!isa<FieldDecl>(ME->getMemberDecl()))
12788 return;
12789 Base = ME->getBase()->IgnoreParenImpCasts();
12790 }
12791 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12792 HandleDeclRefExpr(DRE);
12793 return;
12794 }
12795
12796 Visit(E);
12797 }
12798
12799 // Reference types not handled in HandleValue are handled here since all
12800 // uses of references are bad, not just r-value uses.
12801 void VisitDeclRefExpr(DeclRefExpr *E) {
12802 if (isReferenceType)
12803 HandleDeclRefExpr(E);
12804 }
12805
12806 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12807 if (E->getCastKind() == CK_LValueToRValue) {
12808 HandleValue(E->getSubExpr());
12809 return;
12810 }
12811
12812 Inherited::VisitImplicitCastExpr(E);
12813 }
12814
12815 void VisitMemberExpr(MemberExpr *E) {
12816 if (isInitList) {
12817 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12818 return;
12819 }
12820
12821 // Don't warn on arrays since they can be treated as pointers.
12822 if (E->getType()->canDecayToPointerType()) return;
12823
12824 // Warn when a non-static method call is followed by non-static member
12825 // field accesses, which is followed by a DeclRefExpr.
12826 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12827 bool Warn = (MD && !MD->isStatic());
12829 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12830 if (!isa<FieldDecl>(ME->getMemberDecl()))
12831 Warn = false;
12832 Base = ME->getBase()->IgnoreParenImpCasts();
12833 }
12834
12835 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12836 if (Warn)
12837 HandleDeclRefExpr(DRE);
12838 return;
12839 }
12840
12841 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12842 // Visit that expression.
12843 Visit(Base);
12844 }
12845
12846 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12847 Expr *Callee = E->getCallee();
12848
12849 if (isa<UnresolvedLookupExpr>(Callee))
12850 return Inherited::VisitCXXOperatorCallExpr(E);
12851
12852 Visit(Callee);
12853 for (auto Arg: E->arguments())
12854 HandleValue(Arg->IgnoreParenImpCasts());
12855 }
12856
12857 void VisitUnaryOperator(UnaryOperator *E) {
12858 // For POD record types, addresses of its own members are well-defined.
12859 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12860 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12861 if (!isPODType)
12862 HandleValue(E->getSubExpr());
12863 return;
12864 }
12865
12866 if (E->isIncrementDecrementOp()) {
12867 HandleValue(E->getSubExpr());
12868 return;
12869 }
12870
12871 Inherited::VisitUnaryOperator(E);
12872 }
12873
12874 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12875
12876 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12877 if (E->getConstructor()->isCopyConstructor()) {
12878 Expr *ArgExpr = E->getArg(0);
12879 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12880 if (ILE->getNumInits() == 1)
12881 ArgExpr = ILE->getInit(0);
12882 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12883 if (ICE->getCastKind() == CK_NoOp)
12884 ArgExpr = ICE->getSubExpr();
12885 HandleValue(ArgExpr);
12886 return;
12887 }
12888 Inherited::VisitCXXConstructExpr(E);
12889 }
12890
12891 void VisitCallExpr(CallExpr *E) {
12892 // Treat std::move as a use.
12893 if (E->isCallToStdMove()) {
12894 HandleValue(E->getArg(0));
12895 return;
12896 }
12897
12898 Inherited::VisitCallExpr(E);
12899 }
12900
12901 void VisitBinaryOperator(BinaryOperator *E) {
12902 if (E->isCompoundAssignmentOp()) {
12903 HandleValue(E->getLHS());
12904 Visit(E->getRHS());
12905 return;
12906 }
12907
12908 Inherited::VisitBinaryOperator(E);
12909 }
12910
12911 // A custom visitor for BinaryConditionalOperator is needed because the
12912 // regular visitor would check the condition and true expression separately
12913 // but both point to the same place giving duplicate diagnostics.
12914 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12915 Visit(E->getCond());
12916 Visit(E->getFalseExpr());
12917 }
12918
12919 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12920 Decl* ReferenceDecl = DRE->getDecl();
12921 if (OrigDecl != ReferenceDecl) return;
12922 unsigned diag;
12923 if (isReferenceType) {
12924 diag = diag::warn_uninit_self_reference_in_reference_init;
12925 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12926 diag = diag::warn_static_self_reference_in_init;
12927 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12928 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12929 DRE->getDecl()->getType()->isRecordType()) {
12930 diag = diag::warn_uninit_self_reference_in_init;
12931 } else {
12932 // Local variables will be handled by the CFG analysis.
12933 return;
12934 }
12935
12936 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12937 S.PDiag(diag)
12938 << DRE->getDecl() << OrigDecl->getLocation()
12939 << DRE->getSourceRange());
12940 }
12941 };
12942
12943 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12944 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12945 bool DirectInit) {
12946 // Parameters arguments are occassionially constructed with itself,
12947 // for instance, in recursive functions. Skip them.
12948 if (isa<ParmVarDecl>(OrigDecl))
12949 return;
12950
12951 E = E->IgnoreParens();
12952
12953 // Skip checking T a = a where T is not a record or reference type.
12954 // Doing so is a way to silence uninitialized warnings.
12955 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12956 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12957 if (ICE->getCastKind() == CK_LValueToRValue)
12958 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12959 if (DRE->getDecl() == OrigDecl)
12960 return;
12961
12962 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12963 }
12964} // end anonymous namespace
12965
12966namespace {
12967 // Simple wrapper to add the name of a variable or (if no variable is
12968 // available) a DeclarationName into a diagnostic.
12969 struct VarDeclOrName {
12970 VarDecl *VDecl;
12971 DeclarationName Name;
12972
12973 friend const Sema::SemaDiagnosticBuilder &
12974 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12975 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12976 }
12977 };
12978} // end anonymous namespace
12979
12982 TypeSourceInfo *TSI,
12984 Expr *Init) {
12985 bool IsInitCapture = !VDecl;
12986 assert((!VDecl || !VDecl->isInitCapture()) &&
12987 "init captures are expected to be deduced prior to initialization");
12988
12989 VarDeclOrName VN{VDecl, Name};
12990
12992 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12993
12994 // Diagnose auto array declarations in C23, unless it's a supported extension.
12995 if (getLangOpts().C23 && Type->isArrayType() &&
12996 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12997 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12998 << (int)Deduced->getContainedAutoType()->getKeyword()
12999 << /*in array decl*/ 23 << Range;
13000 return QualType();
13001 }
13002
13003 // C++11 [dcl.spec.auto]p3
13004 if (!Init) {
13005 assert(VDecl && "no init for init capture deduction?");
13006
13007 // Except for class argument deduction, and then for an initializing
13008 // declaration only, i.e. no static at class scope or extern.
13009 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
13010 VDecl->hasExternalStorage() ||
13011 VDecl->isStaticDataMember()) {
13012 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13013 << VDecl->getDeclName() << Type;
13014 return QualType();
13015 }
13016 }
13017
13018 ArrayRef<Expr*> DeduceInits;
13019 if (Init)
13020 DeduceInits = Init;
13021
13022 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13023 if (DirectInit && PL)
13024 DeduceInits = PL->exprs();
13025
13026 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
13027 assert(VDecl && "non-auto type for init capture deduction?");
13030 VDecl->getLocation(), DirectInit, Init);
13031 // FIXME: Initialization should not be taking a mutable list of inits.
13032 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
13033 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13034 InitsCopy);
13035 }
13036
13037 if (DirectInit) {
13038 if (auto *IL = dyn_cast<InitListExpr>(Init))
13039 DeduceInits = IL->inits();
13040 }
13041
13042 // Deduction only works if we have exactly one source expression.
13043 if (DeduceInits.empty()) {
13044 // It isn't possible to write this directly, but it is possible to
13045 // end up in this situation with "auto x(some_pack...);"
13046 Diag(Init->getBeginLoc(), IsInitCapture
13047 ? diag::err_init_capture_no_expression
13048 : diag::err_auto_var_init_no_expression)
13049 << VN << Type << Range;
13050 return QualType();
13051 }
13052
13053 if (DeduceInits.size() > 1) {
13054 Diag(DeduceInits[1]->getBeginLoc(),
13055 IsInitCapture ? diag::err_init_capture_multiple_expressions
13056 : diag::err_auto_var_init_multiple_expressions)
13057 << VN << Type << Range;
13058 return QualType();
13059 }
13060
13061 Expr *DeduceInit = DeduceInits[0];
13062 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13063 Diag(Init->getBeginLoc(), IsInitCapture
13064 ? diag::err_init_capture_paren_braces
13065 : diag::err_auto_var_init_paren_braces)
13066 << isa<InitListExpr>(Init) << VN << Type << Range;
13067 return QualType();
13068 }
13069
13070 // Expressions default to 'id' when we're in a debugger.
13071 bool DefaultedAnyToId = false;
13072 if (getLangOpts().DebuggerCastResultToId &&
13073 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13075 if (Result.isInvalid()) {
13076 return QualType();
13077 }
13078 Init = Result.get();
13079 DefaultedAnyToId = true;
13080 }
13081
13082 // C++ [dcl.decomp]p1:
13083 // If the assignment-expression [...] has array type A and no ref-qualifier
13084 // is present, e has type cv A
13085 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13087 DeduceInit->getType()->isConstantArrayType())
13088 return Context.getQualifiedType(DeduceInit->getType(),
13089 Type.getQualifiers());
13090
13092 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13094 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13097 if (!IsInitCapture)
13098 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13099 else if (isa<InitListExpr>(Init))
13101 diag::err_init_capture_deduction_failure_from_init_list)
13102 << VN
13103 << (DeduceInit->getType().isNull() ? TSI->getType()
13104 : DeduceInit->getType())
13105 << DeduceInit->getSourceRange();
13106 else
13107 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13108 << VN << TSI->getType()
13109 << (DeduceInit->getType().isNull() ? TSI->getType()
13110 : DeduceInit->getType())
13111 << DeduceInit->getSourceRange();
13112 }
13113
13114 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13115 // 'id' instead of a specific object type prevents most of our usual
13116 // checks.
13117 // We only want to warn outside of template instantiations, though:
13118 // inside a template, the 'id' could have come from a parameter.
13119 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13120 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13122 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13123 }
13124
13125 return DeducedType;
13126}
13127
13129 Expr *Init) {
13130 assert(!Init || !Init->containsErrors());
13132 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13133 VDecl->getSourceRange(), DirectInit, Init);
13134 if (DeducedType.isNull()) {
13135 VDecl->setInvalidDecl();
13136 return true;
13137 }
13138
13139 VDecl->setType(DeducedType);
13140 assert(VDecl->isLinkageValid());
13141
13142 // In ARC, infer lifetime.
13143 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13144 VDecl->setInvalidDecl();
13145
13146 if (getLangOpts().OpenCL)
13148
13149 // If this is a redeclaration, check that the type we just deduced matches
13150 // the previously declared type.
13151 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13152 // We never need to merge the type, because we cannot form an incomplete
13153 // array of auto, nor deduce such a type.
13154 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13155 }
13156
13157 // Check the deduced type is valid for a variable declaration.
13159 return VDecl->isInvalidDecl();
13160}
13161
13164 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13165 Init = EWC->getSubExpr();
13166
13167 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13168 Init = CE->getSubExpr();
13169
13170 QualType InitType = Init->getType();
13173 "shouldn't be called if type doesn't have a non-trivial C struct");
13174 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13175 for (auto *I : ILE->inits()) {
13176 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13177 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13178 continue;
13179 SourceLocation SL = I->getExprLoc();
13181 }
13182 return;
13183 }
13184
13185 if (isa<ImplicitValueInitExpr>(Init)) {
13188 NTCUK_Init);
13189 } else {
13190 // Assume all other explicit initializers involving copying some existing
13191 // object.
13192 // TODO: ignore any explicit initializers where we can guarantee
13193 // copy-elision.
13196 }
13197}
13198
13199namespace {
13200
13201bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13202 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13203 // in the source code or implicitly by the compiler if it is in a union
13204 // defined in a system header and has non-trivial ObjC ownership
13205 // qualifications. We don't want those fields to participate in determining
13206 // whether the containing union is non-trivial.
13207 return FD->hasAttr<UnavailableAttr>();
13208}
13209
13210struct DiagNonTrivalCUnionDefaultInitializeVisitor
13211 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13212 void> {
13213 using Super =
13214 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13215 void>;
13216
13217 DiagNonTrivalCUnionDefaultInitializeVisitor(
13218 QualType OrigTy, SourceLocation OrigLoc,
13219 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13220 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13221
13222 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13223 const FieldDecl *FD, bool InNonTrivialUnion) {
13224 if (const auto *AT = S.Context.getAsArrayType(QT))
13225 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13226 InNonTrivialUnion);
13227 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13228 }
13229
13230 void visitARCStrong(QualType QT, const FieldDecl *FD,
13231 bool InNonTrivialUnion) {
13232 if (InNonTrivialUnion)
13233 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13234 << 1 << 0 << QT << FD->getName();
13235 }
13236
13237 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13238 if (InNonTrivialUnion)
13239 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13240 << 1 << 0 << QT << FD->getName();
13241 }
13242
13243 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13244 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13245 if (RD->isUnion()) {
13246 if (OrigLoc.isValid()) {
13247 bool IsUnion = false;
13248 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13249 IsUnion = OrigRD->isUnion();
13250 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13251 << 0 << OrigTy << IsUnion << UseContext;
13252 // Reset OrigLoc so that this diagnostic is emitted only once.
13253 OrigLoc = SourceLocation();
13254 }
13255 InNonTrivialUnion = true;
13256 }
13257
13258 if (InNonTrivialUnion)
13259 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13260 << 0 << 0 << QT.getUnqualifiedType() << "";
13261
13262 for (const FieldDecl *FD : RD->fields())
13263 if (!shouldIgnoreForRecordTriviality(FD))
13264 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13265 }
13266
13267 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13268
13269 // The non-trivial C union type or the struct/union type that contains a
13270 // non-trivial C union.
13271 QualType OrigTy;
13272 SourceLocation OrigLoc;
13274 Sema &S;
13275};
13276
13277struct DiagNonTrivalCUnionDestructedTypeVisitor
13278 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13279 using Super =
13281
13282 DiagNonTrivalCUnionDestructedTypeVisitor(
13283 QualType OrigTy, SourceLocation OrigLoc,
13284 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13285 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13286
13287 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13288 const FieldDecl *FD, bool InNonTrivialUnion) {
13289 if (const auto *AT = S.Context.getAsArrayType(QT))
13290 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13291 InNonTrivialUnion);
13292 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13293 }
13294
13295 void visitARCStrong(QualType QT, const FieldDecl *FD,
13296 bool InNonTrivialUnion) {
13297 if (InNonTrivialUnion)
13298 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13299 << 1 << 1 << QT << FD->getName();
13300 }
13301
13302 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13303 if (InNonTrivialUnion)
13304 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13305 << 1 << 1 << QT << FD->getName();
13306 }
13307
13308 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13309 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13310 if (RD->isUnion()) {
13311 if (OrigLoc.isValid()) {
13312 bool IsUnion = false;
13313 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13314 IsUnion = OrigRD->isUnion();
13315 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13316 << 1 << OrigTy << IsUnion << UseContext;
13317 // Reset OrigLoc so that this diagnostic is emitted only once.
13318 OrigLoc = SourceLocation();
13319 }
13320 InNonTrivialUnion = true;
13321 }
13322
13323 if (InNonTrivialUnion)
13324 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13325 << 0 << 1 << QT.getUnqualifiedType() << "";
13326
13327 for (const FieldDecl *FD : RD->fields())
13328 if (!shouldIgnoreForRecordTriviality(FD))
13329 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13330 }
13331
13332 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13333 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13334 bool InNonTrivialUnion) {}
13335
13336 // The non-trivial C union type or the struct/union type that contains a
13337 // non-trivial C union.
13338 QualType OrigTy;
13339 SourceLocation OrigLoc;
13341 Sema &S;
13342};
13343
13344struct DiagNonTrivalCUnionCopyVisitor
13345 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13347
13348 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13350 Sema &S)
13351 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13352
13353 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13354 const FieldDecl *FD, bool InNonTrivialUnion) {
13355 if (const auto *AT = S.Context.getAsArrayType(QT))
13356 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13357 InNonTrivialUnion);
13358 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13359 }
13360
13361 void visitARCStrong(QualType QT, const FieldDecl *FD,
13362 bool InNonTrivialUnion) {
13363 if (InNonTrivialUnion)
13364 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13365 << 1 << 2 << QT << FD->getName();
13366 }
13367
13368 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13369 if (InNonTrivialUnion)
13370 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13371 << 1 << 2 << QT << FD->getName();
13372 }
13373
13374 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13375 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13376 if (RD->isUnion()) {
13377 if (OrigLoc.isValid()) {
13378 bool IsUnion = false;
13379 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13380 IsUnion = OrigRD->isUnion();
13381 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13382 << 2 << OrigTy << IsUnion << UseContext;
13383 // Reset OrigLoc so that this diagnostic is emitted only once.
13384 OrigLoc = SourceLocation();
13385 }
13386 InNonTrivialUnion = true;
13387 }
13388
13389 if (InNonTrivialUnion)
13390 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13391 << 0 << 2 << QT.getUnqualifiedType() << "";
13392
13393 for (const FieldDecl *FD : RD->fields())
13394 if (!shouldIgnoreForRecordTriviality(FD))
13395 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13396 }
13397
13398 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13399 const FieldDecl *FD, bool InNonTrivialUnion) {}
13400 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13401 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13402 bool InNonTrivialUnion) {}
13403
13404 // The non-trivial C union type or the struct/union type that contains a
13405 // non-trivial C union.
13406 QualType OrigTy;
13407 SourceLocation OrigLoc;
13409 Sema &S;
13410};
13411
13412} // namespace
13413
13415 NonTrivialCUnionContext UseContext,
13416 unsigned NonTrivialKind) {
13420 "shouldn't be called if type doesn't have a non-trivial C union");
13421
13422 if ((NonTrivialKind & NTCUK_Init) &&
13424 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13425 .visit(QT, nullptr, false);
13426 if ((NonTrivialKind & NTCUK_Destruct) &&
13428 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13429 .visit(QT, nullptr, false);
13430 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13431 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13432 .visit(QT, nullptr, false);
13433}
13434
13435/// AddInitializerToDecl - Adds the initializer Init to the
13436/// declaration dcl. If DirectInit is true, this is C++ direct
13437/// initialization rather than copy initialization.
13439 // If there is no declaration, there was an error parsing it. Just ignore
13440 // the initializer.
13441 if (!RealDecl) {
13442 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13443 return;
13444 }
13445
13446 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13447 if (!Method->isInvalidDecl()) {
13448 // Pure-specifiers are handled in ActOnPureSpecifier.
13449 Diag(Method->getLocation(), diag::err_member_function_initialization)
13450 << Method->getDeclName() << Init->getSourceRange();
13451 Method->setInvalidDecl();
13452 }
13453 return;
13454 }
13455
13456 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13457 if (!VDecl) {
13458 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13459 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13460 RealDecl->setInvalidDecl();
13461 return;
13462 }
13463
13464 if (VDecl->isInvalidDecl()) {
13466 SmallVector<Expr *> SubExprs;
13467 if (Res.isUsable())
13468 SubExprs.push_back(Res.get());
13469 ExprResult Recovery =
13470 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13471 if (Expr *E = Recovery.get())
13472 VDecl->setInit(E);
13473 return;
13474 }
13475
13476 // WebAssembly tables can't be used to initialise a variable.
13477 if (Init && !Init->getType().isNull() &&
13478 Init->getType()->isWebAssemblyTableType()) {
13479 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13480 VDecl->setInvalidDecl();
13481 return;
13482 }
13483
13484 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13485 if (VDecl->getType()->isUndeducedType()) {
13486 // Attempt typo correction early so that the type of the init expression can
13487 // be deduced based on the chosen correction if the original init contains a
13488 // TypoExpr.
13490 if (!Res.isUsable()) {
13491 // There are unresolved typos in Init, just drop them.
13492 // FIXME: improve the recovery strategy to preserve the Init.
13493 RealDecl->setInvalidDecl();
13494 return;
13495 }
13496 if (Res.get()->containsErrors()) {
13497 // Invalidate the decl as we don't know the type for recovery-expr yet.
13498 RealDecl->setInvalidDecl();
13499 VDecl->setInit(Res.get());
13500 return;
13501 }
13502 Init = Res.get();
13503
13505 return;
13506 }
13507
13508 // dllimport cannot be used on variable definitions.
13509 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13510 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13511 VDecl->setInvalidDecl();
13512 return;
13513 }
13514
13515 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13516 // the identifier has external or internal linkage, the declaration shall
13517 // have no initializer for the identifier.
13518 // C++14 [dcl.init]p5 is the same restriction for C++.
13519 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13520 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13521 VDecl->setInvalidDecl();
13522 return;
13523 }
13524
13525 if (!VDecl->getType()->isDependentType()) {
13526 // A definition must end up with a complete type, which means it must be
13527 // complete with the restriction that an array type might be completed by
13528 // the initializer; note that later code assumes this restriction.
13529 QualType BaseDeclType = VDecl->getType();
13530 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13531 BaseDeclType = Array->getElementType();
13532 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13533 diag::err_typecheck_decl_incomplete_type)) {
13534 RealDecl->setInvalidDecl();
13535 return;
13536 }
13537
13538 // The variable can not have an abstract class type.
13539 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13540 diag::err_abstract_type_in_decl,
13542 VDecl->setInvalidDecl();
13543 }
13544
13545 // C++ [module.import/6] external definitions are not permitted in header
13546 // units.
13547 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13548 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13549 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13550 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13551 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13552 VDecl->setInvalidDecl();
13553 }
13554
13555 // If adding the initializer will turn this declaration into a definition,
13556 // and we already have a definition for this variable, diagnose or otherwise
13557 // handle the situation.
13558 if (VarDecl *Def = VDecl->getDefinition())
13559 if (Def != VDecl &&
13560 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13562 checkVarDeclRedefinition(Def, VDecl))
13563 return;
13564
13565 if (getLangOpts().CPlusPlus) {
13566 // C++ [class.static.data]p4
13567 // If a static data member is of const integral or const
13568 // enumeration type, its declaration in the class definition can
13569 // specify a constant-initializer which shall be an integral
13570 // constant expression (5.19). In that case, the member can appear
13571 // in integral constant expressions. The member shall still be
13572 // defined in a namespace scope if it is used in the program and the
13573 // namespace scope definition shall not contain an initializer.
13574 //
13575 // We already performed a redefinition check above, but for static
13576 // data members we also need to check whether there was an in-class
13577 // declaration with an initializer.
13578 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13579 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13580 << VDecl->getDeclName();
13581 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13582 diag::note_previous_initializer)
13583 << 0;
13584 return;
13585 }
13586
13587 if (VDecl->hasLocalStorage())
13589
13591 VDecl->setInvalidDecl();
13592 return;
13593 }
13594 }
13595
13596 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13597 // a kernel function cannot be initialized."
13598 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13599 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13600 VDecl->setInvalidDecl();
13601 return;
13602 }
13603
13604 // The LoaderUninitialized attribute acts as a definition (of undef).
13605 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13606 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13607 VDecl->setInvalidDecl();
13608 return;
13609 }
13610
13611 // Get the decls type and save a reference for later, since
13612 // CheckInitializerTypes may change it.
13613 QualType DclT = VDecl->getType(), SavT = DclT;
13614
13615 // Expressions default to 'id' when we're in a debugger
13616 // and we are assigning it to a variable of Objective-C pointer type.
13617 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13618 Init->getType() == Context.UnknownAnyTy) {
13620 if (Result.isInvalid()) {
13621 VDecl->setInvalidDecl();
13622 return;
13623 }
13624 Init = Result.get();
13625 }
13626
13627 // Perform the initialization.
13628 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13629 bool IsParenListInit = false;
13630 if (!VDecl->isInvalidDecl()) {
13633 VDecl->getLocation(), DirectInit, Init);
13634
13635 MultiExprArg Args = Init;
13636 if (CXXDirectInit)
13637 Args = MultiExprArg(CXXDirectInit->getExprs(),
13638 CXXDirectInit->getNumExprs());
13639
13640 // Try to correct any TypoExprs in the initialization arguments.
13641 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13643 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13644 [this, Entity, Kind](Expr *E) {
13645 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13646 return Init.Failed() ? ExprError() : E;
13647 });
13648 if (Res.isInvalid()) {
13649 VDecl->setInvalidDecl();
13650 } else if (Res.get() != Args[Idx]) {
13651 Args[Idx] = Res.get();
13652 }
13653 }
13654 if (VDecl->isInvalidDecl())
13655 return;
13656
13657 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13658 /*TopLevelOfInitList=*/false,
13659 /*TreatUnavailableAsInvalid=*/false);
13660 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13661 if (Result.isInvalid()) {
13662 // If the provided initializer fails to initialize the var decl,
13663 // we attach a recovery expr for better recovery.
13664 auto RecoveryExpr =
13665 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13666 if (RecoveryExpr.get())
13667 VDecl->setInit(RecoveryExpr.get());
13668 // In general, for error recovery purposes, the initalizer doesn't play
13669 // part in the valid bit of the declaration. There are a few exceptions:
13670 // 1) if the var decl has a deduced auto type, and the type cannot be
13671 // deduced by an invalid initializer;
13672 // 2) if the var decl is decompsition decl with a non-deduced type, and
13673 // the initialization fails (e.g. `int [a] = {1, 2};`);
13674 // Case 1) was already handled elsewhere.
13675 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13676 VDecl->setInvalidDecl();
13677 return;
13678 }
13679
13680 Init = Result.getAs<Expr>();
13681 IsParenListInit = !InitSeq.steps().empty() &&
13682 InitSeq.step_begin()->Kind ==
13684 QualType VDeclType = VDecl->getType();
13685 if (Init && !Init->getType().isNull() &&
13686 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13687 Context.getAsIncompleteArrayType(VDeclType) &&
13689 // Bail out if it is not possible to deduce array size from the
13690 // initializer.
13691 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13692 << VDeclType;
13693 VDecl->setInvalidDecl();
13694 return;
13695 }
13696 }
13697
13698 // Check for self-references within variable initializers.
13699 // Variables declared within a function/method body (except for references)
13700 // are handled by a dataflow analysis.
13701 // This is undefined behavior in C++, but valid in C.
13702 if (getLangOpts().CPlusPlus)
13703 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13704 VDecl->getType()->isReferenceType())
13705 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13706
13707 // If the type changed, it means we had an incomplete type that was
13708 // completed by the initializer. For example:
13709 // int ary[] = { 1, 3, 5 };
13710 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13711 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13712 VDecl->setType(DclT);
13713
13714 if (!VDecl->isInvalidDecl()) {
13715 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13716
13717 if (VDecl->hasAttr<BlocksAttr>())
13718 ObjC().checkRetainCycles(VDecl, Init);
13719
13720 // It is safe to assign a weak reference into a strong variable.
13721 // Although this code can still have problems:
13722 // id x = self.weakProp;
13723 // id y = self.weakProp;
13724 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13725 // paths through the function. This should be revisited if
13726 // -Wrepeated-use-of-weak is made flow-sensitive.
13727 if (FunctionScopeInfo *FSI = getCurFunction())
13728 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13730 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13731 Init->getBeginLoc()))
13732 FSI->markSafeWeakUse(Init);
13733 }
13734
13735 // The initialization is usually a full-expression.
13736 //
13737 // FIXME: If this is a braced initialization of an aggregate, it is not
13738 // an expression, and each individual field initializer is a separate
13739 // full-expression. For instance, in:
13740 //
13741 // struct Temp { ~Temp(); };
13742 // struct S { S(Temp); };
13743 // struct T { S a, b; } t = { Temp(), Temp() }
13744 //
13745 // we should destroy the first Temp before constructing the second.
13748 /*DiscardedValue*/ false, VDecl->isConstexpr());
13749 if (Result.isInvalid()) {
13750 VDecl->setInvalidDecl();
13751 return;
13752 }
13753 Init = Result.get();
13754
13755 // Attach the initializer to the decl.
13756 VDecl->setInit(Init);
13757
13758 if (VDecl->isLocalVarDecl()) {
13759 // Don't check the initializer if the declaration is malformed.
13760 if (VDecl->isInvalidDecl()) {
13761 // do nothing
13762
13763 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13764 // This is true even in C++ for OpenCL.
13765 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13767
13768 // Otherwise, C++ does not restrict the initializer.
13769 } else if (getLangOpts().CPlusPlus) {
13770 // do nothing
13771
13772 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13773 // static storage duration shall be constant expressions or string literals.
13774 } else if (VDecl->getStorageClass() == SC_Static) {
13776
13777 // C89 is stricter than C99 for aggregate initializers.
13778 // C89 6.5.7p3: All the expressions [...] in an initializer list
13779 // for an object that has aggregate or union type shall be
13780 // constant expressions.
13781 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13782 isa<InitListExpr>(Init)) {
13783 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13784 }
13785
13786 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13787 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13788 if (VDecl->hasLocalStorage())
13789 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13790 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13791 VDecl->getLexicalDeclContext()->isRecord()) {
13792 // This is an in-class initialization for a static data member, e.g.,
13793 //
13794 // struct S {
13795 // static const int value = 17;
13796 // };
13797
13798 // C++ [class.mem]p4:
13799 // A member-declarator can contain a constant-initializer only
13800 // if it declares a static member (9.4) of const integral or
13801 // const enumeration type, see 9.4.2.
13802 //
13803 // C++11 [class.static.data]p3:
13804 // If a non-volatile non-inline const static data member is of integral
13805 // or enumeration type, its declaration in the class definition can
13806 // specify a brace-or-equal-initializer in which every initializer-clause
13807 // that is an assignment-expression is a constant expression. A static
13808 // data member of literal type can be declared in the class definition
13809 // with the constexpr specifier; if so, its declaration shall specify a
13810 // brace-or-equal-initializer in which every initializer-clause that is
13811 // an assignment-expression is a constant expression.
13812
13813 // Do nothing on dependent types.
13814 if (DclT->isDependentType()) {
13815
13816 // Allow any 'static constexpr' members, whether or not they are of literal
13817 // type. We separately check that every constexpr variable is of literal
13818 // type.
13819 } else if (VDecl->isConstexpr()) {
13820
13821 // Require constness.
13822 } else if (!DclT.isConstQualified()) {
13823 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13824 << Init->getSourceRange();
13825 VDecl->setInvalidDecl();
13826
13827 // We allow integer constant expressions in all cases.
13828 } else if (DclT->isIntegralOrEnumerationType()) {
13829 // Check whether the expression is a constant expression.
13832 // In C++11, a non-constexpr const static data member with an
13833 // in-class initializer cannot be volatile.
13834 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13835 else if (Init->isValueDependent())
13836 ; // Nothing to check.
13837 else if (Init->isIntegerConstantExpr(Context, &Loc))
13838 ; // Ok, it's an ICE!
13839 else if (Init->getType()->isScopedEnumeralType() &&
13840 Init->isCXX11ConstantExpr(Context))
13841 ; // Ok, it is a scoped-enum constant expression.
13842 else if (Init->isEvaluatable(Context)) {
13843 // If we can constant fold the initializer through heroics, accept it,
13844 // but report this as a use of an extension for -pedantic.
13845 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13846 << Init->getSourceRange();
13847 } else {
13848 // Otherwise, this is some crazy unknown case. Report the issue at the
13849 // location provided by the isIntegerConstantExpr failed check.
13850 Diag(Loc, diag::err_in_class_initializer_non_constant)
13851 << Init->getSourceRange();
13852 VDecl->setInvalidDecl();
13853 }
13854
13855 // We allow foldable floating-point constants as an extension.
13856 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13857 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13858 // it anyway and provide a fixit to add the 'constexpr'.
13859 if (getLangOpts().CPlusPlus11) {
13860 Diag(VDecl->getLocation(),
13861 diag::ext_in_class_initializer_float_type_cxx11)
13862 << DclT << Init->getSourceRange();
13863 Diag(VDecl->getBeginLoc(),
13864 diag::note_in_class_initializer_float_type_cxx11)
13865 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13866 } else {
13867 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13868 << DclT << Init->getSourceRange();
13869
13870 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13871 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13872 << Init->getSourceRange();
13873 VDecl->setInvalidDecl();
13874 }
13875 }
13876
13877 // Suggest adding 'constexpr' in C++11 for literal types.
13878 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13879 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13880 << DclT << Init->getSourceRange()
13881 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13882 VDecl->setConstexpr(true);
13883
13884 } else {
13885 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13886 << DclT << Init->getSourceRange();
13887 VDecl->setInvalidDecl();
13888 }
13889 } else if (VDecl->isFileVarDecl()) {
13890 // In C, extern is typically used to avoid tentative definitions when
13891 // declaring variables in headers, but adding an intializer makes it a
13892 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13893 // In C++, extern is often used to give implictly static const variables
13894 // external linkage, so don't warn in that case. If selectany is present,
13895 // this might be header code intended for C and C++ inclusion, so apply the
13896 // C++ rules.
13897 if (VDecl->getStorageClass() == SC_Extern &&
13898 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13900 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13902 Diag(VDecl->getLocation(), diag::warn_extern_init);
13903
13904 // In Microsoft C++ mode, a const variable defined in namespace scope has
13905 // external linkage by default if the variable is declared with
13906 // __declspec(dllexport).
13909 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13910 VDecl->setStorageClass(SC_Extern);
13911
13912 // C99 6.7.8p4. All file scoped initializers need to be constant.
13913 // Avoid duplicate diagnostics for constexpr variables.
13914 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13915 !VDecl->isConstexpr())
13917 }
13918
13919 QualType InitType = Init->getType();
13920 if (!InitType.isNull() &&
13924
13925 // We will represent direct-initialization similarly to copy-initialization:
13926 // int x(1); -as-> int x = 1;
13927 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13928 //
13929 // Clients that want to distinguish between the two forms, can check for
13930 // direct initializer using VarDecl::getInitStyle().
13931 // A major benefit is that clients that don't particularly care about which
13932 // exactly form was it (like the CodeGen) can handle both cases without
13933 // special case code.
13934
13935 // C++ 8.5p11:
13936 // The form of initialization (using parentheses or '=') is generally
13937 // insignificant, but does matter when the entity being initialized has a
13938 // class type.
13939 if (CXXDirectInit) {
13940 assert(DirectInit && "Call-style initializer must be direct init.");
13941 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13943 } else if (DirectInit) {
13944 // This must be list-initialization. No other way is direct-initialization.
13946 }
13947
13948 if (LangOpts.OpenMP &&
13949 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13950 VDecl->isFileVarDecl())
13951 DeclsToCheckForDeferredDiags.insert(VDecl);
13953}
13954
13955/// ActOnInitializerError - Given that there was an error parsing an
13956/// initializer for the given declaration, try to at least re-establish
13957/// invariants such as whether a variable's type is either dependent or
13958/// complete.
13960 // Our main concern here is re-establishing invariants like "a
13961 // variable's type is either dependent or complete".
13962 if (!D || D->isInvalidDecl()) return;
13963
13964 VarDecl *VD = dyn_cast<VarDecl>(D);
13965 if (!VD) return;
13966
13967 // Bindings are not usable if we can't make sense of the initializer.
13968 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13969 for (auto *BD : DD->bindings())
13970 BD->setInvalidDecl();
13971
13972 // Auto types are meaningless if we can't make sense of the initializer.
13973 if (VD->getType()->isUndeducedType()) {
13974 D->setInvalidDecl();
13975 return;
13976 }
13977
13978 QualType Ty = VD->getType();
13979 if (Ty->isDependentType()) return;
13980
13981 // Require a complete type.
13984 diag::err_typecheck_decl_incomplete_type)) {
13985 VD->setInvalidDecl();
13986 return;
13987 }
13988
13989 // Require a non-abstract type.
13990 if (RequireNonAbstractType(VD->getLocation(), Ty,
13991 diag::err_abstract_type_in_decl,
13993 VD->setInvalidDecl();
13994 return;
13995 }
13996
13997 // Don't bother complaining about constructors or destructors,
13998 // though.
13999}
14000
14002 // If there is no declaration, there was an error parsing it. Just ignore it.
14003 if (!RealDecl)
14004 return;
14005
14006 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14007 QualType Type = Var->getType();
14008
14009 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14010 if (isa<DecompositionDecl>(RealDecl)) {
14011 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14012 Var->setInvalidDecl();
14013 return;
14014 }
14015
14016 if (Type->isUndeducedType() &&
14017 DeduceVariableDeclarationType(Var, false, nullptr))
14018 return;
14019
14020 // C++11 [class.static.data]p3: A static data member can be declared with
14021 // the constexpr specifier; if so, its declaration shall specify
14022 // a brace-or-equal-initializer.
14023 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14024 // the definition of a variable [...] or the declaration of a static data
14025 // member.
14026 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14027 !Var->isThisDeclarationADemotedDefinition()) {
14028 if (Var->isStaticDataMember()) {
14029 // C++1z removes the relevant rule; the in-class declaration is always
14030 // a definition there.
14031 if (!getLangOpts().CPlusPlus17 &&
14033 Diag(Var->getLocation(),
14034 diag::err_constexpr_static_mem_var_requires_init)
14035 << Var;
14036 Var->setInvalidDecl();
14037 return;
14038 }
14039 } else {
14040 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14041 Var->setInvalidDecl();
14042 return;
14043 }
14044 }
14045
14046 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14047 // be initialized.
14048 if (!Var->isInvalidDecl() &&
14049 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14050 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14051 bool HasConstExprDefaultConstructor = false;
14052 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14053 for (auto *Ctor : RD->ctors()) {
14054 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14055 Ctor->getMethodQualifiers().getAddressSpace() ==
14057 HasConstExprDefaultConstructor = true;
14058 }
14059 }
14060 }
14061 if (!HasConstExprDefaultConstructor) {
14062 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14063 Var->setInvalidDecl();
14064 return;
14065 }
14066 }
14067
14068 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14069 if (Var->getStorageClass() == SC_Extern) {
14070 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14071 << Var;
14072 Var->setInvalidDecl();
14073 return;
14074 }
14075 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14076 diag::err_typecheck_decl_incomplete_type)) {
14077 Var->setInvalidDecl();
14078 return;
14079 }
14080 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14081 if (!RD->hasTrivialDefaultConstructor()) {
14082 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14083 Var->setInvalidDecl();
14084 return;
14085 }
14086 }
14087 // The declaration is unitialized, no need for further checks.
14088 return;
14089 }
14090
14091 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14092 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14093 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14094 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14096
14097
14098 switch (DefKind) {
14100 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14101 break;
14102
14103 // We have an out-of-line definition of a static data member
14104 // that has an in-class initializer, so we type-check this like
14105 // a declaration.
14106 //
14107 [[fallthrough]];
14108
14110 // It's only a declaration.
14111
14112 // Block scope. C99 6.7p7: If an identifier for an object is
14113 // declared with no linkage (C99 6.2.2p6), the type for the
14114 // object shall be complete.
14115 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14116 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14117 RequireCompleteType(Var->getLocation(), Type,
14118 diag::err_typecheck_decl_incomplete_type))
14119 Var->setInvalidDecl();
14120
14121 // Make sure that the type is not abstract.
14122 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14123 RequireNonAbstractType(Var->getLocation(), Type,
14124 diag::err_abstract_type_in_decl,
14126 Var->setInvalidDecl();
14127 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14128 Var->getStorageClass() == SC_PrivateExtern) {
14129 Diag(Var->getLocation(), diag::warn_private_extern);
14130 Diag(Var->getLocation(), diag::note_private_extern);
14131 }
14132
14134 !Var->isInvalidDecl())
14135 ExternalDeclarations.push_back(Var);
14136
14137 return;
14138
14140 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14141 // object that has file scope without an initializer, and without a
14142 // storage-class specifier or with the storage-class specifier "static",
14143 // constitutes a tentative definition. Note: A tentative definition with
14144 // external linkage is valid (C99 6.2.2p5).
14145 if (!Var->isInvalidDecl()) {
14146 if (const IncompleteArrayType *ArrayT
14149 Var->getLocation(), ArrayT->getElementType(),
14150 diag::err_array_incomplete_or_sizeless_type))
14151 Var->setInvalidDecl();
14152 } else if (Var->getStorageClass() == SC_Static) {
14153 // C99 6.9.2p3: If the declaration of an identifier for an object is
14154 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14155 // declared type shall not be an incomplete type.
14156 // NOTE: code such as the following
14157 // static struct s;
14158 // struct s { int a; };
14159 // is accepted by gcc. Hence here we issue a warning instead of
14160 // an error and we do not invalidate the static declaration.
14161 // NOTE: to avoid multiple warnings, only check the first declaration.
14162 if (Var->isFirstDecl())
14163 RequireCompleteType(Var->getLocation(), Type,
14164 diag::ext_typecheck_decl_incomplete_type);
14165 }
14166 }
14167
14168 // Record the tentative definition; we're done.
14169 if (!Var->isInvalidDecl())
14171 return;
14172 }
14173
14174 // Provide a specific diagnostic for uninitialized variable
14175 // definitions with incomplete array type.
14176 if (Type->isIncompleteArrayType()) {
14177 if (Var->isConstexpr())
14178 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14179 << Var;
14180 else
14181 Diag(Var->getLocation(),
14182 diag::err_typecheck_incomplete_array_needs_initializer);
14183 Var->setInvalidDecl();
14184 return;
14185 }
14186
14187 // Provide a specific diagnostic for uninitialized variable
14188 // definitions with reference type.
14189 if (Type->isReferenceType()) {
14190 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14191 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14192 return;
14193 }
14194
14195 // Do not attempt to type-check the default initializer for a
14196 // variable with dependent type.
14197 if (Type->isDependentType())
14198 return;
14199
14200 if (Var->isInvalidDecl())
14201 return;
14202
14203 if (!Var->hasAttr<AliasAttr>()) {
14204 if (RequireCompleteType(Var->getLocation(),
14206 diag::err_typecheck_decl_incomplete_type)) {
14207 Var->setInvalidDecl();
14208 return;
14209 }
14210 } else {
14211 return;
14212 }
14213
14214 // The variable can not have an abstract class type.
14215 if (RequireNonAbstractType(Var->getLocation(), Type,
14216 diag::err_abstract_type_in_decl,
14218 Var->setInvalidDecl();
14219 return;
14220 }
14221
14222 // Check for jumps past the implicit initializer. C++0x
14223 // clarifies that this applies to a "variable with automatic
14224 // storage duration", not a "local variable".
14225 // C++11 [stmt.dcl]p3
14226 // A program that jumps from a point where a variable with automatic
14227 // storage duration is not in scope to a point where it is in scope is
14228 // ill-formed unless the variable has scalar type, class type with a
14229 // trivial default constructor and a trivial destructor, a cv-qualified
14230 // version of one of these types, or an array of one of the preceding
14231 // types and is declared without an initializer.
14232 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14233 if (const RecordType *Record
14235 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14236 // Mark the function (if we're in one) for further checking even if the
14237 // looser rules of C++11 do not require such checks, so that we can
14238 // diagnose incompatibilities with C++98.
14239 if (!CXXRecord->isPOD())
14241 }
14242 }
14243 // In OpenCL, we can't initialize objects in the __local address space,
14244 // even implicitly, so don't synthesize an implicit initializer.
14245 if (getLangOpts().OpenCL &&
14246 Var->getType().getAddressSpace() == LangAS::opencl_local)
14247 return;
14248 // C++03 [dcl.init]p9:
14249 // If no initializer is specified for an object, and the
14250 // object is of (possibly cv-qualified) non-POD class type (or
14251 // array thereof), the object shall be default-initialized; if
14252 // the object is of const-qualified type, the underlying class
14253 // type shall have a user-declared default
14254 // constructor. Otherwise, if no initializer is specified for
14255 // a non- static object, the object and its subobjects, if
14256 // any, have an indeterminate initial value); if the object
14257 // or any of its subobjects are of const-qualified type, the
14258 // program is ill-formed.
14259 // C++0x [dcl.init]p11:
14260 // If no initializer is specified for an object, the object is
14261 // default-initialized; [...].
14264 = InitializationKind::CreateDefault(Var->getLocation());
14265
14266 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14267 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14268
14269 if (Init.get()) {
14270 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14271 // This is important for template substitution.
14272 Var->setInitStyle(VarDecl::CallInit);
14273 } else if (Init.isInvalid()) {
14274 // If default-init fails, attach a recovery-expr initializer to track
14275 // that initialization was attempted and failed.
14276 auto RecoveryExpr =
14277 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14278 if (RecoveryExpr.get())
14279 Var->setInit(RecoveryExpr.get());
14280 }
14281
14283 }
14284}
14285
14287 // If there is no declaration, there was an error parsing it. Ignore it.
14288 if (!D)
14289 return;
14290
14291 VarDecl *VD = dyn_cast<VarDecl>(D);
14292 if (!VD) {
14293 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14294 D->setInvalidDecl();
14295 return;
14296 }
14297
14298 VD->setCXXForRangeDecl(true);
14299
14300 // for-range-declaration cannot be given a storage class specifier.
14301 int Error = -1;
14302 switch (VD->getStorageClass()) {
14303 case SC_None:
14304 break;
14305 case SC_Extern:
14306 Error = 0;
14307 break;
14308 case SC_Static:
14309 Error = 1;
14310 break;
14311 case SC_PrivateExtern:
14312 Error = 2;
14313 break;
14314 case SC_Auto:
14315 Error = 3;
14316 break;
14317 case SC_Register:
14318 Error = 4;
14319 break;
14320 }
14321
14322 // for-range-declaration cannot be given a storage class specifier con't.
14323 switch (VD->getTSCSpec()) {
14324 case TSCS_thread_local:
14325 Error = 6;
14326 break;
14327 case TSCS___thread:
14328 case TSCS__Thread_local:
14329 case TSCS_unspecified:
14330 break;
14331 }
14332
14333 if (Error != -1) {
14334 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14335 << VD << Error;
14336 D->setInvalidDecl();
14337 }
14338}
14339
14341 IdentifierInfo *Ident,
14342 ParsedAttributes &Attrs) {
14343 // C++1y [stmt.iter]p1:
14344 // A range-based for statement of the form
14345 // for ( for-range-identifier : for-range-initializer ) statement
14346 // is equivalent to
14347 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14348 DeclSpec DS(Attrs.getPool().getFactory());
14349
14350 const char *PrevSpec;
14351 unsigned DiagID;
14352 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14354
14356 D.SetIdentifier(Ident, IdentLoc);
14357 D.takeAttributes(Attrs);
14358
14359 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14360 IdentLoc);
14361 Decl *Var = ActOnDeclarator(S, D);
14362 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14364 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14365 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14366 : IdentLoc);
14367}
14368
14370 if (var->isInvalidDecl()) return;
14371
14373
14374 if (getLangOpts().OpenCL) {
14375 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14376 // initialiser
14377 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14378 !var->hasInit()) {
14379 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14380 << 1 /*Init*/;
14381 var->setInvalidDecl();
14382 return;
14383 }
14384 }
14385
14386 // In Objective-C, don't allow jumps past the implicit initialization of a
14387 // local retaining variable.
14388 if (getLangOpts().ObjC &&
14389 var->hasLocalStorage()) {
14390 switch (var->getType().getObjCLifetime()) {
14394 break;
14395
14399 break;
14400 }
14401 }
14402
14403 if (var->hasLocalStorage() &&
14406
14407 // Warn about externally-visible variables being defined without a
14408 // prior declaration. We only want to do this for global
14409 // declarations, but we also specifically need to avoid doing it for
14410 // class members because the linkage of an anonymous class can
14411 // change if it's later given a typedef name.
14412 if (var->isThisDeclarationADefinition() &&
14414 var->isExternallyVisible() && var->hasLinkage() &&
14415 !var->isInline() && !var->getDescribedVarTemplate() &&
14416 var->getStorageClass() != SC_Register &&
14417 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14419 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14420 var->getLocation())) {
14421 // Find a previous declaration that's not a definition.
14422 VarDecl *prev = var->getPreviousDecl();
14423 while (prev && prev->isThisDeclarationADefinition())
14424 prev = prev->getPreviousDecl();
14425
14426 if (!prev) {
14427 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14428 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14429 << /* variable */ 0;
14430 }
14431 }
14432
14433 // Cache the result of checking for constant initialization.
14434 std::optional<bool> CacheHasConstInit;
14435 const Expr *CacheCulprit = nullptr;
14436 auto checkConstInit = [&]() mutable {
14437 if (!CacheHasConstInit)
14438 CacheHasConstInit = var->getInit()->isConstantInitializer(
14439 Context, var->getType()->isReferenceType(), &CacheCulprit);
14440 return *CacheHasConstInit;
14441 };
14442
14443 if (var->getTLSKind() == VarDecl::TLS_Static) {
14444 if (var->getType().isDestructedType()) {
14445 // GNU C++98 edits for __thread, [basic.start.term]p3:
14446 // The type of an object with thread storage duration shall not
14447 // have a non-trivial destructor.
14448 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14450 Diag(var->getLocation(), diag::note_use_thread_local);
14451 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14452 if (!checkConstInit()) {
14453 // GNU C++98 edits for __thread, [basic.start.init]p4:
14454 // An object of thread storage duration shall not require dynamic
14455 // initialization.
14456 // FIXME: Need strict checking here.
14457 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14458 << CacheCulprit->getSourceRange();
14460 Diag(var->getLocation(), diag::note_use_thread_local);
14461 }
14462 }
14463 }
14464
14465
14466 if (!var->getType()->isStructureType() && var->hasInit() &&
14467 isa<InitListExpr>(var->getInit())) {
14468 const auto *ILE = cast<InitListExpr>(var->getInit());
14469 unsigned NumInits = ILE->getNumInits();
14470 if (NumInits > 2)
14471 for (unsigned I = 0; I < NumInits; ++I) {
14472 const auto *Init = ILE->getInit(I);
14473 if (!Init)
14474 break;
14475 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14476 if (!SL)
14477 break;
14478
14479 unsigned NumConcat = SL->getNumConcatenated();
14480 // Diagnose missing comma in string array initialization.
14481 // Do not warn when all the elements in the initializer are concatenated
14482 // together. Do not warn for macros too.
14483 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14484 bool OnlyOneMissingComma = true;
14485 for (unsigned J = I + 1; J < NumInits; ++J) {
14486 const auto *Init = ILE->getInit(J);
14487 if (!Init)
14488 break;
14489 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14490 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14491 OnlyOneMissingComma = false;
14492 break;
14493 }
14494 }
14495
14496 if (OnlyOneMissingComma) {
14498 for (unsigned i = 0; i < NumConcat - 1; ++i)
14499 Hints.push_back(FixItHint::CreateInsertion(
14500 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14501
14502 Diag(SL->getStrTokenLoc(1),
14503 diag::warn_concatenated_literal_array_init)
14504 << Hints;
14505 Diag(SL->getBeginLoc(),
14506 diag::note_concatenated_string_literal_silence);
14507 }
14508 // In any case, stop now.
14509 break;
14510 }
14511 }
14512 }
14513
14514
14515 QualType type = var->getType();
14516
14517 if (var->hasAttr<BlocksAttr>())
14519
14520 Expr *Init = var->getInit();
14521 bool GlobalStorage = var->hasGlobalStorage();
14522 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14524 bool HasConstInit = true;
14525
14526 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14527 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14528 << var;
14529
14530 // Check whether the initializer is sufficiently constant.
14531 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14532 !type->isDependentType() && Init && !Init->isValueDependent() &&
14533 (GlobalStorage || var->isConstexpr() ||
14535 // If this variable might have a constant initializer or might be usable in
14536 // constant expressions, check whether or not it actually is now. We can't
14537 // do this lazily, because the result might depend on things that change
14538 // later, such as which constexpr functions happen to be defined.
14540 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14541 // Prior to C++11, in contexts where a constant initializer is required,
14542 // the set of valid constant initializers is described by syntactic rules
14543 // in [expr.const]p2-6.
14544 // FIXME: Stricter checking for these rules would be useful for constinit /
14545 // -Wglobal-constructors.
14546 HasConstInit = checkConstInit();
14547
14548 // Compute and cache the constant value, and remember that we have a
14549 // constant initializer.
14550 if (HasConstInit) {
14551 (void)var->checkForConstantInitialization(Notes);
14552 Notes.clear();
14553 } else if (CacheCulprit) {
14554 Notes.emplace_back(CacheCulprit->getExprLoc(),
14555 PDiag(diag::note_invalid_subexpr_in_const_expr));
14556 Notes.back().second << CacheCulprit->getSourceRange();
14557 }
14558 } else {
14559 // Evaluate the initializer to see if it's a constant initializer.
14560 HasConstInit = var->checkForConstantInitialization(Notes);
14561 }
14562
14563 if (HasConstInit) {
14564 // FIXME: Consider replacing the initializer with a ConstantExpr.
14565 } else if (var->isConstexpr()) {
14566 SourceLocation DiagLoc = var->getLocation();
14567 // If the note doesn't add any useful information other than a source
14568 // location, fold it into the primary diagnostic.
14569 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14570 diag::note_invalid_subexpr_in_const_expr) {
14571 DiagLoc = Notes[0].first;
14572 Notes.clear();
14573 }
14574 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14575 << var << Init->getSourceRange();
14576 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14577 Diag(Notes[I].first, Notes[I].second);
14578 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14579 auto *Attr = var->getAttr<ConstInitAttr>();
14580 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14581 << Init->getSourceRange();
14582 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14583 << Attr->getRange() << Attr->isConstinit();
14584 for (auto &it : Notes)
14585 Diag(it.first, it.second);
14586 } else if (IsGlobal &&
14587 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14588 var->getLocation())) {
14589 // Warn about globals which don't have a constant initializer. Don't
14590 // warn about globals with a non-trivial destructor because we already
14591 // warned about them.
14592 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14593 if (!(RD && !RD->hasTrivialDestructor())) {
14594 // checkConstInit() here permits trivial default initialization even in
14595 // C++11 onwards, where such an initializer is not a constant initializer
14596 // but nonetheless doesn't require a global constructor.
14597 if (!checkConstInit())
14598 Diag(var->getLocation(), diag::warn_global_constructor)
14599 << Init->getSourceRange();
14600 }
14601 }
14602 }
14603
14604 // Apply section attributes and pragmas to global variables.
14605 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14607 PragmaStack<StringLiteral *> *Stack = nullptr;
14608 int SectionFlags = ASTContext::PSF_Read;
14609 bool MSVCEnv =
14610 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14611 std::optional<QualType::NonConstantStorageReason> Reason;
14612 if (HasConstInit &&
14613 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14614 Stack = &ConstSegStack;
14615 } else {
14616 SectionFlags |= ASTContext::PSF_Write;
14617 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14618 }
14619 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14620 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14621 SectionFlags |= ASTContext::PSF_Implicit;
14622 UnifySection(SA->getName(), SectionFlags, var);
14623 } else if (Stack->CurrentValue) {
14624 if (Stack != &ConstSegStack && MSVCEnv &&
14625 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14626 var->getType().isConstQualified()) {
14627 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14628 NonConstNonReferenceType) &&
14629 "This case should've already been handled elsewhere");
14630 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14631 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14633 : *Reason);
14634 }
14635 SectionFlags |= ASTContext::PSF_Implicit;
14636 auto SectionName = Stack->CurrentValue->getString();
14637 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14638 Stack->CurrentPragmaLocation,
14639 SectionAttr::Declspec_allocate));
14640 if (UnifySection(SectionName, SectionFlags, var))
14641 var->dropAttr<SectionAttr>();
14642 }
14643
14644 // Apply the init_seg attribute if this has an initializer. If the
14645 // initializer turns out to not be dynamic, we'll end up ignoring this
14646 // attribute.
14647 if (CurInitSeg && var->getInit())
14648 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14649 CurInitSegLoc));
14650 }
14651
14652 // All the following checks are C++ only.
14653 if (!getLangOpts().CPlusPlus) {
14654 // If this variable must be emitted, add it as an initializer for the
14655 // current module.
14656 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14657 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14658 return;
14659 }
14660
14661 // Require the destructor.
14662 if (!type->isDependentType())
14663 if (const RecordType *recordType = baseType->getAs<RecordType>())
14665
14666 // If this variable must be emitted, add it as an initializer for the current
14667 // module.
14668 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14669 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14670
14671 // Build the bindings if this is a structured binding declaration.
14672 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14674}
14675
14676/// Check if VD needs to be dllexport/dllimport due to being in a
14677/// dllexport/import function.
14679 assert(VD->isStaticLocal());
14680
14681 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14682
14683 // Find outermost function when VD is in lambda function.
14684 while (FD && !getDLLAttr(FD) &&
14685 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14686 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14687 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14688 }
14689
14690 if (!FD)
14691 return;
14692
14693 // Static locals inherit dll attributes from their function.
14694 if (Attr *A = getDLLAttr(FD)) {
14695 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14696 NewAttr->setInherited(true);
14697 VD->addAttr(NewAttr);
14698 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14699 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14700 NewAttr->setInherited(true);
14701 VD->addAttr(NewAttr);
14702
14703 // Export this function to enforce exporting this static variable even
14704 // if it is not used in this compilation unit.
14705 if (!FD->hasAttr<DLLExportAttr>())
14706 FD->addAttr(NewAttr);
14707
14708 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14709 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14710 NewAttr->setInherited(true);
14711 VD->addAttr(NewAttr);
14712 }
14713}
14714
14716 assert(VD->getTLSKind());
14717
14718 // Perform TLS alignment check here after attributes attached to the variable
14719 // which may affect the alignment have been processed. Only perform the check
14720 // if the target has a maximum TLS alignment (zero means no constraints).
14721 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14722 // Protect the check so that it's not performed on dependent types and
14723 // dependent alignments (we can't determine the alignment in that case).
14724 if (!VD->hasDependentAlignment()) {
14725 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14726 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14727 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14729 << (unsigned)MaxAlignChars.getQuantity();
14730 }
14731 }
14732 }
14733}
14734
14735/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14736/// any semantic actions necessary after any initializer has been attached.
14738 // Note that we are no longer parsing the initializer for this declaration.
14739 ParsingInitForAutoVars.erase(ThisDecl);
14740
14741 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14742 if (!VD)
14743 return;
14744
14745 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14747 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14749 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14753 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14757 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14761 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14764 }
14765
14766 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14767 for (auto *BD : DD->bindings()) {
14769 }
14770 }
14771
14772 checkAttributesAfterMerging(*this, *VD);
14773
14774 if (VD->isStaticLocal())
14776
14777 if (VD->getTLSKind())
14779
14780 // Perform check for initializers of device-side global variables.
14781 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14782 // 7.5). We must also apply the same checks to all __shared__
14783 // variables whether they are local or not. CUDA also allows
14784 // constant initializers for __constant__ and __device__ variables.
14785 if (getLangOpts().CUDA)
14787
14788 // Grab the dllimport or dllexport attribute off of the VarDecl.
14789 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14790
14791 // Imported static data members cannot be defined out-of-line.
14792 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14793 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14795 // We allow definitions of dllimport class template static data members
14796 // with a warning.
14798 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14799 bool IsClassTemplateMember =
14800 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14801 Context->getDescribedClassTemplate();
14802
14803 Diag(VD->getLocation(),
14804 IsClassTemplateMember
14805 ? diag::warn_attribute_dllimport_static_field_definition
14806 : diag::err_attribute_dllimport_static_field_definition);
14807 Diag(IA->getLocation(), diag::note_attribute);
14808 if (!IsClassTemplateMember)
14809 VD->setInvalidDecl();
14810 }
14811 }
14812
14813 // dllimport/dllexport variables cannot be thread local, their TLS index
14814 // isn't exported with the variable.
14815 if (DLLAttr && VD->getTLSKind()) {
14816 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14817 if (F && getDLLAttr(F)) {
14818 assert(VD->isStaticLocal());
14819 // But if this is a static local in a dlimport/dllexport function, the
14820 // function will never be inlined, which means the var would never be
14821 // imported, so having it marked import/export is safe.
14822 } else {
14823 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14824 << DLLAttr;
14825 VD->setInvalidDecl();
14826 }
14827 }
14828
14829 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14830 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14831 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14832 << Attr;
14833 VD->dropAttr<UsedAttr>();
14834 }
14835 }
14836 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14837 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14838 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14839 << Attr;
14840 VD->dropAttr<RetainAttr>();
14841 }
14842 }
14843
14844 const DeclContext *DC = VD->getDeclContext();
14845 // If there's a #pragma GCC visibility in scope, and this isn't a class
14846 // member, set the visibility of this variable.
14849
14850 // FIXME: Warn on unused var template partial specializations.
14851 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14853
14854 // Now we have parsed the initializer and can update the table of magic
14855 // tag values.
14856 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14858 return;
14859
14860 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14861 const Expr *MagicValueExpr = VD->getInit();
14862 if (!MagicValueExpr) {
14863 continue;
14864 }
14865 std::optional<llvm::APSInt> MagicValueInt;
14866 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14867 Diag(I->getRange().getBegin(),
14868 diag::err_type_tag_for_datatype_not_ice)
14869 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14870 continue;
14871 }
14872 if (MagicValueInt->getActiveBits() > 64) {
14873 Diag(I->getRange().getBegin(),
14874 diag::err_type_tag_for_datatype_too_large)
14875 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14876 continue;
14877 }
14878 uint64_t MagicValue = MagicValueInt->getZExtValue();
14879 RegisterTypeTagForDatatype(I->getArgumentKind(),
14880 MagicValue,
14881 I->getMatchingCType(),
14882 I->getLayoutCompatible(),
14883 I->getMustBeNull());
14884 }
14885}
14886
14888 auto *VD = dyn_cast<VarDecl>(DD);
14889 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14890}
14891
14893 ArrayRef<Decl *> Group) {
14895
14896 if (DS.isTypeSpecOwned())
14897 Decls.push_back(DS.getRepAsDecl());
14898
14899 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14900 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14901 bool DiagnosedMultipleDecomps = false;
14902 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14903 bool DiagnosedNonDeducedAuto = false;
14904
14905 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14906 if (Decl *D = Group[i]) {
14907 // Check if the Decl has been declared in '#pragma omp declare target'
14908 // directive and has static storage duration.
14909 if (auto *VD = dyn_cast<VarDecl>(D);
14910 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14911 VD->hasGlobalStorage())
14913 // For declarators, there are some additional syntactic-ish checks we need
14914 // to perform.
14915 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14916 if (!FirstDeclaratorInGroup)
14917 FirstDeclaratorInGroup = DD;
14918 if (!FirstDecompDeclaratorInGroup)
14919 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14920 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14921 !hasDeducedAuto(DD))
14922 FirstNonDeducedAutoInGroup = DD;
14923
14924 if (FirstDeclaratorInGroup != DD) {
14925 // A decomposition declaration cannot be combined with any other
14926 // declaration in the same group.
14927 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14928 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14929 diag::err_decomp_decl_not_alone)
14930 << FirstDeclaratorInGroup->getSourceRange()
14931 << DD->getSourceRange();
14932 DiagnosedMultipleDecomps = true;
14933 }
14934
14935 // A declarator that uses 'auto' in any way other than to declare a
14936 // variable with a deduced type cannot be combined with any other
14937 // declarator in the same group.
14938 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14939 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14940 diag::err_auto_non_deduced_not_alone)
14941 << FirstNonDeducedAutoInGroup->getType()
14943 << FirstDeclaratorInGroup->getSourceRange()
14944 << DD->getSourceRange();
14945 DiagnosedNonDeducedAuto = true;
14946 }
14947 }
14948 }
14949
14950 Decls.push_back(D);
14951 }
14952 }
14953
14955 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14956 handleTagNumbering(Tag, S);
14957 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14959 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14960 }
14961 }
14962
14963 return BuildDeclaratorGroup(Decls);
14964}
14965
14966/// BuildDeclaratorGroup - convert a list of declarations into a declaration
14967/// group, performing any necessary semantic checking.
14970 // C++14 [dcl.spec.auto]p7: (DR1347)
14971 // If the type that replaces the placeholder type is not the same in each
14972 // deduction, the program is ill-formed.
14973 if (Group.size() > 1) {
14974 QualType Deduced;
14975 VarDecl *DeducedDecl = nullptr;
14976 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14977 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14978 if (!D || D->isInvalidDecl())
14979 break;
14981 if (!DT || DT->getDeducedType().isNull())
14982 continue;
14983 if (Deduced.isNull()) {
14984 Deduced = DT->getDeducedType();
14985 DeducedDecl = D;
14986 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14987 auto *AT = dyn_cast<AutoType>(DT);
14988 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14989 diag::err_auto_different_deductions)
14990 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14991 << DeducedDecl->getDeclName() << DT->getDeducedType()
14992 << D->getDeclName();
14993 if (DeducedDecl->hasInit())
14994 Dia << DeducedDecl->getInit()->getSourceRange();
14995 if (D->getInit())
14996 Dia << D->getInit()->getSourceRange();
14997 D->setInvalidDecl();
14998 break;
14999 }
15000 }
15001 }
15002
15004
15005 return DeclGroupPtrTy::make(
15006 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15007}
15008
15011}
15012
15014 // Don't parse the comment if Doxygen diagnostics are ignored.
15015 if (Group.empty() || !Group[0])
15016 return;
15017
15018 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15019 Group[0]->getLocation()) &&
15020 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15021 Group[0]->getLocation()))
15022 return;
15023
15024 if (Group.size() >= 2) {
15025 // This is a decl group. Normally it will contain only declarations
15026 // produced from declarator list. But in case we have any definitions or
15027 // additional declaration references:
15028 // 'typedef struct S {} S;'
15029 // 'typedef struct S *S;'
15030 // 'struct S *pS;'
15031 // FinalizeDeclaratorGroup adds these as separate declarations.
15032 Decl *MaybeTagDecl = Group[0];
15033 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15034 Group = Group.slice(1);
15035 }
15036 }
15037
15038 // FIMXE: We assume every Decl in the group is in the same file.
15039 // This is false when preprocessor constructs the group from decls in
15040 // different files (e. g. macros or #include).
15042}
15043
15044/// Common checks for a parameter-declaration that should apply to both function
15045/// parameters and non-type template parameters.
15047 // Check that there are no default arguments inside the type of this
15048 // parameter.
15049 if (getLangOpts().CPlusPlus)
15051
15052 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15053 if (D.getCXXScopeSpec().isSet()) {
15054 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15055 << D.getCXXScopeSpec().getRange();
15056 }
15057
15058 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15059 // simple identifier except [...irrelevant cases...].
15060 switch (D.getName().getKind()) {
15062 break;
15063
15071 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15073 break;
15074
15077 // GetNameForDeclarator would not produce a useful name in this case.
15078 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15079 break;
15080 }
15081}
15082
15084 SourceLocation ExplicitThisLoc) {
15085 if (!ExplicitThisLoc.isValid())
15086 return;
15087 assert(S.getLangOpts().CPlusPlus &&
15088 "explicit parameter in non-cplusplus mode");
15089 if (!S.getLangOpts().CPlusPlus23)
15090 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15091 << P->getSourceRange();
15092
15093 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15094 // parameter pack.
15095 if (P->isParameterPack()) {
15096 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15097 << P->getSourceRange();
15098 return;
15099 }
15100 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15101 if (LambdaScopeInfo *LSI = S.getCurLambda())
15102 LSI->ExplicitObjectParameter = P;
15103}
15104
15105/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15106/// to introduce parameters into function prototype scope.
15108 SourceLocation ExplicitThisLoc) {
15109 const DeclSpec &DS = D.getDeclSpec();
15110
15111 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15112
15113 // C++03 [dcl.stc]p2 also permits 'auto'.
15114 StorageClass SC = SC_None;
15116 SC = SC_Register;
15117 // In C++11, the 'register' storage class specifier is deprecated.
15118 // In C++17, it is not allowed, but we tolerate it as an extension.
15119 if (getLangOpts().CPlusPlus11) {
15121 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15122 : diag::warn_deprecated_register)
15124 }
15125 } else if (getLangOpts().CPlusPlus &&
15127 SC = SC_Auto;
15130 diag::err_invalid_storage_class_in_func_decl);
15132 }
15133
15135 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15137 if (DS.isInlineSpecified())
15138 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15139 << getLangOpts().CPlusPlus17;
15140 if (DS.hasConstexprSpecifier())
15141 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15142 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15143
15145
15147
15149 QualType parmDeclType = TInfo->getType();
15150
15151 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15152 const IdentifierInfo *II = D.getIdentifier();
15153 if (II) {
15155 RedeclarationKind::ForVisibleRedeclaration);
15156 LookupName(R, S);
15157 if (!R.empty()) {
15158 NamedDecl *PrevDecl = *R.begin();
15159 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15160 // Maybe we will complain about the shadowed template parameter.
15162 // Just pretend that we didn't see the previous declaration.
15163 PrevDecl = nullptr;
15164 }
15165 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15166 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15167 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15168 // Recover by removing the name
15169 II = nullptr;
15170 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15171 D.setInvalidType(true);
15172 }
15173 }
15174 }
15175
15176 // Temporarily put parameter variables in the translation unit, not
15177 // the enclosing context. This prevents them from accidentally
15178 // looking like class members in C++.
15179 ParmVarDecl *New =
15181 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15182
15183 if (D.isInvalidType())
15184 New->setInvalidDecl();
15185
15186 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15187
15188 assert(S->isFunctionPrototypeScope());
15189 assert(S->getFunctionPrototypeDepth() >= 1);
15190 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15191 S->getNextFunctionPrototypeIndex());
15192
15193 // Add the parameter declaration into this scope.
15194 S->AddDecl(New);
15195 if (II)
15196 IdResolver.AddDecl(New);
15197
15198 ProcessDeclAttributes(S, New, D);
15199
15201 Diag(New->getLocation(), diag::err_module_private_local)
15202 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15204
15205 if (New->hasAttr<BlocksAttr>()) {
15206 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15207 }
15208
15209 if (getLangOpts().OpenCL)
15211
15212 return New;
15213}
15214
15215/// Synthesizes a variable for a parameter arising from a
15216/// typedef.
15219 QualType T) {
15220 /* FIXME: setting StartLoc == Loc.
15221 Would it be worth to modify callers so as to provide proper source
15222 location for the unnamed parameters, embedding the parameter's type? */
15223 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15225 SC_None, nullptr);
15226 Param->setImplicit();
15227 return Param;
15228}
15229
15231 // Don't diagnose unused-parameter errors in template instantiations; we
15232 // will already have done so in the template itself.
15234 return;
15235
15236 for (const ParmVarDecl *Parameter : Parameters) {
15237 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15238 !Parameter->hasAttr<UnusedAttr>() &&
15239 !Parameter->getIdentifier()->isPlaceholder()) {
15240 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15241 << Parameter->getDeclName();
15242 }
15243 }
15244}
15245
15247 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15248 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15249 return;
15250
15251 // Warn if the return value is pass-by-value and larger than the specified
15252 // threshold.
15253 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15254 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15255 if (Size > LangOpts.NumLargeByValueCopy)
15256 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15257 }
15258
15259 // Warn if any parameter is pass-by-value and larger than the specified
15260 // threshold.
15261 for (const ParmVarDecl *Parameter : Parameters) {
15262 QualType T = Parameter->getType();
15263 if (T->isDependentType() || !T.isPODType(Context))
15264 continue;
15265 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15266 if (Size > LangOpts.NumLargeByValueCopy)
15267 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15268 << Parameter << Size;
15269 }
15270}
15271
15273 SourceLocation NameLoc,
15274 const IdentifierInfo *Name, QualType T,
15275 TypeSourceInfo *TSInfo, StorageClass SC) {
15276 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15277 if (getLangOpts().ObjCAutoRefCount &&
15278 T.getObjCLifetime() == Qualifiers::OCL_None &&
15279 T->isObjCLifetimeType()) {
15280
15281 Qualifiers::ObjCLifetime lifetime;
15282
15283 // Special cases for arrays:
15284 // - if it's const, use __unsafe_unretained
15285 // - otherwise, it's an error
15286 if (T->isArrayType()) {
15287 if (!T.isConstQualified()) {
15291 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15292 else
15293 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15294 << TSInfo->getTypeLoc().getSourceRange();
15295 }
15297 } else {
15298 lifetime = T->getObjCARCImplicitLifetime();
15299 }
15300 T = Context.getLifetimeQualifiedType(T, lifetime);
15301 }
15302
15303 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15305 TSInfo, SC, nullptr);
15306
15307 // Make a note if we created a new pack in the scope of a lambda, so that
15308 // we know that references to that pack must also be expanded within the
15309 // lambda scope.
15310 if (New->isParameterPack())
15311 if (auto *LSI = getEnclosingLambda())
15312 LSI->LocalPacks.push_back(New);
15313
15318
15319 // Parameter declarators cannot be interface types. All ObjC objects are
15320 // passed by reference.
15321 if (T->isObjCObjectType()) {
15322 SourceLocation TypeEndLoc =
15324 Diag(NameLoc,
15325 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15326 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15328 New->setType(T);
15329 }
15330
15331 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15332 // duration shall not be qualified by an address-space qualifier."
15333 // Since all parameters have automatic store duration, they can not have
15334 // an address space.
15335 if (T.getAddressSpace() != LangAS::Default &&
15336 // OpenCL allows function arguments declared to be an array of a type
15337 // to be qualified with an address space.
15338 !(getLangOpts().OpenCL &&
15339 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15340 // WebAssembly allows reference types as parameters. Funcref in particular
15341 // lives in a different address space.
15342 !(T->isFunctionPointerType() &&
15343 T.getAddressSpace() == LangAS::wasm_funcref)) {
15344 Diag(NameLoc, diag::err_arg_with_address_space);
15345 New->setInvalidDecl();
15346 }
15347
15348 // PPC MMA non-pointer types are not allowed as function argument types.
15349 if (Context.getTargetInfo().getTriple().isPPC64() &&
15350 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15351 New->setInvalidDecl();
15352 }
15353
15354 return New;
15355}
15356
15358 SourceLocation LocAfterDecls) {
15360
15361 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15362 // in the declaration list shall have at least one declarator, those
15363 // declarators shall only declare identifiers from the identifier list, and
15364 // every identifier in the identifier list shall be declared.
15365 //
15366 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15367 // identifiers it names shall be declared in the declaration list."
15368 //
15369 // This is why we only diagnose in C99 and later. Note, the other conditions
15370 // listed are checked elsewhere.
15371 if (!FTI.hasPrototype) {
15372 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15373 --i;
15374 if (FTI.Params[i].Param == nullptr) {
15375 if (getLangOpts().C99) {
15376 SmallString<256> Code;
15377 llvm::raw_svector_ostream(Code)
15378 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15379 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15380 << FTI.Params[i].Ident
15381 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15382 }
15383
15384 // Implicitly declare the argument as type 'int' for lack of a better
15385 // type.
15386 AttributeFactory attrs;
15387 DeclSpec DS(attrs);
15388 const char* PrevSpec; // unused
15389 unsigned DiagID; // unused
15390 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15391 DiagID, Context.getPrintingPolicy());
15392 // Use the identifier location for the type source range.
15393 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15394 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15397 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15398 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15399 }
15400 }
15401 }
15402}
15403
15404Decl *
15406 MultiTemplateParamsArg TemplateParameterLists,
15407 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15408 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15409 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15410 Scope *ParentScope = FnBodyScope->getParent();
15411
15412 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15413 // we define a non-templated function definition, we will create a declaration
15414 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15415 // The base function declaration will have the equivalent of an `omp declare
15416 // variant` annotation which specifies the mangled definition as a
15417 // specialization function under the OpenMP context defined as part of the
15418 // `omp begin declare variant`.
15420 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15422 ParentScope, D, TemplateParameterLists, Bases);
15423
15425 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15426 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15427
15428 if (!Bases.empty())
15430 Bases);
15431
15432 return Dcl;
15433}
15434
15437}
15438
15440 const FunctionDecl *&PossiblePrototype) {
15441 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15442 Prev = Prev->getPreviousDecl()) {
15443 // Ignore any declarations that occur in function or method
15444 // scope, because they aren't visible from the header.
15445 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15446 continue;
15447
15448 PossiblePrototype = Prev;
15449 return Prev->getType()->isFunctionProtoType();
15450 }
15451 return false;
15452}
15453
15454static bool
15456 const FunctionDecl *&PossiblePrototype) {
15457 // Don't warn about invalid declarations.
15458 if (FD->isInvalidDecl())
15459 return false;
15460
15461 // Or declarations that aren't global.
15462 if (!FD->isGlobal())
15463 return false;
15464
15465 // Don't warn about C++ member functions.
15466 if (isa<CXXMethodDecl>(FD))
15467 return false;
15468
15469 // Don't warn about 'main'.
15470 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15471 if (IdentifierInfo *II = FD->getIdentifier())
15472 if (II->isStr("main") || II->isStr("efi_main"))
15473 return false;
15474
15475 // Don't warn about inline functions.
15476 if (FD->isInlined())
15477 return false;
15478
15479 // Don't warn about function templates.
15481 return false;
15482
15483 // Don't warn about function template specializations.
15485 return false;
15486
15487 // Don't warn for OpenCL kernels.
15488 if (FD->hasAttr<OpenCLKernelAttr>())
15489 return false;
15490
15491 // Don't warn on explicitly deleted functions.
15492 if (FD->isDeleted())
15493 return false;
15494
15495 // Don't warn on implicitly local functions (such as having local-typed
15496 // parameters).
15497 if (!FD->isExternallyVisible())
15498 return false;
15499
15500 // If we were able to find a potential prototype, don't warn.
15501 if (FindPossiblePrototype(FD, PossiblePrototype))
15502 return false;
15503
15504 return true;
15505}
15506
15507void
15509 const FunctionDecl *EffectiveDefinition,
15510 SkipBodyInfo *SkipBody) {
15511 const FunctionDecl *Definition = EffectiveDefinition;
15512 if (!Definition &&
15513 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15514 return;
15515
15516 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15517 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15518 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15519 // A merged copy of the same function, instantiated as a member of
15520 // the same class, is OK.
15521 if (declaresSameEntity(OrigFD, OrigDef) &&
15522 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15523 cast<Decl>(FD->getLexicalDeclContext())))
15524 return;
15525 }
15526 }
15527 }
15528
15530 return;
15531
15532 // Don't emit an error when this is redefinition of a typo-corrected
15533 // definition.
15535 return;
15536
15537 // If we don't have a visible definition of the function, and it's inline or
15538 // a template, skip the new definition.
15539 if (SkipBody && !hasVisibleDefinition(Definition) &&
15540 (Definition->getFormalLinkage() == Linkage::Internal ||
15541 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15542 Definition->getNumTemplateParameterLists())) {
15543 SkipBody->ShouldSkip = true;
15544 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15545 if (auto *TD = Definition->getDescribedFunctionTemplate())
15548 return;
15549 }
15550
15551 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15552 Definition->getStorageClass() == SC_Extern)
15553 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15554 << FD << getLangOpts().CPlusPlus;
15555 else
15556 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15557
15558 Diag(Definition->getLocation(), diag::note_previous_definition);
15559 FD->setInvalidDecl();
15560}
15561
15563 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15564
15566 LSI->CallOperator = CallOperator;
15567 LSI->Lambda = LambdaClass;
15568 LSI->ReturnType = CallOperator->getReturnType();
15569 // This function in calls in situation where the context of the call operator
15570 // is not entered, so we set AfterParameterList to false, so that
15571 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15572 LSI->AfterParameterList = false;
15573 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15574
15575 if (LCD == LCD_None)
15577 else if (LCD == LCD_ByCopy)
15579 else if (LCD == LCD_ByRef)
15581 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15582
15584 LSI->Mutable = !CallOperator->isConst();
15585 if (CallOperator->isExplicitObjectMemberFunction())
15586 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15587
15588 // Add the captures to the LSI so they can be noted as already
15589 // captured within tryCaptureVar.
15590 auto I = LambdaClass->field_begin();
15591 for (const auto &C : LambdaClass->captures()) {
15592 if (C.capturesVariable()) {
15593 ValueDecl *VD = C.getCapturedVar();
15594 if (VD->isInitCapture())
15596 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15597 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15598 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15599 /*EllipsisLoc*/C.isPackExpansion()
15600 ? C.getEllipsisLoc() : SourceLocation(),
15601 I->getType(), /*Invalid*/false);
15602
15603 } else if (C.capturesThis()) {
15604 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15605 C.getCaptureKind() == LCK_StarThis);
15606 } else {
15607 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15608 I->getType());
15609 }
15610 ++I;
15611 }
15612 return LSI;
15613}
15614
15616 SkipBodyInfo *SkipBody,
15617 FnBodyKind BodyKind) {
15618 if (!D) {
15619 // Parsing the function declaration failed in some way. Push on a fake scope
15620 // anyway so we can try to parse the function body.
15623 return D;
15624 }
15625
15626 FunctionDecl *FD = nullptr;
15627
15628 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15629 FD = FunTmpl->getTemplatedDecl();
15630 else
15631 FD = cast<FunctionDecl>(D);
15632
15633 // Do not push if it is a lambda because one is already pushed when building
15634 // the lambda in ActOnStartOfLambdaDefinition().
15635 if (!isLambdaCallOperator(FD))
15636 // [expr.const]/p14.1
15637 // An expression or conversion is in an immediate function context if it is
15638 // potentially evaluated and either: its innermost enclosing non-block scope
15639 // is a function parameter scope of an immediate function.
15642 : ExprEvalContexts.back().Context);
15643
15644 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15645 // context is nested in an immediate function context, so smaller contexts
15646 // that appear inside immediate functions (like variable initializers) are
15647 // considered to be inside an immediate function context even though by
15648 // themselves they are not immediate function contexts. But when a new
15649 // function is entered, we need to reset this tracking, since the entered
15650 // function might be not an immediate function.
15651 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15652 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15653 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15654
15655 // Check for defining attributes before the check for redefinition.
15656 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15657 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15658 FD->dropAttr<AliasAttr>();
15659 FD->setInvalidDecl();
15660 }
15661 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15662 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15663 FD->dropAttr<IFuncAttr>();
15664 FD->setInvalidDecl();
15665 }
15666 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15667 if (!Context.getTargetInfo().hasFeature("fmv") &&
15668 !Attr->isDefaultVersion()) {
15669 // If function multi versioning disabled skip parsing function body
15670 // defined with non-default target_version attribute
15671 if (SkipBody)
15672 SkipBody->ShouldSkip = true;
15673 return nullptr;
15674 }
15675 }
15676
15677 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15678 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15679 Ctor->isDefaultConstructor() &&
15681 // If this is an MS ABI dllexport default constructor, instantiate any
15682 // default arguments.
15684 }
15685 }
15686
15687 // See if this is a redefinition. If 'will have body' (or similar) is already
15688 // set, then these checks were already performed when it was set.
15689 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15691 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15692
15693 // If we're skipping the body, we're done. Don't enter the scope.
15694 if (SkipBody && SkipBody->ShouldSkip)
15695 return D;
15696 }
15697
15698 // Mark this function as "will have a body eventually". This lets users to
15699 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15700 // this function.
15701 FD->setWillHaveBody();
15702
15703 // If we are instantiating a generic lambda call operator, push
15704 // a LambdaScopeInfo onto the function stack. But use the information
15705 // that's already been calculated (ActOnLambdaExpr) to prime the current
15706 // LambdaScopeInfo.
15707 // When the template operator is being specialized, the LambdaScopeInfo,
15708 // has to be properly restored so that tryCaptureVariable doesn't try
15709 // and capture any new variables. In addition when calculating potential
15710 // captures during transformation of nested lambdas, it is necessary to
15711 // have the LSI properly restored.
15713 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15714 // instantiated, explicitly specialized.
15717 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15718 FD->setInvalidDecl();
15720 } else {
15721 assert(inTemplateInstantiation() &&
15722 "There should be an active template instantiation on the stack "
15723 "when instantiating a generic lambda!");
15724 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15725 }
15726 } else {
15727 // Enter a new function scope
15729 }
15730
15731 // Builtin functions cannot be defined.
15732 if (unsigned BuiltinID = FD->getBuiltinID()) {
15735 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15736 FD->setInvalidDecl();
15737 }
15738 }
15739
15740 // The return type of a function definition must be complete (C99 6.9.1p3).
15741 // C++23 [dcl.fct.def.general]/p2
15742 // The type of [...] the return for a function definition
15743 // shall not be a (possibly cv-qualified) class type that is incomplete
15744 // or abstract within the function body unless the function is deleted.
15745 QualType ResultType = FD->getReturnType();
15746 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15747 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15748 (RequireCompleteType(FD->getLocation(), ResultType,
15749 diag::err_func_def_incomplete_result) ||
15751 diag::err_abstract_type_in_decl,
15753 FD->setInvalidDecl();
15754
15755 if (FnBodyScope)
15756 PushDeclContext(FnBodyScope, FD);
15757
15758 // Check the validity of our function parameters
15759 if (BodyKind != FnBodyKind::Delete)
15761 /*CheckParameterNames=*/true);
15762
15763 // Add non-parameter declarations already in the function to the current
15764 // scope.
15765 if (FnBodyScope) {
15766 for (Decl *NPD : FD->decls()) {
15767 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15768 if (!NonParmDecl)
15769 continue;
15770 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15771 "parameters should not be in newly created FD yet");
15772
15773 // If the decl has a name, make it accessible in the current scope.
15774 if (NonParmDecl->getDeclName())
15775 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15776
15777 // Similarly, dive into enums and fish their constants out, making them
15778 // accessible in this scope.
15779 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15780 for (auto *EI : ED->enumerators())
15781 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15782 }
15783 }
15784 }
15785
15786 // Introduce our parameters into the function scope
15787 for (auto *Param : FD->parameters()) {
15788 Param->setOwningFunction(FD);
15789
15790 // If this has an identifier, add it to the scope stack.
15791 if (Param->getIdentifier() && FnBodyScope) {
15792 CheckShadow(FnBodyScope, Param);
15793
15794 PushOnScopeChains(Param, FnBodyScope);
15795 }
15796 }
15797
15798 // C++ [module.import/6] external definitions are not permitted in header
15799 // units. Deleted and Defaulted functions are implicitly inline (but the
15800 // inline state is not set at this point, so check the BodyKind explicitly).
15801 // FIXME: Consider an alternate location for the test where the inlined()
15802 // state is complete.
15803 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15804 !FD->isInvalidDecl() && !FD->isInlined() &&
15805 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15806 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15807 !FD->isTemplateInstantiation()) {
15808 assert(FD->isThisDeclarationADefinition());
15809 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15810 FD->setInvalidDecl();
15811 }
15812
15813 // Ensure that the function's exception specification is instantiated.
15814 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15816
15817 // dllimport cannot be applied to non-inline function definitions.
15818 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15819 !FD->isTemplateInstantiation()) {
15820 assert(!FD->hasAttr<DLLExportAttr>());
15821 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15822 FD->setInvalidDecl();
15823 return D;
15824 }
15825
15826 // Some function attributes (like OptimizeNoneAttr) need actions before
15827 // parsing body started.
15829
15830 // We want to attach documentation to original Decl (which might be
15831 // a function template).
15833 if (getCurLexicalContext()->isObjCContainer() &&
15834 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15835 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15836 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15837
15838 return D;
15839}
15840
15842 if (!FD || FD->isInvalidDecl())
15843 return;
15844 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15845 FD = TD->getTemplatedDecl();
15846 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15850 FpPragmaStack.CurrentValue =
15852 }
15853}
15854
15855/// Given the set of return statements within a function body,
15856/// compute the variables that are subject to the named return value
15857/// optimization.
15858///
15859/// Each of the variables that is subject to the named return value
15860/// optimization will be marked as NRVO variables in the AST, and any
15861/// return statement that has a marked NRVO variable as its NRVO candidate can
15862/// use the named return value optimization.
15863///
15864/// This function applies a very simplistic algorithm for NRVO: if every return
15865/// statement in the scope of a variable has the same NRVO candidate, that
15866/// candidate is an NRVO variable.
15868 ReturnStmt **Returns = Scope->Returns.data();
15869
15870 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15871 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15872 if (!NRVOCandidate->isNRVOVariable())
15873 Returns[I]->setNRVOCandidate(nullptr);
15874 }
15875 }
15876}
15877
15879 // We can't delay parsing the body of a constexpr function template (yet).
15881 return false;
15882
15883 // We can't delay parsing the body of a function template with a deduced
15884 // return type (yet).
15885 if (D.getDeclSpec().hasAutoTypeSpec()) {
15886 // If the placeholder introduces a non-deduced trailing return type,
15887 // we can still delay parsing it.
15888 if (D.getNumTypeObjects()) {
15889 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15890 if (Outer.Kind == DeclaratorChunk::Function &&
15891 Outer.Fun.hasTrailingReturnType()) {
15892 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15893 return Ty.isNull() || !Ty->isUndeducedType();
15894 }
15895 }
15896 return false;
15897 }
15898
15899 return true;
15900}
15901
15903 // We cannot skip the body of a function (or function template) which is
15904 // constexpr, since we may need to evaluate its body in order to parse the
15905 // rest of the file.
15906 // We cannot skip the body of a function with an undeduced return type,
15907 // because any callers of that function need to know the type.
15908 if (const FunctionDecl *FD = D->getAsFunction()) {
15909 if (FD->isConstexpr())
15910 return false;
15911 // We can't simply call Type::isUndeducedType here, because inside template
15912 // auto can be deduced to a dependent type, which is not considered
15913 // "undeduced".
15914 if (FD->getReturnType()->getContainedDeducedType())
15915 return false;
15916 }
15918}
15919
15921 if (!Decl)
15922 return nullptr;
15923 if (FunctionDecl *FD = Decl->getAsFunction())
15924 FD->setHasSkippedBody();
15925 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15926 MD->setHasSkippedBody();
15927 return Decl;
15928}
15929
15931 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15932}
15933
15934/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15935/// body.
15937public:
15938 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15940 if (!IsLambda)
15942 }
15943
15944private:
15945 Sema &S;
15946 bool IsLambda = false;
15947};
15948
15950 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15951
15952 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15953 if (EscapeInfo.count(BD))
15954 return EscapeInfo[BD];
15955
15956 bool R = false;
15957 const BlockDecl *CurBD = BD;
15958
15959 do {
15960 R = !CurBD->doesNotEscape();
15961 if (R)
15962 break;
15963 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15964 } while (CurBD);
15965
15966 return EscapeInfo[BD] = R;
15967 };
15968
15969 // If the location where 'self' is implicitly retained is inside a escaping
15970 // block, emit a diagnostic.
15971 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15973 if (IsOrNestedInEscapingBlock(P.second))
15974 S.Diag(P.first, diag::warn_implicitly_retains_self)
15975 << FixItHint::CreateInsertion(P.first, "self->");
15976}
15977
15978static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15979 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15980 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15981}
15982
15984 return methodHasName(FD, "get_return_object");
15985}
15986
15988 return FD->isStatic() &&
15989 methodHasName(FD, "get_return_object_on_allocation_failure");
15990}
15991
15994 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15995 return;
15996 // Allow some_promise_type::get_return_object().
15998 return;
15999 if (!FD->hasAttr<CoroWrapperAttr>())
16000 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16001}
16002
16004 bool IsInstantiation) {
16006 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16007
16008 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16009 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16010
16012 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16013
16014 // If we skip function body, we can't tell if a function is a coroutine.
16015 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16016 if (FSI->isCoroutine())
16018 else
16020 }
16021
16022 {
16023 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16024 // one is already popped when finishing the lambda in BuildLambdaExpr().
16025 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16026 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16027 if (FD) {
16028 // If this is called by Parser::ParseFunctionDefinition() after marking
16029 // the declaration as deleted, and if the deleted-function-body contains
16030 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
16031 // added to store that message; do not overwrite it in that case.
16032 //
16033 // Since this would always set the body to 'nullptr' in that case anyway,
16034 // which is already done when the function decl is initially created,
16035 // always skipping this irrespective of whether there is a delete message
16036 // should not be a problem.
16037 if (!FD->isDeletedAsWritten())
16038 FD->setBody(Body);
16039 FD->setWillHaveBody(false);
16041
16042 if (getLangOpts().CPlusPlus14) {
16043 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16044 FD->getReturnType()->isUndeducedType()) {
16045 // For a function with a deduced result type to return void,
16046 // the result type as written must be 'auto' or 'decltype(auto)',
16047 // possibly cv-qualified or constrained, but not ref-qualified.
16048 if (!FD->getReturnType()->getAs<AutoType>()) {
16049 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16050 << FD->getReturnType();
16051 FD->setInvalidDecl();
16052 } else {
16053 // Falling off the end of the function is the same as 'return;'.
16054 Expr *Dummy = nullptr;
16056 FD, dcl->getLocation(), Dummy,
16057 FD->getReturnType()->getAs<AutoType>()))
16058 FD->setInvalidDecl();
16059 }
16060 }
16061 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16062 // In C++11, we don't use 'auto' deduction rules for lambda call
16063 // operators because we don't support return type deduction.
16064 auto *LSI = getCurLambda();
16065 if (LSI->HasImplicitReturnType) {
16067
16068 // C++11 [expr.prim.lambda]p4:
16069 // [...] if there are no return statements in the compound-statement
16070 // [the deduced type is] the type void
16071 QualType RetType =
16072 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16073
16074 // Update the return type to the deduced type.
16075 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16076 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16077 Proto->getExtProtoInfo()));
16078 }
16079 }
16080
16081 // If the function implicitly returns zero (like 'main') or is naked,
16082 // don't complain about missing return statements.
16083 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16085
16086 // MSVC permits the use of pure specifier (=0) on function definition,
16087 // defined at class scope, warn about this non-standard construct.
16088 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16089 !FD->isOutOfLine())
16090 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16091
16092 if (!FD->isInvalidDecl()) {
16093 // Don't diagnose unused parameters of defaulted, deleted or naked
16094 // functions.
16095 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16096 !FD->hasAttr<NakedAttr>())
16099 FD->getReturnType(), FD);
16100
16101 // If this is a structor, we need a vtable.
16102 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16103 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16104 else if (CXXDestructorDecl *Destructor =
16105 dyn_cast<CXXDestructorDecl>(FD))
16106 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16107
16108 // Try to apply the named return value optimization. We have to check
16109 // if we can do this here because lambdas keep return statements around
16110 // to deduce an implicit return type.
16111 if (FD->getReturnType()->isRecordType() &&
16113 computeNRVO(Body, FSI);
16114 }
16115
16116 // GNU warning -Wmissing-prototypes:
16117 // Warn if a global function is defined without a previous
16118 // prototype declaration. This warning is issued even if the
16119 // definition itself provides a prototype. The aim is to detect
16120 // global functions that fail to be declared in header files.
16121 const FunctionDecl *PossiblePrototype = nullptr;
16122 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16123 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16124
16125 if (PossiblePrototype) {
16126 // We found a declaration that is not a prototype,
16127 // but that could be a zero-parameter prototype
16128 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16129 TypeLoc TL = TI->getTypeLoc();
16131 Diag(PossiblePrototype->getLocation(),
16132 diag::note_declaration_not_a_prototype)
16133 << (FD->getNumParams() != 0)
16135 FTL.getRParenLoc(), "void")
16136 : FixItHint{});
16137 }
16138 } else {
16139 // Returns true if the token beginning at this Loc is `const`.
16140 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16141 const LangOptions &LangOpts) {
16142 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16143 if (LocInfo.first.isInvalid())
16144 return false;
16145
16146 bool Invalid = false;
16147 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16148 if (Invalid)
16149 return false;
16150
16151 if (LocInfo.second > Buffer.size())
16152 return false;
16153
16154 const char *LexStart = Buffer.data() + LocInfo.second;
16155 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16156
16157 return StartTok.consume_front("const") &&
16158 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16159 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16160 };
16161
16162 auto findBeginLoc = [&]() {
16163 // If the return type has `const` qualifier, we want to insert
16164 // `static` before `const` (and not before the typename).
16165 if ((FD->getReturnType()->isAnyPointerType() &&
16168 // But only do this if we can determine where the `const` is.
16169
16170 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16171 getLangOpts()))
16172
16173 return FD->getBeginLoc();
16174 }
16175 return FD->getTypeSpecStartLoc();
16176 };
16178 diag::note_static_for_internal_linkage)
16179 << /* function */ 1
16180 << (FD->getStorageClass() == SC_None
16181 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16182 : FixItHint{});
16183 }
16184 }
16185
16186 // We might not have found a prototype because we didn't wish to warn on
16187 // the lack of a missing prototype. Try again without the checks for
16188 // whether we want to warn on the missing prototype.
16189 if (!PossiblePrototype)
16190 (void)FindPossiblePrototype(FD, PossiblePrototype);
16191
16192 // If the function being defined does not have a prototype, then we may
16193 // need to diagnose it as changing behavior in C23 because we now know
16194 // whether the function accepts arguments or not. This only handles the
16195 // case where the definition has no prototype but does have parameters
16196 // and either there is no previous potential prototype, or the previous
16197 // potential prototype also has no actual prototype. This handles cases
16198 // like:
16199 // void f(); void f(a) int a; {}
16200 // void g(a) int a; {}
16201 // See MergeFunctionDecl() for other cases of the behavior change
16202 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16203 // type without a prototype.
16204 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16205 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16206 !PossiblePrototype->isImplicit()))) {
16207 // The function definition has parameters, so this will change behavior
16208 // in C23. If there is a possible prototype, it comes before the
16209 // function definition.
16210 // FIXME: The declaration may have already been diagnosed as being
16211 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16212 // there's no way to test for the "changes behavior" condition in
16213 // SemaType.cpp when forming the declaration's function type. So, we do
16214 // this awkward dance instead.
16215 //
16216 // If we have a possible prototype and it declares a function with a
16217 // prototype, we don't want to diagnose it; if we have a possible
16218 // prototype and it has no prototype, it may have already been
16219 // diagnosed in SemaType.cpp as deprecated depending on whether
16220 // -Wstrict-prototypes is enabled. If we already warned about it being
16221 // deprecated, add a note that it also changes behavior. If we didn't
16222 // warn about it being deprecated (because the diagnostic is not
16223 // enabled), warn now that it is deprecated and changes behavior.
16224
16225 // This K&R C function definition definitely changes behavior in C23,
16226 // so diagnose it.
16227 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16228 << /*definition*/ 1 << /* not supported in C23 */ 0;
16229
16230 // If we have a possible prototype for the function which is a user-
16231 // visible declaration, we already tested that it has no prototype.
16232 // This will change behavior in C23. This gets a warning rather than a
16233 // note because it's the same behavior-changing problem as with the
16234 // definition.
16235 if (PossiblePrototype)
16236 Diag(PossiblePrototype->getLocation(),
16237 diag::warn_non_prototype_changes_behavior)
16238 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16239 << /*definition*/ 1;
16240 }
16241
16242 // Warn on CPUDispatch with an actual body.
16243 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16244 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16245 if (!CmpndBody->body_empty())
16246 Diag(CmpndBody->body_front()->getBeginLoc(),
16247 diag::warn_dispatch_body_ignored);
16248
16249 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16250 const CXXMethodDecl *KeyFunction;
16251 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16252 MD->isVirtual() &&
16253 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16254 MD == KeyFunction->getCanonicalDecl()) {
16255 // Update the key-function state if necessary for this ABI.
16256 if (FD->isInlined() &&
16259
16260 // If the newly-chosen key function is already defined, then we
16261 // need to mark the vtable as used retroactively.
16262 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16263 const FunctionDecl *Definition;
16264 if (KeyFunction && KeyFunction->isDefined(Definition))
16265 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16266 } else {
16267 // We just defined they key function; mark the vtable as used.
16268 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16269 }
16270 }
16271 }
16272
16273 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16274 "Function parsing confused");
16275 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16276 assert(MD == getCurMethodDecl() && "Method parsing confused");
16277 MD->setBody(Body);
16278 if (!MD->isInvalidDecl()) {
16280 MD->getReturnType(), MD);
16281
16282 if (Body)
16283 computeNRVO(Body, FSI);
16284 }
16285 if (FSI->ObjCShouldCallSuper) {
16286 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16287 << MD->getSelector().getAsString();
16288 FSI->ObjCShouldCallSuper = false;
16289 }
16291 const ObjCMethodDecl *InitMethod = nullptr;
16292 bool isDesignated =
16293 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16294 assert(isDesignated && InitMethod);
16295 (void)isDesignated;
16296
16297 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16298 auto IFace = MD->getClassInterface();
16299 if (!IFace)
16300 return false;
16301 auto SuperD = IFace->getSuperClass();
16302 if (!SuperD)
16303 return false;
16304 return SuperD->getIdentifier() ==
16305 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16306 };
16307 // Don't issue this warning for unavailable inits or direct subclasses
16308 // of NSObject.
16309 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16310 Diag(MD->getLocation(),
16311 diag::warn_objc_designated_init_missing_super_call);
16312 Diag(InitMethod->getLocation(),
16313 diag::note_objc_designated_init_marked_here);
16314 }
16316 }
16317 if (FSI->ObjCWarnForNoInitDelegation) {
16318 // Don't issue this warning for unavaialable inits.
16319 if (!MD->isUnavailable())
16320 Diag(MD->getLocation(),
16321 diag::warn_objc_secondary_init_missing_init_call);
16322 FSI->ObjCWarnForNoInitDelegation = false;
16323 }
16324
16326 } else {
16327 // Parsing the function declaration failed in some way. Pop the fake scope
16328 // we pushed on.
16329 PopFunctionScopeInfo(ActivePolicy, dcl);
16330 return nullptr;
16331 }
16332
16333 if (Body && FSI->HasPotentialAvailabilityViolations)
16335
16336 assert(!FSI->ObjCShouldCallSuper &&
16337 "This should only be set for ObjC methods, which should have been "
16338 "handled in the block above.");
16339
16340 // Verify and clean out per-function state.
16341 if (Body && (!FD || !FD->isDefaulted())) {
16342 // C++ constructors that have function-try-blocks can't have return
16343 // statements in the handlers of that block. (C++ [except.handle]p14)
16344 // Verify this.
16345 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16346 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16347
16348 // Verify that gotos and switch cases don't jump into scopes illegally.
16351
16352 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16353 if (!Destructor->getParent()->isDependentType())
16355
16357 Destructor->getParent());
16358 }
16359
16360 // If any errors have occurred, clear out any temporaries that may have
16361 // been leftover. This ensures that these temporaries won't be picked up
16362 // for deletion in some later function.
16365 getDiagnostics().getSuppressAllDiagnostics()) {
16367 }
16368 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16369 // Since the body is valid, issue any analysis-based warnings that are
16370 // enabled.
16371 ActivePolicy = &WP;
16372 }
16373
16374 if (!IsInstantiation && FD &&
16375 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16376 !FD->isInvalidDecl() &&
16378 FD->setInvalidDecl();
16379
16380 if (FD && FD->hasAttr<NakedAttr>()) {
16381 for (const Stmt *S : Body->children()) {
16382 // Allow local register variables without initializer as they don't
16383 // require prologue.
16384 bool RegisterVariables = false;
16385 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16386 for (const auto *Decl : DS->decls()) {
16387 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16388 RegisterVariables =
16389 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16390 if (!RegisterVariables)
16391 break;
16392 }
16393 }
16394 }
16395 if (RegisterVariables)
16396 continue;
16397 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16398 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16399 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16400 FD->setInvalidDecl();
16401 break;
16402 }
16403 }
16404 }
16405
16406 assert(ExprCleanupObjects.size() ==
16407 ExprEvalContexts.back().NumCleanupObjects &&
16408 "Leftover temporaries in function");
16409 assert(!Cleanup.exprNeedsCleanups() &&
16410 "Unaccounted cleanups in function");
16411 assert(MaybeODRUseExprs.empty() &&
16412 "Leftover expressions for odr-use checking");
16413 }
16414 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16415 // the declaration context below. Otherwise, we're unable to transform
16416 // 'this' expressions when transforming immediate context functions.
16417
16418 if (!IsInstantiation)
16420
16421 PopFunctionScopeInfo(ActivePolicy, dcl);
16422 // If any errors have occurred, clear out any temporaries that may have
16423 // been leftover. This ensures that these temporaries won't be picked up for
16424 // deletion in some later function.
16427 }
16428
16429 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16430 !LangOpts.OMPTargetTriples.empty())) ||
16431 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16432 auto ES = getEmissionStatus(FD);
16435 DeclsToCheckForDeferredDiags.insert(FD);
16436 }
16437
16438 if (FD && !FD->isDeleted())
16439 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16440
16441 return dcl;
16442}
16443
16444/// When we finish delayed parsing of an attribute, we must attach it to the
16445/// relevant Decl.
16447 ParsedAttributes &Attrs) {
16448 // Always attach attributes to the underlying decl.
16449 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16450 D = TD->getTemplatedDecl();
16451 ProcessDeclAttributeList(S, D, Attrs);
16452 ProcessAPINotes(D);
16453
16454 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16455 if (Method->isStatic())
16457}
16458
16459/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16460/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16462 IdentifierInfo &II, Scope *S) {
16463 // It is not valid to implicitly define a function in C23.
16465 "Implicit function declarations aren't allowed in this language mode");
16466
16467 // Find the scope in which the identifier is injected and the corresponding
16468 // DeclContext.
16469 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16470 // In that case, we inject the declaration into the translation unit scope
16471 // instead.
16472 Scope *BlockScope = S;
16473 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16474 BlockScope = BlockScope->getParent();
16475
16476 // Loop until we find a DeclContext that is either a function/method or the
16477 // translation unit, which are the only two valid places to implicitly define
16478 // a function. This avoids accidentally defining the function within a tag
16479 // declaration, for example.
16480 Scope *ContextScope = BlockScope;
16481 while (!ContextScope->getEntity() ||
16482 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16483 !ContextScope->getEntity()->isTranslationUnit()))
16484 ContextScope = ContextScope->getParent();
16485 ContextRAII SavedContext(*this, ContextScope->getEntity());
16486
16487 // Before we produce a declaration for an implicitly defined
16488 // function, see whether there was a locally-scoped declaration of
16489 // this name as a function or variable. If so, use that
16490 // (non-visible) declaration, and complain about it.
16491 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16492 if (ExternCPrev) {
16493 // We still need to inject the function into the enclosing block scope so
16494 // that later (non-call) uses can see it.
16495 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16496
16497 // C89 footnote 38:
16498 // If in fact it is not defined as having type "function returning int",
16499 // the behavior is undefined.
16500 if (!isa<FunctionDecl>(ExternCPrev) ||
16502 cast<FunctionDecl>(ExternCPrev)->getType(),
16504 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16505 << ExternCPrev << !getLangOpts().C99;
16506 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16507 return ExternCPrev;
16508 }
16509 }
16510
16511 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16512 unsigned diag_id;
16513 if (II.getName().starts_with("__builtin_"))
16514 diag_id = diag::warn_builtin_unknown;
16515 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16516 else if (getLangOpts().C99)
16517 diag_id = diag::ext_implicit_function_decl_c99;
16518 else
16519 diag_id = diag::warn_implicit_function_decl;
16520
16521 TypoCorrection Corrected;
16522 // Because typo correction is expensive, only do it if the implicit
16523 // function declaration is going to be treated as an error.
16524 //
16525 // Perform the correction before issuing the main diagnostic, as some
16526 // consumers use typo-correction callbacks to enhance the main diagnostic.
16527 if (S && !ExternCPrev &&
16531 S, nullptr, CCC, CTK_NonError);
16532 }
16533
16534 Diag(Loc, diag_id) << &II;
16535 if (Corrected) {
16536 // If the correction is going to suggest an implicitly defined function,
16537 // skip the correction as not being a particularly good idea.
16538 bool Diagnose = true;
16539 if (const auto *D = Corrected.getCorrectionDecl())
16540 Diagnose = !D->isImplicit();
16541 if (Diagnose)
16542 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16543 /*ErrorRecovery*/ false);
16544 }
16545
16546 // If we found a prior declaration of this function, don't bother building
16547 // another one. We've already pushed that one into scope, so there's nothing
16548 // more to do.
16549 if (ExternCPrev)
16550 return ExternCPrev;
16551
16552 // Set a Declarator for the implicit definition: int foo();
16553 const char *Dummy;
16554 AttributeFactory attrFactory;
16555 DeclSpec DS(attrFactory);
16556 unsigned DiagID;
16557 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16559 (void)Error; // Silence warning.
16560 assert(!Error && "Error setting up implicit decl!");
16561 SourceLocation NoLoc;
16563 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16564 /*IsAmbiguous=*/false,
16565 /*LParenLoc=*/NoLoc,
16566 /*Params=*/nullptr,
16567 /*NumParams=*/0,
16568 /*EllipsisLoc=*/NoLoc,
16569 /*RParenLoc=*/NoLoc,
16570 /*RefQualifierIsLvalueRef=*/true,
16571 /*RefQualifierLoc=*/NoLoc,
16572 /*MutableLoc=*/NoLoc, EST_None,
16573 /*ESpecRange=*/SourceRange(),
16574 /*Exceptions=*/nullptr,
16575 /*ExceptionRanges=*/nullptr,
16576 /*NumExceptions=*/0,
16577 /*NoexceptExpr=*/nullptr,
16578 /*ExceptionSpecTokens=*/nullptr,
16579 /*DeclsInPrototype=*/std::nullopt,
16580 Loc, Loc, D),
16581 std::move(DS.getAttributes()), SourceLocation());
16582 D.SetIdentifier(&II, Loc);
16583
16584 // Insert this function into the enclosing block scope.
16585 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16586 FD->setImplicit();
16587
16589
16590 return FD;
16591}
16592
16593/// If this function is a C++ replaceable global allocation function
16594/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16595/// adds any function attributes that we know a priori based on the standard.
16596///
16597/// We need to check for duplicate attributes both here and where user-written
16598/// attributes are applied to declarations.
16600 FunctionDecl *FD) {
16601 if (FD->isInvalidDecl())
16602 return;
16603
16604 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16605 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16606 return;
16607
16608 std::optional<unsigned> AlignmentParam;
16609 bool IsNothrow = false;
16610 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16611 return;
16612
16613 // C++2a [basic.stc.dynamic.allocation]p4:
16614 // An allocation function that has a non-throwing exception specification
16615 // indicates failure by returning a null pointer value. Any other allocation
16616 // function never returns a null pointer value and indicates failure only by
16617 // throwing an exception [...]
16618 //
16619 // However, -fcheck-new invalidates this possible assumption, so don't add
16620 // NonNull when that is enabled.
16621 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16622 !getLangOpts().CheckNew)
16623 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16624
16625 // C++2a [basic.stc.dynamic.allocation]p2:
16626 // An allocation function attempts to allocate the requested amount of
16627 // storage. [...] If the request succeeds, the value returned by a
16628 // replaceable allocation function is a [...] pointer value p0 different
16629 // from any previously returned value p1 [...]
16630 //
16631 // However, this particular information is being added in codegen,
16632 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16633
16634 // C++2a [basic.stc.dynamic.allocation]p2:
16635 // An allocation function attempts to allocate the requested amount of
16636 // storage. If it is successful, it returns the address of the start of a
16637 // block of storage whose length in bytes is at least as large as the
16638 // requested size.
16639 if (!FD->hasAttr<AllocSizeAttr>()) {
16640 FD->addAttr(AllocSizeAttr::CreateImplicit(
16641 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16642 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16643 }
16644
16645 // C++2a [basic.stc.dynamic.allocation]p3:
16646 // For an allocation function [...], the pointer returned on a successful
16647 // call shall represent the address of storage that is aligned as follows:
16648 // (3.1) If the allocation function takes an argument of type
16649 // std​::​align_­val_­t, the storage will have the alignment
16650 // specified by the value of this argument.
16651 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16652 FD->addAttr(AllocAlignAttr::CreateImplicit(
16653 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16654 }
16655
16656 // FIXME:
16657 // C++2a [basic.stc.dynamic.allocation]p3:
16658 // For an allocation function [...], the pointer returned on a successful
16659 // call shall represent the address of storage that is aligned as follows:
16660 // (3.2) Otherwise, if the allocation function is named operator new[],
16661 // the storage is aligned for any object that does not have
16662 // new-extended alignment ([basic.align]) and is no larger than the
16663 // requested size.
16664 // (3.3) Otherwise, the storage is aligned for any object that does not
16665 // have new-extended alignment and is of the requested size.
16666}
16667
16668/// Adds any function attributes that we know a priori based on
16669/// the declaration of this function.
16670///
16671/// These attributes can apply both to implicitly-declared builtins
16672/// (like __builtin___printf_chk) or to library-declared functions
16673/// like NSLog or printf.
16674///
16675/// We need to check for duplicate attributes both here and where user-written
16676/// attributes are applied to declarations.
16678 if (FD->isInvalidDecl())
16679 return;
16680
16681 // If this is a built-in function, map its builtin attributes to
16682 // actual attributes.
16683 if (unsigned BuiltinID = FD->getBuiltinID()) {
16684 // Handle printf-formatting attributes.
16685 unsigned FormatIdx;
16686 bool HasVAListArg;
16687 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16688 if (!FD->hasAttr<FormatAttr>()) {
16689 const char *fmt = "printf";
16690 unsigned int NumParams = FD->getNumParams();
16691 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16692 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16693 fmt = "NSString";
16694 FD->addAttr(FormatAttr::CreateImplicit(Context,
16695 &Context.Idents.get(fmt),
16696 FormatIdx+1,
16697 HasVAListArg ? 0 : FormatIdx+2,
16698 FD->getLocation()));
16699 }
16700 }
16701 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16702 HasVAListArg)) {
16703 if (!FD->hasAttr<FormatAttr>())
16704 FD->addAttr(FormatAttr::CreateImplicit(Context,
16705 &Context.Idents.get("scanf"),
16706 FormatIdx+1,
16707 HasVAListArg ? 0 : FormatIdx+2,
16708 FD->getLocation()));
16709 }
16710
16711 // Handle automatically recognized callbacks.
16712 SmallVector<int, 4> Encoding;
16713 if (!FD->hasAttr<CallbackAttr>() &&
16714 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16715 FD->addAttr(CallbackAttr::CreateImplicit(
16716 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16717
16718 // Mark const if we don't care about errno and/or floating point exceptions
16719 // that are the only thing preventing the function from being const. This
16720 // allows IRgen to use LLVM intrinsics for such functions.
16721 bool NoExceptions =
16723 bool ConstWithoutErrnoAndExceptions =
16725 bool ConstWithoutExceptions =
16727 if (!FD->hasAttr<ConstAttr>() &&
16728 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16729 (!ConstWithoutErrnoAndExceptions ||
16730 (!getLangOpts().MathErrno && NoExceptions)) &&
16731 (!ConstWithoutExceptions || NoExceptions))
16732 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16733
16734 // We make "fma" on GNU or Windows const because we know it does not set
16735 // errno in those environments even though it could set errno based on the
16736 // C standard.
16737 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16738 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16739 !FD->hasAttr<ConstAttr>()) {
16740 switch (BuiltinID) {
16741 case Builtin::BI__builtin_fma:
16742 case Builtin::BI__builtin_fmaf:
16743 case Builtin::BI__builtin_fmal:
16744 case Builtin::BIfma:
16745 case Builtin::BIfmaf:
16746 case Builtin::BIfmal:
16747 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16748 break;
16749 default:
16750 break;
16751 }
16752 }
16753
16754 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16755 !FD->hasAttr<ReturnsTwiceAttr>())
16756 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16757 FD->getLocation()));
16758 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16759 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16760 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16761 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16762 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16763 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16764 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16765 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16766 // Add the appropriate attribute, depending on the CUDA compilation mode
16767 // and which target the builtin belongs to. For example, during host
16768 // compilation, aux builtins are __device__, while the rest are __host__.
16769 if (getLangOpts().CUDAIsDevice !=
16771 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16772 else
16773 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16774 }
16775
16776 // Add known guaranteed alignment for allocation functions.
16777 switch (BuiltinID) {
16778 case Builtin::BImemalign:
16779 case Builtin::BIaligned_alloc:
16780 if (!FD->hasAttr<AllocAlignAttr>())
16781 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16782 FD->getLocation()));
16783 break;
16784 default:
16785 break;
16786 }
16787
16788 // Add allocsize attribute for allocation functions.
16789 switch (BuiltinID) {
16790 case Builtin::BIcalloc:
16791 FD->addAttr(AllocSizeAttr::CreateImplicit(
16792 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16793 break;
16794 case Builtin::BImemalign:
16795 case Builtin::BIaligned_alloc:
16796 case Builtin::BIrealloc:
16797 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16798 ParamIdx(), FD->getLocation()));
16799 break;
16800 case Builtin::BImalloc:
16801 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16802 ParamIdx(), FD->getLocation()));
16803 break;
16804 default:
16805 break;
16806 }
16807
16808 // Add lifetime attribute to std::move, std::fowrard et al.
16809 switch (BuiltinID) {
16810 case Builtin::BIaddressof:
16811 case Builtin::BI__addressof:
16812 case Builtin::BI__builtin_addressof:
16813 case Builtin::BIas_const:
16814 case Builtin::BIforward:
16815 case Builtin::BIforward_like:
16816 case Builtin::BImove:
16817 case Builtin::BImove_if_noexcept:
16818 if (ParmVarDecl *P = FD->getParamDecl(0u);
16819 !P->hasAttr<LifetimeBoundAttr>())
16820 P->addAttr(
16821 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16822 break;
16823 default:
16824 break;
16825 }
16826 }
16827
16829
16830 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16831 // throw, add an implicit nothrow attribute to any extern "C" function we come
16832 // across.
16833 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16834 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16835 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16836 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16837 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16838 }
16839
16840 IdentifierInfo *Name = FD->getIdentifier();
16841 if (!Name)
16842 return;
16844 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16845 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16847 // Okay: this could be a libc/libm/Objective-C function we know
16848 // about.
16849 } else
16850 return;
16851
16852 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16853 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16854 // target-specific builtins, perhaps?
16855 if (!FD->hasAttr<FormatAttr>())
16856 FD->addAttr(FormatAttr::CreateImplicit(Context,
16857 &Context.Idents.get("printf"), 2,
16858 Name->isStr("vasprintf") ? 0 : 3,
16859 FD->getLocation()));
16860 }
16861
16862 if (Name->isStr("__CFStringMakeConstantString")) {
16863 // We already have a __builtin___CFStringMakeConstantString,
16864 // but builds that use -fno-constant-cfstrings don't go through that.
16865 if (!FD->hasAttr<FormatArgAttr>())
16866 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16867 FD->getLocation()));
16868 }
16869}
16870
16872 TypeSourceInfo *TInfo) {
16873 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16874 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16875
16876 if (!TInfo) {
16877 assert(D.isInvalidType() && "no declarator info for valid type");
16879 }
16880
16881 // Scope manipulation handled by caller.
16882 TypedefDecl *NewTD =
16884 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16885
16886 // Bail out immediately if we have an invalid declaration.
16887 if (D.isInvalidType()) {
16888 NewTD->setInvalidDecl();
16889 return NewTD;
16890 }
16891
16894 Diag(NewTD->getLocation(), diag::err_module_private_local)
16895 << 2 << NewTD
16899 else
16900 NewTD->setModulePrivate();
16901 }
16902
16903 // C++ [dcl.typedef]p8:
16904 // If the typedef declaration defines an unnamed class (or
16905 // enum), the first typedef-name declared by the declaration
16906 // to be that class type (or enum type) is used to denote the
16907 // class type (or enum type) for linkage purposes only.
16908 // We need to check whether the type was declared in the declaration.
16909 switch (D.getDeclSpec().getTypeSpecType()) {
16910 case TST_enum:
16911 case TST_struct:
16912 case TST_interface:
16913 case TST_union:
16914 case TST_class: {
16915 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16916 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16917 break;
16918 }
16919
16920 default:
16921 break;
16922 }
16923
16924 return NewTD;
16925}
16926
16927/// Check that this is a valid underlying type for an enum declaration.
16929 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16930 QualType T = TI->getType();
16931
16932 if (T->isDependentType())
16933 return false;
16934
16935 // This doesn't use 'isIntegralType' despite the error message mentioning
16936 // integral type because isIntegralType would also allow enum types in C.
16937 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16938 if (BT->isInteger())
16939 return false;
16940
16941 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16942 << T << T->isBitIntType();
16943}
16944
16945/// Check whether this is a valid redeclaration of a previous enumeration.
16946/// \return true if the redeclaration was invalid.
16948 QualType EnumUnderlyingTy, bool IsFixed,
16949 const EnumDecl *Prev) {
16950 if (IsScoped != Prev->isScoped()) {
16951 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16952 << Prev->isScoped();
16953 Diag(Prev->getLocation(), diag::note_previous_declaration);
16954 return true;
16955 }
16956
16957 if (IsFixed && Prev->isFixed()) {
16958 if (!EnumUnderlyingTy->isDependentType() &&
16959 !Prev->getIntegerType()->isDependentType() &&
16960 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16961 Prev->getIntegerType())) {
16962 // TODO: Highlight the underlying type of the redeclaration.
16963 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16964 << EnumUnderlyingTy << Prev->getIntegerType();
16965 Diag(Prev->getLocation(), diag::note_previous_declaration)
16966 << Prev->getIntegerTypeRange();
16967 return true;
16968 }
16969 } else if (IsFixed != Prev->isFixed()) {
16970 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16971 << Prev->isFixed();
16972 Diag(Prev->getLocation(), diag::note_previous_declaration);
16973 return true;
16974 }
16975
16976 return false;
16977}
16978
16979/// Get diagnostic %select index for tag kind for
16980/// redeclaration diagnostic message.
16981/// WARNING: Indexes apply to particular diagnostics only!
16982///
16983/// \returns diagnostic %select index.
16985 switch (Tag) {
16987 return 0;
16989 return 1;
16990 case TagTypeKind::Class:
16991 return 2;
16992 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16993 }
16994}
16995
16996/// Determine if tag kind is a class-key compatible with
16997/// class for redeclaration (class, struct, or __interface).
16998///
16999/// \returns true iff the tag kind is compatible.
17001{
17002 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17004}
17005
17007 TagTypeKind TTK) {
17008 if (isa<TypedefDecl>(PrevDecl))
17009 return NTK_Typedef;
17010 else if (isa<TypeAliasDecl>(PrevDecl))
17011 return NTK_TypeAlias;
17012 else if (isa<ClassTemplateDecl>(PrevDecl))
17013 return NTK_Template;
17014 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17015 return NTK_TypeAliasTemplate;
17016 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17018 switch (TTK) {
17021 case TagTypeKind::Class:
17022 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
17023 case TagTypeKind::Union:
17024 return NTK_NonUnion;
17025 case TagTypeKind::Enum:
17026 return NTK_NonEnum;
17027 }
17028 llvm_unreachable("invalid TTK");
17029}
17030
17031/// Determine whether a tag with a given kind is acceptable
17032/// as a redeclaration of the given tag declaration.
17033///
17034/// \returns true if the new tag kind is acceptable, false otherwise.
17036 TagTypeKind NewTag, bool isDefinition,
17037 SourceLocation NewTagLoc,
17038 const IdentifierInfo *Name) {
17039 // C++ [dcl.type.elab]p3:
17040 // The class-key or enum keyword present in the
17041 // elaborated-type-specifier shall agree in kind with the
17042 // declaration to which the name in the elaborated-type-specifier
17043 // refers. This rule also applies to the form of
17044 // elaborated-type-specifier that declares a class-name or
17045 // friend class since it can be construed as referring to the
17046 // definition of the class. Thus, in any
17047 // elaborated-type-specifier, the enum keyword shall be used to
17048 // refer to an enumeration (7.2), the union class-key shall be
17049 // used to refer to a union (clause 9), and either the class or
17050 // struct class-key shall be used to refer to a class (clause 9)
17051 // declared using the class or struct class-key.
17052 TagTypeKind OldTag = Previous->getTagKind();
17053 if (OldTag != NewTag &&
17054 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
17055 return false;
17056
17057 // Tags are compatible, but we might still want to warn on mismatched tags.
17058 // Non-class tags can't be mismatched at this point.
17059 if (!isClassCompatTagKind(NewTag))
17060 return true;
17061
17062 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17063 // by our warning analysis. We don't want to warn about mismatches with (eg)
17064 // declarations in system headers that are designed to be specialized, but if
17065 // a user asks us to warn, we should warn if their code contains mismatched
17066 // declarations.
17067 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17068 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17069 Loc);
17070 };
17071 if (IsIgnoredLoc(NewTagLoc))
17072 return true;
17073
17074 auto IsIgnored = [&](const TagDecl *Tag) {
17075 return IsIgnoredLoc(Tag->getLocation());
17076 };
17077 while (IsIgnored(Previous)) {
17078 Previous = Previous->getPreviousDecl();
17079 if (!Previous)
17080 return true;
17081 OldTag = Previous->getTagKind();
17082 }
17083
17084 bool isTemplate = false;
17085 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17086 isTemplate = Record->getDescribedClassTemplate();
17087
17089 if (OldTag != NewTag) {
17090 // In a template instantiation, do not offer fix-its for tag mismatches
17091 // since they usually mess up the template instead of fixing the problem.
17092 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17093 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17094 << getRedeclDiagFromTagKind(OldTag);
17095 // FIXME: Note previous location?
17096 }
17097 return true;
17098 }
17099
17100 if (isDefinition) {
17101 // On definitions, check all previous tags and issue a fix-it for each
17102 // one that doesn't match the current tag.
17103 if (Previous->getDefinition()) {
17104 // Don't suggest fix-its for redefinitions.
17105 return true;
17106 }
17107
17108 bool previousMismatch = false;
17109 for (const TagDecl *I : Previous->redecls()) {
17110 if (I->getTagKind() != NewTag) {
17111 // Ignore previous declarations for which the warning was disabled.
17112 if (IsIgnored(I))
17113 continue;
17114
17115 if (!previousMismatch) {
17116 previousMismatch = true;
17117 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17118 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17119 << getRedeclDiagFromTagKind(I->getTagKind());
17120 }
17121 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17122 << getRedeclDiagFromTagKind(NewTag)
17123 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17125 }
17126 }
17127 return true;
17128 }
17129
17130 // Identify the prevailing tag kind: this is the kind of the definition (if
17131 // there is a non-ignored definition), or otherwise the kind of the prior
17132 // (non-ignored) declaration.
17133 const TagDecl *PrevDef = Previous->getDefinition();
17134 if (PrevDef && IsIgnored(PrevDef))
17135 PrevDef = nullptr;
17136 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17137 if (Redecl->getTagKind() != NewTag) {
17138 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17139 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17140 << getRedeclDiagFromTagKind(OldTag);
17141 Diag(Redecl->getLocation(), diag::note_previous_use);
17142
17143 // If there is a previous definition, suggest a fix-it.
17144 if (PrevDef) {
17145 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17149 }
17150 }
17151
17152 return true;
17153}
17154
17155/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17156/// from an outer enclosing namespace or file scope inside a friend declaration.
17157/// This should provide the commented out code in the following snippet:
17158/// namespace N {
17159/// struct X;
17160/// namespace M {
17161/// struct Y { friend struct /*N::*/ X; };
17162/// }
17163/// }
17165 SourceLocation NameLoc) {
17166 // While the decl is in a namespace, do repeated lookup of that name and see
17167 // if we get the same namespace back. If we do not, continue until
17168 // translation unit scope, at which point we have a fully qualified NNS.
17171 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17172 // This tag should be declared in a namespace, which can only be enclosed by
17173 // other namespaces. Bail if there's an anonymous namespace in the chain.
17174 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17175 if (!Namespace || Namespace->isAnonymousNamespace())
17176 return FixItHint();
17177 IdentifierInfo *II = Namespace->getIdentifier();
17178 Namespaces.push_back(II);
17179 NamedDecl *Lookup = SemaRef.LookupSingleName(
17180 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17181 if (Lookup == Namespace)
17182 break;
17183 }
17184
17185 // Once we have all the namespaces, reverse them to go outermost first, and
17186 // build an NNS.
17187 SmallString<64> Insertion;
17188 llvm::raw_svector_ostream OS(Insertion);
17189 if (DC->isTranslationUnit())
17190 OS << "::";
17191 std::reverse(Namespaces.begin(), Namespaces.end());
17192 for (auto *II : Namespaces)
17193 OS << II->getName() << "::";
17194 return FixItHint::CreateInsertion(NameLoc, Insertion);
17195}
17196
17197/// Determine whether a tag originally declared in context \p OldDC can
17198/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17199/// found a declaration in \p OldDC as a previous decl, perhaps through a
17200/// using-declaration).
17202 DeclContext *NewDC) {
17203 OldDC = OldDC->getRedeclContext();
17204 NewDC = NewDC->getRedeclContext();
17205
17206 if (OldDC->Equals(NewDC))
17207 return true;
17208
17209 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17210 // encloses the other).
17211 if (S.getLangOpts().MSVCCompat &&
17212 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17213 return true;
17214
17215 return false;
17216}
17217
17218/// This is invoked when we see 'struct foo' or 'struct {'. In the
17219/// former case, Name will be non-null. In the later case, Name will be null.
17220/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17221/// reference/declaration/definition of a tag.
17222///
17223/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17224/// trailing-type-specifier) other than one in an alias-declaration.
17225///
17226/// \param SkipBody If non-null, will be set to indicate if the caller should
17227/// skip the definition of this tag and treat it as if it were a declaration.
17229Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17230 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17231 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17232 SourceLocation ModulePrivateLoc,
17233 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17234 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17235 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17236 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17237 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17238 // If this is not a definition, it must have a name.
17239 IdentifierInfo *OrigName = Name;
17240 assert((Name != nullptr || TUK == TUK_Definition) &&
17241 "Nameless record must be a definition!");
17242 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17243
17244 OwnedDecl = false;
17246 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17247
17248 // FIXME: Check member specializations more carefully.
17249 bool isMemberSpecialization = false;
17250 bool Invalid = false;
17251
17252 // We only need to do this matching if we have template parameters
17253 // or a scope specifier, which also conveniently avoids this work
17254 // for non-C++ cases.
17255 if (TemplateParameterLists.size() > 0 ||
17256 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17257 TemplateParameterList *TemplateParams =
17259 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17260 TUK == TUK_Friend, isMemberSpecialization, Invalid);
17261
17262 // C++23 [dcl.type.elab] p2:
17263 // If an elaborated-type-specifier is the sole constituent of a
17264 // declaration, the declaration is ill-formed unless it is an explicit
17265 // specialization, an explicit instantiation or it has one of the
17266 // following forms: [...]
17267 // C++23 [dcl.enum] p1:
17268 // If the enum-head-name of an opaque-enum-declaration contains a
17269 // nested-name-specifier, the declaration shall be an explicit
17270 // specialization.
17271 //
17272 // FIXME: Class template partial specializations can be forward declared
17273 // per CWG2213, but the resolution failed to allow qualified forward
17274 // declarations. This is almost certainly unintentional, so we allow them.
17275 if (TUK == TUK_Declaration && SS.isNotEmpty() && !isMemberSpecialization)
17276 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17278
17279 if (TemplateParams) {
17280 if (Kind == TagTypeKind::Enum) {
17281 Diag(KWLoc, diag::err_enum_template);
17282 return true;
17283 }
17284
17285 if (TemplateParams->size() > 0) {
17286 // This is a declaration or definition of a class template (which may
17287 // be a member of another template).
17288
17289 if (Invalid)
17290 return true;
17291
17292 OwnedDecl = false;
17294 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17295 AS, ModulePrivateLoc,
17296 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17297 TemplateParameterLists.data(), SkipBody);
17298 return Result.get();
17299 } else {
17300 // The "template<>" header is extraneous.
17301 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17302 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17303 isMemberSpecialization = true;
17304 }
17305 }
17306
17307 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17308 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17309 return true;
17310 }
17311
17312 if (TUK == TUK_Friend && Kind == TagTypeKind::Enum) {
17313 // C++23 [dcl.type.elab]p4:
17314 // If an elaborated-type-specifier appears with the friend specifier as
17315 // an entire member-declaration, the member-declaration shall have one
17316 // of the following forms:
17317 // friend class-key nested-name-specifier(opt) identifier ;
17318 // friend class-key simple-template-id ;
17319 // friend class-key nested-name-specifier template(opt)
17320 // simple-template-id ;
17321 //
17322 // Since enum is not a class-key, so declarations like "friend enum E;"
17323 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17324 // invalid, most implementations accept so we issue a pedantic warning.
17325 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17326 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17327 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17328 Diag(KWLoc, diag::note_enum_friend)
17329 << (ScopedEnum + ScopedEnumUsesClassTag);
17330 }
17331
17332 // Figure out the underlying type if this a enum declaration. We need to do
17333 // this early, because it's needed to detect if this is an incompatible
17334 // redeclaration.
17335 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17336 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17337
17338 if (Kind == TagTypeKind::Enum) {
17339 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17340 // No underlying type explicitly specified, or we failed to parse the
17341 // type, default to int.
17342 EnumUnderlying = Context.IntTy.getTypePtr();
17343 } else if (UnderlyingType.get()) {
17344 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17345 // integral type; any cv-qualification is ignored.
17346 TypeSourceInfo *TI = nullptr;
17347 GetTypeFromParser(UnderlyingType.get(), &TI);
17348 EnumUnderlying = TI;
17349
17351 // Recover by falling back to int.
17352 EnumUnderlying = Context.IntTy.getTypePtr();
17353
17356 EnumUnderlying = Context.IntTy.getTypePtr();
17357
17358 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17359 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17360 // of 'int'. However, if this is an unfixed forward declaration, don't set
17361 // the underlying type unless the user enables -fms-compatibility. This
17362 // makes unfixed forward declared enums incomplete and is more conforming.
17363 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17364 EnumUnderlying = Context.IntTy.getTypePtr();
17365 }
17366 }
17367
17368 DeclContext *SearchDC = CurContext;
17369 DeclContext *DC = CurContext;
17370 bool isStdBadAlloc = false;
17371 bool isStdAlignValT = false;
17372
17374 if (TUK == TUK_Friend || TUK == TUK_Reference)
17375 Redecl = RedeclarationKind::NotForRedeclaration;
17376
17377 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17378 /// implemented asks for structural equivalence checking, the returned decl
17379 /// here is passed back to the parser, allowing the tag body to be parsed.
17380 auto createTagFromNewDecl = [&]() -> TagDecl * {
17381 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17382 // If there is an identifier, use the location of the identifier as the
17383 // location of the decl, otherwise use the location of the struct/union
17384 // keyword.
17385 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17386 TagDecl *New = nullptr;
17387
17388 if (Kind == TagTypeKind::Enum) {
17389 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17390 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17391 // If this is an undefined enum, bail.
17392 if (TUK != TUK_Definition && !Invalid)
17393 return nullptr;
17394 if (EnumUnderlying) {
17395 EnumDecl *ED = cast<EnumDecl>(New);
17396 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17398 else
17399 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17400 QualType EnumTy = ED->getIntegerType();
17403 : EnumTy);
17404 }
17405 } else { // struct/union
17406 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17407 nullptr);
17408 }
17409
17410 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17411 // Add alignment attributes if necessary; these attributes are checked
17412 // when the ASTContext lays out the structure.
17413 //
17414 // It is important for implementing the correct semantics that this
17415 // happen here (in ActOnTag). The #pragma pack stack is
17416 // maintained as a result of parser callbacks which can occur at
17417 // many points during the parsing of a struct declaration (because
17418 // the #pragma tokens are effectively skipped over during the
17419 // parsing of the struct).
17420 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17423 }
17424 }
17426 return New;
17427 };
17428
17429 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17430 if (Name && SS.isNotEmpty()) {
17431 // We have a nested-name tag ('struct foo::bar').
17432
17433 // Check for invalid 'foo::'.
17434 if (SS.isInvalid()) {
17435 Name = nullptr;
17436 goto CreateNewDecl;
17437 }
17438
17439 // If this is a friend or a reference to a class in a dependent
17440 // context, don't try to make a decl for it.
17441 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17442 DC = computeDeclContext(SS, false);
17443 if (!DC) {
17444 IsDependent = true;
17445 return true;
17446 }
17447 } else {
17448 DC = computeDeclContext(SS, true);
17449 if (!DC) {
17450 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17451 << SS.getRange();
17452 return true;
17453 }
17454 }
17455
17456 if (RequireCompleteDeclContext(SS, DC))
17457 return true;
17458
17459 SearchDC = DC;
17460 // Look-up name inside 'foo::'.
17462
17463 if (Previous.isAmbiguous())
17464 return true;
17465
17466 if (Previous.empty()) {
17467 // Name lookup did not find anything. However, if the
17468 // nested-name-specifier refers to the current instantiation,
17469 // and that current instantiation has any dependent base
17470 // classes, we might find something at instantiation time: treat
17471 // this as a dependent elaborated-type-specifier.
17472 // But this only makes any sense for reference-like lookups.
17473 if (Previous.wasNotFoundInCurrentInstantiation() &&
17474 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17475 IsDependent = true;
17476 return true;
17477 }
17478
17479 // A tag 'foo::bar' must already exist.
17480 Diag(NameLoc, diag::err_not_tag_in_scope)
17481 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17482 Name = nullptr;
17483 Invalid = true;
17484 goto CreateNewDecl;
17485 }
17486 } else if (Name) {
17487 // C++14 [class.mem]p14:
17488 // If T is the name of a class, then each of the following shall have a
17489 // name different from T:
17490 // -- every member of class T that is itself a type
17491 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17492 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17493 return true;
17494
17495 // If this is a named struct, check to see if there was a previous forward
17496 // declaration or definition.
17497 // FIXME: We're looking into outer scopes here, even when we
17498 // shouldn't be. Doing so can result in ambiguities that we
17499 // shouldn't be diagnosing.
17500 LookupName(Previous, S);
17501
17502 // When declaring or defining a tag, ignore ambiguities introduced
17503 // by types using'ed into this scope.
17504 if (Previous.isAmbiguous() &&
17505 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17506 LookupResult::Filter F = Previous.makeFilter();
17507 while (F.hasNext()) {
17508 NamedDecl *ND = F.next();
17509 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17510 SearchDC->getRedeclContext()))
17511 F.erase();
17512 }
17513 F.done();
17514 }
17515
17516 // C++11 [namespace.memdef]p3:
17517 // If the name in a friend declaration is neither qualified nor
17518 // a template-id and the declaration is a function or an
17519 // elaborated-type-specifier, the lookup to determine whether
17520 // the entity has been previously declared shall not consider
17521 // any scopes outside the innermost enclosing namespace.
17522 //
17523 // MSVC doesn't implement the above rule for types, so a friend tag
17524 // declaration may be a redeclaration of a type declared in an enclosing
17525 // scope. They do implement this rule for friend functions.
17526 //
17527 // Does it matter that this should be by scope instead of by
17528 // semantic context?
17529 if (!Previous.empty() && TUK == TUK_Friend) {
17530 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17531 LookupResult::Filter F = Previous.makeFilter();
17532 bool FriendSawTagOutsideEnclosingNamespace = false;
17533 while (F.hasNext()) {
17534 NamedDecl *ND = F.next();
17536 if (DC->isFileContext() &&
17537 !EnclosingNS->Encloses(ND->getDeclContext())) {
17538 if (getLangOpts().MSVCCompat)
17539 FriendSawTagOutsideEnclosingNamespace = true;
17540 else
17541 F.erase();
17542 }
17543 }
17544 F.done();
17545
17546 // Diagnose this MSVC extension in the easy case where lookup would have
17547 // unambiguously found something outside the enclosing namespace.
17548 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17549 NamedDecl *ND = Previous.getFoundDecl();
17550 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17551 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17552 }
17553 }
17554
17555 // Note: there used to be some attempt at recovery here.
17556 if (Previous.isAmbiguous())
17557 return true;
17558
17559 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17560 // FIXME: This makes sure that we ignore the contexts associated
17561 // with C structs, unions, and enums when looking for a matching
17562 // tag declaration or definition. See the similar lookup tweak
17563 // in Sema::LookupName; is there a better way to deal with this?
17564 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17565 SearchDC = SearchDC->getParent();
17566 } else if (getLangOpts().CPlusPlus) {
17567 // Inside ObjCContainer want to keep it as a lexical decl context but go
17568 // past it (most often to TranslationUnit) to find the semantic decl
17569 // context.
17570 while (isa<ObjCContainerDecl>(SearchDC))
17571 SearchDC = SearchDC->getParent();
17572 }
17573 } else if (getLangOpts().CPlusPlus) {
17574 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17575 // TagDecl the same way as we skip it for named TagDecl.
17576 while (isa<ObjCContainerDecl>(SearchDC))
17577 SearchDC = SearchDC->getParent();
17578 }
17579
17580 if (Previous.isSingleResult() &&
17581 Previous.getFoundDecl()->isTemplateParameter()) {
17582 // Maybe we will complain about the shadowed template parameter.
17583 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17584 // Just pretend that we didn't see the previous declaration.
17585 Previous.clear();
17586 }
17587
17588 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17589 DC->Equals(getStdNamespace())) {
17590 if (Name->isStr("bad_alloc")) {
17591 // This is a declaration of or a reference to "std::bad_alloc".
17592 isStdBadAlloc = true;
17593
17594 // If std::bad_alloc has been implicitly declared (but made invisible to
17595 // name lookup), fill in this implicit declaration as the previous
17596 // declaration, so that the declarations get chained appropriately.
17597 if (Previous.empty() && StdBadAlloc)
17598 Previous.addDecl(getStdBadAlloc());
17599 } else if (Name->isStr("align_val_t")) {
17600 isStdAlignValT = true;
17601 if (Previous.empty() && StdAlignValT)
17602 Previous.addDecl(getStdAlignValT());
17603 }
17604 }
17605
17606 // If we didn't find a previous declaration, and this is a reference
17607 // (or friend reference), move to the correct scope. In C++, we
17608 // also need to do a redeclaration lookup there, just in case
17609 // there's a shadow friend decl.
17610 if (Name && Previous.empty() &&
17611 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17612 if (Invalid) goto CreateNewDecl;
17613 assert(SS.isEmpty());
17614
17615 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17616 // C++ [basic.scope.pdecl]p5:
17617 // -- for an elaborated-type-specifier of the form
17618 //
17619 // class-key identifier
17620 //
17621 // if the elaborated-type-specifier is used in the
17622 // decl-specifier-seq or parameter-declaration-clause of a
17623 // function defined in namespace scope, the identifier is
17624 // declared as a class-name in the namespace that contains
17625 // the declaration; otherwise, except as a friend
17626 // declaration, the identifier is declared in the smallest
17627 // non-class, non-function-prototype scope that contains the
17628 // declaration.
17629 //
17630 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17631 // C structs and unions.
17632 //
17633 // It is an error in C++ to declare (rather than define) an enum
17634 // type, including via an elaborated type specifier. We'll
17635 // diagnose that later; for now, declare the enum in the same
17636 // scope as we would have picked for any other tag type.
17637 //
17638 // GNU C also supports this behavior as part of its incomplete
17639 // enum types extension, while GNU C++ does not.
17640 //
17641 // Find the context where we'll be declaring the tag.
17642 // FIXME: We would like to maintain the current DeclContext as the
17643 // lexical context,
17644 SearchDC = getTagInjectionContext(SearchDC);
17645
17646 // Find the scope where we'll be declaring the tag.
17648 } else {
17649 assert(TUK == TUK_Friend);
17650 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17651
17652 // C++ [namespace.memdef]p3:
17653 // If a friend declaration in a non-local class first declares a
17654 // class or function, the friend class or function is a member of
17655 // the innermost enclosing namespace.
17656 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17657 : SearchDC->getEnclosingNamespaceContext();
17658 }
17659
17660 // In C++, we need to do a redeclaration lookup to properly
17661 // diagnose some problems.
17662 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17663 // hidden declaration so that we don't get ambiguity errors when using a
17664 // type declared by an elaborated-type-specifier. In C that is not correct
17665 // and we should instead merge compatible types found by lookup.
17666 if (getLangOpts().CPlusPlus) {
17667 // FIXME: This can perform qualified lookups into function contexts,
17668 // which are meaningless.
17669 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17670 LookupQualifiedName(Previous, SearchDC);
17671 } else {
17672 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17673 LookupName(Previous, S);
17674 }
17675 }
17676
17677 // If we have a known previous declaration to use, then use it.
17678 if (Previous.empty() && SkipBody && SkipBody->Previous)
17679 Previous.addDecl(SkipBody->Previous);
17680
17681 if (!Previous.empty()) {
17682 NamedDecl *PrevDecl = Previous.getFoundDecl();
17683 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17684
17685 // It's okay to have a tag decl in the same scope as a typedef
17686 // which hides a tag decl in the same scope. Finding this
17687 // with a redeclaration lookup can only actually happen in C++.
17688 //
17689 // This is also okay for elaborated-type-specifiers, which is
17690 // technically forbidden by the current standard but which is
17691 // okay according to the likely resolution of an open issue;
17692 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17693 if (getLangOpts().CPlusPlus) {
17694 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17695 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17696 TagDecl *Tag = TT->getDecl();
17697 if (Tag->getDeclName() == Name &&
17699 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17700 PrevDecl = Tag;
17701 Previous.clear();
17702 Previous.addDecl(Tag);
17703 Previous.resolveKind();
17704 }
17705 }
17706 }
17707 }
17708
17709 // If this is a redeclaration of a using shadow declaration, it must
17710 // declare a tag in the same context. In MSVC mode, we allow a
17711 // redefinition if either context is within the other.
17712 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17713 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17714 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17715 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17716 !(OldTag && isAcceptableTagRedeclContext(
17717 *this, OldTag->getDeclContext(), SearchDC))) {
17718 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17719 Diag(Shadow->getTargetDecl()->getLocation(),
17720 diag::note_using_decl_target);
17721 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17722 << 0;
17723 // Recover by ignoring the old declaration.
17724 Previous.clear();
17725 goto CreateNewDecl;
17726 }
17727 }
17728
17729 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17730 // If this is a use of a previous tag, or if the tag is already declared
17731 // in the same scope (so that the definition/declaration completes or
17732 // rementions the tag), reuse the decl.
17733 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17734 isDeclInScope(DirectPrevDecl, SearchDC, S,
17735 SS.isNotEmpty() || isMemberSpecialization)) {
17736 // Make sure that this wasn't declared as an enum and now used as a
17737 // struct or something similar.
17738 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17739 TUK == TUK_Definition, KWLoc,
17740 Name)) {
17741 bool SafeToContinue =
17742 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17743 Kind != TagTypeKind::Enum);
17744 if (SafeToContinue)
17745 Diag(KWLoc, diag::err_use_with_wrong_tag)
17746 << Name
17748 PrevTagDecl->getKindName());
17749 else
17750 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17751 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17752
17753 if (SafeToContinue)
17754 Kind = PrevTagDecl->getTagKind();
17755 else {
17756 // Recover by making this an anonymous redefinition.
17757 Name = nullptr;
17758 Previous.clear();
17759 Invalid = true;
17760 }
17761 }
17762
17763 if (Kind == TagTypeKind::Enum &&
17764 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17765 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17766 if (TUK == TUK_Reference || TUK == TUK_Friend)
17767 return PrevTagDecl;
17768
17769 QualType EnumUnderlyingTy;
17770 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17771 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17772 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17773 EnumUnderlyingTy = QualType(T, 0);
17774
17775 // All conflicts with previous declarations are recovered by
17776 // returning the previous declaration, unless this is a definition,
17777 // in which case we want the caller to bail out.
17778 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17779 ScopedEnum, EnumUnderlyingTy,
17780 IsFixed, PrevEnum))
17781 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17782 }
17783
17784 // C++11 [class.mem]p1:
17785 // A member shall not be declared twice in the member-specification,
17786 // except that a nested class or member class template can be declared
17787 // and then later defined.
17788 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17789 S->isDeclScope(PrevDecl)) {
17790 Diag(NameLoc, diag::ext_member_redeclared);
17791 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17792 }
17793
17794 if (!Invalid) {
17795 // If this is a use, just return the declaration we found, unless
17796 // we have attributes.
17797 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17798 if (!Attrs.empty()) {
17799 // FIXME: Diagnose these attributes. For now, we create a new
17800 // declaration to hold them.
17801 } else if (TUK == TUK_Reference &&
17802 (PrevTagDecl->getFriendObjectKind() ==
17804 PrevDecl->getOwningModule() != getCurrentModule()) &&
17805 SS.isEmpty()) {
17806 // This declaration is a reference to an existing entity, but
17807 // has different visibility from that entity: it either makes
17808 // a friend visible or it makes a type visible in a new module.
17809 // In either case, create a new declaration. We only do this if
17810 // the declaration would have meant the same thing if no prior
17811 // declaration were found, that is, if it was found in the same
17812 // scope where we would have injected a declaration.
17813 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17814 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17815 return PrevTagDecl;
17816 // This is in the injected scope, create a new declaration in
17817 // that scope.
17819 } else {
17820 return PrevTagDecl;
17821 }
17822 }
17823
17824 // Diagnose attempts to redefine a tag.
17825 if (TUK == TUK_Definition) {
17826 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17827 // If we're defining a specialization and the previous definition
17828 // is from an implicit instantiation, don't emit an error
17829 // here; we'll catch this in the general case below.
17830 bool IsExplicitSpecializationAfterInstantiation = false;
17831 if (isMemberSpecialization) {
17832 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17833 IsExplicitSpecializationAfterInstantiation =
17834 RD->getTemplateSpecializationKind() !=
17836 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17837 IsExplicitSpecializationAfterInstantiation =
17838 ED->getTemplateSpecializationKind() !=
17840 }
17841
17842 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17843 // not keep more that one definition around (merge them). However,
17844 // ensure the decl passes the structural compatibility check in
17845 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17846 NamedDecl *Hidden = nullptr;
17847 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17848 // There is a definition of this tag, but it is not visible. We
17849 // explicitly make use of C++'s one definition rule here, and
17850 // assume that this definition is identical to the hidden one
17851 // we already have. Make the existing definition visible and
17852 // use it in place of this one.
17853 if (!getLangOpts().CPlusPlus) {
17854 // Postpone making the old definition visible until after we
17855 // complete parsing the new one and do the structural
17856 // comparison.
17857 SkipBody->CheckSameAsPrevious = true;
17858 SkipBody->New = createTagFromNewDecl();
17859 SkipBody->Previous = Def;
17860 return Def;
17861 } else {
17862 SkipBody->ShouldSkip = true;
17863 SkipBody->Previous = Def;
17865 // Carry on and handle it like a normal definition. We'll
17866 // skip starting the definitiion later.
17867 }
17868 } else if (!IsExplicitSpecializationAfterInstantiation) {
17869 // A redeclaration in function prototype scope in C isn't
17870 // visible elsewhere, so merely issue a warning.
17871 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17872 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17873 else
17874 Diag(NameLoc, diag::err_redefinition) << Name;
17876 NameLoc.isValid() ? NameLoc : KWLoc);
17877 // If this is a redefinition, recover by making this
17878 // struct be anonymous, which will make any later
17879 // references get the previous definition.
17880 Name = nullptr;
17881 Previous.clear();
17882 Invalid = true;
17883 }
17884 } else {
17885 // If the type is currently being defined, complain
17886 // about a nested redefinition.
17887 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17888 if (TD->isBeingDefined()) {
17889 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17890 Diag(PrevTagDecl->getLocation(),
17891 diag::note_previous_definition);
17892 Name = nullptr;
17893 Previous.clear();
17894 Invalid = true;
17895 }
17896 }
17897
17898 // Okay, this is definition of a previously declared or referenced
17899 // tag. We're going to create a new Decl for it.
17900 }
17901
17902 // Okay, we're going to make a redeclaration. If this is some kind
17903 // of reference, make sure we build the redeclaration in the same DC
17904 // as the original, and ignore the current access specifier.
17905 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17906 SearchDC = PrevTagDecl->getDeclContext();
17907 AS = AS_none;
17908 }
17909 }
17910 // If we get here we have (another) forward declaration or we
17911 // have a definition. Just create a new decl.
17912
17913 } else {
17914 // If we get here, this is a definition of a new tag type in a nested
17915 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17916 // new decl/type. We set PrevDecl to NULL so that the entities
17917 // have distinct types.
17918 Previous.clear();
17919 }
17920 // If we get here, we're going to create a new Decl. If PrevDecl
17921 // is non-NULL, it's a definition of the tag declared by
17922 // PrevDecl. If it's NULL, we have a new definition.
17923
17924 // Otherwise, PrevDecl is not a tag, but was found with tag
17925 // lookup. This is only actually possible in C++, where a few
17926 // things like templates still live in the tag namespace.
17927 } else {
17928 // Use a better diagnostic if an elaborated-type-specifier
17929 // found the wrong kind of type on the first
17930 // (non-redeclaration) lookup.
17931 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17932 !Previous.isForRedeclaration()) {
17933 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17934 Diag(NameLoc, diag::err_tag_reference_non_tag)
17935 << PrevDecl << NTK << llvm::to_underlying(Kind);
17936 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17937 Invalid = true;
17938
17939 // Otherwise, only diagnose if the declaration is in scope.
17940 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17941 SS.isNotEmpty() || isMemberSpecialization)) {
17942 // do nothing
17943
17944 // Diagnose implicit declarations introduced by elaborated types.
17945 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17946 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17947 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17948 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17949 Invalid = true;
17950
17951 // Otherwise it's a declaration. Call out a particularly common
17952 // case here.
17953 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17954 unsigned Kind = 0;
17955 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17956 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17957 << Name << Kind << TND->getUnderlyingType();
17958 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17959 Invalid = true;
17960
17961 // Otherwise, diagnose.
17962 } else {
17963 // The tag name clashes with something else in the target scope,
17964 // issue an error and recover by making this tag be anonymous.
17965 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17966 notePreviousDefinition(PrevDecl, NameLoc);
17967 Name = nullptr;
17968 Invalid = true;
17969 }
17970
17971 // The existing declaration isn't relevant to us; we're in a
17972 // new scope, so clear out the previous declaration.
17973 Previous.clear();
17974 }
17975 }
17976
17977CreateNewDecl:
17978
17979 TagDecl *PrevDecl = nullptr;
17980 if (Previous.isSingleResult())
17981 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17982
17983 // If there is an identifier, use the location of the identifier as the
17984 // location of the decl, otherwise use the location of the struct/union
17985 // keyword.
17986 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17987
17988 // Otherwise, create a new declaration. If there is a previous
17989 // declaration of the same entity, the two will be linked via
17990 // PrevDecl.
17991 TagDecl *New;
17992
17993 if (Kind == TagTypeKind::Enum) {
17994 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17995 // enum X { A, B, C } D; D should chain to X.
17996 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17997 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17998 ScopedEnumUsesClassTag, IsFixed);
17999
18000 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18001 StdAlignValT = cast<EnumDecl>(New);
18002
18003 // If this is an undefined enum, warn.
18004 if (TUK != TUK_Definition && !Invalid) {
18005 TagDecl *Def;
18006 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18007 // C++0x: 7.2p2: opaque-enum-declaration.
18008 // Conflicts are diagnosed above. Do nothing.
18009 }
18010 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18011 Diag(Loc, diag::ext_forward_ref_enum_def)
18012 << New;
18013 Diag(Def->getLocation(), diag::note_previous_definition);
18014 } else {
18015 unsigned DiagID = diag::ext_forward_ref_enum;
18016 if (getLangOpts().MSVCCompat)
18017 DiagID = diag::ext_ms_forward_ref_enum;
18018 else if (getLangOpts().CPlusPlus)
18019 DiagID = diag::err_forward_ref_enum;
18020 Diag(Loc, DiagID);
18021 }
18022 }
18023
18024 if (EnumUnderlying) {
18025 EnumDecl *ED = cast<EnumDecl>(New);
18026 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
18028 else
18029 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
18030 QualType EnumTy = ED->getIntegerType();
18033 : EnumTy);
18034 assert(ED->isComplete() && "enum with type should be complete");
18035 }
18036 } else {
18037 // struct/union/class
18038
18039 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18040 // struct X { int A; } D; D should chain to X.
18041 if (getLangOpts().CPlusPlus) {
18042 // FIXME: Look for a way to use RecordDecl for simple structs.
18043 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18044 cast_or_null<CXXRecordDecl>(PrevDecl));
18045
18046 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18047 StdBadAlloc = cast<CXXRecordDecl>(New);
18048 } else
18049 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18050 cast_or_null<RecordDecl>(PrevDecl));
18051 }
18052
18053 // Only C23 and later allow defining new types in 'offsetof()'.
18054 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus &&
18055 !getLangOpts().C23)
18056 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18057 << (OOK == OOK_Macro) << New->getSourceRange();
18058
18059 // C++11 [dcl.type]p3:
18060 // A type-specifier-seq shall not define a class or enumeration [...].
18061 if (!Invalid && getLangOpts().CPlusPlus &&
18062 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
18063 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18064 << Context.getTagDeclType(New);
18065 Invalid = true;
18066 }
18067
18068 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
18069 DC->getDeclKind() == Decl::Enum) {
18070 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18071 << Context.getTagDeclType(New);
18072 Invalid = true;
18073 }
18074
18075 // Maybe add qualifier info.
18076 if (SS.isNotEmpty()) {
18077 if (SS.isSet()) {
18078 // If this is either a declaration or a definition, check the
18079 // nested-name-specifier against the current context.
18080 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
18081 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18082 /*TemplateId=*/nullptr,
18083 isMemberSpecialization))
18084 Invalid = true;
18085
18087 if (TemplateParameterLists.size() > 0) {
18088 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18089 }
18090 }
18091 else
18092 Invalid = true;
18093 }
18094
18095 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18096 // Add alignment attributes if necessary; these attributes are checked when
18097 // the ASTContext lays out the structure.
18098 //
18099 // It is important for implementing the correct semantics that this
18100 // happen here (in ActOnTag). The #pragma pack stack is
18101 // maintained as a result of parser callbacks which can occur at
18102 // many points during the parsing of a struct declaration (because
18103 // the #pragma tokens are effectively skipped over during the
18104 // parsing of the struct).
18105 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18108 }
18109 }
18110
18111 if (ModulePrivateLoc.isValid()) {
18112 if (isMemberSpecialization)
18113 Diag(New->getLocation(), diag::err_module_private_specialization)
18114 << 2
18115 << FixItHint::CreateRemoval(ModulePrivateLoc);
18116 // __module_private__ does not apply to local classes. However, we only
18117 // diagnose this as an error when the declaration specifiers are
18118 // freestanding. Here, we just ignore the __module_private__.
18119 else if (!SearchDC->isFunctionOrMethod())
18120 New->setModulePrivate();
18121 }
18122
18123 // If this is a specialization of a member class (of a class template),
18124 // check the specialization.
18125 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18126 Invalid = true;
18127
18128 // If we're declaring or defining a tag in function prototype scope in C,
18129 // note that this type can only be used within the function and add it to
18130 // the list of decls to inject into the function definition scope.
18131 if ((Name || Kind == TagTypeKind::Enum) &&
18132 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18133 if (getLangOpts().CPlusPlus) {
18134 // C++ [dcl.fct]p6:
18135 // Types shall not be defined in return or parameter types.
18136 if (TUK == TUK_Definition && !IsTypeSpecifier) {
18137 Diag(Loc, diag::err_type_defined_in_param_type)
18138 << Name;
18139 Invalid = true;
18140 }
18141 } else if (!PrevDecl) {
18142 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18143 }
18144 }
18145
18146 if (Invalid)
18147 New->setInvalidDecl();
18148
18149 // Set the lexical context. If the tag has a C++ scope specifier, the
18150 // lexical context will be different from the semantic context.
18152
18153 // Mark this as a friend decl if applicable.
18154 // In Microsoft mode, a friend declaration also acts as a forward
18155 // declaration so we always pass true to setObjectOfFriendDecl to make
18156 // the tag name visible.
18157 if (TUK == TUK_Friend)
18158 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18159
18160 // Set the access specifier.
18161 if (!Invalid && SearchDC->isRecord())
18162 SetMemberAccessSpecifier(New, PrevDecl, AS);
18163
18164 if (PrevDecl)
18165 CheckRedeclarationInModule(New, PrevDecl);
18166
18167 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18168 New->startDefinition();
18169
18170 ProcessDeclAttributeList(S, New, Attrs);
18171 AddPragmaAttributes(S, New);
18172
18173 // If this has an identifier, add it to the scope stack.
18174 if (TUK == TUK_Friend) {
18175 // We might be replacing an existing declaration in the lookup tables;
18176 // if so, borrow its access specifier.
18177 if (PrevDecl)
18178 New->setAccess(PrevDecl->getAccess());
18179
18181 DC->makeDeclVisibleInContext(New);
18182 if (Name) // can be null along some error paths
18183 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18184 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18185 } else if (Name) {
18186 S = getNonFieldDeclScope(S);
18187 PushOnScopeChains(New, S, true);
18188 } else {
18189 CurContext->addDecl(New);
18190 }
18191
18192 // If this is the C FILE type, notify the AST context.
18193 if (IdentifierInfo *II = New->getIdentifier())
18194 if (!New->isInvalidDecl() &&
18196 II->isStr("FILE"))
18197 Context.setFILEDecl(New);
18198
18199 if (PrevDecl)
18200 mergeDeclAttributes(New, PrevDecl);
18201
18202 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18205 }
18206
18207 // If there's a #pragma GCC visibility in scope, set the visibility of this
18208 // record.
18210
18211 if (isMemberSpecialization && !New->isInvalidDecl())
18213
18214 OwnedDecl = true;
18215 // In C++, don't return an invalid declaration. We can't recover well from
18216 // the cases where we make the type anonymous.
18217 if (Invalid && getLangOpts().CPlusPlus) {
18218 if (New->isBeingDefined())
18219 if (auto RD = dyn_cast<RecordDecl>(New))
18220 RD->completeDefinition();
18221 return true;
18222 } else if (SkipBody && SkipBody->ShouldSkip) {
18223 return SkipBody->Previous;
18224 } else {
18225 return New;
18226 }
18227}
18228
18231 TagDecl *Tag = cast<TagDecl>(TagD);
18232
18233 // Enter the tag context.
18234 PushDeclContext(S, Tag);
18235
18237
18238 // If there's a #pragma GCC visibility in scope, set the visibility of this
18239 // record.
18241}
18242
18244 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18245 return false;
18246
18247 // Make the previous decl visible.
18249 return true;
18250}
18251
18253 SourceLocation FinalLoc,
18254 bool IsFinalSpelledSealed,
18255 bool IsAbstract,
18256 SourceLocation LBraceLoc) {
18258 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18259
18260 FieldCollector->StartClass();
18261
18262 if (!Record->getIdentifier())
18263 return;
18264
18265 if (IsAbstract)
18266 Record->markAbstract();
18267
18268 if (FinalLoc.isValid()) {
18269 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18270 IsFinalSpelledSealed
18271 ? FinalAttr::Keyword_sealed
18272 : FinalAttr::Keyword_final));
18273 }
18274 // C++ [class]p2:
18275 // [...] The class-name is also inserted into the scope of the
18276 // class itself; this is known as the injected-class-name. For
18277 // purposes of access checking, the injected-class-name is treated
18278 // as if it were a public member name.
18279 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18280 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18281 Record->getLocation(), Record->getIdentifier(),
18282 /*PrevDecl=*/nullptr,
18283 /*DelayTypeCreation=*/true);
18284 Context.getTypeDeclType(InjectedClassName, Record);
18285 InjectedClassName->setImplicit();
18286 InjectedClassName->setAccess(AS_public);
18287 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18288 InjectedClassName->setDescribedClassTemplate(Template);
18289 PushOnScopeChains(InjectedClassName, S);
18290 assert(InjectedClassName->isInjectedClassName() &&
18291 "Broken injected-class-name");
18292}
18293
18295 SourceRange BraceRange) {
18297 TagDecl *Tag = cast<TagDecl>(TagD);
18298 Tag->setBraceRange(BraceRange);
18299
18300 // Make sure we "complete" the definition even it is invalid.
18301 if (Tag->isBeingDefined()) {
18302 assert(Tag->isInvalidDecl() && "We should already have completed it");
18303 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18304 RD->completeDefinition();
18305 }
18306
18307 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18308 FieldCollector->FinishClass();
18309 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18310 auto *Def = RD->getDefinition();
18311 assert(Def && "The record is expected to have a completed definition");
18312 unsigned NumInitMethods = 0;
18313 for (auto *Method : Def->methods()) {
18314 if (!Method->getIdentifier())
18315 continue;
18316 if (Method->getName() == "__init")
18317 NumInitMethods++;
18318 }
18319 if (NumInitMethods > 1 || !Def->hasInitMethod())
18320 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18321 }
18322 }
18323
18324 // Exit this scope of this tag's definition.
18326
18327 if (getCurLexicalContext()->isObjCContainer() &&
18328 Tag->getDeclContext()->isFileContext())
18330
18331 // Notify the consumer that we've defined a tag.
18332 if (!Tag->isInvalidDecl())
18334
18335 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18336 // from XLs and instead matches the XL #pragma pack(1) behavior.
18337 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18338 AlignPackStack.hasValue()) {
18339 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18340 // Only diagnose #pragma align(packed).
18341 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18342 return;
18343 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18344 if (!RD)
18345 return;
18346 // Only warn if there is at least 1 bitfield member.
18347 if (llvm::any_of(RD->fields(),
18348 [](const FieldDecl *FD) { return FD->isBitField(); }))
18349 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18350 }
18351}
18352
18355 TagDecl *Tag = cast<TagDecl>(TagD);
18356 Tag->setInvalidDecl();
18357
18358 // Make sure we "complete" the definition even it is invalid.
18359 if (Tag->isBeingDefined()) {
18360 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18361 RD->completeDefinition();
18362 }
18363
18364 // We're undoing ActOnTagStartDefinition here, not
18365 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18366 // the FieldCollector.
18367
18369}
18370
18371// Note that FieldName may be null for anonymous bitfields.
18373 const IdentifierInfo *FieldName,
18374 QualType FieldTy, bool IsMsStruct,
18375 Expr *BitWidth) {
18376 assert(BitWidth);
18377 if (BitWidth->containsErrors())
18378 return ExprError();
18379
18380 // C99 6.7.2.1p4 - verify the field type.
18381 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18382 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18383 // Handle incomplete and sizeless types with a specific error.
18384 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18385 diag::err_field_incomplete_or_sizeless))
18386 return ExprError();
18387 if (FieldName)
18388 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18389 << FieldName << FieldTy << BitWidth->getSourceRange();
18390 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18391 << FieldTy << BitWidth->getSourceRange();
18392 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18394 return ExprError();
18395
18396 // If the bit-width is type- or value-dependent, don't try to check
18397 // it now.
18398 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18399 return BitWidth;
18400
18401 llvm::APSInt Value;
18403 if (ICE.isInvalid())
18404 return ICE;
18405 BitWidth = ICE.get();
18406
18407 // Zero-width bitfield is ok for anonymous field.
18408 if (Value == 0 && FieldName)
18409 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18410 << FieldName << BitWidth->getSourceRange();
18411
18412 if (Value.isSigned() && Value.isNegative()) {
18413 if (FieldName)
18414 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18415 << FieldName << toString(Value, 10);
18416 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18417 << toString(Value, 10);
18418 }
18419
18420 // The size of the bit-field must not exceed our maximum permitted object
18421 // size.
18422 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18423 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18424 << !FieldName << FieldName << toString(Value, 10);
18425 }
18426
18427 if (!FieldTy->isDependentType()) {
18428 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18429 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18430 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18431
18432 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18433 // ABI.
18434 bool CStdConstraintViolation =
18435 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18436 bool MSBitfieldViolation =
18437 Value.ugt(TypeStorageSize) &&
18438 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18439 if (CStdConstraintViolation || MSBitfieldViolation) {
18440 unsigned DiagWidth =
18441 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18442 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18443 << (bool)FieldName << FieldName << toString(Value, 10)
18444 << !CStdConstraintViolation << DiagWidth;
18445 }
18446
18447 // Warn on types where the user might conceivably expect to get all
18448 // specified bits as value bits: that's all integral types other than
18449 // 'bool'.
18450 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18451 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18452 << FieldName << toString(Value, 10)
18453 << (unsigned)TypeWidth;
18454 }
18455 }
18456
18457 return BitWidth;
18458}
18459
18460/// ActOnField - Each field of a C struct/union is passed into this in order
18461/// to create a FieldDecl object for it.
18463 Declarator &D, Expr *BitfieldWidth) {
18464 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18465 D, BitfieldWidth,
18466 /*InitStyle=*/ICIS_NoInit, AS_public);
18467 return Res;
18468}
18469
18470/// HandleField - Analyze a field of a C struct or a C++ data member.
18471///
18473 SourceLocation DeclStart,
18474 Declarator &D, Expr *BitWidth,
18475 InClassInitStyle InitStyle,
18476 AccessSpecifier AS) {
18477 if (D.isDecompositionDeclarator()) {
18479 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18480 << Decomp.getSourceRange();
18481 return nullptr;
18482 }
18483
18484 const IdentifierInfo *II = D.getIdentifier();
18485 SourceLocation Loc = DeclStart;
18486 if (II) Loc = D.getIdentifierLoc();
18487
18489 QualType T = TInfo->getType();
18490 if (getLangOpts().CPlusPlus) {
18492
18495 D.setInvalidType();
18496 T = Context.IntTy;
18498 }
18499 }
18500
18502
18504 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18505 << getLangOpts().CPlusPlus17;
18508 diag::err_invalid_thread)
18510
18511 // Check to see if this name was declared as a member previously
18512 NamedDecl *PrevDecl = nullptr;
18514 RedeclarationKind::ForVisibleRedeclaration);
18515 LookupName(Previous, S);
18516 switch (Previous.getResultKind()) {
18519 PrevDecl = Previous.getAsSingle<NamedDecl>();
18520 break;
18521
18523 PrevDecl = Previous.getRepresentativeDecl();
18524 break;
18525
18529 break;
18530 }
18531 Previous.suppressDiagnostics();
18532
18533 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18534 // Maybe we will complain about the shadowed template parameter.
18536 // Just pretend that we didn't see the previous declaration.
18537 PrevDecl = nullptr;
18538 }
18539
18540 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18541 PrevDecl = nullptr;
18542
18543 bool Mutable
18545 SourceLocation TSSL = D.getBeginLoc();
18546 FieldDecl *NewFD
18547 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18548 TSSL, AS, PrevDecl, &D);
18549
18550 if (NewFD->isInvalidDecl())
18551 Record->setInvalidDecl();
18552
18554 NewFD->setModulePrivate();
18555
18556 if (NewFD->isInvalidDecl() && PrevDecl) {
18557 // Don't introduce NewFD into scope; there's already something
18558 // with the same name in the same scope.
18559 } else if (II) {
18560 PushOnScopeChains(NewFD, S);
18561 } else
18562 Record->addDecl(NewFD);
18563
18564 return NewFD;
18565}
18566
18567/// Build a new FieldDecl and check its well-formedness.
18568///
18569/// This routine builds a new FieldDecl given the fields name, type,
18570/// record, etc. \p PrevDecl should refer to any previous declaration
18571/// with the same name and in the same scope as the field to be
18572/// created.
18573///
18574/// \returns a new FieldDecl.
18575///
18576/// \todo The Declarator argument is a hack. It will be removed once
18578 TypeSourceInfo *TInfo,
18580 bool Mutable, Expr *BitWidth,
18581 InClassInitStyle InitStyle,
18582 SourceLocation TSSL,
18583 AccessSpecifier AS, NamedDecl *PrevDecl,
18584 Declarator *D) {
18585 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18586 bool InvalidDecl = false;
18587 if (D) InvalidDecl = D->isInvalidType();
18588
18589 // If we receive a broken type, recover by assuming 'int' and
18590 // marking this declaration as invalid.
18591 if (T.isNull() || T->containsErrors()) {
18592 InvalidDecl = true;
18593 T = Context.IntTy;
18594 }
18595
18597 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18598 if (RequireCompleteSizedType(Loc, EltTy,
18599 diag::err_field_incomplete_or_sizeless)) {
18600 // Fields of incomplete type force their record to be invalid.
18601 Record->setInvalidDecl();
18602 InvalidDecl = true;
18603 } else {
18604 NamedDecl *Def;
18605 EltTy->isIncompleteType(&Def);
18606 if (Def && Def->isInvalidDecl()) {
18607 Record->setInvalidDecl();
18608 InvalidDecl = true;
18609 }
18610 }
18611 }
18612
18613 // TR 18037 does not allow fields to be declared with address space
18614 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18616 Diag(Loc, diag::err_field_with_address_space);
18617 Record->setInvalidDecl();
18618 InvalidDecl = true;
18619 }
18620
18621 if (LangOpts.OpenCL) {
18622 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18623 // used as structure or union field: image, sampler, event or block types.
18624 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18625 T->isBlockPointerType()) {
18626 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18627 Record->setInvalidDecl();
18628 InvalidDecl = true;
18629 }
18630 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18631 // is enabled.
18632 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18633 "__cl_clang_bitfields", LangOpts)) {
18634 Diag(Loc, diag::err_opencl_bitfields);
18635 InvalidDecl = true;
18636 }
18637 }
18638
18639 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18640 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18641 T.hasQualifiers()) {
18642 InvalidDecl = true;
18643 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18644 }
18645
18646 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18647 // than a variably modified type.
18648 if (!InvalidDecl && T->isVariablyModifiedType()) {
18650 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18651 InvalidDecl = true;
18652 }
18653
18654 // Fields can not have abstract class types
18655 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18656 diag::err_abstract_type_in_decl,
18658 InvalidDecl = true;
18659
18660 if (InvalidDecl)
18661 BitWidth = nullptr;
18662 // If this is declared as a bit-field, check the bit-field.
18663 if (BitWidth) {
18664 BitWidth =
18665 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18666 if (!BitWidth) {
18667 InvalidDecl = true;
18668 BitWidth = nullptr;
18669 }
18670 }
18671
18672 // Check that 'mutable' is consistent with the type of the declaration.
18673 if (!InvalidDecl && Mutable) {
18674 unsigned DiagID = 0;
18675 if (T->isReferenceType())
18676 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18677 : diag::err_mutable_reference;
18678 else if (T.isConstQualified())
18679 DiagID = diag::err_mutable_const;
18680
18681 if (DiagID) {
18682 SourceLocation ErrLoc = Loc;
18683 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18684 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18685 Diag(ErrLoc, DiagID);
18686 if (DiagID != diag::ext_mutable_reference) {
18687 Mutable = false;
18688 InvalidDecl = true;
18689 }
18690 }
18691 }
18692
18693 // C++11 [class.union]p8 (DR1460):
18694 // At most one variant member of a union may have a
18695 // brace-or-equal-initializer.
18696 if (InitStyle != ICIS_NoInit)
18697 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18698
18699 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18700 BitWidth, Mutable, InitStyle);
18701 if (InvalidDecl)
18702 NewFD->setInvalidDecl();
18703
18704 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18705 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18706 Diag(Loc, diag::err_duplicate_member) << II;
18707 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18708 NewFD->setInvalidDecl();
18709 }
18710
18711 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18712 if (Record->isUnion()) {
18713 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18714 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18715 if (RDecl->getDefinition()) {
18716 // C++ [class.union]p1: An object of a class with a non-trivial
18717 // constructor, a non-trivial copy constructor, a non-trivial
18718 // destructor, or a non-trivial copy assignment operator
18719 // cannot be a member of a union, nor can an array of such
18720 // objects.
18721 if (CheckNontrivialField(NewFD))
18722 NewFD->setInvalidDecl();
18723 }
18724 }
18725
18726 // C++ [class.union]p1: If a union contains a member of reference type,
18727 // the program is ill-formed, except when compiling with MSVC extensions
18728 // enabled.
18729 if (EltTy->isReferenceType()) {
18730 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18731 diag::ext_union_member_of_reference_type :
18732 diag::err_union_member_of_reference_type)
18733 << NewFD->getDeclName() << EltTy;
18734 if (!getLangOpts().MicrosoftExt)
18735 NewFD->setInvalidDecl();
18736 }
18737 }
18738 }
18739
18740 // FIXME: We need to pass in the attributes given an AST
18741 // representation, not a parser representation.
18742 if (D) {
18743 // FIXME: The current scope is almost... but not entirely... correct here.
18744 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18745
18746 if (NewFD->hasAttrs())
18748 }
18749
18750 // In auto-retain/release, infer strong retension for fields of
18751 // retainable type.
18752 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18753 NewFD->setInvalidDecl();
18754
18755 if (T.isObjCGCWeak())
18756 Diag(Loc, diag::warn_attribute_weak_on_field);
18757
18758 // PPC MMA non-pointer types are not allowed as field types.
18759 if (Context.getTargetInfo().getTriple().isPPC64() &&
18760 CheckPPCMMAType(T, NewFD->getLocation()))
18761 NewFD->setInvalidDecl();
18762
18763 NewFD->setAccess(AS);
18764 return NewFD;
18765}
18766
18768 assert(FD);
18769 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18770
18771 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18772 return false;
18773
18775 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18776 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18777 if (RDecl->getDefinition()) {
18778 // We check for copy constructors before constructors
18779 // because otherwise we'll never get complaints about
18780 // copy constructors.
18781
18783 // We're required to check for any non-trivial constructors. Since the
18784 // implicit default constructor is suppressed if there are any
18785 // user-declared constructors, we just need to check that there is a
18786 // trivial default constructor and a trivial copy constructor. (We don't
18787 // worry about move constructors here, since this is a C++98 check.)
18788 if (RDecl->hasNonTrivialCopyConstructor())
18790 else if (!RDecl->hasTrivialDefaultConstructor())
18792 else if (RDecl->hasNonTrivialCopyAssignment())
18794 else if (RDecl->hasNonTrivialDestructor())
18796
18797 if (member != CXXSpecialMemberKind::Invalid) {
18798 if (!getLangOpts().CPlusPlus11 &&
18799 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18800 // Objective-C++ ARC: it is an error to have a non-trivial field of
18801 // a union. However, system headers in Objective-C programs
18802 // occasionally have Objective-C lifetime objects within unions,
18803 // and rather than cause the program to fail, we make those
18804 // members unavailable.
18806 if (getSourceManager().isInSystemHeader(Loc)) {
18807 if (!FD->hasAttr<UnavailableAttr>())
18808 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18809 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18810 return false;
18811 }
18812 }
18813
18814 Diag(
18815 FD->getLocation(),
18817 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18818 : diag::err_illegal_union_or_anon_struct_member)
18819 << FD->getParent()->isUnion() << FD->getDeclName()
18820 << llvm::to_underlying(member);
18821 DiagnoseNontrivial(RDecl, member);
18822 return !getLangOpts().CPlusPlus11;
18823 }
18824 }
18825 }
18826
18827 return false;
18828}
18829
18830/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18831/// class and class extensions. For every class \@interface and class
18832/// extension \@interface, if the last ivar is a bitfield of any type,
18833/// then add an implicit `char :0` ivar to the end of that interface.
18835 SmallVectorImpl<Decl *> &AllIvarDecls) {
18836 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18837 return;
18838
18839 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18840 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18841
18842 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18843 return;
18844 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18845 if (!ID) {
18846 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18847 if (!CD->IsClassExtension())
18848 return;
18849 }
18850 // No need to add this to end of @implementation.
18851 else
18852 return;
18853 }
18854 // All conditions are met. Add a new bitfield to the tail end of ivars.
18855 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18856 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18857
18858 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18859 DeclLoc, DeclLoc, nullptr,
18862 DeclLoc),
18864 true);
18865 AllIvarDecls.push_back(Ivar);
18866}
18867
18868/// [class.dtor]p4:
18869/// At the end of the definition of a class, overload resolution is
18870/// performed among the prospective destructors declared in that class with
18871/// an empty argument list to select the destructor for the class, also
18872/// known as the selected destructor.
18873///
18874/// We do the overload resolution here, then mark the selected constructor in the AST.
18875/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18877 if (!Record->hasUserDeclaredDestructor()) {
18878 return;
18879 }
18880
18881 SourceLocation Loc = Record->getLocation();
18883
18884 for (auto *Decl : Record->decls()) {
18885 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18886 if (DD->isInvalidDecl())
18887 continue;
18888 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18889 OCS);
18890 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18891 }
18892 }
18893
18894 if (OCS.empty()) {
18895 return;
18896 }
18898 unsigned Msg = 0;
18899 OverloadCandidateDisplayKind DisplayKind;
18900
18901 switch (OCS.BestViableFunction(S, Loc, Best)) {
18902 case OR_Success:
18903 case OR_Deleted:
18904 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18905 break;
18906
18907 case OR_Ambiguous:
18908 Msg = diag::err_ambiguous_destructor;
18909 DisplayKind = OCD_AmbiguousCandidates;
18910 break;
18911
18913 Msg = diag::err_no_viable_destructor;
18914 DisplayKind = OCD_AllCandidates;
18915 break;
18916 }
18917
18918 if (Msg) {
18919 // OpenCL have got their own thing going with destructors. It's slightly broken,
18920 // but we allow it.
18921 if (!S.LangOpts.OpenCL) {
18922 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18923 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18924 Record->setInvalidDecl();
18925 }
18926 // It's a bit hacky: At this point we've raised an error but we want the
18927 // rest of the compiler to continue somehow working. However almost
18928 // everything we'll try to do with the class will depend on there being a
18929 // destructor. So let's pretend the first one is selected and hope for the
18930 // best.
18931 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18932 }
18933}
18934
18935/// [class.mem.special]p5
18936/// Two special member functions are of the same kind if:
18937/// - they are both default constructors,
18938/// - they are both copy or move constructors with the same first parameter
18939/// type, or
18940/// - they are both copy or move assignment operators with the same first
18941/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18943 CXXMethodDecl *M1,
18944 CXXMethodDecl *M2,
18946 // We don't want to compare templates to non-templates: See
18947 // https://github.com/llvm/llvm-project/issues/59206
18949 return bool(M1->getDescribedFunctionTemplate()) ==
18951 // FIXME: better resolve CWG
18952 // https://cplusplus.github.io/CWG/issues/2787.html
18953 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18954 M2->getNonObjectParameter(0)->getType()))
18955 return false;
18958 return false;
18959
18960 return true;
18961}
18962
18963/// [class.mem.special]p6:
18964/// An eligible special member function is a special member function for which:
18965/// - the function is not deleted,
18966/// - the associated constraints, if any, are satisfied, and
18967/// - no special member function of the same kind whose associated constraints
18968/// [CWG2595], if any, are satisfied is more constrained.
18972 SmallVector<bool, 4> SatisfactionStatus;
18973
18974 for (CXXMethodDecl *Method : Methods) {
18975 const Expr *Constraints = Method->getTrailingRequiresClause();
18976 if (!Constraints)
18977 SatisfactionStatus.push_back(true);
18978 else {
18979 ConstraintSatisfaction Satisfaction;
18980 if (S.CheckFunctionConstraints(Method, Satisfaction))
18981 SatisfactionStatus.push_back(false);
18982 else
18983 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18984 }
18985 }
18986
18987 for (size_t i = 0; i < Methods.size(); i++) {
18988 if (!SatisfactionStatus[i])
18989 continue;
18990 CXXMethodDecl *Method = Methods[i];
18991 CXXMethodDecl *OrigMethod = Method;
18992 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18993 OrigMethod = cast<CXXMethodDecl>(MF);
18994
18995 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18996 bool AnotherMethodIsMoreConstrained = false;
18997 for (size_t j = 0; j < Methods.size(); j++) {
18998 if (i == j || !SatisfactionStatus[j])
18999 continue;
19000 CXXMethodDecl *OtherMethod = Methods[j];
19001 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19002 OtherMethod = cast<CXXMethodDecl>(MF);
19003
19004 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19005 CSM))
19006 continue;
19007
19008 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
19009 if (!OtherConstraints)
19010 continue;
19011 if (!Constraints) {
19012 AnotherMethodIsMoreConstrained = true;
19013 break;
19014 }
19015 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
19016 {Constraints},
19017 AnotherMethodIsMoreConstrained)) {
19018 // There was an error with the constraints comparison. Exit the loop
19019 // and don't consider this function eligible.
19020 AnotherMethodIsMoreConstrained = true;
19021 }
19022 if (AnotherMethodIsMoreConstrained)
19023 break;
19024 }
19025 // FIXME: Do not consider deleted methods as eligible after implementing
19026 // DR1734 and DR1496.
19027 if (!AnotherMethodIsMoreConstrained) {
19028 Method->setIneligibleOrNotSelected(false);
19029 Record->addedEligibleSpecialMemberFunction(Method,
19030 1 << llvm::to_underlying(CSM));
19031 }
19032 }
19033}
19034
19037 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19038 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19039 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19040 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19041 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19042
19043 for (auto *Decl : Record->decls()) {
19044 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19045 if (!MD) {
19046 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19047 if (FTD)
19048 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19049 }
19050 if (!MD)
19051 continue;
19052 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19053 if (CD->isInvalidDecl())
19054 continue;
19055 if (CD->isDefaultConstructor())
19056 DefaultConstructors.push_back(MD);
19057 else if (CD->isCopyConstructor())
19058 CopyConstructors.push_back(MD);
19059 else if (CD->isMoveConstructor())
19060 MoveConstructors.push_back(MD);
19061 } else if (MD->isCopyAssignmentOperator()) {
19062 CopyAssignmentOperators.push_back(MD);
19063 } else if (MD->isMoveAssignmentOperator()) {
19064 MoveAssignmentOperators.push_back(MD);
19065 }
19066 }
19067
19068 SetEligibleMethods(S, Record, DefaultConstructors,
19070 SetEligibleMethods(S, Record, CopyConstructors,
19072 SetEligibleMethods(S, Record, MoveConstructors,
19074 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19076 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19078}
19079
19080void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19081 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19082 SourceLocation RBrac,
19083 const ParsedAttributesView &Attrs) {
19084 assert(EnclosingDecl && "missing record or interface decl");
19085
19086 // If this is an Objective-C @implementation or category and we have
19087 // new fields here we should reset the layout of the interface since
19088 // it will now change.
19089 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19090 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19091 switch (DC->getKind()) {
19092 default: break;
19093 case Decl::ObjCCategory:
19094 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19095 break;
19096 case Decl::ObjCImplementation:
19097 Context.
19098 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19099 break;
19100 }
19101 }
19102
19103 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19104 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19105
19106 // Start counting up the number of named members; make sure to include
19107 // members of anonymous structs and unions in the total.
19108 unsigned NumNamedMembers = 0;
19109 if (Record) {
19110 for (const auto *I : Record->decls()) {
19111 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19112 if (IFD->getDeclName())
19113 ++NumNamedMembers;
19114 }
19115 }
19116
19117 // Verify that all the fields are okay.
19119
19120 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19121 i != end; ++i) {
19122 FieldDecl *FD = cast<FieldDecl>(*i);
19123
19124 // Get the type for the field.
19125 const Type *FDTy = FD->getType().getTypePtr();
19126
19127 if (!FD->isAnonymousStructOrUnion()) {
19128 // Remember all fields written by the user.
19129 RecFields.push_back(FD);
19130 }
19131
19132 // If the field is already invalid for some reason, don't emit more
19133 // diagnostics about it.
19134 if (FD->isInvalidDecl()) {
19135 EnclosingDecl->setInvalidDecl();
19136 continue;
19137 }
19138
19139 // C99 6.7.2.1p2:
19140 // A structure or union shall not contain a member with
19141 // incomplete or function type (hence, a structure shall not
19142 // contain an instance of itself, but may contain a pointer to
19143 // an instance of itself), except that the last member of a
19144 // structure with more than one named member may have incomplete
19145 // array type; such a structure (and any union containing,
19146 // possibly recursively, a member that is such a structure)
19147 // shall not be a member of a structure or an element of an
19148 // array.
19149 bool IsLastField = (i + 1 == Fields.end());
19150 if (FDTy->isFunctionType()) {
19151 // Field declared as a function.
19152 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19153 << FD->getDeclName();
19154 FD->setInvalidDecl();
19155 EnclosingDecl->setInvalidDecl();
19156 continue;
19157 } else if (FDTy->isIncompleteArrayType() &&
19158 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19159 if (Record) {
19160 // Flexible array member.
19161 // Microsoft and g++ is more permissive regarding flexible array.
19162 // It will accept flexible array in union and also
19163 // as the sole element of a struct/class.
19164 unsigned DiagID = 0;
19165 if (!Record->isUnion() && !IsLastField) {
19166 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19167 << FD->getDeclName() << FD->getType()
19168 << llvm::to_underlying(Record->getTagKind());
19169 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19170 FD->setInvalidDecl();
19171 EnclosingDecl->setInvalidDecl();
19172 continue;
19173 } else if (Record->isUnion())
19174 DiagID = getLangOpts().MicrosoftExt
19175 ? diag::ext_flexible_array_union_ms
19176 : diag::ext_flexible_array_union_gnu;
19177 else if (NumNamedMembers < 1)
19178 DiagID = getLangOpts().MicrosoftExt
19179 ? diag::ext_flexible_array_empty_aggregate_ms
19180 : diag::ext_flexible_array_empty_aggregate_gnu;
19181
19182 if (DiagID)
19183 Diag(FD->getLocation(), DiagID)
19184 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19185 // While the layout of types that contain virtual bases is not specified
19186 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19187 // virtual bases after the derived members. This would make a flexible
19188 // array member declared at the end of an object not adjacent to the end
19189 // of the type.
19190 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19191 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19192 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19193 if (!getLangOpts().C99)
19194 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19195 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19196
19197 // If the element type has a non-trivial destructor, we would not
19198 // implicitly destroy the elements, so disallow it for now.
19199 //
19200 // FIXME: GCC allows this. We should probably either implicitly delete
19201 // the destructor of the containing class, or just allow this.
19202 QualType BaseElem = Context.getBaseElementType(FD->getType());
19203 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19204 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19205 << FD->getDeclName() << FD->getType();
19206 FD->setInvalidDecl();
19207 EnclosingDecl->setInvalidDecl();
19208 continue;
19209 }
19210 // Okay, we have a legal flexible array member at the end of the struct.
19211 Record->setHasFlexibleArrayMember(true);
19212 } else {
19213 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19214 // unless they are followed by another ivar. That check is done
19215 // elsewhere, after synthesized ivars are known.
19216 }
19217 } else if (!FDTy->isDependentType() &&
19219 FD->getLocation(), FD->getType(),
19220 diag::err_field_incomplete_or_sizeless)) {
19221 // Incomplete type
19222 FD->setInvalidDecl();
19223 EnclosingDecl->setInvalidDecl();
19224 continue;
19225 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19226 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19227 // A type which contains a flexible array member is considered to be a
19228 // flexible array member.
19229 Record->setHasFlexibleArrayMember(true);
19230 if (!Record->isUnion()) {
19231 // If this is a struct/class and this is not the last element, reject
19232 // it. Note that GCC supports variable sized arrays in the middle of
19233 // structures.
19234 if (!IsLastField)
19235 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19236 << FD->getDeclName() << FD->getType();
19237 else {
19238 // We support flexible arrays at the end of structs in
19239 // other structs as an extension.
19240 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19241 << FD->getDeclName();
19242 }
19243 }
19244 }
19245 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19247 diag::err_abstract_type_in_decl,
19249 // Ivars can not have abstract class types
19250 FD->setInvalidDecl();
19251 }
19252 if (Record && FDTTy->getDecl()->hasObjectMember())
19253 Record->setHasObjectMember(true);
19254 if (Record && FDTTy->getDecl()->hasVolatileMember())
19255 Record->setHasVolatileMember(true);
19256 } else if (FDTy->isObjCObjectType()) {
19257 /// A field cannot be an Objective-c object
19258 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19261 FD->setType(T);
19262 } else if (Record && Record->isUnion() &&
19264 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19265 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19268 // For backward compatibility, fields of C unions declared in system
19269 // headers that have non-trivial ObjC ownership qualifications are marked
19270 // as unavailable unless the qualifier is explicit and __strong. This can
19271 // break ABI compatibility between programs compiled with ARC and MRR, but
19272 // is a better option than rejecting programs using those unions under
19273 // ARC.
19274 FD->addAttr(UnavailableAttr::CreateImplicit(
19275 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19276 FD->getLocation()));
19277 } else if (getLangOpts().ObjC &&
19278 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19279 !Record->hasObjectMember()) {
19280 if (FD->getType()->isObjCObjectPointerType() ||
19281 FD->getType().isObjCGCStrong())
19282 Record->setHasObjectMember(true);
19283 else if (Context.getAsArrayType(FD->getType())) {
19284 QualType BaseType = Context.getBaseElementType(FD->getType());
19285 if (BaseType->isRecordType() &&
19286 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19287 Record->setHasObjectMember(true);
19288 else if (BaseType->isObjCObjectPointerType() ||
19289 BaseType.isObjCGCStrong())
19290 Record->setHasObjectMember(true);
19291 }
19292 }
19293
19294 if (Record && !getLangOpts().CPlusPlus &&
19295 !shouldIgnoreForRecordTriviality(FD)) {
19296 QualType FT = FD->getType();
19298 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19300 Record->isUnion())
19301 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19302 }
19305 Record->setNonTrivialToPrimitiveCopy(true);
19306 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19307 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19308 }
19309 if (FT.isDestructedType()) {
19310 Record->setNonTrivialToPrimitiveDestroy(true);
19311 Record->setParamDestroyedInCallee(true);
19312 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19313 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19314 }
19315
19316 if (const auto *RT = FT->getAs<RecordType>()) {
19317 if (RT->getDecl()->getArgPassingRestrictions() ==
19319 Record->setArgPassingRestrictions(
19322 Record->setArgPassingRestrictions(
19324 }
19325
19326 if (Record && FD->getType().isVolatileQualified())
19327 Record->setHasVolatileMember(true);
19328 // Keep track of the number of named members.
19329 if (FD->getIdentifier())
19330 ++NumNamedMembers;
19331 }
19332
19333 // Okay, we successfully defined 'Record'.
19334 if (Record) {
19335 bool Completed = false;
19336 if (S) {
19337 Scope *Parent = S->getParent();
19338 if (Parent && Parent->isTypeAliasScope() &&
19339 Parent->isTemplateParamScope())
19340 Record->setInvalidDecl();
19341 }
19342
19343 if (CXXRecord) {
19344 if (!CXXRecord->isInvalidDecl()) {
19345 // Set access bits correctly on the directly-declared conversions.
19347 I = CXXRecord->conversion_begin(),
19348 E = CXXRecord->conversion_end(); I != E; ++I)
19349 I.setAccess((*I)->getAccess());
19350 }
19351
19352 // Add any implicitly-declared members to this class.
19354
19355 if (!CXXRecord->isDependentType()) {
19356 if (!CXXRecord->isInvalidDecl()) {
19357 // If we have virtual base classes, we may end up finding multiple
19358 // final overriders for a given virtual function. Check for this
19359 // problem now.
19360 if (CXXRecord->getNumVBases()) {
19361 CXXFinalOverriderMap FinalOverriders;
19362 CXXRecord->getFinalOverriders(FinalOverriders);
19363
19364 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19365 MEnd = FinalOverriders.end();
19366 M != MEnd; ++M) {
19367 for (OverridingMethods::iterator SO = M->second.begin(),
19368 SOEnd = M->second.end();
19369 SO != SOEnd; ++SO) {
19370 assert(SO->second.size() > 0 &&
19371 "Virtual function without overriding functions?");
19372 if (SO->second.size() == 1)
19373 continue;
19374
19375 // C++ [class.virtual]p2:
19376 // In a derived class, if a virtual member function of a base
19377 // class subobject has more than one final overrider the
19378 // program is ill-formed.
19379 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19380 << (const NamedDecl *)M->first << Record;
19381 Diag(M->first->getLocation(),
19382 diag::note_overridden_virtual_function);
19384 OM = SO->second.begin(),
19385 OMEnd = SO->second.end();
19386 OM != OMEnd; ++OM)
19387 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19388 << (const NamedDecl *)M->first << OM->Method->getParent();
19389
19390 Record->setInvalidDecl();
19391 }
19392 }
19393 CXXRecord->completeDefinition(&FinalOverriders);
19394 Completed = true;
19395 }
19396 }
19397 ComputeSelectedDestructor(*this, CXXRecord);
19399 }
19400 }
19401
19402 if (!Completed)
19403 Record->completeDefinition();
19404
19405 // Handle attributes before checking the layout.
19407
19408 // Check to see if a FieldDecl is a pointer to a function.
19409 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19410 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19411 if (!FD) {
19412 // Check whether this is a forward declaration that was inserted by
19413 // Clang. This happens when a non-forward declared / defined type is
19414 // used, e.g.:
19415 //
19416 // struct foo {
19417 // struct bar *(*f)();
19418 // struct bar *(*g)();
19419 // };
19420 //
19421 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19422 // incomplete definition.
19423 if (const auto *TD = dyn_cast<TagDecl>(D))
19424 return !TD->isCompleteDefinition();
19425 return false;
19426 }
19427 QualType FieldType = FD->getType().getDesugaredType(Context);
19428 if (isa<PointerType>(FieldType)) {
19429 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19430 return PointeeType.getDesugaredType(Context)->isFunctionType();
19431 }
19432 return false;
19433 };
19434
19435 // Maybe randomize the record's decls. We automatically randomize a record
19436 // of function pointers, unless it has the "no_randomize_layout" attribute.
19437 if (!getLangOpts().CPlusPlus &&
19438 (Record->hasAttr<RandomizeLayoutAttr>() ||
19439 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19440 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19441 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19442 !Record->isRandomized()) {
19443 SmallVector<Decl *, 32> NewDeclOrdering;
19445 NewDeclOrdering))
19446 Record->reorderDecls(NewDeclOrdering);
19447 }
19448
19449 // We may have deferred checking for a deleted destructor. Check now.
19450 if (CXXRecord) {
19451 auto *Dtor = CXXRecord->getDestructor();
19452 if (Dtor && Dtor->isImplicit() &&
19454 CXXRecord->setImplicitDestructorIsDeleted();
19455 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19456 }
19457 }
19458
19459 if (Record->hasAttrs()) {
19461
19462 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19463 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19464 IA->getRange(), IA->getBestCase(),
19465 IA->getInheritanceModel());
19466 }
19467
19468 // Check if the structure/union declaration is a type that can have zero
19469 // size in C. For C this is a language extension, for C++ it may cause
19470 // compatibility problems.
19471 bool CheckForZeroSize;
19472 if (!getLangOpts().CPlusPlus) {
19473 CheckForZeroSize = true;
19474 } else {
19475 // For C++ filter out types that cannot be referenced in C code.
19476 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19477 CheckForZeroSize =
19478 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19479 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19480 CXXRecord->isCLike();
19481 }
19482 if (CheckForZeroSize) {
19483 bool ZeroSize = true;
19484 bool IsEmpty = true;
19485 unsigned NonBitFields = 0;
19486 for (RecordDecl::field_iterator I = Record->field_begin(),
19487 E = Record->field_end();
19488 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19489 IsEmpty = false;
19490 if (I->isUnnamedBitField()) {
19491 if (!I->isZeroLengthBitField(Context))
19492 ZeroSize = false;
19493 } else {
19494 ++NonBitFields;
19495 QualType FieldType = I->getType();
19496 if (FieldType->isIncompleteType() ||
19497 !Context.getTypeSizeInChars(FieldType).isZero())
19498 ZeroSize = false;
19499 }
19500 }
19501
19502 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19503 // allowed in C++, but warn if its declaration is inside
19504 // extern "C" block.
19505 if (ZeroSize) {
19506 Diag(RecLoc, getLangOpts().CPlusPlus ?
19507 diag::warn_zero_size_struct_union_in_extern_c :
19508 diag::warn_zero_size_struct_union_compat)
19509 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19510 }
19511
19512 // Structs without named members are extension in C (C99 6.7.2.1p7),
19513 // but are accepted by GCC.
19514 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19515 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19516 diag::ext_no_named_members_in_struct_union)
19517 << Record->isUnion();
19518 }
19519 }
19520 } else {
19521 ObjCIvarDecl **ClsFields =
19522 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19523 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19524 ID->setEndOfDefinitionLoc(RBrac);
19525 // Add ivar's to class's DeclContext.
19526 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19527 ClsFields[i]->setLexicalDeclContext(ID);
19528 ID->addDecl(ClsFields[i]);
19529 }
19530 // Must enforce the rule that ivars in the base classes may not be
19531 // duplicates.
19532 if (ID->getSuperClass())
19533 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19534 } else if (ObjCImplementationDecl *IMPDecl =
19535 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19536 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19537 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19538 // Ivar declared in @implementation never belongs to the implementation.
19539 // Only it is in implementation's lexical context.
19540 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19541 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19542 RBrac);
19543 IMPDecl->setIvarLBraceLoc(LBrac);
19544 IMPDecl->setIvarRBraceLoc(RBrac);
19545 } else if (ObjCCategoryDecl *CDecl =
19546 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19547 // case of ivars in class extension; all other cases have been
19548 // reported as errors elsewhere.
19549 // FIXME. Class extension does not have a LocEnd field.
19550 // CDecl->setLocEnd(RBrac);
19551 // Add ivar's to class extension's DeclContext.
19552 // Diagnose redeclaration of private ivars.
19553 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19554 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19555 if (IDecl) {
19556 if (const ObjCIvarDecl *ClsIvar =
19557 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19558 Diag(ClsFields[i]->getLocation(),
19559 diag::err_duplicate_ivar_declaration);
19560 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19561 continue;
19562 }
19563 for (const auto *Ext : IDecl->known_extensions()) {
19564 if (const ObjCIvarDecl *ClsExtIvar
19565 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19566 Diag(ClsFields[i]->getLocation(),
19567 diag::err_duplicate_ivar_declaration);
19568 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19569 continue;
19570 }
19571 }
19572 }
19573 ClsFields[i]->setLexicalDeclContext(CDecl);
19574 CDecl->addDecl(ClsFields[i]);
19575 }
19576 CDecl->setIvarLBraceLoc(LBrac);
19577 CDecl->setIvarRBraceLoc(RBrac);
19578 }
19579 }
19581}
19582
19583/// Determine whether the given integral value is representable within
19584/// the given type T.
19586 llvm::APSInt &Value,
19587 QualType T) {
19588 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19589 "Integral type required!");
19590 unsigned BitWidth = Context.getIntWidth(T);
19591
19592 if (Value.isUnsigned() || Value.isNonNegative()) {
19594 --BitWidth;
19595 return Value.getActiveBits() <= BitWidth;
19596 }
19597 return Value.getSignificantBits() <= BitWidth;
19598}
19599
19600// Given an integral type, return the next larger integral type
19601// (or a NULL type of no such type exists).
19603 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19604 // enum checking below.
19605 assert((T->isIntegralType(Context) ||
19606 T->isEnumeralType()) && "Integral type required!");
19607 const unsigned NumTypes = 4;
19608 QualType SignedIntegralTypes[NumTypes] = {
19609 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19610 };
19611 QualType UnsignedIntegralTypes[NumTypes] = {
19612 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19613 Context.UnsignedLongLongTy
19614 };
19615
19616 unsigned BitWidth = Context.getTypeSize(T);
19617 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19618 : UnsignedIntegralTypes;
19619 for (unsigned I = 0; I != NumTypes; ++I)
19620 if (Context.getTypeSize(Types[I]) > BitWidth)
19621 return Types[I];
19622
19623 return QualType();
19624}
19625
19627 EnumConstantDecl *LastEnumConst,
19628 SourceLocation IdLoc,
19630 Expr *Val) {
19631 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19632 llvm::APSInt EnumVal(IntWidth);
19633 QualType EltTy;
19634
19636 Val = nullptr;
19637
19638 if (Val)
19639 Val = DefaultLvalueConversion(Val).get();
19640
19641 if (Val) {
19642 if (Enum->isDependentType() || Val->isTypeDependent() ||
19643 Val->containsErrors())
19644 EltTy = Context.DependentTy;
19645 else {
19646 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19647 // underlying type, but do allow it in all other contexts.
19648 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19649 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19650 // constant-expression in the enumerator-definition shall be a converted
19651 // constant expression of the underlying type.
19652 EltTy = Enum->getIntegerType();
19653 ExprResult Converted =
19654 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19656 if (Converted.isInvalid())
19657 Val = nullptr;
19658 else
19659 Val = Converted.get();
19660 } else if (!Val->isValueDependent() &&
19661 !(Val =
19663 .get())) {
19664 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19665 } else {
19666 if (Enum->isComplete()) {
19667 EltTy = Enum->getIntegerType();
19668
19669 // In Obj-C and Microsoft mode, require the enumeration value to be
19670 // representable in the underlying type of the enumeration. In C++11,
19671 // we perform a non-narrowing conversion as part of converted constant
19672 // expression checking.
19673 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19675 .getTriple()
19676 .isWindowsMSVCEnvironment()) {
19677 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19678 } else {
19679 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19680 }
19681 }
19682
19683 // Cast to the underlying type.
19684 Val = ImpCastExprToType(Val, EltTy,
19685 EltTy->isBooleanType() ? CK_IntegralToBoolean
19686 : CK_IntegralCast)
19687 .get();
19688 } else if (getLangOpts().CPlusPlus) {
19689 // C++11 [dcl.enum]p5:
19690 // If the underlying type is not fixed, the type of each enumerator
19691 // is the type of its initializing value:
19692 // - If an initializer is specified for an enumerator, the
19693 // initializing value has the same type as the expression.
19694 EltTy = Val->getType();
19695 } else {
19696 // C99 6.7.2.2p2:
19697 // The expression that defines the value of an enumeration constant
19698 // shall be an integer constant expression that has a value
19699 // representable as an int.
19700
19701 // Complain if the value is not representable in an int.
19703 Diag(IdLoc, diag::ext_enum_value_not_int)
19704 << toString(EnumVal, 10) << Val->getSourceRange()
19705 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19706 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19707 // Force the type of the expression to 'int'.
19708 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19709 }
19710 EltTy = Val->getType();
19711 }
19712 }
19713 }
19714 }
19715
19716 if (!Val) {
19717 if (Enum->isDependentType())
19718 EltTy = Context.DependentTy;
19719 else if (!LastEnumConst) {
19720 // C++0x [dcl.enum]p5:
19721 // If the underlying type is not fixed, the type of each enumerator
19722 // is the type of its initializing value:
19723 // - If no initializer is specified for the first enumerator, the
19724 // initializing value has an unspecified integral type.
19725 //
19726 // GCC uses 'int' for its unspecified integral type, as does
19727 // C99 6.7.2.2p3.
19728 if (Enum->isFixed()) {
19729 EltTy = Enum->getIntegerType();
19730 }
19731 else {
19732 EltTy = Context.IntTy;
19733 }
19734 } else {
19735 // Assign the last value + 1.
19736 EnumVal = LastEnumConst->getInitVal();
19737 ++EnumVal;
19738 EltTy = LastEnumConst->getType();
19739
19740 // Check for overflow on increment.
19741 if (EnumVal < LastEnumConst->getInitVal()) {
19742 // C++0x [dcl.enum]p5:
19743 // If the underlying type is not fixed, the type of each enumerator
19744 // is the type of its initializing value:
19745 //
19746 // - Otherwise the type of the initializing value is the same as
19747 // the type of the initializing value of the preceding enumerator
19748 // unless the incremented value is not representable in that type,
19749 // in which case the type is an unspecified integral type
19750 // sufficient to contain the incremented value. If no such type
19751 // exists, the program is ill-formed.
19753 if (T.isNull() || Enum->isFixed()) {
19754 // There is no integral type larger enough to represent this
19755 // value. Complain, then allow the value to wrap around.
19756 EnumVal = LastEnumConst->getInitVal();
19757 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19758 ++EnumVal;
19759 if (Enum->isFixed())
19760 // When the underlying type is fixed, this is ill-formed.
19761 Diag(IdLoc, diag::err_enumerator_wrapped)
19762 << toString(EnumVal, 10)
19763 << EltTy;
19764 else
19765 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19766 << toString(EnumVal, 10);
19767 } else {
19768 EltTy = T;
19769 }
19770
19771 // Retrieve the last enumerator's value, extent that type to the
19772 // type that is supposed to be large enough to represent the incremented
19773 // value, then increment.
19774 EnumVal = LastEnumConst->getInitVal();
19775 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19776 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19777 ++EnumVal;
19778
19779 // If we're not in C++, diagnose the overflow of enumerator values,
19780 // which in C99 means that the enumerator value is not representable in
19781 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19782 // permits enumerator values that are representable in some larger
19783 // integral type.
19784 if (!getLangOpts().CPlusPlus && !T.isNull())
19785 Diag(IdLoc, diag::warn_enum_value_overflow);
19786 } else if (!getLangOpts().CPlusPlus &&
19787 !EltTy->isDependentType() &&
19788 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19789 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19790 Diag(IdLoc, diag::ext_enum_value_not_int)
19791 << toString(EnumVal, 10) << 1;
19792 }
19793 }
19794 }
19795
19796 if (!EltTy->isDependentType()) {
19797 // Make the enumerator value match the signedness and size of the
19798 // enumerator's type.
19799 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19800 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19801 }
19802
19803 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19804 Val, EnumVal);
19805}
19806
19808 SourceLocation IILoc) {
19809 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19811 return SkipBodyInfo();
19812
19813 // We have an anonymous enum definition. Look up the first enumerator to
19814 // determine if we should merge the definition with an existing one and
19815 // skip the body.
19816 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19818 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19819 if (!PrevECD)
19820 return SkipBodyInfo();
19821
19822 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19823 NamedDecl *Hidden;
19824 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19825 SkipBodyInfo Skip;
19826 Skip.Previous = Hidden;
19827 return Skip;
19828 }
19829
19830 return SkipBodyInfo();
19831}
19832
19833Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19835 const ParsedAttributesView &Attrs,
19836 SourceLocation EqualLoc, Expr *Val) {
19837 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19838 EnumConstantDecl *LastEnumConst =
19839 cast_or_null<EnumConstantDecl>(lastEnumConst);
19840
19841 // The scope passed in may not be a decl scope. Zip up the scope tree until
19842 // we find one that is.
19843 S = getNonFieldDeclScope(S);
19844
19845 // Verify that there isn't already something declared with this name in this
19846 // scope.
19847 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19848 RedeclarationKind::ForVisibleRedeclaration);
19849 LookupName(R, S);
19850 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19851
19852 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19853 // Maybe we will complain about the shadowed template parameter.
19854 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19855 // Just pretend that we didn't see the previous declaration.
19856 PrevDecl = nullptr;
19857 }
19858
19859 // C++ [class.mem]p15:
19860 // If T is the name of a class, then each of the following shall have a name
19861 // different from T:
19862 // - every enumerator of every member of class T that is an unscoped
19863 // enumerated type
19864 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19866 DeclarationNameInfo(Id, IdLoc));
19867
19868 EnumConstantDecl *New =
19869 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19870 if (!New)
19871 return nullptr;
19872
19873 if (PrevDecl) {
19874 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19875 // Check for other kinds of shadowing not already handled.
19876 CheckShadow(New, PrevDecl, R);
19877 }
19878
19879 // When in C++, we may get a TagDecl with the same name; in this case the
19880 // enum constant will 'hide' the tag.
19881 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19882 "Received TagDecl when not in C++!");
19883 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19884 if (isa<EnumConstantDecl>(PrevDecl))
19885 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19886 else
19887 Diag(IdLoc, diag::err_redefinition) << Id;
19888 notePreviousDefinition(PrevDecl, IdLoc);
19889 return nullptr;
19890 }
19891 }
19892
19893 // Process attributes.
19894 ProcessDeclAttributeList(S, New, Attrs);
19895 AddPragmaAttributes(S, New);
19896 ProcessAPINotes(New);
19897
19898 // Register this decl in the current scope stack.
19899 New->setAccess(TheEnumDecl->getAccess());
19900 PushOnScopeChains(New, S);
19901
19903
19904 return New;
19905}
19906
19907// Returns true when the enum initial expression does not trigger the
19908// duplicate enum warning. A few common cases are exempted as follows:
19909// Element2 = Element1
19910// Element2 = Element1 + 1
19911// Element2 = Element1 - 1
19912// Where Element2 and Element1 are from the same enum.
19914 Expr *InitExpr = ECD->getInitExpr();
19915 if (!InitExpr)
19916 return true;
19917 InitExpr = InitExpr->IgnoreImpCasts();
19918
19919 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19920 if (!BO->isAdditiveOp())
19921 return true;
19922 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19923 if (!IL)
19924 return true;
19925 if (IL->getValue() != 1)
19926 return true;
19927
19928 InitExpr = BO->getLHS();
19929 }
19930
19931 // This checks if the elements are from the same enum.
19932 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19933 if (!DRE)
19934 return true;
19935
19936 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19937 if (!EnumConstant)
19938 return true;
19939
19940 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19941 Enum)
19942 return true;
19943
19944 return false;
19945}
19946
19947// Emits a warning when an element is implicitly set a value that
19948// a previous element has already been set to.
19951 // Avoid anonymous enums
19952 if (!Enum->getIdentifier())
19953 return;
19954
19955 // Only check for small enums.
19956 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19957 return;
19958
19959 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19960 return;
19961
19962 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19963 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19964
19965 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19966
19967 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19968 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19969
19970 // Use int64_t as a key to avoid needing special handling for map keys.
19971 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19972 llvm::APSInt Val = D->getInitVal();
19973 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19974 };
19975
19976 DuplicatesVector DupVector;
19977 ValueToVectorMap EnumMap;
19978
19979 // Populate the EnumMap with all values represented by enum constants without
19980 // an initializer.
19981 for (auto *Element : Elements) {
19982 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19983
19984 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19985 // this constant. Skip this enum since it may be ill-formed.
19986 if (!ECD) {
19987 return;
19988 }
19989
19990 // Constants with initializers are handled in the next loop.
19991 if (ECD->getInitExpr())
19992 continue;
19993
19994 // Duplicate values are handled in the next loop.
19995 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19996 }
19997
19998 if (EnumMap.size() == 0)
19999 return;
20000
20001 // Create vectors for any values that has duplicates.
20002 for (auto *Element : Elements) {
20003 // The last loop returned if any constant was null.
20004 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
20005 if (!ValidDuplicateEnum(ECD, Enum))
20006 continue;
20007
20008 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20009 if (Iter == EnumMap.end())
20010 continue;
20011
20012 DeclOrVector& Entry = Iter->second;
20013 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
20014 // Ensure constants are different.
20015 if (D == ECD)
20016 continue;
20017
20018 // Create new vector and push values onto it.
20019 auto Vec = std::make_unique<ECDVector>();
20020 Vec->push_back(D);
20021 Vec->push_back(ECD);
20022
20023 // Update entry to point to the duplicates vector.
20024 Entry = Vec.get();
20025
20026 // Store the vector somewhere we can consult later for quick emission of
20027 // diagnostics.
20028 DupVector.emplace_back(std::move(Vec));
20029 continue;
20030 }
20031
20032 ECDVector *Vec = Entry.get<ECDVector*>();
20033 // Make sure constants are not added more than once.
20034 if (*Vec->begin() == ECD)
20035 continue;
20036
20037 Vec->push_back(ECD);
20038 }
20039
20040 // Emit diagnostics.
20041 for (const auto &Vec : DupVector) {
20042 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20043
20044 // Emit warning for one enum constant.
20045 auto *FirstECD = Vec->front();
20046 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20047 << FirstECD << toString(FirstECD->getInitVal(), 10)
20048 << FirstECD->getSourceRange();
20049
20050 // Emit one note for each of the remaining enum constants with
20051 // the same value.
20052 for (auto *ECD : llvm::drop_begin(*Vec))
20053 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20054 << ECD << toString(ECD->getInitVal(), 10)
20055 << ECD->getSourceRange();
20056 }
20057}
20058
20059bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20060 bool AllowMask) const {
20061 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20062 assert(ED->isCompleteDefinition() && "expected enum definition");
20063
20064 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20065 llvm::APInt &FlagBits = R.first->second;
20066
20067 if (R.second) {
20068 for (auto *E : ED->enumerators()) {
20069 const auto &EVal = E->getInitVal();
20070 // Only single-bit enumerators introduce new flag values.
20071 if (EVal.isPowerOf2())
20072 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20073 }
20074 }
20075
20076 // A value is in a flag enum if either its bits are a subset of the enum's
20077 // flag bits (the first condition) or we are allowing masks and the same is
20078 // true of its complement (the second condition). When masks are allowed, we
20079 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20080 //
20081 // While it's true that any value could be used as a mask, the assumption is
20082 // that a mask will have all of the insignificant bits set. Anything else is
20083 // likely a logic error.
20084 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20085 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20086}
20087
20089 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20090 const ParsedAttributesView &Attrs) {
20091 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20093
20094 ProcessDeclAttributeList(S, Enum, Attrs);
20096
20097 if (Enum->isDependentType()) {
20098 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20099 EnumConstantDecl *ECD =
20100 cast_or_null<EnumConstantDecl>(Elements[i]);
20101 if (!ECD) continue;
20102
20103 ECD->setType(EnumType);
20104 }
20105
20106 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20107 return;
20108 }
20109
20110 // TODO: If the result value doesn't fit in an int, it must be a long or long
20111 // long value. ISO C does not support this, but GCC does as an extension,
20112 // emit a warning.
20113 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20114 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20115 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20116
20117 // Verify that all the values are okay, compute the size of the values, and
20118 // reverse the list.
20119 unsigned NumNegativeBits = 0;
20120 unsigned NumPositiveBits = 0;
20121
20122 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20123 EnumConstantDecl *ECD =
20124 cast_or_null<EnumConstantDecl>(Elements[i]);
20125 if (!ECD) continue; // Already issued a diagnostic.
20126
20127 const llvm::APSInt &InitVal = ECD->getInitVal();
20128
20129 // Keep track of the size of positive and negative values.
20130 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20131 // If the enumerator is zero that should still be counted as a positive
20132 // bit since we need a bit to store the value zero.
20133 unsigned ActiveBits = InitVal.getActiveBits();
20134 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20135 } else {
20136 NumNegativeBits =
20137 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20138 }
20139 }
20140
20141 // If we have an empty set of enumerators we still need one bit.
20142 // From [dcl.enum]p8
20143 // If the enumerator-list is empty, the values of the enumeration are as if
20144 // the enumeration had a single enumerator with value 0
20145 if (!NumPositiveBits && !NumNegativeBits)
20146 NumPositiveBits = 1;
20147
20148 // Figure out the type that should be used for this enum.
20149 QualType BestType;
20150 unsigned BestWidth;
20151
20152 // C++0x N3000 [conv.prom]p3:
20153 // An rvalue of an unscoped enumeration type whose underlying
20154 // type is not fixed can be converted to an rvalue of the first
20155 // of the following types that can represent all the values of
20156 // the enumeration: int, unsigned int, long int, unsigned long
20157 // int, long long int, or unsigned long long int.
20158 // C99 6.4.4.3p2:
20159 // An identifier declared as an enumeration constant has type int.
20160 // The C99 rule is modified by a gcc extension
20161 QualType BestPromotionType;
20162
20163 bool Packed = Enum->hasAttr<PackedAttr>();
20164 // -fshort-enums is the equivalent to specifying the packed attribute on all
20165 // enum definitions.
20166 if (LangOpts.ShortEnums)
20167 Packed = true;
20168
20169 // If the enum already has a type because it is fixed or dictated by the
20170 // target, promote that type instead of analyzing the enumerators.
20171 if (Enum->isComplete()) {
20172 BestType = Enum->getIntegerType();
20173 if (Context.isPromotableIntegerType(BestType))
20174 BestPromotionType = Context.getPromotedIntegerType(BestType);
20175 else
20176 BestPromotionType = BestType;
20177
20178 BestWidth = Context.getIntWidth(BestType);
20179 }
20180 else if (NumNegativeBits) {
20181 // If there is a negative value, figure out the smallest integer type (of
20182 // int/long/longlong) that fits.
20183 // If it's packed, check also if it fits a char or a short.
20184 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20185 BestType = Context.SignedCharTy;
20186 BestWidth = CharWidth;
20187 } else if (Packed && NumNegativeBits <= ShortWidth &&
20188 NumPositiveBits < ShortWidth) {
20189 BestType = Context.ShortTy;
20190 BestWidth = ShortWidth;
20191 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20192 BestType = Context.IntTy;
20193 BestWidth = IntWidth;
20194 } else {
20195 BestWidth = Context.getTargetInfo().getLongWidth();
20196
20197 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20198 BestType = Context.LongTy;
20199 } else {
20200 BestWidth = Context.getTargetInfo().getLongLongWidth();
20201
20202 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20203 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20204 BestType = Context.LongLongTy;
20205 }
20206 }
20207 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20208 } else {
20209 // If there is no negative value, figure out the smallest type that fits
20210 // all of the enumerator values.
20211 // If it's packed, check also if it fits a char or a short.
20212 if (Packed && NumPositiveBits <= CharWidth) {
20213 BestType = Context.UnsignedCharTy;
20214 BestPromotionType = Context.IntTy;
20215 BestWidth = CharWidth;
20216 } else if (Packed && NumPositiveBits <= ShortWidth) {
20217 BestType = Context.UnsignedShortTy;
20218 BestPromotionType = Context.IntTy;
20219 BestWidth = ShortWidth;
20220 } else if (NumPositiveBits <= IntWidth) {
20221 BestType = Context.UnsignedIntTy;
20222 BestWidth = IntWidth;
20223 BestPromotionType
20224 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20226 } else if (NumPositiveBits <=
20227 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20228 BestType = Context.UnsignedLongTy;
20229 BestPromotionType
20230 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20232 } else {
20233 BestWidth = Context.getTargetInfo().getLongLongWidth();
20234 if (NumPositiveBits > BestWidth) {
20235 // This can happen with bit-precise integer types, but those are not
20236 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20237 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20238 // a 128-bit integer, we should consider doing the same.
20239 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20240 }
20241 BestType = Context.UnsignedLongLongTy;
20242 BestPromotionType
20243 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20245 }
20246 }
20247
20248 // Loop over all of the enumerator constants, changing their types to match
20249 // the type of the enum if needed.
20250 for (auto *D : Elements) {
20251 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20252 if (!ECD) continue; // Already issued a diagnostic.
20253
20254 // Standard C says the enumerators have int type, but we allow, as an
20255 // extension, the enumerators to be larger than int size. If each
20256 // enumerator value fits in an int, type it as an int, otherwise type it the
20257 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20258 // that X has type 'int', not 'unsigned'.
20259
20260 // Determine whether the value fits into an int.
20261 llvm::APSInt InitVal = ECD->getInitVal();
20262
20263 // If it fits into an integer type, force it. Otherwise force it to match
20264 // the enum decl type.
20265 QualType NewTy;
20266 unsigned NewWidth;
20267 bool NewSign;
20268 if (!getLangOpts().CPlusPlus &&
20269 !Enum->isFixed() &&
20271 NewTy = Context.IntTy;
20272 NewWidth = IntWidth;
20273 NewSign = true;
20274 } else if (ECD->getType() == BestType) {
20275 // Already the right type!
20276 if (getLangOpts().CPlusPlus)
20277 // C++ [dcl.enum]p4: Following the closing brace of an
20278 // enum-specifier, each enumerator has the type of its
20279 // enumeration.
20280 ECD->setType(EnumType);
20281 continue;
20282 } else {
20283 NewTy = BestType;
20284 NewWidth = BestWidth;
20285 NewSign = BestType->isSignedIntegerOrEnumerationType();
20286 }
20287
20288 // Adjust the APSInt value.
20289 InitVal = InitVal.extOrTrunc(NewWidth);
20290 InitVal.setIsSigned(NewSign);
20291 ECD->setInitVal(Context, InitVal);
20292
20293 // Adjust the Expr initializer and type.
20294 if (ECD->getInitExpr() &&
20295 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20296 ECD->setInitExpr(ImplicitCastExpr::Create(
20297 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20298 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20299 if (getLangOpts().CPlusPlus)
20300 // C++ [dcl.enum]p4: Following the closing brace of an
20301 // enum-specifier, each enumerator has the type of its
20302 // enumeration.
20303 ECD->setType(EnumType);
20304 else
20305 ECD->setType(NewTy);
20306 }
20307
20308 Enum->completeDefinition(BestType, BestPromotionType,
20309 NumPositiveBits, NumNegativeBits);
20310
20311 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20312
20313 if (Enum->isClosedFlag()) {
20314 for (Decl *D : Elements) {
20315 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20316 if (!ECD) continue; // Already issued a diagnostic.
20317
20318 llvm::APSInt InitVal = ECD->getInitVal();
20319 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20320 !IsValueInFlagEnum(Enum, InitVal, true))
20321 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20322 << ECD << Enum;
20323 }
20324 }
20325
20326 // Now that the enum type is defined, ensure it's not been underaligned.
20327 if (Enum->hasAttrs())
20329}
20330
20332 SourceLocation StartLoc,
20333 SourceLocation EndLoc) {
20334 StringLiteral *AsmString = cast<StringLiteral>(expr);
20335
20337 AsmString, StartLoc,
20338 EndLoc);
20339 CurContext->addDecl(New);
20340 return New;
20341}
20342
20344 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20345 CurContext->addDecl(New);
20346 PushDeclContext(S, New);
20348 PushCompoundScope(false);
20349 return New;
20350}
20351
20353 D->setStmt(Statement);
20357}
20358
20360 IdentifierInfo* AliasName,
20361 SourceLocation PragmaLoc,
20362 SourceLocation NameLoc,
20363 SourceLocation AliasNameLoc) {
20364 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20366 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20368 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20369 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20370
20371 // If a declaration that:
20372 // 1) declares a function or a variable
20373 // 2) has external linkage
20374 // already exists, add a label attribute to it.
20375 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20376 if (isDeclExternC(PrevDecl))
20377 PrevDecl->addAttr(Attr);
20378 else
20379 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20380 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20381 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20382 } else
20383 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20384}
20385
20387 SourceLocation PragmaLoc,
20388 SourceLocation NameLoc) {
20389 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20390
20391 if (PrevDecl) {
20392 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20393 } else {
20394 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20395 }
20396}
20397
20399 IdentifierInfo* AliasName,
20400 SourceLocation PragmaLoc,
20401 SourceLocation NameLoc,
20402 SourceLocation AliasNameLoc) {
20403 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20405 WeakInfo W = WeakInfo(Name, NameLoc);
20406
20407 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20408 if (!PrevDecl->hasAttr<AliasAttr>())
20409 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20411 } else {
20412 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20413 }
20414}
20415
20417 bool Final) {
20418 assert(FD && "Expected non-null FunctionDecl");
20419
20420 // SYCL functions can be template, so we check if they have appropriate
20421 // attribute prior to checking if it is a template.
20422 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20424
20425 // Templates are emitted when they're instantiated.
20426 if (FD->isDependentContext())
20428
20429 // Check whether this function is an externally visible definition.
20430 auto IsEmittedForExternalSymbol = [this, FD]() {
20431 // We have to check the GVA linkage of the function's *definition* -- if we
20432 // only have a declaration, we don't know whether or not the function will
20433 // be emitted, because (say) the definition could include "inline".
20434 const FunctionDecl *Def = FD->getDefinition();
20435
20436 return Def && !isDiscardableGVALinkage(
20437 getASTContext().GetGVALinkageForFunction(Def));
20438 };
20439
20440 if (LangOpts.OpenMPIsTargetDevice) {
20441 // In OpenMP device mode we will not emit host only functions, or functions
20442 // we don't need due to their linkage.
20443 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20444 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20445 // DevTy may be changed later by
20446 // #pragma omp declare target to(*) device_type(*).
20447 // Therefore DevTy having no value does not imply host. The emission status
20448 // will be checked again at the end of compilation unit with Final = true.
20449 if (DevTy)
20450 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20452 // If we have an explicit value for the device type, or we are in a target
20453 // declare context, we need to emit all extern and used symbols.
20454 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20455 if (IsEmittedForExternalSymbol())
20457 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20458 // we'll omit it.
20459 if (Final)
20461 } else if (LangOpts.OpenMP > 45) {
20462 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20463 // function. In 5.0, no_host was introduced which might cause a function to
20464 // be ommitted.
20465 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20466 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20467 if (DevTy)
20468 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20470 }
20471
20472 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20474
20475 if (LangOpts.CUDA) {
20476 // When compiling for device, host functions are never emitted. Similarly,
20477 // when compiling for host, device and global functions are never emitted.
20478 // (Technically, we do emit a host-side stub for global functions, but this
20479 // doesn't count for our purposes here.)
20481 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20483 if (!LangOpts.CUDAIsDevice &&
20486
20487 if (IsEmittedForExternalSymbol())
20489 }
20490
20491 // Otherwise, the function is known-emitted if it's in our set of
20492 // known-emitted functions.
20494}
20495
20497 // Host-side references to a __global__ function refer to the stub, so the
20498 // function itself is never emitted and therefore should not be marked.
20499 // If we have host fn calls kernel fn calls host+device, the HD function
20500 // does not get instantiated on the host. We model this by omitting at the
20501 // call to the kernel from the callgraph. This ensures that, when compiling
20502 // for host, only HD functions actually called from the host get marked as
20503 // known-emitted.
20504 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20506}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
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.
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:2226
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.
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15949
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6941
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:148
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15455
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11413
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:203
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3408
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:3575
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:816
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6628
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:1496
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:6666
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2345
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9237
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:3522
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2861
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8214
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9586
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3306
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7461
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8600
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11833
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:2750
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4493
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11939
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15439
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11549
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2092
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15083
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:563
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11422
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:7228
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:19585
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19949
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:5047
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:2989
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:17000
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3557
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6988
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:6005
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:4917
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9273
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:9769
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15978
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3464
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8569
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2719
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9458
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3104
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8239
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:17164
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:5332
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:8486
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1968
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9780
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:5412
OpenCLParamType
Definition: SemaDecl.cpp:9449
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9453
@ ValidKernelParam
Definition: SemaDecl.cpp:9450
@ InvalidKernelParam
Definition: SemaDecl.cpp:9454
@ RecordKernelParam
Definition: SemaDecl.cpp:9455
@ PtrKernelParam
Definition: SemaDecl.cpp:9452
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9451
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:6114
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:18942
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:583
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:18876
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7273
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5496
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11342
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:9760
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3369
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3501
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16984
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2221
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4383
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:9086
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:6040
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:18969
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:831
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7300
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8203
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8210
@ SDK_Field
Definition: SemaDecl.cpp:8207
@ SDK_Global
Definition: SemaDecl.cpp:8205
@ SDK_Local
Definition: SemaDecl.cpp:8204
@ SDK_Typedef
Definition: SemaDecl.cpp:8208
@ SDK_StaticMember
Definition: SemaDecl.cpp:8206
@ SDK_Using
Definition: SemaDecl.cpp:8209
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4863
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3485
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9480
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5510
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12562
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7353
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1825
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:19035
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11171
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1814
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2963
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:6550
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14887
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7449
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5987
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11438
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1879
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11121
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6902
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5475
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:245
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:11580
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:8230
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:11388
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7079
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11186
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:2469
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19913
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19602
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7259
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2738
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:11002
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1841
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:17201
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
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:15936
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15938
llvm::APInt getValue() const
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
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:57
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:145
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:705
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1100
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:648
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2086
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:1872
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
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:1976
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:1898
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1954
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:2774
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:1119
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:1591
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
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:775
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:496
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:2074
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:1988
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
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:2157
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1100
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:697
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:2064
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
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:2341
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:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1120
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
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:1569
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1421
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:2771
CanQualType ShortTy
Definition: ASTContext.h:1100
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1885
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:757
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:2180
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:1964
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:1100
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:2243
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2249
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2246
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2255
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2252
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:2372
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:3298
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:3518
QualType getElementType() const
Definition: Type.h:3530
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:5604
QualType getModifiedType() const
Definition: Type.h:5626
bool isCallingConv() const
Definition: Type.cpp:4079
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5659
SourceLocation getConceptNameLoc() const
Definition: TypeLoc.h:2219
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5981
AutoTypeKeyword getKeyword() const
Definition: Type.h:6012
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4295
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition: Expr.h:4283
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
Expr * getRHS() const
Definition: Expr.h:3891
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3980
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4494
bool doesNotEscape() const
Definition: Decl.h:4645
This class is used for builtin types like 'int'.
Definition: Type.h:2981
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:209
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 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:204
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:199
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:1542
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1685
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2762
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:2723
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
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:2890
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:2157
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
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:2857
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:2060
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:2455
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2509
bool isVirtual() const
Definition: DeclCXX.h:2115
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2576
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
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:2274
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
bool isConst() const
Definition: DeclCXX.h:2112
bool isStatic() const
Definition: DeclCXX.cpp:2186
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
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:1335
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
base_class_iterator bases_end()
Definition: DeclCXX.h:628
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1548
base_class_range bases()
Definition: DeclCXX.h:619
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1377
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
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:1930
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:626
capture_const_range captures() const
Definition: DeclCXX.h:1101
bool hasDefinition() const
Definition: DeclCXX.h:571
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1063
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1901
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1289
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h: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:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
bool isCallToStdMove() const
Definition: Expr.cpp:3510
Expr * getCallee()
Definition: Expr.h:2970
arg_range arguments()
Definition: Expr.h:3059
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CastKind getCastKind() const
Definition: Expr.h:3527
Expr * getSubExpr()
Definition: Expr.h:3533
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:4179
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:3612
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:2342
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:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1993
bool isObjCContainer() const
Definition: DeclBase.h:2105
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
bool isClosure() const
Definition: DeclBase.h:2099
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
bool isNamespace() const
Definition: DeclBase.h:2151
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1249
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1635
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1585
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1956
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1372
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1233
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1363
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:1260
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
ValueDecl * getDecl()
Definition: Expr.h:1328
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:645
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:826
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:592
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:641
void ClearStorageClassSpecs()
Definition: DeclSpec.h:512
bool isNoreturnSpecified() const
Definition: DeclSpec.h:658
TST getTypeSpecType() const
Definition: DeclSpec.h:534
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:856
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:572
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:571
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:706
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:613
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:705
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:659
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:502
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:651
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:827
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1497
ParsedType getRepAsType() const
Definition: DeclSpec.h:544
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:785
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:499
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:870
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:623
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:614
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:652
Expr * getRepAsExpr() const
Definition: DeclSpec.h:552
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:466
bool isInlineSpecified() const
Definition: DeclSpec.h:634
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:615
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
void ClearConstexprSpec()
Definition: DeclSpec.h:838
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:558
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:508
Decl * getRepAsDecl() const
Definition: DeclSpec.h:548
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:646
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:833
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:579
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:789
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:325
ExplicitSpecifier getExplicitSpecifier() const
Definition: DeclSpec.h:641
bool isTypeSpecOwned() const
Definition: DeclSpec.h:538
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:637
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:618
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:616
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:818
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:648
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:834
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:829
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:295
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
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:579
bool hasAttrs() const
Definition: DeclBase.h:524
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:526
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:754
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
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:638
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:262
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1090
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:555
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:833
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1121
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
void dropAttrs()
Definition: DeclBase.cpp:984
@ 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:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
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:565
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:820
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:614
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
DeclContext * getDeclContext()
Definition: DeclBase.h:454
attr_range attrs() const
Definition: DeclBase.h:541
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:828
void dropAttr()
Definition: DeclBase.h:562
AttrVec & getAttrs()
Definition: DeclBase.h:530
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1225
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
Kind getKind() const
Definition: DeclBase.h:448
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 isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2047
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2087
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:858
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1997
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2031
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2456
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
Expr * getAsmLabel() const
Definition: DeclSpec.h:2702
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2741
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2683
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2764
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2336
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2339
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2084
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2633
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2713
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition: DeclSpec.h:2663
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
bool isRedeclaration() const
Definition: DeclSpec.h:2765
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2686
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2068
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:436
bool isFunctionDefinition() const
Definition: DeclSpec.h:2737
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2066
bool hasInitializer() const
Definition: DeclSpec.h:2746
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2733
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2062
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2676
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2353
bool isInvalidType() const
Definition: DeclSpec.h:2714
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:424
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2082
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2326
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2749
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2054
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2487
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
A decomposition declaration.
Definition: DeclCXX.h:4166
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3360
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1789
SourceRange getSourceRange() const
Definition: DeclSpec.h:1836
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1834
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5947
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5968
bool isDeduced() const
Definition: Type.h:5969
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
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:3297
llvm::APSInt getInitVal() const
Definition: Decl.h:3317
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5453
const Expr * getInitExpr() const
Definition: Decl.h:3315
Represents an enum.
Definition: Decl.h:3867
enumerator_range enumerators() const
Definition: Decl.h:4000
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4072
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4036
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4039
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4086
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4852
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4897
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4081
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4872
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4022
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4027
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
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:3059
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:3055
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition: Expr.cpp:3287
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:915
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1028
bool isFPConstrained() const
Definition: LangOptions.h:843
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1022
Represents a member of a struct/union/class.
Definition: Decl.h:3057
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3148
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4560
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:4597
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
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:4545
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5586
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:1971
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2599
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2438
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3603
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4047
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3255
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2283
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2611
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2590
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3873
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
param_iterator param_end()
Definition: Decl.h:2696
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2830
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2605
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3576
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2351
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2339
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3488
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2410
void setWillHaveBody(bool V=true)
Definition: Decl.h:2596
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2405
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4172
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3617
param_iterator param_begin()
Definition: Decl.h:2695
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2732
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2295
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3314
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4106
@ TK_MemberSpecialization
Definition: Decl.h:1983
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2797
bool isStatic() const
Definition: Decl.h:2838
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4372
void setTrivial(bool IT)
Definition: Decl.h:2340
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
bool isDeletedAsWritten() const
Definition: Decl.h:2506
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2427
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2322
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3492
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2326
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2390
bool isImmediateEscalating() const
Definition: Decl.cpp:3268
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2318
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2589
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2251
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2825
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:3366
bool param_empty() const
Definition: Decl.h:2694
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:2160
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3180
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2189
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3572
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2347
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2383
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4395
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2842
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3987
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2435
void setDefaulted(bool D=true)
Definition: Decl.h:2348
bool isConsteval() const
Definition: Decl.h:2444
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:2771
void setBody(Stmt *B)
Definition: Decl.cpp:3248
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3506
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3126
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2421
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2182
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3156
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2397
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:3203
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2808
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3558
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2595
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
unsigned getNumParams() const
Definition: Type.h:4889
QualType getParamType(unsigned i) const
Definition: Type.h:4891
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4921
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4896
ArrayRef< QualType > param_types() const
Definition: Type.h:5044
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
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.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:522
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:4367
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4482
CallingConv getCC() const
Definition: Type.h:4429
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4448
unsigned getRegParm() const
Definition: Type.h:4422
bool getNoCallerSavedRegs() const
Definition: Type.h:4418
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4441
bool getHasRegParm() const
Definition: Type.h:4420
bool getNoReturn() const
Definition: Type.h:4415
bool getProducesResult() const
Definition: Type.h:4416
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4462
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4476
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
ExtInfo getExtInfo() const
Definition: Type.h:4585
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3485
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4543
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4539
unsigned getRegParmType() const
Definition: Type.h:4576
CallingConv getCallConv() const
Definition: Type.h:4584
QualType getReturnType() const
Definition: Type.h:4573
bool getCmseNSCallAttr() const
Definition: Type.h:4583
@ SME_PStateSMEnabledMask
Definition: Type.h:4517
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:3655
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:3703
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3341
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5481
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
Describes an C or C++ initializer list.
Definition: Expr.h:4847
child_range children()
Definition: Expr.h:5039
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:8601
@ 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:461
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:753
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:658
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
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:553
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:664
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:535
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:2934
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2920
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:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
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
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:631
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:597
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:1072
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:1082
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:419
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
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1850
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:686
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
bool isExternallyVisible() const
Definition: Decl.h:408
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1119
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:605
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.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
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:2326
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
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:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1760
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
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:1168
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:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:5664
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5653
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:3113
Represents a parameter to a function.
Definition: Decl.h:1761
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1821
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1825
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
QualType getOriginalType() const
Definition: Decl.cpp:2924
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:2915
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:7208
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:3139
QualType getPointeeType() const
Definition: Type.h:3149
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:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7437
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:7506
@ DK_nontrivial_c_struct
Definition: Type.h:1523
PrimitiveDefaultInitializeKind
Definition: Type.h:1451
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2823
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
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:2871
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7485
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:7500
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
std::optional< NonConstantStorageReason > isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Determine whether instances of this type can be placed in immutable storage.
Definition: Type.cpp:116
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2855
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1427
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
bool isCanonical() const
Definition: Type.h:7416
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1436
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2574
NonConstantStorageReason
Definition: Type.h:1024
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1481
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1486
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:7494
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7299
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7306
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4287
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
bool hasConst() const
Definition: Type.h:443
void removeConst()
Definition: Type.h:445
void addConst()
Definition: Type.h:446
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
bool empty() const
Definition: Type.h:633
Represents a struct/union/class.
Definition: Decl.h:4168
bool hasObjectMember() const
Definition: Decl.h:4228
field_range fields() const
Definition: Decl.h:4374
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5015
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5035
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5081
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4359
field_iterator field_begin() const
Definition: Decl.cpp:5069
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6909
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:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
redecl_iterator redecls_end() const
Definition: Redeclarable.h:303
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4994
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:223
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3067
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:56
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:658
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1061
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:210
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:128
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
Definition: SemaHLSL.cpp:143
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:176
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:1157
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:1443
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:578
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.
bool IsAlignAttr() const
Definition: Sema.h:1264
Mode getAlignMode() const
Definition: Sema.h:1266
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2531
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:927
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:939
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:2746
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:2756
static NameClassification Unknown()
Definition: Sema.h:2726
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:2730
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:2774
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:2762
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:2736
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:2768
static NameClassification UndeclaredNonType()
Definition: Sema.h:2742
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:2750
static NameClassification Error()
Definition: Sema.h:2724
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9410
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9440
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14340
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:11037
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6350
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6793
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9703
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:688
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:2546
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:8845
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:6711
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:9807
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
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:1585
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:15230
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:6291
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4599
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7285
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:7308
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7324
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:7321
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7297
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7292
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6729
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2237
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5365
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15920
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12980
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:40
NonTrivialCUnionContext
Definition: Sema.h:2982
@ NTCUC_CopyInit
Definition: Sema.h:2992
@ NTCUC_AutoVar
Definition: Sema.h:2990
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:2988
@ NTCUC_FunctionReturn
Definition: Sema.h:2986
@ NTCUC_FunctionParam
Definition: Sema.h:2984
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:3626
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:6198
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:992
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18353
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
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:6165
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:815
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18294
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:3468
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:2605
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1190
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:16461
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:4753
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15107
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:1093
SemaCUDA & CUDA()
Definition: Sema.h:993
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:17296
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.
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
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:1480
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:2251
Preprocessor & getPreprocessor() const
Definition: Sema.h:516
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6947
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1421
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1415
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:1161
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
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:6326
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:17081
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:4869
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:12402
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16677
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:2156
@ 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:18372
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:18472
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:14715
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:1456
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15562
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:1499
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3493
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:647
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1691
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:20331
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15217
ASTContext & Context
Definition: Sema.h:848
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14737
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5864
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20352
void * SkippedDefinitionContext
Definition: Sema.h:3228
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:918
SemaObjC & ObjC()
Definition: Sema.h:1003
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5374
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4979
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:67
@ AllowFold
Definition: Sema.h:5724
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1523
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1418
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:2613
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:2403
ASTContext & getASTContext() const
Definition: Sema.h:517
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:15992
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
Definition: SemaDecl.cpp:1756
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:17722
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1414
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:645
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:685
SmallVector< VarDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:2623
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3185
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:4824
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9217
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20496
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
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:5531
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
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:17035
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9073
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:9168
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6402
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:693
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:4406
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2132
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:1269
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:3363
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16928
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:512
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2150
void PopCompoundScope()
Definition: Sema.cpp:2289
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19807
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:10727
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:10730
@ UPPC_Initializer
An initializer.
Definition: Sema.h:10742
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:10736
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10715
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:10754
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:10739
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:10718
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:10721
const LangOptions & getLangOpts() const
Definition: Sema.h:510
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:1454
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:2630
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1413
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:6683
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:6721
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1628
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:847
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:8267
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:1916
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:846
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2366
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:11615
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15405
SemaHLSL & HLSL()
Definition: Sema.h:998
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1885
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11982
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:18577
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:1191
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:3695
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:19933
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.
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
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:1205
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1403
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:15878
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5149
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1413
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:692
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:9316
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:7905
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:880
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:17006
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1400
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8419
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:12581
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19833
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:882
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2284
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14969
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2362
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2337
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20386
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18767
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5146
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1215
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:18252
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:10754
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8946
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:652
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:3273
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11609
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1453
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20416
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7663
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:8968
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:15508
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init)
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18243
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15435
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15009
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5870
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
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:15272
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 ...
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:8461
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1311
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4767
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15841
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:2627
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:8953
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:15902
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:11057
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10402
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3145
@ NTK_Typedef
Definition: Sema.h:3150
@ NTK_NonUnion
Definition: Sema.h:3148
@ NTK_TypeAlias
Definition: Sema.h:3151
@ NTK_NonClass
Definition: Sema.h:3147
@ NTK_NonEnum
Definition: Sema.h:3149
@ NTK_NonStruct
Definition: Sema.h:3146
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3154
@ NTK_TypeAliasTemplate
Definition: Sema.h:3153
@ NTK_Template
Definition: Sema.h:3152
SourceManager & getSourceManager() const
Definition: Sema.h:515
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition: Sema.h:2580
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:4324
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20088
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:1365
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:11229
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18229
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:1192
@ NTCUK_Destruct
Definition: Sema.h:3012
@ NTCUK_Init
Definition: Sema.h:3011
@ NTCUK_Copy
Definition: Sema.h:3013
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1189
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20127
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15930
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:13959
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:1250
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:20359
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:4981
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:228
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:20343
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8301
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:7528
@ CTK_ErrorRecovery
Definition: Sema.h:7529
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14369
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14892
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2307
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:4530
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:4775
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:593
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:7950
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18834
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3157
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:1948
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:2601
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:291
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19626
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12616
ASTConsumer & Consumer
Definition: Sema.h:849
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3391
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:7858
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:7850
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:7854
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:5153
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2105
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:887
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1622
@ 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:16599
@ 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:3317
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:3319
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:3325
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:3328
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:3331
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:3322
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15013
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5678
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14678
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:17229
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:4849
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:8831
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15357
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:820
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1358
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20777
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19080
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:1184
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:11090
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:2620
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17800
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6364
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1330
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:851
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:5820
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15987
DiagnosticsEngine & Diags
Definition: Sema.h:850
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:511
FPOptions CurFPFeatures
Definition: Sema.h:844
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15983
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6746
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1412
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:650
@ TUK_Definition
Definition: Sema.h:3168
@ TUK_Declaration
Definition: Sema.h:3167
@ TUK_Friend
Definition: Sema.h:3169
@ TUK_Reference
Definition: Sema.h:3166
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7320
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:15046
@ TPC_FriendFunctionTemplate
Definition: Sema.h:8903
@ TPC_ClassTemplateMember
Definition: Sema.h:8901
@ TPC_FunctionTemplate
Definition: Sema.h:8900
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:8904
@ TPC_VarTemplate
Definition: Sema.h:8899
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:6833
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16446
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2123
void PopDeclContext()
Definition: SemaDecl.cpp:1337
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4787
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:1607
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:8976
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14001
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:13162
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:1590
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16871
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2349
OffsetOfKind
Definition: Sema.h:3172
@ OOK_Outside
Definition: Sema.h:3174
@ OOK_Macro
Definition: Sema.h:3179
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13438
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:18462
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:4360
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:14286
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:280
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:2595
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
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:21042
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1188
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6132
@ AbstractVariableType
Definition: Sema.h:4548
@ AbstractReturnType
Definition: Sema.h:4546
@ AbstractFieldType
Definition: Sema.h:4549
@ AbstractIvarType
Definition: Sema.h:4550
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)
Definition: SemaDecl.cpp:1730
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6406
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:1259
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:7919
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20398
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8632
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:1344
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13128
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:2507
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2805
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:2576
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1168
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:15867
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:13414
IdentifierResolver IdResolver
Definition: Sema.h:2524
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:20059
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2298
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:701
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:15246
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:6372
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:2867
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6119
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:16947
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:218
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7488
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:6652
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:1286
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:1773
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1926
StringRef getString() const
Definition: Expr.h:1850
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3859
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3707
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3682
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3668
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3687
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3812
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4737
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4728
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4720
bool isUnion() const
Definition: Decl.h:3790
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4783
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4820
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3808
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3725
TagKind getTagKind() const
Definition: Decl.h:3779
void setBraceRange(SourceRange R)
Definition: Decl.h:3664
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:1518
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:1797
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:1561
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1569
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1504
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:1483
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:1472
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:202
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:6089
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4209
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:4457
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5601
void setStmt(Stmt *S)
Definition: Decl.cpp:5621
Represents a declaration of a type.
Definition: Decl.h:3390
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3415
const Type * getTypeForDecl() const
Definition: Decl.h:3414
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:740
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:747
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:7330
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:7341
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6352
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3134
The base class of the type hierarchy.
Definition: Type.h:1813
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:2455
bool isStructureType() const
Definition: Type.cpp:629
bool isDecltypeType() const
Definition: Type.h:7799
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isDependentSizedArrayType() const
Definition: Type.h:7698
bool isBlockPointerType() const
Definition: Type.h:7620
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
bool isFunctionReferenceType() const
Definition: Type.h:7653
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2156
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8083
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:730
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2893
bool isIncompleteArrayType() const
Definition: Type.h:7686
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8202
bool isDependentAddressSpaceType() const
Definition: Type.h:7740
bool isConstantArrayType() const
Definition: Type.h:7682
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8063
bool isVoidPointerType() const
Definition: Type.cpp:655
bool isArrayType() const
Definition: Type.h:7678
bool isFunctionPointerType() const
Definition: Type.h:7646
bool isPointerType() const
Definition: Type.h:7612
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2461
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
bool isScalarType() const
Definition: Type.h:8004
bool isVariableArrayType() const
Definition: Type.h:7690
bool isClkEventT() const
Definition: Type.h:7817
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool isImageType() const
Definition: Type.h:7829
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2758
bool isPipeType() const
Definition: Type.h:7836
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2661
bool isBitIntType() const
Definition: Type.h:7840
bool isOpenCLSpecificType() const
Definition: Type.h:7865
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2327
bool isHalfType() const
Definition: Type.h:7909
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2000
const RecordType * getAsStructureType() const
Definition: Type.cpp:711
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2445
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2647
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8076
bool isAtomicType() const
Definition: Type.h:7757
bool isFunctionProtoType() const
Definition: Type.h:2494
bool isObjCIdType() const
Definition: Type.h:7777
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
bool isObjCObjectType() const
Definition: Type.h:7748
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4898
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool isEventT() const
Definition: Type.h:7813
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4841
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8143
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool isMemberFunctionPointerType() const
Definition: Type.h:7664
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2475
bool isFloatingType() const
Definition: Type.cpp:2238
bool isAnyPointerType() const
Definition: Type.h:7616
TypeClass getTypeClass() const
Definition: Type.h:2300
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2005
bool isSamplerT() const
Definition: Type.h:7809
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
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:7938
bool isRecordType() const
Definition: Type.h:7706
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4625
bool isUnionType() const
Definition: Type.cpp:661
bool isFunctionNoProtoType() const
Definition: Type.h:2493
bool isReserveIDT() const
Definition: Type.h:7825
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:1879
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2457
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1875
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3534
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5503
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3432
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3482
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3498
QualType getUnderlyingType() const
Definition: Decl.h:3487
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3494
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5512
TypedefNameDecl * getDecl() const
Definition: Type.h:5217
QualType desugar() const
Definition: Type.cpp:3828
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:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2283
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1234
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1083
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1107
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1077
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
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:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3113
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5371
Represents a variable declaration or definition.
Definition: Decl.h:918
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2787
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1505
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1549
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool hasInit() const
Definition: Decl.cpp:2395
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1432
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2257
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
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:2438
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2254
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
bool isCXXCondDecl() const
Definition: Decl.h:1595
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:929
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:932
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:926
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2160
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1577
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2363
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2463
void setInlineSpecified()
Definition: Decl.h:1538
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1195
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1329
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1160
bool checkForConstantInitialization(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the initializer of this variable to determine whether it's a constant initializer.
Definition: Decl.cpp:2637
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1531
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1164
const Expr * getInit() const
Definition: Decl.h:1355
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1204
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2423
void setConstexpr(bool IC)
Definition: Decl.h:1552
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:941
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:944
void setInit(Expr *I)
Definition: Decl.cpp:2454
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2342
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1285
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1282
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1288
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2792
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2242
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1240
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
void setImplicitlyInline()
Definition: Decl.h:1543
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1456
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1572
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2683
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1249
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:2756
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1466
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
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:3747
Expr * getSizeExpr() const
Definition: Type.h:3766
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:36
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:1883
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ GNUMode
Definition: LangStandard.h:63
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
@ 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:132
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:268
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
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:44
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:245
@ SC_Auto
Definition: Specifiers.h:253
@ SC_PrivateExtern
Definition: Specifiers.h:250
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:238
@ TSCS_unspecified
Definition: Specifiers.h:233
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:241
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:235
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:54
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:304
TagTypeKind
The kind of a tag type.
Definition: Type.h:6299
@ 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:109
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:1035
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:425
@ 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:132
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:1950
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:367
@ 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:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_X86StdCall
Definition: Specifiers.h:277
@ 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:5760
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:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
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:1425
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1576
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1359
const IdentifierInfo * Ident
Definition: DeclSpec.h:1331
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1248
enum clang::DeclaratorChunk::@221 Kind
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1660
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:1641
FunctionTypeInfo Fun
Definition: DeclSpec.h:1639
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1684
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:4735
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:4754
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:1185
ValueType CurrentValue
Definition: Sema.h:1388
bool CheckSameAsPrevious
Definition: Sema.h:353
NamedDecl * Previous
Definition: Sema.h:354
NamedDecl * New
Definition: Sema.h:355
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.