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"
49#include "clang/Sema/Template.h"
50#include "llvm/ADT/SmallString.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/TargetParser/Triple.h"
53#include <algorithm>
54#include <cstring>
55#include <functional>
56#include <optional>
57#include <unordered_map>
58
59using namespace clang;
60using namespace sema;
61
63 if (OwnedType) {
64 Decl *Group[2] = { OwnedType, Ptr };
66 }
67
69}
70
71namespace {
72
73class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
74 public:
75 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
76 bool AllowTemplates = false,
77 bool AllowNonTemplates = true)
78 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
79 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
80 WantExpressionKeywords = false;
81 WantCXXNamedCasts = false;
82 WantRemainingKeywords = false;
83 }
84
85 bool ValidateCandidate(const TypoCorrection &candidate) override {
86 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
87 if (!AllowInvalidDecl && ND->isInvalidDecl())
88 return false;
89
91 return AllowTemplates;
92
93 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
94 if (!IsType)
95 return false;
96
97 if (AllowNonTemplates)
98 return true;
99
100 // An injected-class-name of a class template (specialization) is valid
101 // as a template or as a non-template.
102 if (AllowTemplates) {
103 auto *RD = dyn_cast<CXXRecordDecl>(ND);
104 if (!RD || !RD->isInjectedClassName())
105 return false;
106 RD = cast<CXXRecordDecl>(RD->getDeclContext());
107 return RD->getDescribedClassTemplate() ||
108 isa<ClassTemplateSpecializationDecl>(RD);
109 }
110
111 return false;
112 }
113
114 return !WantClassName && candidate.isKeyword();
115 }
116
117 std::unique_ptr<CorrectionCandidateCallback> clone() override {
118 return std::make_unique<TypeNameValidatorCCC>(*this);
119 }
120
121 private:
122 bool AllowInvalidDecl;
123 bool WantClassName;
124 bool AllowTemplates;
125 bool AllowNonTemplates;
126};
127
128} // end anonymous namespace
129
130namespace {
131enum class UnqualifiedTypeNameLookupResult {
132 NotFound,
133 FoundNonType,
134 FoundType
135};
136} // end anonymous namespace
137
138/// Tries to perform unqualified lookup of the type decls in bases for
139/// dependent class.
140/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
141/// type decl, \a FoundType if only type decls are found.
142static UnqualifiedTypeNameLookupResult
144 SourceLocation NameLoc,
145 const CXXRecordDecl *RD) {
146 if (!RD->hasDefinition())
147 return UnqualifiedTypeNameLookupResult::NotFound;
148 // Look for type decls in base classes.
149 UnqualifiedTypeNameLookupResult FoundTypeDecl =
150 UnqualifiedTypeNameLookupResult::NotFound;
151 for (const auto &Base : RD->bases()) {
152 const CXXRecordDecl *BaseRD = nullptr;
153 if (auto *BaseTT = Base.getType()->getAs<TagType>())
154 BaseRD = BaseTT->getAsCXXRecordDecl();
155 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
156 // Look for type decls in dependent base classes that have known primary
157 // templates.
158 if (!TST || !TST->isDependentType())
159 continue;
160 auto *TD = TST->getTemplateName().getAsTemplateDecl();
161 if (!TD)
162 continue;
163 if (auto *BasePrimaryTemplate =
164 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
165 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
166 BaseRD = BasePrimaryTemplate;
167 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
169 CTD->findPartialSpecialization(Base.getType()))
170 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
171 BaseRD = PS;
172 }
173 }
174 }
175 if (BaseRD) {
176 for (NamedDecl *ND : BaseRD->lookup(&II)) {
177 if (!isa<TypeDecl>(ND))
178 return UnqualifiedTypeNameLookupResult::FoundNonType;
179 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
180 }
181 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
182 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
183 case UnqualifiedTypeNameLookupResult::FoundNonType:
184 return UnqualifiedTypeNameLookupResult::FoundNonType;
185 case UnqualifiedTypeNameLookupResult::FoundType:
186 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
187 break;
188 case UnqualifiedTypeNameLookupResult::NotFound:
189 break;
190 }
191 }
192 }
193 }
194
195 return FoundTypeDecl;
196}
197
199 const IdentifierInfo &II,
200 SourceLocation NameLoc) {
201 // Lookup in the parent class template context, if any.
202 const CXXRecordDecl *RD = nullptr;
203 UnqualifiedTypeNameLookupResult FoundTypeDecl =
204 UnqualifiedTypeNameLookupResult::NotFound;
205 for (DeclContext *DC = S.CurContext;
206 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
207 DC = DC->getParent()) {
208 // Look for type decls in dependent base classes that have known primary
209 // templates.
210 RD = dyn_cast<CXXRecordDecl>(DC);
211 if (RD && RD->getDescribedClassTemplate())
212 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
213 }
214 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
215 return nullptr;
216
217 // We found some types in dependent base classes. Recover as if the user
218 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
219 // lookup during template instantiation.
220 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
221
222 ASTContext &Context = S.Context;
223 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
224 cast<Type>(Context.getRecordType(RD)));
225 QualType T =
227
228 CXXScopeSpec SS;
229 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
230
231 TypeLocBuilder Builder;
232 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
233 DepTL.setNameLoc(NameLoc);
235 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
236 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
237}
238
239/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
241 SourceLocation NameLoc,
242 bool WantNontrivialTypeSourceInfo = true) {
243 switch (T->getTypeClass()) {
244 case Type::DeducedTemplateSpecialization:
245 case Type::Enum:
246 case Type::InjectedClassName:
247 case Type::Record:
248 case Type::Typedef:
249 case Type::UnresolvedUsing:
250 case Type::Using:
251 break;
252 // These can never be qualified so an ElaboratedType node
253 // would carry no additional meaning.
254 case Type::ObjCInterface:
255 case Type::ObjCTypeParam:
256 case Type::TemplateTypeParm:
257 return ParsedType::make(T);
258 default:
259 llvm_unreachable("Unexpected Type Class");
260 }
261
262 if (!SS || SS->isEmpty())
264 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
265
267 if (!WantNontrivialTypeSourceInfo)
268 return ParsedType::make(ElTy);
269
270 TypeLocBuilder Builder;
271 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
272 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
275 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
276}
277
278/// If the identifier refers to a type name within this scope,
279/// return the declaration of that type.
280///
281/// This routine performs ordinary name lookup of the identifier II
282/// within the given scope, with optional C++ scope specifier SS, to
283/// determine whether the name refers to a type. If so, returns an
284/// opaque pointer (actually a QualType) corresponding to that
285/// type. Otherwise, returns NULL.
287 Scope *S, CXXScopeSpec *SS, bool isClassName,
288 bool HasTrailingDot, ParsedType ObjectTypePtr,
289 bool IsCtorOrDtorName,
290 bool WantNontrivialTypeSourceInfo,
291 bool IsClassTemplateDeductionContext,
292 ImplicitTypenameContext AllowImplicitTypename,
293 IdentifierInfo **CorrectedII) {
294 // FIXME: Consider allowing this outside C++1z mode as an extension.
295 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297 !isClassName && !HasTrailingDot;
298
299 // Determine where we will perform name lookup.
300 DeclContext *LookupCtx = nullptr;
301 if (ObjectTypePtr) {
302 QualType ObjectType = ObjectTypePtr.get();
303 if (ObjectType->isRecordType())
304 LookupCtx = computeDeclContext(ObjectType);
305 } else if (SS && SS->isNotEmpty()) {
306 LookupCtx = computeDeclContext(*SS, false);
307
308 if (!LookupCtx) {
309 if (isDependentScopeSpecifier(*SS)) {
310 // C++ [temp.res]p3:
311 // A qualified-id that refers to a type and in which the
312 // nested-name-specifier depends on a template-parameter (14.6.2)
313 // shall be prefixed by the keyword typename to indicate that the
314 // qualified-id denotes a type, forming an
315 // elaborated-type-specifier (7.1.5.3).
316 //
317 // We therefore do not perform any name lookup if the result would
318 // refer to a member of an unknown specialization.
319 // In C++2a, in several contexts a 'typename' is not required. Also
320 // allow this as an extension.
321 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
322 !isClassName && !IsCtorOrDtorName)
323 return nullptr;
324 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
325 if (IsImplicitTypename) {
326 SourceLocation QualifiedLoc = SS->getRange().getBegin();
328 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
329 else
330 Diag(QualifiedLoc, diag::ext_implicit_typename)
331 << SS->getScopeRep() << II.getName()
332 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
333 }
334
335 // We know from the grammar that this name refers to a type,
336 // so build a dependent node to describe the type.
337 if (WantNontrivialTypeSourceInfo)
338 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
339 (ImplicitTypenameContext)IsImplicitTypename)
340 .get();
341
344 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
346 SourceLocation(), QualifierLoc, II, NameLoc);
347 return ParsedType::make(T);
348 }
349
350 return nullptr;
351 }
352
353 if (!LookupCtx->isDependentContext() &&
354 RequireCompleteDeclContext(*SS, LookupCtx))
355 return nullptr;
356 }
357
358 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
359 // lookup for class-names.
360 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
362 LookupResult Result(*this, &II, NameLoc, Kind);
363 if (LookupCtx) {
364 // Perform "qualified" name lookup into the declaration context we
365 // computed, which is either the type of the base of a member access
366 // expression or the declaration context associated with a prior
367 // nested-name-specifier.
368 LookupQualifiedName(Result, LookupCtx);
369
370 if (ObjectTypePtr && Result.empty()) {
371 // C++ [basic.lookup.classref]p3:
372 // If the unqualified-id is ~type-name, the type-name is looked up
373 // in the context of the entire postfix-expression. If the type T of
374 // the object expression is of a class type C, the type-name is also
375 // looked up in the scope of class C. At least one of the lookups shall
376 // find a name that refers to (possibly cv-qualified) T.
377 LookupName(Result, S);
378 }
379 } else {
380 // Perform unqualified name lookup.
381 LookupName(Result, S);
382
383 // For unqualified lookup in a class template in MSVC mode, look into
384 // dependent base classes where the primary class template is known.
385 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
386 if (ParsedType TypeInBase =
387 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
388 return TypeInBase;
389 }
390 }
391
392 NamedDecl *IIDecl = nullptr;
393 UsingShadowDecl *FoundUsingShadow = nullptr;
394 switch (Result.getResultKind()) {
396 if (CorrectedII) {
397 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
398 AllowDeducedTemplate);
399 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
400 S, SS, CCC, CTK_ErrorRecovery);
401 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
402 TemplateTy Template;
403 bool MemberOfUnknownSpecialization;
405 TemplateName.setIdentifier(NewII, NameLoc);
407 CXXScopeSpec NewSS, *NewSSPtr = SS;
408 if (SS && NNS) {
409 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
410 NewSSPtr = &NewSS;
411 }
412 if (Correction && (NNS || NewII != &II) &&
413 // Ignore a correction to a template type as the to-be-corrected
414 // identifier is not a template (typo correction for template names
415 // is handled elsewhere).
416 !(getLangOpts().CPlusPlus && NewSSPtr &&
417 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
418 Template, MemberOfUnknownSpecialization))) {
419 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
420 isClassName, HasTrailingDot, ObjectTypePtr,
421 IsCtorOrDtorName,
422 WantNontrivialTypeSourceInfo,
423 IsClassTemplateDeductionContext);
424 if (Ty) {
425 diagnoseTypo(Correction,
426 PDiag(diag::err_unknown_type_or_class_name_suggest)
427 << Result.getLookupName() << isClassName);
428 if (SS && NNS)
429 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
430 *CorrectedII = NewII;
431 return Ty;
432 }
433 }
434 }
435 Result.suppressDiagnostics();
436 return nullptr;
438 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
440 SS->getScopeRep(), &II);
441 TypeLocBuilder TLB;
445 TL.setNameLoc(NameLoc);
446 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
447 }
448 [[fallthrough]];
451 Result.suppressDiagnostics();
452 return nullptr;
453
455 // Recover from type-hiding ambiguities by hiding the type. We'll
456 // do the lookup again when looking for an object, and we can
457 // diagnose the error then. If we don't do this, then the error
458 // about hiding the type will be immediately followed by an error
459 // that only makes sense if the identifier was treated like a type.
460 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
461 Result.suppressDiagnostics();
462 return nullptr;
463 }
464
465 // Look to see if we have a type anywhere in the list of results.
466 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
467 Res != ResEnd; ++Res) {
468 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
469 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
470 RealRes) ||
471 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
472 if (!IIDecl ||
473 // Make the selection of the recovery decl deterministic.
474 RealRes->getLocation() < IIDecl->getLocation()) {
475 IIDecl = RealRes;
476 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
477 }
478 }
479 }
480
481 if (!IIDecl) {
482 // None of the entities we found is a type, so there is no way
483 // to even assume that the result is a type. In this case, don't
484 // complain about the ambiguity. The parser will either try to
485 // perform this lookup again (e.g., as an object name), which
486 // will produce the ambiguity, or will complain that it expected
487 // a type name.
488 Result.suppressDiagnostics();
489 return nullptr;
490 }
491
492 // We found a type within the ambiguous lookup; diagnose the
493 // ambiguity and then return that type. This might be the right
494 // answer, or it might not be, but it suppresses any attempt to
495 // perform the name lookup again.
496 break;
497
499 IIDecl = Result.getFoundDecl();
500 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
501 break;
502 }
503
504 assert(IIDecl && "Didn't find decl");
505
506 QualType T;
507 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
508 // C++ [class.qual]p2: A lookup that would find the injected-class-name
509 // instead names the constructors of the class, except when naming a class.
510 // This is ill-formed when we're not actually forming a ctor or dtor name.
511 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
512 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
513 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
514 FoundRD->isInjectedClassName() &&
515 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
516 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
517 << &II << /*Type*/1;
518
519 DiagnoseUseOfDecl(IIDecl, NameLoc);
520
521 T = Context.getTypeDeclType(TD);
522 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
523 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
524 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
525 if (!HasTrailingDot)
526 T = Context.getObjCInterfaceType(IDecl);
527 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
528 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
529 (void)DiagnoseUseOfDecl(UD, NameLoc);
530 // Recover with 'int'
532 } else if (AllowDeducedTemplate) {
533 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
534 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
535 TemplateName Template =
536 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
538 false);
539 // Don't wrap in a further UsingType.
540 FoundUsingShadow = nullptr;
541 }
542 }
543
544 if (T.isNull()) {
545 // If it's not plausibly a type, suppress diagnostics.
546 Result.suppressDiagnostics();
547 return nullptr;
548 }
549
550 if (FoundUsingShadow)
551 T = Context.getUsingType(FoundUsingShadow, T);
552
553 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
554}
555
556// Builds a fake NNS for the given decl context.
557static NestedNameSpecifier *
559 for (;; DC = DC->getLookupParent()) {
560 DC = DC->getPrimaryContext();
561 auto *ND = dyn_cast<NamespaceDecl>(DC);
562 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
563 return NestedNameSpecifier::Create(Context, nullptr, ND);
564 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
565 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
566 RD->getTypeForDecl());
567 else if (isa<TranslationUnitDecl>(DC))
569 }
570 llvm_unreachable("something isn't in TU scope?");
571}
572
573/// Find the parent class with dependent bases of the innermost enclosing method
574/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
575/// up allowing unqualified dependent type names at class-level, which MSVC
576/// correctly rejects.
577static const CXXRecordDecl *
579 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
580 DC = DC->getPrimaryContext();
581 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
582 if (MD->getParent()->hasAnyDependentBases())
583 return MD->getParent();
584 }
585 return nullptr;
586}
587
589 SourceLocation NameLoc,
590 bool IsTemplateTypeArg) {
591 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
592
593 NestedNameSpecifier *NNS = nullptr;
594 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
595 // If we weren't able to parse a default template argument, delay lookup
596 // until instantiation time by making a non-dependent DependentTypeName. We
597 // pretend we saw a NestedNameSpecifier referring to the current scope, and
598 // lookup is retried.
599 // FIXME: This hurts our diagnostic quality, since we get errors like "no
600 // type named 'Foo' in 'current_namespace'" when the user didn't write any
601 // name specifiers.
603 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
604 } else if (const CXXRecordDecl *RD =
606 // Build a DependentNameType that will perform lookup into RD at
607 // instantiation time.
608 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
609 RD->getTypeForDecl());
610
611 // Diagnose that this identifier was undeclared, and retry the lookup during
612 // template instantiation.
613 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
614 << RD;
615 } else {
616 // This is not a situation that we should recover from.
617 return ParsedType();
618 }
619
620 QualType T =
622
623 // Build type location information. We synthesized the qualifier, so we have
624 // to build a fake NestedNameSpecifierLoc.
625 NestedNameSpecifierLocBuilder NNSLocBuilder;
626 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
627 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
628
629 TypeLocBuilder Builder;
630 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
631 DepTL.setNameLoc(NameLoc);
633 DepTL.setQualifierLoc(QualifierLoc);
634 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
635}
636
637/// isTagName() - This method is called *for error recovery purposes only*
638/// to determine if the specified name is a valid tag name ("struct foo"). If
639/// so, this returns the TST for the tag corresponding to it (TST_enum,
640/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
641/// cases in C where the user forgot to specify the tag.
643 // Do a tag name lookup in this scope.
644 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
645 LookupName(R, S, false);
648 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
649 switch (TD->getTagKind()) {
655 return DeclSpec::TST_union;
657 return DeclSpec::TST_class;
659 return DeclSpec::TST_enum;
660 }
661 }
662
664}
665
666/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
667/// if a CXXScopeSpec's type is equal to the type of one of the base classes
668/// then downgrade the missing typename error to a warning.
669/// This is needed for MSVC compatibility; Example:
670/// @code
671/// template<class T> class A {
672/// public:
673/// typedef int TYPE;
674/// };
675/// template<class T> class B : public A<T> {
676/// public:
677/// A<T>::TYPE a; // no typename required because A<T> is a base class.
678/// };
679/// @endcode
681 if (CurContext->isRecord()) {
683 return true;
684
685 const Type *Ty = SS->getScopeRep()->getAsType();
686
687 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
688 for (const auto &Base : RD->bases())
689 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
690 return true;
691 return S->isFunctionPrototypeScope();
692 }
693 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
694}
695
697 SourceLocation IILoc,
698 Scope *S,
699 CXXScopeSpec *SS,
700 ParsedType &SuggestedType,
701 bool IsTemplateName) {
702 // Don't report typename errors for editor placeholders.
703 if (II->isEditorPlaceholder())
704 return;
705 // We don't have anything to suggest (yet).
706 SuggestedType = nullptr;
707
708 // There may have been a typo in the name of the type. Look up typo
709 // results, in case we have something that we can suggest.
710 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
711 /*AllowTemplates=*/IsTemplateName,
712 /*AllowNonTemplates=*/!IsTemplateName);
713 if (TypoCorrection Corrected =
715 CCC, CTK_ErrorRecovery)) {
716 // FIXME: Support error recovery for the template-name case.
717 bool CanRecover = !IsTemplateName;
718 if (Corrected.isKeyword()) {
719 // We corrected to a keyword.
720 diagnoseTypo(Corrected,
721 PDiag(IsTemplateName ? diag::err_no_template_suggest
722 : diag::err_unknown_typename_suggest)
723 << II);
724 II = Corrected.getCorrectionAsIdentifierInfo();
725 } else {
726 // We found a similarly-named type or interface; suggest that.
727 if (!SS || !SS->isSet()) {
728 diagnoseTypo(Corrected,
729 PDiag(IsTemplateName ? diag::err_no_template_suggest
730 : diag::err_unknown_typename_suggest)
731 << II, CanRecover);
732 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
733 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
734 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
735 II->getName().equals(CorrectedStr);
736 diagnoseTypo(Corrected,
737 PDiag(IsTemplateName
738 ? diag::err_no_member_template_suggest
739 : diag::err_unknown_nested_typename_suggest)
740 << II << DC << DroppedSpecifier << SS->getRange(),
741 CanRecover);
742 } else {
743 llvm_unreachable("could not have corrected a typo here");
744 }
745
746 if (!CanRecover)
747 return;
748
749 CXXScopeSpec tmpSS;
750 if (Corrected.getCorrectionSpecifier())
751 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
752 SourceRange(IILoc));
753 // FIXME: Support class template argument deduction here.
754 SuggestedType =
755 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
756 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
757 /*IsCtorOrDtorName=*/false,
758 /*WantNontrivialTypeSourceInfo=*/true);
759 }
760 return;
761 }
762
763 if (getLangOpts().CPlusPlus && !IsTemplateName) {
764 // See if II is a class template that the user forgot to pass arguments to.
765 UnqualifiedId Name;
766 Name.setIdentifier(II, IILoc);
767 CXXScopeSpec EmptySS;
768 TemplateTy TemplateResult;
769 bool MemberOfUnknownSpecialization;
770 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
771 Name, nullptr, true, TemplateResult,
772 MemberOfUnknownSpecialization) == TNK_Type_template) {
773 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
774 return;
775 }
776 }
777
778 // FIXME: Should we move the logic that tries to recover from a missing tag
779 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
780
781 if (!SS || (!SS->isSet() && !SS->isInvalid()))
782 Diag(IILoc, IsTemplateName ? diag::err_no_template
783 : diag::err_unknown_typename)
784 << II;
785 else if (DeclContext *DC = computeDeclContext(*SS, false))
786 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
787 : diag::err_typename_nested_not_found)
788 << II << DC << SS->getRange();
789 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
790 SuggestedType =
791 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
792 } else if (isDependentScopeSpecifier(*SS)) {
793 unsigned DiagID = diag::err_typename_missing;
794 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
795 DiagID = diag::ext_typename_missing;
796
797 Diag(SS->getRange().getBegin(), DiagID)
798 << SS->getScopeRep() << II->getName()
799 << SourceRange(SS->getRange().getBegin(), IILoc)
800 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
801 SuggestedType = ActOnTypenameType(S, SourceLocation(),
802 *SS, *II, IILoc).get();
803 } else {
804 assert(SS && SS->isInvalid() &&
805 "Invalid scope specifier has already been diagnosed");
806 }
807}
808
809/// Determine whether the given result set contains either a type name
810/// or
811static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
812 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
813 NextToken.is(tok::less);
814
815 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
816 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
817 return true;
818
819 if (CheckTemplate && isa<TemplateDecl>(*I))
820 return true;
821 }
822
823 return false;
824}
825
827 Scope *S, CXXScopeSpec &SS,
828 IdentifierInfo *&Name,
829 SourceLocation NameLoc) {
830 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
831 SemaRef.LookupParsedName(R, S, &SS);
832 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
833 StringRef FixItTagName;
834 switch (Tag->getTagKind()) {
836 FixItTagName = "class ";
837 break;
838
840 FixItTagName = "enum ";
841 break;
842
844 FixItTagName = "struct ";
845 break;
846
848 FixItTagName = "__interface ";
849 break;
850
852 FixItTagName = "union ";
853 break;
854 }
855
856 StringRef TagName = FixItTagName.drop_back();
857 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
858 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
859 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
860
861 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
862 I != IEnd; ++I)
863 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
864 << Name << TagName;
865
866 // Replace lookup results with just the tag decl.
868 SemaRef.LookupParsedName(Result, S, &SS);
869 return true;
870 }
871
872 return false;
873}
874
876 IdentifierInfo *&Name,
877 SourceLocation NameLoc,
878 const Token &NextToken,
880 DeclarationNameInfo NameInfo(Name, NameLoc);
881 ObjCMethodDecl *CurMethod = getCurMethodDecl();
882
883 assert(NextToken.isNot(tok::coloncolon) &&
884 "parse nested name specifiers before calling ClassifyName");
885 if (getLangOpts().CPlusPlus && SS.isSet() &&
886 isCurrentClassName(*Name, S, &SS)) {
887 // Per [class.qual]p2, this names the constructors of SS, not the
888 // injected-class-name. We don't have a classification for that.
889 // There's not much point caching this result, since the parser
890 // will reject it later.
892 }
893
894 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
895 LookupParsedName(Result, S, &SS, !CurMethod);
896
897 if (SS.isInvalid())
899
900 // For unqualified lookup in a class template in MSVC mode, look into
901 // dependent base classes where the primary class template is known.
902 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
903 if (ParsedType TypeInBase =
904 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
905 return TypeInBase;
906 }
907
908 // Perform lookup for Objective-C instance variables (including automatically
909 // synthesized instance variables), if we're in an Objective-C method.
910 // FIXME: This lookup really, really needs to be folded in to the normal
911 // unqualified lookup mechanism.
912 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
914 if (Ivar.isInvalid())
916 if (Ivar.isUsable())
917 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
918
919 // We defer builtin creation until after ivar lookup inside ObjC methods.
920 if (Result.empty())
922 }
923
924 bool SecondTry = false;
925 bool IsFilteredTemplateName = false;
926
927Corrected:
928 switch (Result.getResultKind()) {
930 // If an unqualified-id is followed by a '(', then we have a function
931 // call.
932 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
933 // In C++, this is an ADL-only call.
934 // FIXME: Reference?
937
938 // C90 6.3.2.2:
939 // If the expression that precedes the parenthesized argument list in a
940 // function call consists solely of an identifier, and if no
941 // declaration is visible for this identifier, the identifier is
942 // implicitly declared exactly as if, in the innermost block containing
943 // the function call, the declaration
944 //
945 // extern int identifier ();
946 //
947 // appeared.
948 //
949 // We also allow this in C99 as an extension. However, this is not
950 // allowed in all language modes as functions without prototypes may not
951 // be supported.
952 if (getLangOpts().implicitFunctionsAllowed()) {
953 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
955 }
956 }
957
958 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
959 // In C++20 onwards, this could be an ADL-only call to a function
960 // template, and we're required to assume that this is a template name.
961 //
962 // FIXME: Find a way to still do typo correction in this case.
963 TemplateName Template =
966 }
967
968 // In C, we first see whether there is a tag type by the same name, in
969 // which case it's likely that the user just forgot to write "enum",
970 // "struct", or "union".
971 if (!getLangOpts().CPlusPlus && !SecondTry &&
972 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
973 break;
974 }
975
976 // Perform typo correction to determine if there is another name that is
977 // close to this name.
978 if (!SecondTry && CCC) {
979 SecondTry = true;
980 if (TypoCorrection Corrected =
981 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
982 &SS, *CCC, CTK_ErrorRecovery)) {
983 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
984 unsigned QualifiedDiag = diag::err_no_member_suggest;
985
986 NamedDecl *FirstDecl = Corrected.getFoundDecl();
987 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
988 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
989 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
990 UnqualifiedDiag = diag::err_no_template_suggest;
991 QualifiedDiag = diag::err_no_member_template_suggest;
992 } else if (UnderlyingFirstDecl &&
993 (isa<TypeDecl>(UnderlyingFirstDecl) ||
994 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
995 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
996 UnqualifiedDiag = diag::err_unknown_typename_suggest;
997 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
998 }
999
1000 if (SS.isEmpty()) {
1001 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1002 } else {// FIXME: is this even reachable? Test it.
1003 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1004 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1005 Name->getName().equals(CorrectedStr);
1006 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1007 << Name << computeDeclContext(SS, false)
1008 << DroppedSpecifier << SS.getRange());
1009 }
1010
1011 // Update the name, so that the caller has the new name.
1012 Name = Corrected.getCorrectionAsIdentifierInfo();
1013
1014 // Typo correction corrected to a keyword.
1015 if (Corrected.isKeyword())
1016 return Name;
1017
1018 // Also update the LookupResult...
1019 // FIXME: This should probably go away at some point
1020 Result.clear();
1021 Result.setLookupName(Corrected.getCorrection());
1022 if (FirstDecl)
1023 Result.addDecl(FirstDecl);
1024
1025 // If we found an Objective-C instance variable, let
1026 // LookupInObjCMethod build the appropriate expression to
1027 // reference the ivar.
1028 // FIXME: This is a gross hack.
1029 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1030 DeclResult R =
1031 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1032 if (R.isInvalid())
1034 if (R.isUsable())
1035 return NameClassification::NonType(Ivar);
1036 }
1037
1038 goto Corrected;
1039 }
1040 }
1041
1042 // We failed to correct; just fall through and let the parser deal with it.
1043 Result.suppressDiagnostics();
1045
1047 // We performed name lookup into the current instantiation, and there were
1048 // dependent bases, so we treat this result the same way as any other
1049 // dependent nested-name-specifier.
1050
1051 // C++ [temp.res]p2:
1052 // A name used in a template declaration or definition and that is
1053 // dependent on a template-parameter is assumed not to name a type
1054 // unless the applicable name lookup finds a type name or the name is
1055 // qualified by the keyword typename.
1056 //
1057 // FIXME: If the next token is '<', we might want to ask the parser to
1058 // perform some heroics to see if we actually have a
1059 // template-argument-list, which would indicate a missing 'template'
1060 // keyword here.
1062 }
1063
1067 break;
1068
1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1072 /*AllowDependent=*/false)) {
1073 // C++ [temp.local]p3:
1074 // A lookup that finds an injected-class-name (10.2) can result in an
1075 // ambiguity in certain cases (for example, if it is found in more than
1076 // one base class). If all of the injected-class-names that are found
1077 // refer to specializations of the same class template, and if the name
1078 // is followed by a template-argument-list, the reference refers to the
1079 // class template itself and not a specialization thereof, and is not
1080 // ambiguous.
1081 //
1082 // This filtering can make an ambiguous result into an unambiguous one,
1083 // so try again after filtering out template names.
1085 if (!Result.isAmbiguous()) {
1086 IsFilteredTemplateName = true;
1087 break;
1088 }
1089 }
1090
1091 // Diagnose the ambiguity and return an error.
1093 }
1094
1095 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1096 (IsFilteredTemplateName ||
1098 Result, /*AllowFunctionTemplates=*/true,
1099 /*AllowDependent=*/false,
1100 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1102 // C++ [temp.names]p3:
1103 // After name lookup (3.4) finds that a name is a template-name or that
1104 // an operator-function-id or a literal- operator-id refers to a set of
1105 // overloaded functions any member of which is a function template if
1106 // this is followed by a <, the < is always taken as the delimiter of a
1107 // template-argument-list and never as the less-than operator.
1108 // C++2a [temp.names]p2:
1109 // A name is also considered to refer to a template if it is an
1110 // unqualified-id followed by a < and name lookup finds either one
1111 // or more functions or finds nothing.
1112 if (!IsFilteredTemplateName)
1114
1115 bool IsFunctionTemplate;
1116 bool IsVarTemplate;
1117 TemplateName Template;
1118 if (Result.end() - Result.begin() > 1) {
1119 IsFunctionTemplate = true;
1120 Template = Context.getOverloadedTemplateName(Result.begin(),
1121 Result.end());
1122 } else if (!Result.empty()) {
1123 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1124 *Result.begin(), /*AllowFunctionTemplates=*/true,
1125 /*AllowDependent=*/false));
1126 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1127 IsVarTemplate = isa<VarTemplateDecl>(TD);
1128
1129 UsingShadowDecl *FoundUsingShadow =
1130 dyn_cast<UsingShadowDecl>(*Result.begin());
1131 assert(!FoundUsingShadow ||
1132 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1133 Template =
1134 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1135 if (SS.isNotEmpty())
1137 /*TemplateKeyword=*/false,
1138 Template);
1139 } else {
1140 // All results were non-template functions. This is a function template
1141 // name.
1142 IsFunctionTemplate = true;
1143 Template = Context.getAssumedTemplateName(NameInfo.getName());
1144 }
1145
1146 if (IsFunctionTemplate) {
1147 // Function templates always go through overload resolution, at which
1148 // point we'll perform the various checks (e.g., accessibility) we need
1149 // to based on which function we selected.
1150 Result.suppressDiagnostics();
1151
1152 return NameClassification::FunctionTemplate(Template);
1153 }
1154
1155 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1157 }
1158
1159 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1161 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1162 T = Context.getUsingType(USD, T);
1163 return buildNamedType(*this, &SS, T, NameLoc);
1164 };
1165
1166 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1167 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1168 DiagnoseUseOfDecl(Type, NameLoc);
1169 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1170 return BuildTypeFor(Type, *Result.begin());
1171 }
1172
1173 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1174 if (!Class) {
1175 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1176 if (ObjCCompatibleAliasDecl *Alias =
1177 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1178 Class = Alias->getClassInterface();
1179 }
1180
1181 if (Class) {
1182 DiagnoseUseOfDecl(Class, NameLoc);
1183
1184 if (NextToken.is(tok::period)) {
1185 // Interface. <something> is parsed as a property reference expression.
1186 // Just return "unknown" as a fall-through for now.
1187 Result.suppressDiagnostics();
1189 }
1190
1192 return ParsedType::make(T);
1193 }
1194
1195 if (isa<ConceptDecl>(FirstDecl)) {
1196 // We want to preserve the UsingShadowDecl for concepts.
1197 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1200 TemplateName(cast<TemplateDecl>(FirstDecl)));
1201 }
1202
1203 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1204 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1206 }
1207
1208 // We can have a type template here if we're classifying a template argument.
1209 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1210 !isa<VarTemplateDecl>(FirstDecl))
1212 TemplateName(cast<TemplateDecl>(FirstDecl)));
1213
1214 // Check for a tag type hidden by a non-type decl in a few cases where it
1215 // seems likely a type is wanted instead of the non-type that was found.
1216 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1217 if ((NextToken.is(tok::identifier) ||
1218 (NextIsOp &&
1219 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1220 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1221 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1222 DiagnoseUseOfDecl(Type, NameLoc);
1223 return BuildTypeFor(Type, *Result.begin());
1224 }
1225
1226 // If we already know which single declaration is referenced, just annotate
1227 // that declaration directly. Defer resolving even non-overloaded class
1228 // member accesses, as we need to defer certain access checks until we know
1229 // the context.
1230 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1231 if (Result.isSingleResult() && !ADL &&
1232 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1233 return NameClassification::NonType(Result.getRepresentativeDecl());
1234
1235 // Otherwise, this is an overload set that we will need to resolve later.
1236 Result.suppressDiagnostics();
1238 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1239 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1240 Result.begin(), Result.end()));
1241}
1242
1245 SourceLocation NameLoc) {
1246 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1247 CXXScopeSpec SS;
1248 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1249 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1250}
1251
1254 IdentifierInfo *Name,
1255 SourceLocation NameLoc,
1256 bool IsAddressOfOperand) {
1257 DeclarationNameInfo NameInfo(Name, NameLoc);
1258 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1259 NameInfo, IsAddressOfOperand,
1260 /*TemplateArgs=*/nullptr);
1261}
1262
1264 NamedDecl *Found,
1265 SourceLocation NameLoc,
1266 const Token &NextToken) {
1267 if (getCurMethodDecl() && SS.isEmpty())
1268 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1269 return BuildIvarRefExpr(S, NameLoc, Ivar);
1270
1271 // Reconstruct the lookup result.
1272 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1273 Result.addDecl(Found);
1274 Result.resolveKind();
1275
1276 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1277 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1278}
1279
1281 // For an implicit class member access, transform the result into a member
1282 // access expression if necessary.
1283 auto *ULE = cast<UnresolvedLookupExpr>(E);
1284 if ((*ULE->decls_begin())->isCXXClassMember()) {
1285 CXXScopeSpec SS;
1286 SS.Adopt(ULE->getQualifierLoc());
1287
1288 // Reconstruct the lookup result.
1289 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1291 Result.setNamingClass(ULE->getNamingClass());
1292 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1293 Result.addDecl(*I, I.getAccess());
1294 Result.resolveKind();
1296 nullptr, S);
1297 }
1298
1299 // Otherwise, this is already in the form we needed, and no further checks
1300 // are necessary.
1301 return ULE;
1302}
1303
1306 auto *TD = Name.getAsTemplateDecl();
1307 if (!TD)
1309 if (isa<ClassTemplateDecl>(TD))
1311 if (isa<FunctionTemplateDecl>(TD))
1313 if (isa<VarTemplateDecl>(TD))
1315 if (isa<TypeAliasTemplateDecl>(TD))
1317 if (isa<TemplateTemplateParmDecl>(TD))
1319 if (isa<ConceptDecl>(TD))
1322}
1323
1325 assert(DC->getLexicalParent() == CurContext &&
1326 "The next DeclContext should be lexically contained in the current one.");
1327 CurContext = DC;
1328 S->setEntity(DC);
1329}
1330
1332 assert(CurContext && "DeclContext imbalance!");
1333
1335 assert(CurContext && "Popped translation unit!");
1336}
1337
1339 Decl *D) {
1340 // Unlike PushDeclContext, the context to which we return is not necessarily
1341 // the containing DC of TD, because the new context will be some pre-existing
1342 // TagDecl definition instead of a fresh one.
1343 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1344 CurContext = cast<TagDecl>(D)->getDefinition();
1345 assert(CurContext && "skipping definition of undefined tag");
1346 // Start lookups from the parent of the current context; we don't want to look
1347 // into the pre-existing complete definition.
1348 S->setEntity(CurContext->getLookupParent());
1349 return Result;
1350}
1351
1353 CurContext = static_cast<decltype(CurContext)>(Context);
1354}
1355
1356/// EnterDeclaratorContext - Used when we must lookup names in the context
1357/// of a declarator's nested name specifier.
1358///
1360 // C++0x [basic.lookup.unqual]p13:
1361 // A name used in the definition of a static data member of class
1362 // X (after the qualified-id of the static member) is looked up as
1363 // if the name was used in a member function of X.
1364 // C++0x [basic.lookup.unqual]p14:
1365 // If a variable member of a namespace is defined outside of the
1366 // scope of its namespace then any name used in the definition of
1367 // the variable member (after the declarator-id) is looked up as
1368 // if the definition of the variable member occurred in its
1369 // namespace.
1370 // Both of these imply that we should push a scope whose context
1371 // is the semantic context of the declaration. We can't use
1372 // PushDeclContext here because that context is not necessarily
1373 // lexically contained in the current context. Fortunately,
1374 // the containing scope should have the appropriate information.
1375
1376 assert(!S->getEntity() && "scope already has entity");
1377
1378#ifndef NDEBUG
1379 Scope *Ancestor = S->getParent();
1380 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1381 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1382#endif
1383
1384 CurContext = DC;
1385 S->setEntity(DC);
1386
1387 if (S->getParent()->isTemplateParamScope()) {
1388 // Also set the corresponding entities for all immediately-enclosing
1389 // template parameter scopes.
1390 EnterTemplatedContext(S->getParent(), DC);
1391 }
1392}
1393
1395 assert(S->getEntity() == CurContext && "Context imbalance!");
1396
1397 // Switch back to the lexical context. The safety of this is
1398 // enforced by an assert in EnterDeclaratorContext.
1399 Scope *Ancestor = S->getParent();
1400 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1401 CurContext = Ancestor->getEntity();
1402
1403 // We don't need to do anything with the scope, which is going to
1404 // disappear.
1405}
1406
1408 assert(S->isTemplateParamScope() &&
1409 "expected to be initializing a template parameter scope");
1410
1411 // C++20 [temp.local]p7:
1412 // In the definition of a member of a class template that appears outside
1413 // of the class template definition, the name of a member of the class
1414 // template hides the name of a template-parameter of any enclosing class
1415 // templates (but not a template-parameter of the member if the member is a
1416 // class or function template).
1417 // C++20 [temp.local]p9:
1418 // In the definition of a class template or in the definition of a member
1419 // of such a template that appears outside of the template definition, for
1420 // each non-dependent base class (13.8.2.1), if the name of the base class
1421 // or the name of a member of the base class is the same as the name of a
1422 // template-parameter, the base class name or member name hides the
1423 // template-parameter name (6.4.10).
1424 //
1425 // This means that a template parameter scope should be searched immediately
1426 // after searching the DeclContext for which it is a template parameter
1427 // scope. For example, for
1428 // template<typename T> template<typename U> template<typename V>
1429 // void N::A<T>::B<U>::f(...)
1430 // we search V then B<U> (and base classes) then U then A<T> (and base
1431 // classes) then T then N then ::.
1432 unsigned ScopeDepth = getTemplateDepth(S);
1433 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1434 DeclContext *SearchDCAfterScope = DC;
1435 for (; DC; DC = DC->getLookupParent()) {
1436 if (const TemplateParameterList *TPL =
1437 cast<Decl>(DC)->getDescribedTemplateParams()) {
1438 unsigned DCDepth = TPL->getDepth() + 1;
1439 if (DCDepth > ScopeDepth)
1440 continue;
1441 if (ScopeDepth == DCDepth)
1442 SearchDCAfterScope = DC = DC->getLookupParent();
1443 break;
1444 }
1445 }
1446 S->setLookupEntity(SearchDCAfterScope);
1447 }
1448}
1449
1451 // We assume that the caller has already called
1452 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1453 FunctionDecl *FD = D->getAsFunction();
1454 if (!FD)
1455 return;
1456
1457 // Same implementation as PushDeclContext, but enters the context
1458 // from the lexical parent, rather than the top-level class.
1459 assert(CurContext == FD->getLexicalParent() &&
1460 "The next DeclContext should be lexically contained in the current one.");
1461 CurContext = FD;
1462 S->setEntity(CurContext);
1463
1464 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1465 ParmVarDecl *Param = FD->getParamDecl(P);
1466 // If the parameter has an identifier, then add it to the scope
1467 if (Param->getIdentifier()) {
1468 S->AddDecl(Param);
1469 IdResolver.AddDecl(Param);
1470 }
1471 }
1472}
1473
1475 // Same implementation as PopDeclContext, but returns to the lexical parent,
1476 // rather than the top-level class.
1477 assert(CurContext && "DeclContext imbalance!");
1479 assert(CurContext && "Popped translation unit!");
1480}
1481
1482/// Determine whether overloading is allowed for a new function
1483/// declaration considering prior declarations of the same name.
1484///
1485/// This routine determines whether overloading is possible, not
1486/// whether a new declaration actually overloads a previous one.
1487/// It will return true in C++ (where overloads are alway permitted)
1488/// or, as a C extension, when either the new declaration or a
1489/// previous one is declared with the 'overloadable' attribute.
1491 ASTContext &Context,
1492 const FunctionDecl *New) {
1493 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1494 return true;
1495
1496 // Multiversion function declarations are not overloads in the
1497 // usual sense of that term, but lookup will report that an
1498 // overload set was found if more than one multiversion function
1499 // declaration is present for the same name. It is therefore
1500 // inadequate to assume that some prior declaration(s) had
1501 // the overloadable attribute; checking is required. Since one
1502 // declaration is permitted to omit the attribute, it is necessary
1503 // to check at least two; hence the 'any_of' check below. Note that
1504 // the overloadable attribute is implicitly added to declarations
1505 // that were required to have it but did not.
1506 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1507 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1508 return ND->hasAttr<OverloadableAttr>();
1509 });
1510 } else if (Previous.getResultKind() == LookupResult::Found)
1511 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1512
1513 return false;
1514}
1515
1516/// Add this decl to the scope shadowed decl chains.
1517void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1518 // Move up the scope chain until we find the nearest enclosing
1519 // non-transparent context. The declaration will be introduced into this
1520 // scope.
1521 while (S->getEntity() && S->getEntity()->isTransparentContext())
1522 S = S->getParent();
1523
1524 // Add scoped declarations into their context, so that they can be
1525 // found later. Declarations without a context won't be inserted
1526 // into any context.
1527 if (AddToContext)
1528 CurContext->addDecl(D);
1529
1530 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1531 // are function-local declarations.
1532 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1533 return;
1534
1535 // Template instantiations should also not be pushed into scope.
1536 if (isa<FunctionDecl>(D) &&
1537 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1538 return;
1539
1540 // If this replaces anything in the current scope,
1542 IEnd = IdResolver.end();
1543 for (; I != IEnd; ++I) {
1544 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1545 S->RemoveDecl(*I);
1547
1548 // Should only need to replace one decl.
1549 break;
1550 }
1551 }
1552
1553 S->AddDecl(D);
1554
1555 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1556 // Implicitly-generated labels may end up getting generated in an order that
1557 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1558 // the label at the appropriate place in the identifier chain.
1559 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1560 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1561 if (IDC == CurContext) {
1562 if (!S->isDeclScope(*I))
1563 continue;
1564 } else if (IDC->Encloses(CurContext))
1565 break;
1566 }
1567
1569 } else {
1571 }
1573}
1574
1576 bool AllowInlineNamespace) const {
1577 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1578}
1579
1581 DeclContext *TargetDC = DC->getPrimaryContext();
1582 do {
1583 if (DeclContext *ScopeDC = S->getEntity())
1584 if (ScopeDC->getPrimaryContext() == TargetDC)
1585 return S;
1586 } while ((S = S->getParent()));
1587
1588 return nullptr;
1589}
1590
1592 DeclContext*,
1593 ASTContext&);
1594
1595/// Filters out lookup results that don't fall within the given scope
1596/// as determined by isDeclInScope.
1598 bool ConsiderLinkage,
1599 bool AllowInlineNamespace) {
1601 while (F.hasNext()) {
1602 NamedDecl *D = F.next();
1603
1604 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1605 continue;
1606
1607 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1608 continue;
1609
1610 F.erase();
1611 }
1612
1613 F.done();
1614}
1615
1616/// We've determined that \p New is a redeclaration of \p Old. Check that they
1617/// have compatible owning modules.
1619 // [module.interface]p7:
1620 // A declaration is attached to a module as follows:
1621 // - If the declaration is a non-dependent friend declaration that nominates a
1622 // function with a declarator-id that is a qualified-id or template-id or that
1623 // nominates a class other than with an elaborated-type-specifier with neither
1624 // a nested-name-specifier nor a simple-template-id, it is attached to the
1625 // module to which the friend is attached ([basic.link]).
1626 if (New->getFriendObjectKind() &&
1630 return false;
1631 }
1632
1633 Module *NewM = New->getOwningModule();
1634 Module *OldM = Old->getOwningModule();
1635
1636 if (NewM && NewM->isPrivateModule())
1637 NewM = NewM->Parent;
1638 if (OldM && OldM->isPrivateModule())
1639 OldM = OldM->Parent;
1640
1641 if (NewM == OldM)
1642 return false;
1643
1644 if (NewM && OldM) {
1645 // A module implementation unit has visibility of the decls in its
1646 // implicitly imported interface.
1647 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1648 return false;
1649
1650 // Partitions are part of the module, but a partition could import another
1651 // module, so verify that the PMIs agree.
1652 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1655 return false;
1656 }
1657
1658 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1659 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1660 if (NewIsModuleInterface || OldIsModuleInterface) {
1661 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1662 // if a declaration of D [...] appears in the purview of a module, all
1663 // other such declarations shall appear in the purview of the same module
1664 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1665 << New
1666 << NewIsModuleInterface
1667 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1668 << OldIsModuleInterface
1669 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1670 Diag(Old->getLocation(), diag::note_previous_declaration);
1671 New->setInvalidDecl();
1672 return true;
1673 }
1674
1675 return false;
1676}
1677
1678// [module.interface]p6:
1679// A redeclaration of an entity X is implicitly exported if X was introduced by
1680// an exported declaration; otherwise it shall not be exported.
1682 // [module.interface]p1:
1683 // An export-declaration shall inhabit a namespace scope.
1684 //
1685 // So it is meaningless to talk about redeclaration which is not at namespace
1686 // scope.
1687 if (!New->getLexicalDeclContext()
1689 ->isFileContext() ||
1690 !Old->getLexicalDeclContext()
1692 ->isFileContext())
1693 return false;
1694
1695 bool IsNewExported = New->isInExportDeclContext();
1696 bool IsOldExported = Old->isInExportDeclContext();
1697
1698 // It should be irrevelant if both of them are not exported.
1699 if (!IsNewExported && !IsOldExported)
1700 return false;
1701
1702 if (IsOldExported)
1703 return false;
1704
1705 assert(IsNewExported);
1706
1707 auto Lk = Old->getFormalLinkage();
1708 int S = 0;
1709 if (Lk == Linkage::Internal)
1710 S = 1;
1711 else if (Lk == Linkage::Module)
1712 S = 2;
1713 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1714 Diag(Old->getLocation(), diag::note_previous_declaration);
1715 return true;
1716}
1717
1718// A wrapper function for checking the semantic restrictions of
1719// a redeclaration within a module.
1722 return true;
1723
1724 if (CheckRedeclarationExported(New, Old))
1725 return true;
1726
1727 return false;
1728}
1729
1730// Check the redefinition in C++20 Modules.
1731//
1732// [basic.def.odr]p14:
1733// For any definable item D with definitions in multiple translation units,
1734// - if D is a non-inline non-templated function or variable, or
1735// - if the definitions in different translation units do not satisfy the
1736// following requirements,
1737// the program is ill-formed; a diagnostic is required only if the definable
1738// item is attached to a named module and a prior definition is reachable at
1739// the point where a later definition occurs.
1740// - Each such definition shall not be attached to a named module
1741// ([module.unit]).
1742// - Each such definition shall consist of the same sequence of tokens, ...
1743// ...
1744//
1745// Return true if the redefinition is not allowed. Return false otherwise.
1747 const NamedDecl *Old) const {
1748 assert(getASTContext().isSameEntity(New, Old) &&
1749 "New and Old are not the same definition, we should diagnostic it "
1750 "immediately instead of checking it.");
1751 assert(const_cast<Sema *>(this)->isReachable(New) &&
1752 const_cast<Sema *>(this)->isReachable(Old) &&
1753 "We shouldn't see unreachable definitions here.");
1754
1755 Module *NewM = New->getOwningModule();
1756 Module *OldM = Old->getOwningModule();
1757
1758 // We only checks for named modules here. The header like modules is skipped.
1759 // FIXME: This is not right if we import the header like modules in the module
1760 // purview.
1761 //
1762 // For example, assuming "header.h" provides definition for `D`.
1763 // ```C++
1764 // //--- M.cppm
1765 // export module M;
1766 // import "header.h"; // or #include "header.h" but import it by clang modules
1767 // actually.
1768 //
1769 // //--- Use.cpp
1770 // import M;
1771 // import "header.h"; // or uses clang modules.
1772 // ```
1773 //
1774 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1775 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1776 // reject it. But the current implementation couldn't detect the case since we
1777 // don't record the information about the importee modules.
1778 //
1779 // But this might not be painful in practice. Since the design of C++20 Named
1780 // Modules suggests us to use headers in global module fragment instead of
1781 // module purview.
1782 if (NewM && NewM->isHeaderLikeModule())
1783 NewM = nullptr;
1784 if (OldM && OldM->isHeaderLikeModule())
1785 OldM = nullptr;
1786
1787 if (!NewM && !OldM)
1788 return true;
1789
1790 // [basic.def.odr]p14.3
1791 // Each such definition shall not be attached to a named module
1792 // ([module.unit]).
1793 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1794 return true;
1795
1796 // Then New and Old lives in the same TU if their share one same module unit.
1797 if (NewM)
1798 NewM = NewM->getTopLevelModule();
1799 if (OldM)
1800 OldM = OldM->getTopLevelModule();
1801 return OldM == NewM;
1802}
1803
1805 if (D->getDeclContext()->isFileContext())
1806 return false;
1807
1808 return isa<UsingShadowDecl>(D) ||
1809 isa<UnresolvedUsingTypenameDecl>(D) ||
1810 isa<UnresolvedUsingValueDecl>(D);
1811}
1812
1813/// Removes using shadow declarations not at class scope from the lookup
1814/// results.
1817 while (F.hasNext())
1819 F.erase();
1820
1821 F.done();
1822}
1823
1824/// Check for this common pattern:
1825/// @code
1826/// class S {
1827/// S(const S&); // DO NOT IMPLEMENT
1828/// void operator=(const S&); // DO NOT IMPLEMENT
1829/// };
1830/// @endcode
1832 // FIXME: Should check for private access too but access is set after we get
1833 // the decl here.
1835 return false;
1836
1837 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1838 return CD->isCopyConstructor();
1839 return D->isCopyAssignmentOperator();
1840}
1841
1842// We need this to handle
1843//
1844// typedef struct {
1845// void *foo() { return 0; }
1846// } A;
1847//
1848// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1849// for example. If 'A', foo will have external linkage. If we have '*A',
1850// foo will have no linkage. Since we can't know until we get to the end
1851// of the typedef, this function finds out if D might have non-external linkage.
1852// Callers should verify at the end of the TU if it D has external linkage or
1853// not.
1854bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1855 const DeclContext *DC = D->getDeclContext();
1856 while (!DC->isTranslationUnit()) {
1857 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1858 if (!RD->hasNameForLinkage())
1859 return true;
1860 }
1861 DC = DC->getParent();
1862 }
1863
1864 return !D->isExternallyVisible();
1865}
1866
1867// FIXME: This needs to be refactored; some other isInMainFile users want
1868// these semantics.
1869static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1871 return false;
1872 return S.SourceMgr.isInMainFile(Loc);
1873}
1874
1876 assert(D);
1877
1878 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1879 return false;
1880
1881 // Ignore all entities declared within templates, and out-of-line definitions
1882 // of members of class templates.
1883 if (D->getDeclContext()->isDependentContext() ||
1885 return false;
1886
1887 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1888 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1889 return false;
1890 // A non-out-of-line declaration of a member specialization was implicitly
1891 // instantiated; it's the out-of-line declaration that we're interested in.
1892 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1893 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1894 return false;
1895
1896 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1897 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1898 return false;
1899 } else {
1900 // 'static inline' functions are defined in headers; don't warn.
1901 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1902 return false;
1903 }
1904
1905 if (FD->doesThisDeclarationHaveABody() &&
1907 return false;
1908 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1909 // Constants and utility variables are defined in headers with internal
1910 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1911 // like "inline".)
1912 if (!isMainFileLoc(*this, VD->getLocation()))
1913 return false;
1914
1915 if (Context.DeclMustBeEmitted(VD))
1916 return false;
1917
1918 if (VD->isStaticDataMember() &&
1919 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1920 return false;
1921 if (VD->isStaticDataMember() &&
1922 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1923 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1924 return false;
1925
1926 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1927 return false;
1928 } else {
1929 return false;
1930 }
1931
1932 // Only warn for unused decls internal to the translation unit.
1933 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1934 // for inline functions defined in the main source file, for instance.
1935 return mightHaveNonExternalLinkage(D);
1936}
1937
1939 if (!D)
1940 return;
1941
1942 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1943 const FunctionDecl *First = FD->getFirstDecl();
1945 return; // First should already be in the vector.
1946 }
1947
1948 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1949 const VarDecl *First = VD->getFirstDecl();
1951 return; // First should already be in the vector.
1952 }
1953
1956}
1957
1958static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1959 const NamedDecl *D) {
1960 if (D->isInvalidDecl())
1961 return false;
1962
1963 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1964 // For a decomposition declaration, warn if none of the bindings are
1965 // referenced, instead of if the variable itself is referenced (which
1966 // it is, by the bindings' expressions).
1967 bool IsAllPlaceholders = true;
1968 for (const auto *BD : DD->bindings()) {
1969 if (BD->isReferenced())
1970 return false;
1971 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1972 }
1973 if (IsAllPlaceholders)
1974 return false;
1975 } else if (!D->getDeclName()) {
1976 return false;
1977 } else if (D->isReferenced() || D->isUsed()) {
1978 return false;
1979 }
1980
1981 if (D->isPlaceholderVar(LangOpts))
1982 return false;
1983
1984 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1985 D->hasAttr<CleanupAttr>())
1986 return false;
1987
1988 if (isa<LabelDecl>(D))
1989 return true;
1990
1991 // Except for labels, we only care about unused decls that are local to
1992 // functions.
1993 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1994 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1995 // For dependent types, the diagnostic is deferred.
1996 WithinFunction =
1997 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1998 if (!WithinFunction)
1999 return false;
2000
2001 if (isa<TypedefNameDecl>(D))
2002 return true;
2003
2004 // White-list anything that isn't a local variable.
2005 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2006 return false;
2007
2008 // Types of valid local variables should be complete, so this should succeed.
2009 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2010
2011 const Expr *Init = VD->getInit();
2012 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2013 Init = Cleanups->getSubExpr();
2014
2015 const auto *Ty = VD->getType().getTypePtr();
2016
2017 // Only look at the outermost level of typedef.
2018 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2019 // Allow anything marked with __attribute__((unused)).
2020 if (TT->getDecl()->hasAttr<UnusedAttr>())
2021 return false;
2022 }
2023
2024 // Warn for reference variables whose initializtion performs lifetime
2025 // extension.
2026 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2027 MTE && MTE->getExtendingDecl()) {
2028 Ty = VD->getType().getNonReferenceType().getTypePtr();
2029 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2030 }
2031
2032 // If we failed to complete the type for some reason, or if the type is
2033 // dependent, don't diagnose the variable.
2034 if (Ty->isIncompleteType() || Ty->isDependentType())
2035 return false;
2036
2037 // Look at the element type to ensure that the warning behaviour is
2038 // consistent for both scalars and arrays.
2039 Ty = Ty->getBaseElementTypeUnsafe();
2040
2041 if (const TagType *TT = Ty->getAs<TagType>()) {
2042 const TagDecl *Tag = TT->getDecl();
2043 if (Tag->hasAttr<UnusedAttr>())
2044 return false;
2045
2046 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2047 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2048 return false;
2049
2050 if (Init) {
2051 const auto *Construct =
2052 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2053 if (Construct && !Construct->isElidable()) {
2054 const CXXConstructorDecl *CD = Construct->getConstructor();
2055 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2056 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2057 return false;
2058 }
2059
2060 // Suppress the warning if we don't know how this is constructed, and
2061 // it could possibly be non-trivial constructor.
2062 if (Init->isTypeDependent()) {
2063 for (const CXXConstructorDecl *Ctor : RD->ctors())
2064 if (!Ctor->isTrivial())
2065 return false;
2066 }
2067
2068 // Suppress the warning if the constructor is unresolved because
2069 // its arguments are dependent.
2070 if (isa<CXXUnresolvedConstructExpr>(Init))
2071 return false;
2072 }
2073 }
2074 }
2075
2076 // TODO: __attribute__((unused)) templates?
2077 }
2078
2079 return true;
2080}
2081
2083 FixItHint &Hint) {
2084 if (isa<LabelDecl>(D)) {
2086 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2087 /*SkipTrailingWhitespaceAndNewline=*/false);
2088 if (AfterColon.isInvalid())
2089 return;
2091 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2092 }
2093}
2094
2097 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2098}
2099
2101 DiagReceiverTy DiagReceiver) {
2102 if (D->getTypeForDecl()->isDependentType())
2103 return;
2104
2105 for (auto *TmpD : D->decls()) {
2106 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2107 DiagnoseUnusedDecl(T, DiagReceiver);
2108 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2109 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2110 }
2111}
2112
2115 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2116}
2117
2118/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2119/// unless they are marked attr(unused).
2122 return;
2123
2124 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2125 // typedefs can be referenced later on, so the diagnostics are emitted
2126 // at end-of-translation-unit.
2128 return;
2129 }
2130
2131 FixItHint Hint;
2133
2134 unsigned DiagID;
2135 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2136 DiagID = diag::warn_unused_exception_param;
2137 else if (isa<LabelDecl>(D))
2138 DiagID = diag::warn_unused_label;
2139 else
2140 DiagID = diag::warn_unused_variable;
2141
2142 SourceLocation DiagLoc = D->getLocation();
2143 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2144}
2145
2147 DiagReceiverTy DiagReceiver) {
2148 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2149 // it's not really unused.
2150 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2151 return;
2152
2153 // In C++, `_` variables behave as if they were maybe_unused
2154 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2155 return;
2156
2157 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2158
2159 if (Ty->isReferenceType() || Ty->isDependentType())
2160 return;
2161
2162 if (const TagType *TT = Ty->getAs<TagType>()) {
2163 const TagDecl *Tag = TT->getDecl();
2164 if (Tag->hasAttr<UnusedAttr>())
2165 return;
2166 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2167 // mimic gcc's behavior.
2168 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2169 RD && !RD->hasAttr<WarnUnusedAttr>())
2170 return;
2171 }
2172
2173 // Don't warn about __block Objective-C pointer variables, as they might
2174 // be assigned in the block but not used elsewhere for the purpose of lifetime
2175 // extension.
2176 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2177 return;
2178
2179 // Don't warn about Objective-C pointer variables with precise lifetime
2180 // semantics; they can be used to ensure ARC releases the object at a known
2181 // time, which may mean assignment but no other references.
2182 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2183 return;
2184
2185 auto iter = RefsMinusAssignments.find(VD);
2186 if (iter == RefsMinusAssignments.end())
2187 return;
2188
2189 assert(iter->getSecond() >= 0 &&
2190 "Found a negative number of references to a VarDecl");
2191 if (iter->getSecond() != 0)
2192 return;
2193 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2194 : diag::warn_unused_but_set_variable;
2195 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2196}
2197
2199 Sema::DiagReceiverTy DiagReceiver) {
2200 // Verify that we have no forward references left. If so, there was a goto
2201 // or address of a label taken, but no definition of it. Label fwd
2202 // definitions are indicated with a null substmt which is also not a resolved
2203 // MS inline assembly label name.
2204 bool Diagnose = false;
2205 if (L->isMSAsmLabel())
2206 Diagnose = !L->isResolvedMSAsmLabel();
2207 else
2208 Diagnose = L->getStmt() == nullptr;
2209 if (Diagnose)
2210 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2211 << L);
2212}
2213
2215 S->applyNRVO();
2216
2217 if (S->decl_empty()) return;
2218 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2219 "Scope shouldn't contain decls!");
2220
2221 /// We visit the decls in non-deterministic order, but we want diagnostics
2222 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2223 /// and sort the diagnostics before emitting them, after we visited all decls.
2224 struct LocAndDiag {
2225 SourceLocation Loc;
2226 std::optional<SourceLocation> PreviousDeclLoc;
2228 };
2230 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2231 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2232 };
2233 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2234 SourceLocation PreviousDeclLoc,
2235 PartialDiagnostic PD) {
2236 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2237 };
2238
2239 for (auto *TmpD : S->decls()) {
2240 assert(TmpD && "This decl didn't get pushed??");
2241
2242 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2243 NamedDecl *D = cast<NamedDecl>(TmpD);
2244
2245 // Diagnose unused variables in this scope.
2246 if (!S->hasUnrecoverableErrorOccurred()) {
2247 DiagnoseUnusedDecl(D, addDiag);
2248 if (const auto *RD = dyn_cast<RecordDecl>(D))
2249 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2250 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2251 DiagnoseUnusedButSetDecl(VD, addDiag);
2252 RefsMinusAssignments.erase(VD);
2253 }
2254 }
2255
2256 if (!D->getDeclName()) continue;
2257
2258 // If this was a forward reference to a label, verify it was defined.
2259 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2260 CheckPoppedLabel(LD, *this, addDiag);
2261
2262 // Remove this name from our lexical scope, and warn on it if we haven't
2263 // already.
2265 auto ShadowI = ShadowingDecls.find(D);
2266 if (ShadowI != ShadowingDecls.end()) {
2267 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2268 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2269 PDiag(diag::warn_ctor_parm_shadows_field)
2270 << D << FD << FD->getParent());
2271 }
2272 ShadowingDecls.erase(ShadowI);
2273 }
2274
2275 if (!getLangOpts().CPlusPlus && S->isClassScope()) {
2276 if (auto *FD = dyn_cast<FieldDecl>(TmpD);
2277 FD && FD->hasAttr<CountedByAttr>())
2278 CheckCountedByAttr(S, FD);
2279 }
2280 }
2281
2282 llvm::sort(DeclDiags,
2283 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2284 // The particular order for diagnostics is not important, as long
2285 // as the order is deterministic. Using the raw location is going
2286 // to generally be in source order unless there are macro
2287 // expansions involved.
2288 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2289 });
2290 for (const LocAndDiag &D : DeclDiags) {
2291 Diag(D.Loc, D.PD);
2292 if (D.PreviousDeclLoc)
2293 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2294 }
2295}
2296
2297/// Look for an Objective-C class in the translation unit.
2298///
2299/// \param Id The name of the Objective-C class we're looking for. If
2300/// typo-correction fixes this name, the Id will be updated
2301/// to the fixed name.
2302///
2303/// \param IdLoc The location of the name in the translation unit.
2304///
2305/// \param DoTypoCorrection If true, this routine will attempt typo correction
2306/// if there is no class with the given name.
2307///
2308/// \returns The declaration of the named Objective-C class, or NULL if the
2309/// class could not be found.
2311 SourceLocation IdLoc,
2312 bool DoTypoCorrection) {
2313 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2314 // creation from this context.
2316
2317 if (!IDecl && DoTypoCorrection) {
2318 // Perform typo correction at the given location, but only if we
2319 // find an Objective-C class name.
2321 if (TypoCorrection C =
2323 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2324 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2325 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2326 Id = IDecl->getIdentifier();
2327 }
2328 }
2329 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2330 // This routine must always return a class definition, if any.
2331 if (Def && Def->getDefinition())
2332 Def = Def->getDefinition();
2333 return Def;
2334}
2335
2336/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2337/// from S, where a non-field would be declared. This routine copes
2338/// with the difference between C and C++ scoping rules in structs and
2339/// unions. For example, the following code is well-formed in C but
2340/// ill-formed in C++:
2341/// @code
2342/// struct S6 {
2343/// enum { BAR } e;
2344/// };
2345///
2346/// void test_S6() {
2347/// struct S6 a;
2348/// a.e = BAR;
2349/// }
2350/// @endcode
2351/// For the declaration of BAR, this routine will return a different
2352/// scope. The scope S will be the scope of the unnamed enumeration
2353/// within S6. In C++, this routine will return the scope associated
2354/// with S6, because the enumeration's scope is a transparent
2355/// context but structures can contain non-field names. In C, this
2356/// routine will return the translation unit scope, since the
2357/// enumeration's scope is a transparent context and structures cannot
2358/// contain non-field names.
2360 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2361 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2362 (S->isClassScope() && !getLangOpts().CPlusPlus))
2363 S = S->getParent();
2364 return S;
2365}
2366
2367static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2369 switch (Error) {
2371 return "";
2373 return BuiltinInfo.getHeaderName(ID);
2375 return "stdio.h";
2377 return "setjmp.h";
2379 return "ucontext.h";
2380 }
2381 llvm_unreachable("unhandled error kind");
2382}
2383
2385 unsigned ID, SourceLocation Loc) {
2387
2388 if (getLangOpts().CPlusPlus) {
2390 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2391 CLinkageDecl->setImplicit();
2392 Parent->addDecl(CLinkageDecl);
2393 Parent = CLinkageDecl;
2394 }
2395
2396 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2397 /*TInfo=*/nullptr, SC_Extern,
2398 getCurFPFeatures().isFPConstrained(),
2399 false, Type->isFunctionProtoType());
2400 New->setImplicit();
2401 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2402
2403 // Create Decl objects for each parameter, adding them to the
2404 // FunctionDecl.
2405 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2407 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2409 Context, New, SourceLocation(), SourceLocation(), nullptr,
2410 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2411 parm->setScopeInfo(0, i);
2412 Params.push_back(parm);
2413 }
2414 New->setParams(Params);
2415 }
2416
2418 return New;
2419}
2420
2421/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2422/// file scope. lazily create a decl for it. ForRedeclaration is true
2423/// if we're creating this built-in in anticipation of redeclaring the
2424/// built-in.
2426 Scope *S, bool ForRedeclaration,
2427 SourceLocation Loc) {
2429
2431 QualType R = Context.GetBuiltinType(ID, Error);
2432 if (Error) {
2433 if (!ForRedeclaration)
2434 return nullptr;
2435
2436 // If we have a builtin without an associated type we should not emit a
2437 // warning when we were not able to find a type for it.
2438 if (Error == ASTContext::GE_Missing_type ||
2440 return nullptr;
2441
2442 // If we could not find a type for setjmp it is because the jmp_buf type was
2443 // not defined prior to the setjmp declaration.
2444 if (Error == ASTContext::GE_Missing_setjmp) {
2445 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2447 return nullptr;
2448 }
2449
2450 // Generally, we emit a warning that the declaration requires the
2451 // appropriate header.
2452 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2453 << getHeaderName(Context.BuiltinInfo, ID, Error)
2455 return nullptr;
2456 }
2457
2458 if (!ForRedeclaration &&
2461 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2462 : diag::ext_implicit_lib_function_decl)
2463 << Context.BuiltinInfo.getName(ID) << R;
2464 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2465 Diag(Loc, diag::note_include_header_or_declare)
2466 << Header << Context.BuiltinInfo.getName(ID);
2467 }
2468
2469 if (R.isNull())
2470 return nullptr;
2471
2472 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2474
2475 // TUScope is the translation-unit scope to insert this function into.
2476 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2477 // relate Scopes to DeclContexts, and probably eliminate CurContext
2478 // entirely, but we're not there yet.
2479 DeclContext *SavedContext = CurContext;
2480 CurContext = New->getDeclContext();
2482 CurContext = SavedContext;
2483 return New;
2484}
2485
2486/// Typedef declarations don't have linkage, but they still denote the same
2487/// entity if their types are the same.
2488/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2489/// isSameEntity.
2493 // This is only interesting when modules are enabled.
2494 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2495 return;
2496
2497 // Empty sets are uninteresting.
2498 if (Previous.empty())
2499 return;
2500
2501 LookupResult::Filter Filter = Previous.makeFilter();
2502 while (Filter.hasNext()) {
2503 NamedDecl *Old = Filter.next();
2504
2505 // Non-hidden declarations are never ignored.
2506 if (S.isVisible(Old))
2507 continue;
2508
2509 // Declarations of the same entity are not ignored, even if they have
2510 // different linkages.
2511 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2512 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2513 Decl->getUnderlyingType()))
2514 continue;
2515
2516 // If both declarations give a tag declaration a typedef name for linkage
2517 // purposes, then they declare the same entity.
2518 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2519 Decl->getAnonDeclWithTypedefName())
2520 continue;
2521 }
2522
2523 Filter.erase();
2524 }
2525
2526 Filter.done();
2527}
2528
2530 QualType OldType;
2531 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2532 OldType = OldTypedef->getUnderlyingType();
2533 else
2534 OldType = Context.getTypeDeclType(Old);
2535 QualType NewType = New->getUnderlyingType();
2536
2537 if (NewType->isVariablyModifiedType()) {
2538 // Must not redefine a typedef with a variably-modified type.
2539 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2540 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2541 << Kind << NewType;
2542 if (Old->getLocation().isValid())
2544 New->setInvalidDecl();
2545 return true;
2546 }
2547
2548 if (OldType != NewType &&
2549 !OldType->isDependentType() &&
2550 !NewType->isDependentType() &&
2551 !Context.hasSameType(OldType, NewType)) {
2552 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2553 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2554 << Kind << NewType << OldType;
2555 if (Old->getLocation().isValid())
2557 New->setInvalidDecl();
2558 return true;
2559 }
2560 return false;
2561}
2562
2563/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2564/// same name and scope as a previous declaration 'Old'. Figure out
2565/// how to resolve this situation, merging decls or emitting
2566/// diagnostics as appropriate. If there was an error, set New to be invalid.
2567///
2569 LookupResult &OldDecls) {
2570 // If the new decl is known invalid already, don't bother doing any
2571 // merging checks.
2572 if (New->isInvalidDecl()) return;
2573
2574 // Allow multiple definitions for ObjC built-in typedefs.
2575 // FIXME: Verify the underlying types are equivalent!
2576 if (getLangOpts().ObjC) {
2577 const IdentifierInfo *TypeID = New->getIdentifier();
2578 switch (TypeID->getLength()) {
2579 default: break;
2580 case 2:
2581 {
2582 if (!TypeID->isStr("id"))
2583 break;
2584 QualType T = New->getUnderlyingType();
2585 if (!T->isPointerType())
2586 break;
2587 if (!T->isVoidPointerType()) {
2588 QualType PT = T->castAs<PointerType>()->getPointeeType();
2589 if (!PT->isStructureType())
2590 break;
2591 }
2593 // Install the built-in type for 'id', ignoring the current definition.
2595 return;
2596 }
2597 case 5:
2598 if (!TypeID->isStr("Class"))
2599 break;
2601 // Install the built-in type for 'Class', ignoring the current definition.
2603 return;
2604 case 3:
2605 if (!TypeID->isStr("SEL"))
2606 break;
2608 // Install the built-in type for 'SEL', ignoring the current definition.
2610 return;
2611 }
2612 // Fall through - the typedef name was not a builtin type.
2613 }
2614
2615 // Verify the old decl was also a type.
2616 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2617 if (!Old) {
2618 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2619 << New->getDeclName();
2620
2621 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2622 if (OldD->getLocation().isValid())
2623 notePreviousDefinition(OldD, New->getLocation());
2624
2625 return New->setInvalidDecl();
2626 }
2627
2628 // If the old declaration is invalid, just give up here.
2629 if (Old->isInvalidDecl())
2630 return New->setInvalidDecl();
2631
2632 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2633 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2634 auto *NewTag = New->getAnonDeclWithTypedefName();
2635 NamedDecl *Hidden = nullptr;
2636 if (OldTag && NewTag &&
2637 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2638 !hasVisibleDefinition(OldTag, &Hidden)) {
2639 // There is a definition of this tag, but it is not visible. Use it
2640 // instead of our tag.
2641 New->setTypeForDecl(OldTD->getTypeForDecl());
2642 if (OldTD->isModed())
2643 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2644 OldTD->getUnderlyingType());
2645 else
2646 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2647
2648 // Make the old tag definition visible.
2650
2651 // If this was an unscoped enumeration, yank all of its enumerators
2652 // out of the scope.
2653 if (isa<EnumDecl>(NewTag)) {
2654 Scope *EnumScope = getNonFieldDeclScope(S);
2655 for (auto *D : NewTag->decls()) {
2656 auto *ED = cast<EnumConstantDecl>(D);
2657 assert(EnumScope->isDeclScope(ED));
2658 EnumScope->RemoveDecl(ED);
2660 ED->getLexicalDeclContext()->removeDecl(ED);
2661 }
2662 }
2663 }
2664 }
2665
2666 // If the typedef types are not identical, reject them in all languages and
2667 // with any extensions enabled.
2668 if (isIncompatibleTypedef(Old, New))
2669 return;
2670
2671 // The types match. Link up the redeclaration chain and merge attributes if
2672 // the old declaration was a typedef.
2673 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2674 New->setPreviousDecl(Typedef);
2675 mergeDeclAttributes(New, Old);
2676 }
2677
2678 if (getLangOpts().MicrosoftExt)
2679 return;
2680
2681 if (getLangOpts().CPlusPlus) {
2682 // C++ [dcl.typedef]p2:
2683 // In a given non-class scope, a typedef specifier can be used to
2684 // redefine the name of any type declared in that scope to refer
2685 // to the type to which it already refers.
2686 if (!isa<CXXRecordDecl>(CurContext))
2687 return;
2688
2689 // C++0x [dcl.typedef]p4:
2690 // In a given class scope, a typedef specifier can be used to redefine
2691 // any class-name declared in that scope that is not also a typedef-name
2692 // to refer to the type to which it already refers.
2693 //
2694 // This wording came in via DR424, which was a correction to the
2695 // wording in DR56, which accidentally banned code like:
2696 //
2697 // struct S {
2698 // typedef struct A { } A;
2699 // };
2700 //
2701 // in the C++03 standard. We implement the C++0x semantics, which
2702 // allow the above but disallow
2703 //
2704 // struct S {
2705 // typedef int I;
2706 // typedef int I;
2707 // };
2708 //
2709 // since that was the intent of DR56.
2710 if (!isa<TypedefNameDecl>(Old))
2711 return;
2712
2713 Diag(New->getLocation(), diag::err_redefinition)
2714 << New->getDeclName();
2716 return New->setInvalidDecl();
2717 }
2718
2719 // Modules always permit redefinition of typedefs, as does C11.
2720 if (getLangOpts().Modules || getLangOpts().C11)
2721 return;
2722
2723 // If we have a redefinition of a typedef in C, emit a warning. This warning
2724 // is normally mapped to an error, but can be controlled with
2725 // -Wtypedef-redefinition. If either the original or the redefinition is
2726 // in a system header, don't emit this for compatibility with GCC.
2727 if (getDiagnostics().getSuppressSystemWarnings() &&
2728 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2729 (Old->isImplicit() ||
2732 return;
2733
2734 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2735 << New->getDeclName();
2737}
2738
2739/// DeclhasAttr - returns true if decl Declaration already has the target
2740/// attribute.
2741static bool DeclHasAttr(const Decl *D, const Attr *A) {
2742 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2743 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2744 for (const auto *i : D->attrs())
2745 if (i->getKind() == A->getKind()) {
2746 if (Ann) {
2747 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2748 return true;
2749 continue;
2750 }
2751 // FIXME: Don't hardcode this check
2752 if (OA && isa<OwnershipAttr>(i))
2753 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2754 return true;
2755 }
2756
2757 return false;
2758}
2759
2761 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2762 return VD->isThisDeclarationADefinition();
2763 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2764 return TD->isCompleteDefinition() || TD->isBeingDefined();
2765 return true;
2766}
2767
2768/// Merge alignment attributes from \p Old to \p New, taking into account the
2769/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2770///
2771/// \return \c true if any attributes were added to \p New.
2772static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2773 // Look for alignas attributes on Old, and pick out whichever attribute
2774 // specifies the strictest alignment requirement.
2775 AlignedAttr *OldAlignasAttr = nullptr;
2776 AlignedAttr *OldStrictestAlignAttr = nullptr;
2777 unsigned OldAlign = 0;
2778 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2779 // FIXME: We have no way of representing inherited dependent alignments
2780 // in a case like:
2781 // template<int A, int B> struct alignas(A) X;
2782 // template<int A, int B> struct alignas(B) X {};
2783 // For now, we just ignore any alignas attributes which are not on the
2784 // definition in such a case.
2785 if (I->isAlignmentDependent())
2786 return false;
2787
2788 if (I->isAlignas())
2789 OldAlignasAttr = I;
2790
2791 unsigned Align = I->getAlignment(S.Context);
2792 if (Align > OldAlign) {
2793 OldAlign = Align;
2794 OldStrictestAlignAttr = I;
2795 }
2796 }
2797
2798 // Look for alignas attributes on New.
2799 AlignedAttr *NewAlignasAttr = nullptr;
2800 unsigned NewAlign = 0;
2801 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2802 if (I->isAlignmentDependent())
2803 return false;
2804
2805 if (I->isAlignas())
2806 NewAlignasAttr = I;
2807
2808 unsigned Align = I->getAlignment(S.Context);
2809 if (Align > NewAlign)
2810 NewAlign = Align;
2811 }
2812
2813 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2814 // Both declarations have 'alignas' attributes. We require them to match.
2815 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2816 // fall short. (If two declarations both have alignas, they must both match
2817 // every definition, and so must match each other if there is a definition.)
2818
2819 // If either declaration only contains 'alignas(0)' specifiers, then it
2820 // specifies the natural alignment for the type.
2821 if (OldAlign == 0 || NewAlign == 0) {
2822 QualType Ty;
2823 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2824 Ty = VD->getType();
2825 else
2826 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2827
2828 if (OldAlign == 0)
2829 OldAlign = S.Context.getTypeAlign(Ty);
2830 if (NewAlign == 0)
2831 NewAlign = S.Context.getTypeAlign(Ty);
2832 }
2833
2834 if (OldAlign != NewAlign) {
2835 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2838 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2839 }
2840 }
2841
2842 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2843 // C++11 [dcl.align]p6:
2844 // if any declaration of an entity has an alignment-specifier,
2845 // every defining declaration of that entity shall specify an
2846 // equivalent alignment.
2847 // C11 6.7.5/7:
2848 // If the definition of an object does not have an alignment
2849 // specifier, any other declaration of that object shall also
2850 // have no alignment specifier.
2851 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2852 << OldAlignasAttr;
2853 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2854 << OldAlignasAttr;
2855 }
2856
2857 bool AnyAdded = false;
2858
2859 // Ensure we have an attribute representing the strictest alignment.
2860 if (OldAlign > NewAlign) {
2861 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2862 Clone->setInherited(true);
2863 New->addAttr(Clone);
2864 AnyAdded = true;
2865 }
2866
2867 // Ensure we have an alignas attribute if the old declaration had one.
2868 if (OldAlignasAttr && !NewAlignasAttr &&
2869 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2870 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2871 Clone->setInherited(true);
2872 New->addAttr(Clone);
2873 AnyAdded = true;
2874 }
2875
2876 return AnyAdded;
2877}
2878
2879#define WANT_DECL_MERGE_LOGIC
2880#include "clang/Sema/AttrParsedAttrImpl.inc"
2881#undef WANT_DECL_MERGE_LOGIC
2882
2884 const InheritableAttr *Attr,
2886 // Diagnose any mutual exclusions between the attribute that we want to add
2887 // and attributes that already exist on the declaration.
2888 if (!DiagnoseMutualExclusions(S, D, Attr))
2889 return false;
2890
2891 // This function copies an attribute Attr from a previous declaration to the
2892 // new declaration D if the new declaration doesn't itself have that attribute
2893 // yet or if that attribute allows duplicates.
2894 // If you're adding a new attribute that requires logic different from
2895 // "use explicit attribute on decl if present, else use attribute from
2896 // previous decl", for example if the attribute needs to be consistent
2897 // between redeclarations, you need to call a custom merge function here.
2898 InheritableAttr *NewAttr = nullptr;
2899 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2900 NewAttr = S.mergeAvailabilityAttr(
2901 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2902 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2903 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2904 AA->getPriority());
2905 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2906 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2907 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2908 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2909 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2910 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2911 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2912 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2913 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2914 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2915 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2916 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2917 FA->getFirstArg());
2918 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2919 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2920 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2921 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2922 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2923 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2924 IA->getInheritanceModel());
2925 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2926 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2927 &S.Context.Idents.get(AA->getSpelling()));
2928 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2929 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2930 isa<CUDAGlobalAttr>(Attr))) {
2931 // CUDA target attributes are part of function signature for
2932 // overloading purposes and must not be merged.
2933 return false;
2934 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2935 NewAttr = S.mergeMinSizeAttr(D, *MA);
2936 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2937 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2938 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2939 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2940 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2941 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2942 else if (isa<AlignedAttr>(Attr))
2943 // AlignedAttrs are handled separately, because we need to handle all
2944 // such attributes on a declaration at the same time.
2945 NewAttr = nullptr;
2946 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2947 (AMK == Sema::AMK_Override ||
2950 NewAttr = nullptr;
2951 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2952 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2953 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2954 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2955 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2956 NewAttr = S.mergeImportNameAttr(D, *INA);
2957 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2958 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2959 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2960 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2961 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2962 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2963 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2964 NewAttr =
2965 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2966 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2967 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2968 else if (isa<SuppressAttr>(Attr))
2969 // Do nothing. Each redeclaration should be suppressed separately.
2970 NewAttr = nullptr;
2971 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2972 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2973
2974 if (NewAttr) {
2975 NewAttr->setInherited(true);
2976 D->addAttr(NewAttr);
2977 if (isa<MSInheritanceAttr>(NewAttr))
2978 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2979 return true;
2980 }
2981
2982 return false;
2983}
2984
2985static const NamedDecl *getDefinition(const Decl *D) {
2986 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2987 return TD->getDefinition();
2988 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2989 const VarDecl *Def = VD->getDefinition();
2990 if (Def)
2991 return Def;
2992 return VD->getActingDefinition();
2993 }
2994 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2995 const FunctionDecl *Def = nullptr;
2996 if (FD->isDefined(Def, true))
2997 return Def;
2998 }
2999 return nullptr;
3000}
3001
3002static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3003 for (const auto *Attribute : D->attrs())
3004 if (Attribute->getKind() == Kind)
3005 return true;
3006 return false;
3007}
3008
3009/// checkNewAttributesAfterDef - If we already have a definition, check that
3010/// there are no new attributes in this declaration.
3011static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3012 if (!New->hasAttrs())
3013 return;
3014
3015 const NamedDecl *Def = getDefinition(Old);
3016 if (!Def || Def == New)
3017 return;
3018
3019 AttrVec &NewAttributes = New->getAttrs();
3020 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3021 const Attr *NewAttribute = NewAttributes[I];
3022
3023 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3025 Sema::SkipBodyInfo SkipBody;
3026 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3027
3028 // If we're skipping this definition, drop the "alias" attribute.
3029 if (SkipBody.ShouldSkip) {
3030 NewAttributes.erase(NewAttributes.begin() + I);
3031 --E;
3032 continue;
3033 }
3034 } else {
3035 VarDecl *VD = cast<VarDecl>(New);
3036 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3038 ? diag::err_alias_after_tentative
3039 : diag::err_redefinition;
3040 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3041 if (Diag == diag::err_redefinition)
3042 S.notePreviousDefinition(Def, VD->getLocation());
3043 else
3044 S.Diag(Def->getLocation(), diag::note_previous_definition);
3045 VD->setInvalidDecl();
3046 }
3047 ++I;
3048 continue;
3049 }
3050
3051 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3052 // Tentative definitions are only interesting for the alias check above.
3053 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3054 ++I;
3055 continue;
3056 }
3057 }
3058
3059 if (hasAttribute(Def, NewAttribute->getKind())) {
3060 ++I;
3061 continue; // regular attr merging will take care of validating this.
3062 }
3063
3064 if (isa<C11NoReturnAttr>(NewAttribute)) {
3065 // C's _Noreturn is allowed to be added to a function after it is defined.
3066 ++I;
3067 continue;
3068 } else if (isa<UuidAttr>(NewAttribute)) {
3069 // msvc will allow a subsequent definition to add an uuid to a class
3070 ++I;
3071 continue;
3072 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3073 if (AA->isAlignas()) {
3074 // C++11 [dcl.align]p6:
3075 // if any declaration of an entity has an alignment-specifier,
3076 // every defining declaration of that entity shall specify an
3077 // equivalent alignment.
3078 // C11 6.7.5/7:
3079 // If the definition of an object does not have an alignment
3080 // specifier, any other declaration of that object shall also
3081 // have no alignment specifier.
3082 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3083 << AA;
3084 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3085 << AA;
3086 NewAttributes.erase(NewAttributes.begin() + I);
3087 --E;
3088 continue;
3089 }
3090 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3091 // If there is a C definition followed by a redeclaration with this
3092 // attribute then there are two different definitions. In C++, prefer the
3093 // standard diagnostics.
3094 if (!S.getLangOpts().CPlusPlus) {
3095 S.Diag(NewAttribute->getLocation(),
3096 diag::err_loader_uninitialized_redeclaration);
3097 S.Diag(Def->getLocation(), diag::note_previous_definition);
3098 NewAttributes.erase(NewAttributes.begin() + I);
3099 --E;
3100 continue;
3101 }
3102 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3103 cast<VarDecl>(New)->isInline() &&
3104 !cast<VarDecl>(New)->isInlineSpecified()) {
3105 // Don't warn about applying selectany to implicitly inline variables.
3106 // Older compilers and language modes would require the use of selectany
3107 // to make such variables inline, and it would have no effect if we
3108 // honored it.
3109 ++I;
3110 continue;
3111 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3112 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3113 // declarations after definitions.
3114 ++I;
3115 continue;
3116 }
3117
3118 S.Diag(NewAttribute->getLocation(),
3119 diag::warn_attribute_precede_definition);
3120 S.Diag(Def->getLocation(), diag::note_previous_definition);
3121 NewAttributes.erase(NewAttributes.begin() + I);
3122 --E;
3123 }
3124}
3125
3126static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3127 const ConstInitAttr *CIAttr,
3128 bool AttrBeforeInit) {
3129 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3130
3131 // Figure out a good way to write this specifier on the old declaration.
3132 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3133 // enough of the attribute list spelling information to extract that without
3134 // heroics.
3135 std::string SuitableSpelling;
3136 if (S.getLangOpts().CPlusPlus20)
3137 SuitableSpelling = std::string(
3138 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3139 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3140 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3141 InsertLoc, {tok::l_square, tok::l_square,
3142 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3143 S.PP.getIdentifierInfo("require_constant_initialization"),
3144 tok::r_square, tok::r_square}));
3145 if (SuitableSpelling.empty())
3146 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3147 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3148 S.PP.getIdentifierInfo("require_constant_initialization"),
3149 tok::r_paren, tok::r_paren}));
3150 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3151 SuitableSpelling = "constinit";
3152 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3153 SuitableSpelling = "[[clang::require_constant_initialization]]";
3154 if (SuitableSpelling.empty())
3155 SuitableSpelling = "__attribute__((require_constant_initialization))";
3156 SuitableSpelling += " ";
3157
3158 if (AttrBeforeInit) {
3159 // extern constinit int a;
3160 // int a = 0; // error (missing 'constinit'), accepted as extension
3161 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3162 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3163 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3164 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3165 } else {
3166 // int a = 0;
3167 // constinit extern int a; // error (missing 'constinit')
3168 S.Diag(CIAttr->getLocation(),
3169 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3170 : diag::warn_require_const_init_added_too_late)
3171 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3172 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3173 << CIAttr->isConstinit()
3174 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3175 }
3176}
3177
3178/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3181 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3182 UsedAttr *NewAttr = OldAttr->clone(Context);
3183 NewAttr->setInherited(true);
3184 New->addAttr(NewAttr);
3185 }
3186 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3187 RetainAttr *NewAttr = OldAttr->clone(Context);
3188 NewAttr->setInherited(true);
3189 New->addAttr(NewAttr);
3190 }
3191
3192 if (!Old->hasAttrs() && !New->hasAttrs())
3193 return;
3194
3195 // [dcl.constinit]p1:
3196 // If the [constinit] specifier is applied to any declaration of a
3197 // variable, it shall be applied to the initializing declaration.
3198 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3199 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3200 if (bool(OldConstInit) != bool(NewConstInit)) {
3201 const auto *OldVD = cast<VarDecl>(Old);
3202 auto *NewVD = cast<VarDecl>(New);
3203
3204 // Find the initializing declaration. Note that we might not have linked
3205 // the new declaration into the redeclaration chain yet.
3206 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3207 if (!InitDecl &&
3208 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3209 InitDecl = NewVD;
3210
3211 if (InitDecl == NewVD) {
3212 // This is the initializing declaration. If it would inherit 'constinit',
3213 // that's ill-formed. (Note that we do not apply this to the attribute
3214 // form).
3215 if (OldConstInit && OldConstInit->isConstinit())
3216 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3217 /*AttrBeforeInit=*/true);
3218 } else if (NewConstInit) {
3219 // This is the first time we've been told that this declaration should
3220 // have a constant initializer. If we already saw the initializing
3221 // declaration, this is too late.
3222 if (InitDecl && InitDecl != NewVD) {
3223 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3224 /*AttrBeforeInit=*/false);
3225 NewVD->dropAttr<ConstInitAttr>();
3226 }
3227 }
3228 }
3229
3230 // Attributes declared post-definition are currently ignored.
3231 checkNewAttributesAfterDef(*this, New, Old);
3232
3233 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3234 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3235 if (!OldA->isEquivalent(NewA)) {
3236 // This redeclaration changes __asm__ label.
3237 Diag(New->getLocation(), diag::err_different_asm_label);
3238 Diag(OldA->getLocation(), diag::note_previous_declaration);
3239 }
3240 } else if (Old->isUsed()) {
3241 // This redeclaration adds an __asm__ label to a declaration that has
3242 // already been ODR-used.
3243 Diag(New->getLocation(), diag::err_late_asm_label_name)
3244 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3245 }
3246 }
3247
3248 // Re-declaration cannot add abi_tag's.
3249 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3250 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3251 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3252 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3253 Diag(NewAbiTagAttr->getLocation(),
3254 diag::err_new_abi_tag_on_redeclaration)
3255 << NewTag;
3256 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3257 }
3258 }
3259 } else {
3260 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3261 Diag(Old->getLocation(), diag::note_previous_declaration);
3262 }
3263 }
3264
3265 // This redeclaration adds a section attribute.
3266 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3267 if (auto *VD = dyn_cast<VarDecl>(New)) {
3268 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3269 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3270 Diag(Old->getLocation(), diag::note_previous_declaration);
3271 }
3272 }
3273 }
3274
3275 // Redeclaration adds code-seg attribute.
3276 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3277 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3278 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3279 Diag(New->getLocation(), diag::warn_mismatched_section)
3280 << 0 /*codeseg*/;
3281 Diag(Old->getLocation(), diag::note_previous_declaration);
3282 }
3283
3284 if (!Old->hasAttrs())
3285 return;
3286
3287 bool foundAny = New->hasAttrs();
3288
3289 // Ensure that any moving of objects within the allocated map is done before
3290 // we process them.
3291 if (!foundAny) New->setAttrs(AttrVec());
3292
3293 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3294 // Ignore deprecated/unavailable/availability attributes if requested.
3296 if (isa<DeprecatedAttr>(I) ||
3297 isa<UnavailableAttr>(I) ||
3298 isa<AvailabilityAttr>(I)) {
3299 switch (AMK) {
3300 case AMK_None:
3301 continue;
3302
3303 case AMK_Redeclaration:
3304 case AMK_Override:
3307 LocalAMK = AMK;
3308 break;
3309 }
3310 }
3311
3312 // Already handled.
3313 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3314 continue;
3315
3316 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3317 foundAny = true;
3318 }
3319
3320 if (mergeAlignedAttrs(*this, New, Old))
3321 foundAny = true;
3322
3323 if (!foundAny) New->dropAttrs();
3324}
3325
3326/// mergeParamDeclAttributes - Copy attributes from the old parameter
3327/// to the new one.
3329 const ParmVarDecl *oldDecl,
3330 Sema &S) {
3331 // C++11 [dcl.attr.depend]p2:
3332 // The first declaration of a function shall specify the
3333 // carries_dependency attribute for its declarator-id if any declaration
3334 // of the function specifies the carries_dependency attribute.
3335 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3336 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3337 S.Diag(CDA->getLocation(),
3338 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3339 // Find the first declaration of the parameter.
3340 // FIXME: Should we build redeclaration chains for function parameters?
3341 const FunctionDecl *FirstFD =
3342 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3343 const ParmVarDecl *FirstVD =
3344 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3345 S.Diag(FirstVD->getLocation(),
3346 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3347 }
3348
3349 // HLSL parameter declarations for inout and out must match between
3350 // declarations. In HLSL inout and out are ambiguous at the call site, but
3351 // have different calling behavior, so you cannot overload a method based on a
3352 // difference between inout and out annotations.
3353 if (S.getLangOpts().HLSL) {
3354 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3355 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3356 // We don't need to cover the case where one declaration doesn't have an
3357 // attribute. The only possible case there is if one declaration has an `in`
3358 // attribute and the other declaration has no attribute. This case is
3359 // allowed since parameters are `in` by default.
3360 if (NDAttr && ODAttr &&
3361 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3362 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3363 << NDAttr << newDecl;
3364 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3365 << ODAttr;
3366 }
3367 }
3368
3369 if (!oldDecl->hasAttrs())
3370 return;
3371
3372 bool foundAny = newDecl->hasAttrs();
3373
3374 // Ensure that any moving of objects within the allocated map is
3375 // done before we process them.
3376 if (!foundAny) newDecl->setAttrs(AttrVec());
3377
3378 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3379 if (!DeclHasAttr(newDecl, I)) {
3380 InheritableAttr *newAttr =
3381 cast<InheritableParamAttr>(I->clone(S.Context));
3382 newAttr->setInherited(true);
3383 newDecl->addAttr(newAttr);
3384 foundAny = true;
3385 }
3386 }
3387
3388 if (!foundAny) newDecl->dropAttrs();
3389}
3390
3392 const ASTContext &Ctx) {
3393
3394 auto NoSizeInfo = [&Ctx](QualType Ty) {
3395 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3396 return true;
3397 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3398 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3399 return false;
3400 };
3401
3402 // `type[]` is equivalent to `type *` and `type[*]`.
3403 if (NoSizeInfo(Old) && NoSizeInfo(New))
3404 return true;
3405
3406 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3407 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3408 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3409 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3410 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3411 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3412 return false;
3413 return true;
3414 }
3415
3416 // Only compare size, ignore Size modifiers and CVR.
3417 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3418 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3419 Ctx.getAsConstantArrayType(New)->getSize();
3420 }
3421
3422 // Don't try to compare dependent sized array
3424 return true;
3425 }
3426
3427 return Old == New;
3428}
3429
3430static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3431 const ParmVarDecl *OldParam,
3432 Sema &S) {
3433 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3434 if (auto Newnullability = NewParam->getType()->getNullability()) {
3435 if (*Oldnullability != *Newnullability) {
3436 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3438 *Newnullability,
3440 != 0))
3442 *Oldnullability,
3444 != 0));
3445 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3446 }
3447 } else {
3448 QualType NewT = NewParam->getType();
3449 NewT = S.Context.getAttributedType(
3451 NewT, NewT);
3452 NewParam->setType(NewT);
3453 }
3454 }
3455 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3456 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3457 if (OldParamDT && NewParamDT &&
3458 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3459 QualType OldParamOT = OldParamDT->getOriginalType();
3460 QualType NewParamOT = NewParamDT->getOriginalType();
3461 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3462 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3463 << NewParam << NewParamOT;
3464 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3465 << OldParamOT;
3466 }
3467 }
3468}
3469
3470namespace {
3471
3472/// Used in MergeFunctionDecl to keep track of function parameters in
3473/// C.
3474struct GNUCompatibleParamWarning {
3475 ParmVarDecl *OldParm;
3476 ParmVarDecl *NewParm;
3477 QualType PromotedType;
3478};
3479
3480} // end anonymous namespace
3481
3482// Determine whether the previous declaration was a definition, implicit
3483// declaration, or a declaration.
3484template <typename T>
3485static std::pair<diag::kind, SourceLocation>
3486getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3487 diag::kind PrevDiag;
3488 SourceLocation OldLocation = Old->getLocation();
3489 if (Old->isThisDeclarationADefinition())
3490 PrevDiag = diag::note_previous_definition;
3491 else if (Old->isImplicit()) {
3492 PrevDiag = diag::note_previous_implicit_declaration;
3493 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3494 if (FD->getBuiltinID())
3495 PrevDiag = diag::note_previous_builtin_declaration;
3496 }
3497 if (OldLocation.isInvalid())
3498 OldLocation = New->getLocation();
3499 } else
3500 PrevDiag = diag::note_previous_declaration;
3501 return std::make_pair(PrevDiag, OldLocation);
3502}
3503
3504/// canRedefineFunction - checks if a function can be redefined. Currently,
3505/// only extern inline functions can be redefined, and even then only in
3506/// GNU89 mode.
3507static bool canRedefineFunction(const FunctionDecl *FD,
3508 const LangOptions& LangOpts) {
3509 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3510 !LangOpts.CPlusPlus &&
3511 FD->isInlineSpecified() &&
3512 FD->getStorageClass() == SC_Extern);
3513}
3514
3516 const AttributedType *AT = T->getAs<AttributedType>();
3517 while (AT && !AT->isCallingConv())
3518 AT = AT->getModifiedType()->getAs<AttributedType>();
3519 return AT;
3520}
3521
3522template <typename T>
3523static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3524 const DeclContext *DC = Old->getDeclContext();
3525 if (DC->isRecord())
3526 return false;
3527
3528 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3529 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3530 return true;
3531 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3532 return true;
3533 return false;
3534}
3535
3536template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3537static bool isExternC(VarTemplateDecl *) { return false; }
3538static bool isExternC(FunctionTemplateDecl *) { return false; }
3539
3540/// Check whether a redeclaration of an entity introduced by a
3541/// using-declaration is valid, given that we know it's not an overload
3542/// (nor a hidden tag declaration).
3543template<typename ExpectedDecl>
3545 ExpectedDecl *New) {
3546 // C++11 [basic.scope.declarative]p4:
3547 // Given a set of declarations in a single declarative region, each of
3548 // which specifies the same unqualified name,
3549 // -- they shall all refer to the same entity, or all refer to functions
3550 // and function templates; or
3551 // -- exactly one declaration shall declare a class name or enumeration
3552 // name that is not a typedef name and the other declarations shall all
3553 // refer to the same variable or enumerator, or all refer to functions
3554 // and function templates; in this case the class name or enumeration
3555 // name is hidden (3.3.10).
3556
3557 // C++11 [namespace.udecl]p14:
3558 // If a function declaration in namespace scope or block scope has the
3559 // same name and the same parameter-type-list as a function introduced
3560 // by a using-declaration, and the declarations do not declare the same
3561 // function, the program is ill-formed.
3562
3563 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3564 if (Old &&
3565 !Old->getDeclContext()->getRedeclContext()->Equals(
3566 New->getDeclContext()->getRedeclContext()) &&
3567 !(isExternC(Old) && isExternC(New)))
3568 Old = nullptr;
3569
3570 if (!Old) {
3571 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3572 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3573 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3574 return true;
3575 }
3576 return false;
3577}
3578
3580 const FunctionDecl *B) {
3581 assert(A->getNumParams() == B->getNumParams());
3582
3583 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3584 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3585 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3586 if (AttrA == AttrB)
3587 return true;
3588 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3589 AttrA->isDynamic() == AttrB->isDynamic();
3590 };
3591
3592 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3593}
3594
3595/// If necessary, adjust the semantic declaration context for a qualified
3596/// declaration to name the correct inline namespace within the qualifier.
3598 DeclaratorDecl *OldD) {
3599 // The only case where we need to update the DeclContext is when
3600 // redeclaration lookup for a qualified name finds a declaration
3601 // in an inline namespace within the context named by the qualifier:
3602 //
3603 // inline namespace N { int f(); }
3604 // int ::f(); // Sema DC needs adjusting from :: to N::.
3605 //
3606 // For unqualified declarations, the semantic context *can* change
3607 // along the redeclaration chain (for local extern declarations,
3608 // extern "C" declarations, and friend declarations in particular).
3609 if (!NewD->getQualifier())
3610 return;
3611
3612 // NewD is probably already in the right context.
3613 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3614 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3615 if (NamedDC->Equals(SemaDC))
3616 return;
3617
3618 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3619 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3620 "unexpected context for redeclaration");
3621
3622 auto *LexDC = NewD->getLexicalDeclContext();
3623 auto FixSemaDC = [=](NamedDecl *D) {
3624 if (!D)
3625 return;
3626 D->setDeclContext(SemaDC);
3627 D->setLexicalDeclContext(LexDC);
3628 };
3629
3630 FixSemaDC(NewD);
3631 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3632 FixSemaDC(FD->getDescribedFunctionTemplate());
3633 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3634 FixSemaDC(VD->getDescribedVarTemplate());
3635}
3636
3637/// MergeFunctionDecl - We just parsed a function 'New' from
3638/// declarator D which has the same name and scope as a previous
3639/// declaration 'Old'. Figure out how to resolve this situation,
3640/// merging decls or emitting diagnostics as appropriate.
3641///
3642/// In C++, New and Old must be declarations that are not
3643/// overloaded. Use IsOverload to determine whether New and Old are
3644/// overloaded, and to select the Old declaration that New should be
3645/// merged with.
3646///
3647/// Returns true if there was an error, false otherwise.
3649 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3650 // Verify the old decl was also a function.
3651 FunctionDecl *Old = OldD->getAsFunction();
3652 if (!Old) {
3653 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3654 if (New->getFriendObjectKind()) {
3655 Diag(New->getLocation(), diag::err_using_decl_friend);
3656 Diag(Shadow->getTargetDecl()->getLocation(),
3657 diag::note_using_decl_target);
3658 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3659 << 0;
3660 return true;
3661 }
3662
3663 // Check whether the two declarations might declare the same function or
3664 // function template.
3665 if (FunctionTemplateDecl *NewTemplate =
3667 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3668 NewTemplate))
3669 return true;
3670 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3671 ->getAsFunction();
3672 } else {
3673 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3674 return true;
3675 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3676 }
3677 } else {
3678 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3679 << New->getDeclName();
3680 notePreviousDefinition(OldD, New->getLocation());
3681 return true;
3682 }
3683 }
3684
3685 // If the old declaration was found in an inline namespace and the new
3686 // declaration was qualified, update the DeclContext to match.
3688
3689 // If the old declaration is invalid, just give up here.
3690 if (Old->isInvalidDecl())
3691 return true;
3692
3693 // Disallow redeclaration of some builtins.
3694 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3695 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3696 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3697 << Old << Old->getType();
3698 return true;
3699 }
3700
3701 diag::kind PrevDiag;
3702 SourceLocation OldLocation;
3703 std::tie(PrevDiag, OldLocation) =
3705
3706 // Don't complain about this if we're in GNU89 mode and the old function
3707 // is an extern inline function.
3708 // Don't complain about specializations. They are not supposed to have
3709 // storage classes.
3710 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3711 New->getStorageClass() == SC_Static &&
3712 Old->hasExternalFormalLinkage() &&
3715 if (getLangOpts().MicrosoftExt) {
3716 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3717 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3718 } else {
3719 Diag(New->getLocation(), diag::err_static_non_static) << New;
3720 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3721 return true;
3722 }
3723 }
3724
3725 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3726 if (!Old->hasAttr<InternalLinkageAttr>()) {
3727 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3728 << ILA;
3729 Diag(Old->getLocation(), diag::note_previous_declaration);
3730 New->dropAttr<InternalLinkageAttr>();
3731 }
3732
3733 if (auto *EA = New->getAttr<ErrorAttr>()) {
3734 if (!Old->hasAttr<ErrorAttr>()) {
3735 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3736 Diag(Old->getLocation(), diag::note_previous_declaration);
3737 New->dropAttr<ErrorAttr>();
3738 }
3739 }
3740
3741 if (CheckRedeclarationInModule(New, Old))
3742 return true;
3743
3744 if (!getLangOpts().CPlusPlus) {
3745 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3746 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3747 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3748 << New << OldOvl;
3749
3750 // Try our best to find a decl that actually has the overloadable
3751 // attribute for the note. In most cases (e.g. programs with only one
3752 // broken declaration/definition), this won't matter.
3753 //
3754 // FIXME: We could do this if we juggled some extra state in
3755 // OverloadableAttr, rather than just removing it.
3756 const Decl *DiagOld = Old;
3757 if (OldOvl) {
3758 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3759 const auto *A = D->getAttr<OverloadableAttr>();
3760 return A && !A->isImplicit();
3761 });
3762 // If we've implicitly added *all* of the overloadable attrs to this
3763 // chain, emitting a "previous redecl" note is pointless.
3764 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3765 }
3766
3767 if (DiagOld)
3768 Diag(DiagOld->getLocation(),
3769 diag::note_attribute_overloadable_prev_overload)
3770 << OldOvl;
3771
3772 if (OldOvl)
3773 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3774 else
3775 New->dropAttr<OverloadableAttr>();
3776 }
3777 }
3778
3779 // It is not permitted to redeclare an SME function with different SME
3780 // attributes.
3781 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3782 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3783 << New->getType() << Old->getType();
3784 Diag(OldLocation, diag::note_previous_declaration);
3785 return true;
3786 }
3787
3788 // If a function is first declared with a calling convention, but is later
3789 // declared or defined without one, all following decls assume the calling
3790 // convention of the first.
3791 //
3792 // It's OK if a function is first declared without a calling convention,
3793 // but is later declared or defined with the default calling convention.
3794 //
3795 // To test if either decl has an explicit calling convention, we look for
3796 // AttributedType sugar nodes on the type as written. If they are missing or
3797 // were canonicalized away, we assume the calling convention was implicit.
3798 //
3799 // Note also that we DO NOT return at this point, because we still have
3800 // other tests to run.
3801 QualType OldQType = Context.getCanonicalType(Old->getType());
3802 QualType NewQType = Context.getCanonicalType(New->getType());
3803 const FunctionType *OldType = cast<FunctionType>(OldQType);
3804 const FunctionType *NewType = cast<FunctionType>(NewQType);
3805 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3806 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3807 bool RequiresAdjustment = false;
3808
3809 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3811 const FunctionType *FT =
3812 First->getType().getCanonicalType()->castAs<FunctionType>();
3814 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3815 if (!NewCCExplicit) {
3816 // Inherit the CC from the previous declaration if it was specified
3817 // there but not here.
3818 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3819 RequiresAdjustment = true;
3820 } else if (Old->getBuiltinID()) {
3821 // Builtin attribute isn't propagated to the new one yet at this point,
3822 // so we check if the old one is a builtin.
3823
3824 // Calling Conventions on a Builtin aren't really useful and setting a
3825 // default calling convention and cdecl'ing some builtin redeclarations is
3826 // common, so warn and ignore the calling convention on the redeclaration.
3827 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3828 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3830 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3831 RequiresAdjustment = true;
3832 } else {
3833 // Calling conventions aren't compatible, so complain.
3834 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3835 Diag(New->getLocation(), diag::err_cconv_change)
3836 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3837 << !FirstCCExplicit
3838 << (!FirstCCExplicit ? "" :
3840
3841 // Put the note on the first decl, since it is the one that matters.
3842 Diag(First->getLocation(), diag::note_previous_declaration);
3843 return true;
3844 }
3845 }
3846
3847 // FIXME: diagnose the other way around?
3848 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3849 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3850 RequiresAdjustment = true;
3851 }
3852
3853 // Merge regparm attribute.
3854 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3855 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3856 if (NewTypeInfo.getHasRegParm()) {
3857 Diag(New->getLocation(), diag::err_regparm_mismatch)
3858 << NewType->getRegParmType()
3859 << OldType->getRegParmType();
3860 Diag(OldLocation, diag::note_previous_declaration);
3861 return true;
3862 }
3863
3864 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3865 RequiresAdjustment = true;
3866 }
3867
3868 // Merge ns_returns_retained attribute.
3869 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3870 if (NewTypeInfo.getProducesResult()) {
3871 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3872 << "'ns_returns_retained'";
3873 Diag(OldLocation, diag::note_previous_declaration);
3874 return true;
3875 }
3876
3877 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3878 RequiresAdjustment = true;
3879 }
3880
3881 if (OldTypeInfo.getNoCallerSavedRegs() !=
3882 NewTypeInfo.getNoCallerSavedRegs()) {
3883 if (NewTypeInfo.getNoCallerSavedRegs()) {
3884 AnyX86NoCallerSavedRegistersAttr *Attr =
3885 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3886 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3887 Diag(OldLocation, diag::note_previous_declaration);
3888 return true;
3889 }
3890
3891 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3892 RequiresAdjustment = true;
3893 }
3894
3895 if (RequiresAdjustment) {
3898 New->setType(QualType(AdjustedType, 0));
3899 NewQType = Context.getCanonicalType(New->getType());
3900 }
3901
3902 // If this redeclaration makes the function inline, we may need to add it to
3903 // UndefinedButUsed.
3904 if (!Old->isInlined() && New->isInlined() &&
3905 !New->hasAttr<GNUInlineAttr>() &&
3906 !getLangOpts().GNUInline &&
3907 Old->isUsed(false) &&
3908 !Old->isDefined() && !New->isThisDeclarationADefinition())
3909 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3910 SourceLocation()));
3911
3912 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3913 // about it.
3914 if (New->hasAttr<GNUInlineAttr>() &&
3915 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3916 UndefinedButUsed.erase(Old->getCanonicalDecl());
3917 }
3918
3919 // If pass_object_size params don't match up perfectly, this isn't a valid
3920 // redeclaration.
3921 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3923 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3924 << New->getDeclName();
3925 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3926 return true;
3927 }
3928
3929 if (getLangOpts().CPlusPlus) {
3930 OldQType = Context.getCanonicalType(Old->getType());
3931 NewQType = Context.getCanonicalType(New->getType());
3932
3933 // Go back to the type source info to compare the declared return types,
3934 // per C++1y [dcl.type.auto]p13:
3935 // Redeclarations or specializations of a function or function template
3936 // with a declared return type that uses a placeholder type shall also
3937 // use that placeholder, not a deduced type.
3938 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3939 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3940 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3941 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3942 OldDeclaredReturnType)) {
3943 QualType ResQT;
3944 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3945 OldDeclaredReturnType->isObjCObjectPointerType())
3946 // FIXME: This does the wrong thing for a deduced return type.
3947 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3948 if (ResQT.isNull()) {
3949 if (New->isCXXClassMember() && New->isOutOfLine())
3950 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3951 << New << New->getReturnTypeSourceRange();
3952 else
3953 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3954 << New->getReturnTypeSourceRange();
3955 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3956 << Old->getReturnTypeSourceRange();
3957 return true;
3958 }
3959 else
3960 NewQType = ResQT;
3961 }
3962
3963 QualType OldReturnType = OldType->getReturnType();
3964 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3965 if (OldReturnType != NewReturnType) {
3966 // If this function has a deduced return type and has already been
3967 // defined, copy the deduced value from the old declaration.
3968 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3969 if (OldAT && OldAT->isDeduced()) {
3970 QualType DT = OldAT->getDeducedType();
3971 if (DT.isNull()) {
3973 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3974 } else {
3975 New->setType(SubstAutoType(New->getType(), DT));
3976 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3977 }
3978 }
3979 }
3980
3981 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3982 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3983 if (OldMethod && NewMethod) {
3984 // Preserve triviality.
3985 NewMethod->setTrivial(OldMethod->isTrivial());
3986
3987 // MSVC allows explicit template specialization at class scope:
3988 // 2 CXXMethodDecls referring to the same function will be injected.
3989 // We don't want a redeclaration error.
3990 bool IsClassScopeExplicitSpecialization =
3991 OldMethod->isFunctionTemplateSpecialization() &&
3993 bool isFriend = NewMethod->getFriendObjectKind();
3994
3995 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3996 !IsClassScopeExplicitSpecialization) {
3997 // -- Member function declarations with the same name and the
3998 // same parameter types cannot be overloaded if any of them
3999 // is a static member function declaration.
4000 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4001 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4002 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4003 return true;
4004 }
4005
4006 // C++ [class.mem]p1:
4007 // [...] A member shall not be declared twice in the
4008 // member-specification, except that a nested class or member
4009 // class template can be declared and then later defined.
4010 if (!inTemplateInstantiation()) {
4011 unsigned NewDiag;
4012 if (isa<CXXConstructorDecl>(OldMethod))
4013 NewDiag = diag::err_constructor_redeclared;
4014 else if (isa<CXXDestructorDecl>(NewMethod))
4015 NewDiag = diag::err_destructor_redeclared;
4016 else if (isa<CXXConversionDecl>(NewMethod))
4017 NewDiag = diag::err_conv_function_redeclared;
4018 else
4019 NewDiag = diag::err_member_redeclared;
4020
4021 Diag(New->getLocation(), NewDiag);
4022 } else {
4023 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4024 << New << New->getType();
4025 }
4026 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4027 return true;
4028
4029 // Complain if this is an explicit declaration of a special
4030 // member that was initially declared implicitly.
4031 //
4032 // As an exception, it's okay to befriend such methods in order
4033 // to permit the implicit constructor/destructor/operator calls.
4034 } else if (OldMethod->isImplicit()) {
4035 if (isFriend) {
4036 NewMethod->setImplicit();
4037 } else {
4038 Diag(NewMethod->getLocation(),
4039 diag::err_definition_of_implicitly_declared_member)
4040 << New << getSpecialMember(OldMethod);
4041 return true;
4042 }
4043 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4044 Diag(NewMethod->getLocation(),
4045 diag::err_definition_of_explicitly_defaulted_member)
4046 << getSpecialMember(OldMethod);
4047 return true;
4048 }
4049 }
4050
4051 // C++1z [over.load]p2
4052 // Certain function declarations cannot be overloaded:
4053 // -- Function declarations that differ only in the return type,
4054 // the exception specification, or both cannot be overloaded.
4055
4056 // Check the exception specifications match. This may recompute the type of
4057 // both Old and New if it resolved exception specifications, so grab the
4058 // types again after this. Because this updates the type, we do this before
4059 // any of the other checks below, which may update the "de facto" NewQType
4060 // but do not necessarily update the type of New.
4061 if (CheckEquivalentExceptionSpec(Old, New))
4062 return true;
4063
4064 // C++11 [dcl.attr.noreturn]p1:
4065 // The first declaration of a function shall specify the noreturn
4066 // attribute if any declaration of that function specifies the noreturn
4067 // attribute.
4068 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4069 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4070 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4071 << NRA;
4072 Diag(Old->getLocation(), diag::note_previous_declaration);
4073 }
4074
4075 // C++11 [dcl.attr.depend]p2:
4076 // The first declaration of a function shall specify the
4077 // carries_dependency attribute for its declarator-id if any declaration
4078 // of the function specifies the carries_dependency attribute.
4079 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4080 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4081 Diag(CDA->getLocation(),
4082 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4083 Diag(Old->getFirstDecl()->getLocation(),
4084 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4085 }
4086
4087 // (C++98 8.3.5p3):
4088 // All declarations for a function shall agree exactly in both the
4089 // return type and the parameter-type-list.
4090 // We also want to respect all the extended bits except noreturn.
4091
4092 // noreturn should now match unless the old type info didn't have it.
4093 QualType OldQTypeForComparison = OldQType;
4094 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4095 auto *OldType = OldQType->castAs<FunctionProtoType>();
4096 const FunctionType *OldTypeForComparison
4097 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4098 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4099 assert(OldQTypeForComparison.isCanonical());
4100 }
4101
4102 if (haveIncompatibleLanguageLinkages(Old, New)) {
4103 // As a special case, retain the language linkage from previous
4104 // declarations of a friend function as an extension.
4105 //
4106 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4107 // and is useful because there's otherwise no way to specify language
4108 // linkage within class scope.
4109 //
4110 // Check cautiously as the friend object kind isn't yet complete.
4111 if (New->getFriendObjectKind() != Decl::FOK_None) {
4112 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4113 Diag(OldLocation, PrevDiag);
4114 } else {
4115 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4116 Diag(OldLocation, PrevDiag);
4117 return true;
4118 }
4119 }
4120
4121 // If the function types are compatible, merge the declarations. Ignore the
4122 // exception specifier because it was already checked above in
4123 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4124 // about incompatible types under -fms-compatibility.
4125 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4126 NewQType))
4127 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4128
4129 // If the types are imprecise (due to dependent constructs in friends or
4130 // local extern declarations), it's OK if they differ. We'll check again
4131 // during instantiation.
4132 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4133 return false;
4134
4135 // Fall through for conflicting redeclarations and redefinitions.
4136 }
4137
4138 // C: Function types need to be compatible, not identical. This handles
4139 // duplicate function decls like "void f(int); void f(enum X);" properly.
4140 if (!getLangOpts().CPlusPlus) {
4141 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4142 // type is specified by a function definition that contains a (possibly
4143 // empty) identifier list, both shall agree in the number of parameters
4144 // and the type of each parameter shall be compatible with the type that
4145 // results from the application of default argument promotions to the
4146 // type of the corresponding identifier. ...
4147 // This cannot be handled by ASTContext::typesAreCompatible() because that
4148 // doesn't know whether the function type is for a definition or not when
4149 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4150 // we need to cover here is that the number of arguments agree as the
4151 // default argument promotion rules were already checked by
4152 // ASTContext::typesAreCompatible().
4153 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4154 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4155 if (Old->hasInheritedPrototype())
4156 Old = Old->getCanonicalDecl();
4157 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4158 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4159 return true;
4160 }
4161
4162 // If we are merging two functions where only one of them has a prototype,
4163 // we may have enough information to decide to issue a diagnostic that the
4164 // function without a protoype will change behavior in C23. This handles
4165 // cases like:
4166 // void i(); void i(int j);
4167 // void i(int j); void i();
4168 // void i(); void i(int j) {}
4169 // See ActOnFinishFunctionBody() for other cases of the behavior change
4170 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4171 // type without a prototype.
4172 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4173 !New->isImplicit() && !Old->isImplicit()) {
4174 const FunctionDecl *WithProto, *WithoutProto;
4175 if (New->hasWrittenPrototype()) {
4176 WithProto = New;
4177 WithoutProto = Old;
4178 } else {
4179 WithProto = Old;
4180 WithoutProto = New;
4181 }
4182
4183 if (WithProto->getNumParams() != 0) {
4184 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4185 // The one without the prototype will be changing behavior in C23, so
4186 // warn about that one so long as it's a user-visible declaration.
4187 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4188 if (WithoutProto == New)
4189 IsWithoutProtoADef = NewDeclIsDefn;
4190 else
4191 IsWithProtoADef = NewDeclIsDefn;
4192 Diag(WithoutProto->getLocation(),
4193 diag::warn_non_prototype_changes_behavior)
4194 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4195 << (WithoutProto == Old) << IsWithProtoADef;
4196
4197 // The reason the one without the prototype will be changing behavior
4198 // is because of the one with the prototype, so note that so long as
4199 // it's a user-visible declaration. There is one exception to this:
4200 // when the new declaration is a definition without a prototype, the
4201 // old declaration with a prototype is not the cause of the issue,
4202 // and that does not need to be noted because the one with a
4203 // prototype will not change behavior in C23.
4204 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4205 !IsWithoutProtoADef)
4206 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4207 }
4208 }
4209 }
4210
4211 if (Context.typesAreCompatible(OldQType, NewQType)) {
4212 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4213 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4214 const FunctionProtoType *OldProto = nullptr;
4215 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4216 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4217 // The old declaration provided a function prototype, but the
4218 // new declaration does not. Merge in the prototype.
4219 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4220 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4221 OldProto->getParamTypes(),
4222 OldProto->getExtProtoInfo());
4223 New->setType(NewQType);
4225
4226 // Synthesize parameters with the same types.
4228 for (const auto &ParamType : OldProto->param_types()) {
4230 Context, New, SourceLocation(), SourceLocation(), nullptr,
4231 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4232 Param->setScopeInfo(0, Params.size());
4233 Param->setImplicit();
4234 Params.push_back(Param);
4235 }
4236
4237 New->setParams(Params);
4238 }
4239
4240 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4241 }
4242 }
4243
4244 // Check if the function types are compatible when pointer size address
4245 // spaces are ignored.
4246 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4247 return false;
4248
4249 // GNU C permits a K&R definition to follow a prototype declaration
4250 // if the declared types of the parameters in the K&R definition
4251 // match the types in the prototype declaration, even when the
4252 // promoted types of the parameters from the K&R definition differ
4253 // from the types in the prototype. GCC then keeps the types from
4254 // the prototype.
4255 //
4256 // If a variadic prototype is followed by a non-variadic K&R definition,
4257 // the K&R definition becomes variadic. This is sort of an edge case, but
4258 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4259 // C99 6.9.1p8.
4260 if (!getLangOpts().CPlusPlus &&
4261 Old->hasPrototype() && !New->hasPrototype() &&
4262 New->getType()->getAs<FunctionProtoType>() &&
4263 Old->getNumParams() == New->getNumParams()) {
4266 const FunctionProtoType *OldProto
4267 = Old->getType()->getAs<FunctionProtoType>();
4268 const FunctionProtoType *NewProto
4269 = New->getType()->getAs<FunctionProtoType>();
4270
4271 // Determine whether this is the GNU C extension.
4272 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4273 NewProto->getReturnType());
4274 bool LooseCompatible = !MergedReturn.isNull();
4275 for (unsigned Idx = 0, End = Old->getNumParams();
4276 LooseCompatible && Idx != End; ++Idx) {
4277 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4278 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4279 if (Context.typesAreCompatible(OldParm->getType(),
4280 NewProto->getParamType(Idx))) {
4281 ArgTypes.push_back(NewParm->getType());
4282 } else if (Context.typesAreCompatible(OldParm->getType(),
4283 NewParm->getType(),
4284 /*CompareUnqualified=*/true)) {
4285 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4286 NewProto->getParamType(Idx) };
4287 Warnings.push_back(Warn);
4288 ArgTypes.push_back(NewParm->getType());
4289 } else
4290 LooseCompatible = false;
4291 }
4292
4293 if (LooseCompatible) {
4294 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4295 Diag(Warnings[Warn].NewParm->getLocation(),
4296 diag::ext_param_promoted_not_compatible_with_prototype)
4297 << Warnings[Warn].PromotedType
4298 << Warnings[Warn].OldParm->getType();
4299 if (Warnings[Warn].OldParm->getLocation().isValid())
4300 Diag(Warnings[Warn].OldParm->getLocation(),
4301 diag::note_previous_declaration);
4302 }
4303
4304 if (MergeTypeWithOld)
4305 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4306 OldProto->getExtProtoInfo()));
4307 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4308 }
4309
4310 // Fall through to diagnose conflicting types.
4311 }
4312
4313 // A function that has already been declared has been redeclared or
4314 // defined with a different type; show an appropriate diagnostic.
4315
4316 // If the previous declaration was an implicitly-generated builtin
4317 // declaration, then at the very least we should use a specialized note.
4318 unsigned BuiltinID;
4319 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4320 // If it's actually a library-defined builtin function like 'malloc'
4321 // or 'printf', just warn about the incompatible redeclaration.
4323 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4324 Diag(OldLocation, diag::note_previous_builtin_declaration)
4325 << Old << Old->getType();
4326 return false;
4327 }
4328
4329 PrevDiag = diag::note_previous_builtin_declaration;
4330 }
4331
4332 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4333 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4334 return true;
4335}
4336
4337/// Completes the merge of two function declarations that are
4338/// known to be compatible.
4339///
4340/// This routine handles the merging of attributes and other
4341/// properties of function declarations from the old declaration to
4342/// the new declaration, once we know that New is in fact a
4343/// redeclaration of Old.
4344///
4345/// \returns false
4347 Scope *S, bool MergeTypeWithOld) {
4348 // Merge the attributes
4349 mergeDeclAttributes(New, Old);
4350
4351 // Merge "pure" flag.
4352 if (Old->isPureVirtual())
4353 New->setIsPureVirtual();
4354
4355 // Merge "used" flag.
4356 if (Old->getMostRecentDecl()->isUsed(false))
4357 New->setIsUsed();
4358
4359 // Merge attributes from the parameters. These can mismatch with K&R
4360 // declarations.
4361 if (New->getNumParams() == Old->getNumParams())
4362 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4363 ParmVarDecl *NewParam = New->getParamDecl(i);
4364 ParmVarDecl *OldParam = Old->getParamDecl(i);
4365 mergeParamDeclAttributes(NewParam, OldParam, *this);
4366 mergeParamDeclTypes(NewParam, OldParam, *this);
4367 }
4368
4369 if (getLangOpts().CPlusPlus)
4370 return MergeCXXFunctionDecl(New, Old, S);
4371
4372 // Merge the function types so the we get the composite types for the return
4373 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4374 // was visible.
4375 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4376 if (!Merged.isNull() && MergeTypeWithOld)
4377 New->setType(Merged);
4378
4379 return false;
4380}
4381
4383 ObjCMethodDecl *oldMethod) {
4384 // Merge the attributes, including deprecated/unavailable
4385 AvailabilityMergeKind MergeKind =
4386 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4389 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4390 : AMK_Override;
4391
4392 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4393
4394 // Merge attributes from the parameters.
4396 oe = oldMethod->param_end();
4398 ni = newMethod->param_begin(), ne = newMethod->param_end();
4399 ni != ne && oi != oe; ++ni, ++oi)
4400 mergeParamDeclAttributes(*ni, *oi, *this);
4401
4402 CheckObjCMethodOverride(newMethod, oldMethod);
4403}
4404
4406 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4407
4409 ? diag::err_redefinition_different_type
4410 : diag::err_redeclaration_different_type)
4411 << New->getDeclName() << New->getType() << Old->getType();
4412
4413 diag::kind PrevDiag;
4414 SourceLocation OldLocation;
4415 std::tie(PrevDiag, OldLocation)
4417 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4418 New->setInvalidDecl();
4419}
4420
4421/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4422/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4423/// emitting diagnostics as appropriate.
4424///
4425/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4426/// to here in AddInitializerToDecl. We can't check them before the initializer
4427/// is attached.
4429 bool MergeTypeWithOld) {
4430 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4431 return;
4432
4433 QualType MergedT;
4434 if (getLangOpts().CPlusPlus) {
4435 if (New->getType()->isUndeducedType()) {
4436 // We don't know what the new type is until the initializer is attached.
4437 return;
4438 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4439 // These could still be something that needs exception specs checked.
4440 return MergeVarDeclExceptionSpecs(New, Old);
4441 }
4442 // C++ [basic.link]p10:
4443 // [...] the types specified by all declarations referring to a given
4444 // object or function shall be identical, except that declarations for an
4445 // array object can specify array types that differ by the presence or
4446 // absence of a major array bound (8.3.4).
4447 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4448 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4449 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4450
4451 // We are merging a variable declaration New into Old. If it has an array
4452 // bound, and that bound differs from Old's bound, we should diagnose the
4453 // mismatch.
4454 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4455 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4456 PrevVD = PrevVD->getPreviousDecl()) {
4457 QualType PrevVDTy = PrevVD->getType();
4458 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4459 continue;
4460
4461 if (!Context.hasSameType(New->getType(), PrevVDTy))
4462 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4463 }
4464 }
4465
4466 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4467 if (Context.hasSameType(OldArray->getElementType(),
4468 NewArray->getElementType()))
4469 MergedT = New->getType();
4470 }
4471 // FIXME: Check visibility. New is hidden but has a complete type. If New
4472 // has no array bound, it should not inherit one from Old, if Old is not
4473 // visible.
4474 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4475 if (Context.hasSameType(OldArray->getElementType(),
4476 NewArray->getElementType()))
4477 MergedT = Old->getType();
4478 }
4479 }
4480 else if (New->getType()->isObjCObjectPointerType() &&
4481 Old->getType()->isObjCObjectPointerType()) {
4482 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4483 Old->getType());
4484 }
4485 } else {
4486 // C 6.2.7p2:
4487 // All declarations that refer to the same object or function shall have
4488 // compatible type.
4489 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4490 }
4491 if (MergedT.isNull()) {
4492 // It's OK if we couldn't merge types if either type is dependent, for a
4493 // block-scope variable. In other cases (static data members of class
4494 // templates, variable templates, ...), we require the types to be
4495 // equivalent.
4496 // FIXME: The C++ standard doesn't say anything about this.
4497 if ((New->getType()->isDependentType() ||
4498 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4499 // If the old type was dependent, we can't merge with it, so the new type
4500 // becomes dependent for now. We'll reproduce the original type when we
4501 // instantiate the TypeSourceInfo for the variable.
4502 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4504 return;
4505 }
4506 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4507 }
4508
4509 // Don't actually update the type on the new declaration if the old
4510 // declaration was an extern declaration in a different scope.
4511 if (MergeTypeWithOld)
4512 New->setType(MergedT);
4513}
4514
4515static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4517 // C11 6.2.7p4:
4518 // For an identifier with internal or external linkage declared
4519 // in a scope in which a prior declaration of that identifier is
4520 // visible, if the prior declaration specifies internal or
4521 // external linkage, the type of the identifier at the later
4522 // declaration becomes the composite type.
4523 //
4524 // If the variable isn't visible, we do not merge with its type.
4525 if (Previous.isShadowed())
4526 return false;
4527
4528 if (S.getLangOpts().CPlusPlus) {
4529 // C++11 [dcl.array]p3:
4530 // If there is a preceding declaration of the entity in the same
4531 // scope in which the bound was specified, an omitted array bound
4532 // is taken to be the same as in that earlier declaration.
4533 return NewVD->isPreviousDeclInSameBlockScope() ||
4536 } else {
4537 // If the old declaration was function-local, don't merge with its
4538 // type unless we're in the same function.
4539 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4540 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4541 }
4542}
4543
4544/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4545/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4546/// situation, merging decls or emitting diagnostics as appropriate.
4547///
4548/// Tentative definition rules (C99 6.9.2p2) are checked by
4549/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4550/// definitions here, since the initializer hasn't been attached.
4551///
4553 // If the new decl is already invalid, don't do any other checking.
4554 if (New->isInvalidDecl())
4555 return;
4556
4557 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4558 return;
4559
4560 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4561
4562 // Verify the old decl was also a variable or variable template.
4563 VarDecl *Old = nullptr;
4564 VarTemplateDecl *OldTemplate = nullptr;
4565 if (Previous.isSingleResult()) {
4566 if (NewTemplate) {
4567 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4568 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4569
4570 if (auto *Shadow =
4571 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4572 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4573 return New->setInvalidDecl();
4574 } else {
4575 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4576
4577 if (auto *Shadow =
4578 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4579 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4580 return New->setInvalidDecl();
4581 }
4582 }
4583 if (!Old) {
4584 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4585 << New->getDeclName();
4586 notePreviousDefinition(Previous.getRepresentativeDecl(),
4587 New->getLocation());
4588 return New->setInvalidDecl();
4589 }
4590
4591 // If the old declaration was found in an inline namespace and the new
4592 // declaration was qualified, update the DeclContext to match.
4594
4595 // Ensure the template parameters are compatible.
4596 if (NewTemplate &&
4598 OldTemplate->getTemplateParameters(),
4599 /*Complain=*/true, TPL_TemplateMatch))
4600 return New->setInvalidDecl();
4601
4602 // C++ [class.mem]p1:
4603 // A member shall not be declared twice in the member-specification [...]
4604 //
4605 // Here, we need only consider static data members.
4606 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4607 Diag(New->getLocation(), diag::err_duplicate_member)
4608 << New->getIdentifier();
4609 Diag(Old->getLocation(), diag::note_previous_declaration);
4610 New->setInvalidDecl();
4611 }
4612
4613 mergeDeclAttributes(New, Old);
4614 // Warn if an already-declared variable is made a weak_import in a subsequent
4615 // declaration
4616 if (New->hasAttr<WeakImportAttr>() &&
4617 Old->getStorageClass() == SC_None &&
4618 !Old->hasAttr<WeakImportAttr>()) {
4619 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4620 Diag(Old->getLocation(), diag::note_previous_declaration);
4621 // Remove weak_import attribute on new declaration.
4622 New->dropAttr<WeakImportAttr>();
4623 }
4624
4625 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4626 if (!Old->hasAttr<InternalLinkageAttr>()) {
4627 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4628 << ILA;
4629 Diag(Old->getLocation(), diag::note_previous_declaration);
4630 New->dropAttr<InternalLinkageAttr>();
4631 }
4632
4633 // Merge the types.
4634 VarDecl *MostRecent = Old->getMostRecentDecl();
4635 if (MostRecent != Old) {
4636 MergeVarDeclTypes(New, MostRecent,
4637 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4638 if (New->isInvalidDecl())
4639 return;
4640 }
4641
4642 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4643 if (New->isInvalidDecl())
4644 return;
4645
4646 diag::kind PrevDiag;
4647 SourceLocation OldLocation;
4648 std::tie(PrevDiag, OldLocation) =
4650
4651 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4652 if (New->getStorageClass() == SC_Static &&
4653 !New->isStaticDataMember() &&
4654 Old->hasExternalFormalLinkage()) {
4655 if (getLangOpts().MicrosoftExt) {
4656 Diag(New->getLocation(), diag::ext_static_non_static)
4657 << New->getDeclName();
4658 Diag(OldLocation, PrevDiag);
4659 } else {
4660 Diag(New->getLocation(), diag::err_static_non_static)
4661 << New->getDeclName();
4662 Diag(OldLocation, PrevDiag);
4663 return New->setInvalidDecl();
4664 }
4665 }
4666 // C99 6.2.2p4:
4667 // For an identifier declared with the storage-class specifier
4668 // extern in a scope in which a prior declaration of that
4669 // identifier is visible,23) if the prior declaration specifies
4670 // internal or external linkage, the linkage of the identifier at
4671 // the later declaration is the same as the linkage specified at
4672 // the prior declaration. If no prior declaration is visible, or
4673 // if the prior declaration specifies no linkage, then the
4674 // identifier has external linkage.
4675 if (New->hasExternalStorage() && Old->hasLinkage())
4676 /* Okay */;
4677 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4678 !New->isStaticDataMember() &&
4680 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4681 Diag(OldLocation, PrevDiag);
4682 return New->setInvalidDecl();
4683 }
4684
4685 // Check if extern is followed by non-extern and vice-versa.
4686 if (New->hasExternalStorage() &&
4687 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4688 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4689 Diag(OldLocation, PrevDiag);
4690 return New->setInvalidDecl();
4691 }
4692 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4693 !New->hasExternalStorage()) {
4694 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4695 Diag(OldLocation, PrevDiag);
4696 return New->setInvalidDecl();
4697 }
4698
4699 if (CheckRedeclarationInModule(New, Old))
4700 return;
4701
4702 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4703
4704 // FIXME: The test for external storage here seems wrong? We still
4705 // need to check for mismatches.
4706 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4707 // Don't complain about out-of-line definitions of static members.
4708 !(Old->getLexicalDeclContext()->isRecord() &&
4709 !New->getLexicalDeclContext()->isRecord())) {
4710 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4711 Diag(OldLocation, PrevDiag);
4712 return New->setInvalidDecl();
4713 }
4714
4715 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4716 if (VarDecl *Def = Old->getDefinition()) {
4717 // C++1z [dcl.fcn.spec]p4:
4718 // If the definition of a variable appears in a translation unit before
4719 // its first declaration as inline, the program is ill-formed.
4720 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4721 Diag(Def->getLocation(), diag::note_previous_definition);
4722 }
4723 }
4724
4725 // If this redeclaration makes the variable inline, we may need to add it to
4726 // UndefinedButUsed.
4727 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4729 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4730 SourceLocation()));
4731
4732 if (New->getTLSKind() != Old->getTLSKind()) {
4733 if (!Old->getTLSKind()) {
4734 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4735 Diag(OldLocation, PrevDiag);
4736 } else if (!New->getTLSKind()) {
4737 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4738 Diag(OldLocation, PrevDiag);
4739 } else {
4740 // Do not allow redeclaration to change the variable between requiring
4741 // static and dynamic initialization.
4742 // FIXME: GCC allows this, but uses the TLS keyword on the first
4743 // declaration to determine the kind. Do we need to be compatible here?
4744 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4745 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4746 Diag(OldLocation, PrevDiag);
4747 }
4748 }
4749
4750 // C++ doesn't have tentative definitions, so go right ahead and check here.
4751 if (getLangOpts().CPlusPlus) {
4752 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4753 Old->getCanonicalDecl()->isConstexpr()) {
4754 // This definition won't be a definition any more once it's been merged.
4755 Diag(New->getLocation(),
4756 diag::warn_deprecated_redundant_constexpr_static_def);
4758 VarDecl *Def = Old->getDefinition();
4759 if (Def && checkVarDeclRedefinition(Def, New))
4760 return;
4761 }
4762 }
4763
4764 if (haveIncompatibleLanguageLinkages(Old, New)) {
4765 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4766 Diag(OldLocation, PrevDiag);
4767 New->setInvalidDecl();
4768 return;
4769 }
4770
4771 // Merge "used" flag.
4772 if (Old->getMostRecentDecl()->isUsed(false))
4773 New->setIsUsed();
4774
4775 // Keep a chain of previous declarations.
4776 New->setPreviousDecl(Old);
4777 if (NewTemplate)
4778 NewTemplate->setPreviousDecl(OldTemplate);
4779
4780 // Inherit access appropriately.
4781 New->setAccess(Old->getAccess());
4782 if (NewTemplate)
4783 NewTemplate->setAccess(New->getAccess());
4784
4785 if (Old->isInline())
4786 New->setImplicitlyInline();
4787}
4788
4790 SourceManager &SrcMgr = getSourceManager();
4791 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4792 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4793 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4794 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4795 auto &HSI = PP.getHeaderSearchInfo();
4796 StringRef HdrFilename =
4797 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4798
4799 auto noteFromModuleOrInclude = [&](Module *Mod,
4800 SourceLocation IncLoc) -> bool {
4801 // Redefinition errors with modules are common with non modular mapped
4802 // headers, example: a non-modular header H in module A that also gets
4803 // included directly in a TU. Pointing twice to the same header/definition
4804 // is confusing, try to get better diagnostics when modules is on.
4805 if (IncLoc.isValid()) {
4806 if (Mod) {
4807 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4808 << HdrFilename.str() << Mod->getFullModuleName();
4809 if (!Mod->DefinitionLoc.isInvalid())
4810 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4811 << Mod->getFullModuleName();
4812 } else {
4813 Diag(IncLoc, diag::note_redefinition_include_same_file)
4814 << HdrFilename.str();
4815 }
4816 return true;
4817 }
4818
4819 return false;
4820 };
4821
4822 // Is it the same file and same offset? Provide more information on why
4823 // this leads to a redefinition error.
4824 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4825 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4826 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4827 bool EmittedDiag =
4828 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4829 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4830
4831 // If the header has no guards, emit a note suggesting one.
4832 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4833 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4834
4835 if (EmittedDiag)
4836 return;
4837 }
4838
4839 // Redefinition coming from different files or couldn't do better above.
4840 if (Old->getLocation().isValid())
4841 Diag(Old->getLocation(), diag::note_previous_definition);
4842}
4843
4844/// We've just determined that \p Old and \p New both appear to be definitions
4845/// of the same variable. Either diagnose or fix the problem.
4847 if (!hasVisibleDefinition(Old) &&
4848 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4849 isa<VarTemplateSpecializationDecl>(New) ||
4852 // The previous definition is hidden, and multiple definitions are
4853 // permitted (in separate TUs). Demote this to a declaration.
4855
4856 // Make the canonical definition visible.
4857 if (auto *OldTD = Old->getDescribedVarTemplate())
4860 return false;
4861 } else {
4862 Diag(New->getLocation(), diag::err_redefinition) << New;
4864 New->setInvalidDecl();
4865 return true;
4866 }
4867}
4868
4869/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4870/// no declarator (e.g. "struct foo;") is parsed.
4872 DeclSpec &DS,
4873 const ParsedAttributesView &DeclAttrs,
4874 RecordDecl *&AnonRecord) {
4876 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4877}
4878
4879// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4880// disambiguate entities defined in different scopes.
4881// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4882// compatibility.
4883// We will pick our mangling number depending on which version of MSVC is being
4884// targeted.
4885static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4887 ? S->getMSCurManglingNumber()
4888 : S->getMSLastManglingNumber();
4889}
4890
4891void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4892 if (!Context.getLangOpts().CPlusPlus)
4893 return;
4894
4895 if (isa<CXXRecordDecl>(Tag->getParent())) {
4896 // If this tag is the direct child of a class, number it if
4897 // it is anonymous.
4898 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4899 return;
4903 Tag, MCtx.getManglingNumber(
4904 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4905 return;
4906 }
4907
4908 // If this tag isn't a direct child of a class, number it if it is local.
4910 Decl *ManglingContextDecl;
4911 std::tie(MCtx, ManglingContextDecl) =
4913 if (MCtx) {
4915 Tag, MCtx->getManglingNumber(
4916 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4917 }
4918}
4919
4920namespace {
4921struct NonCLikeKind {
4922 enum {
4923 None,
4924 BaseClass,
4925 DefaultMemberInit,
4926 Lambda,
4927 Friend,
4928 OtherMember,
4929 Invalid,
4930 } Kind = None;
4931 SourceRange Range;
4932
4933 explicit operator bool() { return Kind != None; }
4934};
4935}
4936
4937/// Determine whether a class is C-like, according to the rules of C++
4938/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4939static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4940 if (RD->isInvalidDecl())
4941 return {NonCLikeKind::Invalid, {}};
4942
4943 // C++ [dcl.typedef]p9: [P1766R1]
4944 // An unnamed class with a typedef name for linkage purposes shall not
4945 //
4946 // -- have any base classes
4947 if (RD->getNumBases())
4948 return {NonCLikeKind::BaseClass,
4950 RD->bases_end()[-1].getEndLoc())};
4951 bool Invalid = false;
4952 for (Decl *D : RD->decls()) {
4953 // Don't complain about things we already diagnosed.
4954 if (D->isInvalidDecl()) {
4955 Invalid = true;
4956 continue;
4957 }
4958
4959 // -- have any [...] default member initializers
4960 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4961 if (FD->hasInClassInitializer()) {
4962 auto *Init = FD->getInClassInitializer();
4963 return {NonCLikeKind::DefaultMemberInit,
4964 Init ? Init->getSourceRange() : D->getSourceRange()};
4965 }
4966 continue;
4967 }
4968
4969 // FIXME: We don't allow friend declarations. This violates the wording of
4970 // P1766, but not the intent.
4971 if (isa<FriendDecl>(D))
4972 return {NonCLikeKind::Friend, D->getSourceRange()};
4973
4974 // -- declare any members other than non-static data members, member
4975 // enumerations, or member classes,
4976 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4977 isa<EnumDecl>(D))
4978 continue;
4979 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4980 if (!MemberRD) {
4981 if (D->isImplicit())
4982 continue;
4983 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4984 }
4985
4986 // -- contain a lambda-expression,
4987 if (MemberRD->isLambda())
4988 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4989
4990 // and all member classes shall also satisfy these requirements
4991 // (recursively).
4992 if (MemberRD->isThisDeclarationADefinition()) {
4993 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4994 return Kind;
4995 }
4996 }
4997
4998 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4999}
5000
5002 TypedefNameDecl *NewTD) {
5003 if (TagFromDeclSpec->isInvalidDecl())
5004 return;
5005
5006 // Do nothing if the tag already has a name for linkage purposes.
5007 if (TagFromDeclSpec->hasNameForLinkage())
5008 return;
5009
5010 // A well-formed anonymous tag must always be a TUK_Definition.
5011 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5012
5013 // The type must match the tag exactly; no qualifiers allowed.
5015 Context.getTagDeclType(TagFromDeclSpec))) {
5016 if (getLangOpts().CPlusPlus)
5017 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5018 return;
5019 }
5020
5021 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5022 // An unnamed class with a typedef name for linkage purposes shall [be
5023 // C-like].
5024 //
5025 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5026 // shouldn't happen, but there are constructs that the language rule doesn't
5027 // disallow for which we can't reasonably avoid computing linkage early.
5028 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5029 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5030 : NonCLikeKind();
5031 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5032 if (NonCLike || ChangesLinkage) {
5033 if (NonCLike.Kind == NonCLikeKind::Invalid)
5034 return;
5035
5036 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5037 if (ChangesLinkage) {
5038 // If the linkage changes, we can't accept this as an extension.
5039 if (NonCLike.Kind == NonCLikeKind::None)
5040 DiagID = diag::err_typedef_changes_linkage;
5041 else
5042 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5043 }
5044
5045 SourceLocation FixitLoc =
5046 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5047 llvm::SmallString<40> TextToInsert;
5048 TextToInsert += ' ';
5049 TextToInsert += NewTD->getIdentifier()->getName();
5050
5051 Diag(FixitLoc, DiagID)
5052 << isa<TypeAliasDecl>(NewTD)
5053 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5054 if (NonCLike.Kind != NonCLikeKind::None) {
5055 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5056 << NonCLike.Kind - 1 << NonCLike.Range;
5057 }
5058 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5059 << NewTD << isa<TypeAliasDecl>(NewTD);
5060
5061 if (ChangesLinkage)
5062 return;
5063 }
5064
5065 // Otherwise, set this as the anon-decl typedef for the tag.
5066 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5067}
5068
5069static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5071 switch (T) {
5073 return 0;
5075 return 1;
5077 return 2;
5079 return 3;
5080 case DeclSpec::TST_enum:
5081 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5082 if (ED->isScopedUsingClassTag())
5083 return 5;
5084 if (ED->isScoped())
5085 return 6;
5086 }
5087 return 4;
5088 default:
5089 llvm_unreachable("unexpected type specifier");
5090 }
5091}
5092/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5093/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5094/// parameters to cope with template friend declarations.
5096 DeclSpec &DS,
5097 const ParsedAttributesView &DeclAttrs,
5098 MultiTemplateParamsArg TemplateParams,
5099 bool IsExplicitInstantiation,
5100 RecordDecl *&AnonRecord) {
5101 Decl *TagD = nullptr;
5102 TagDecl *Tag = nullptr;
5108 TagD = DS.getRepAsDecl();
5109
5110 if (!TagD) // We probably had an error
5111 return nullptr;
5112
5113 // Note that the above type specs guarantee that the
5114 // type rep is a Decl, whereas in many of the others
5115 // it's a Type.
5116 if (isa<TagDecl>(TagD))
5117 Tag = cast<TagDecl>(TagD);
5118 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5119 Tag = CTD->getTemplatedDecl();
5120 }
5121
5122 if (Tag) {
5123 handleTagNumbering(Tag, S);
5124 Tag->setFreeStanding();
5125 if (Tag->isInvalidDecl())
5126 return Tag;
5127 }
5128
5129 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5130 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5131 // or incomplete types shall not be restrict-qualified."
5132 if (TypeQuals & DeclSpec::TQ_restrict)
5134 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5135 << DS.getSourceRange();
5136 }
5137
5138 if (DS.isInlineSpecified())
5139 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5140 << getLangOpts().CPlusPlus17;
5141
5142 if (DS.hasConstexprSpecifier()) {
5143 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5144 // and definitions of functions and variables.
5145 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5146 // the declaration of a function or function template
5147 if (Tag)
5148 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5150 << static_cast<int>(DS.getConstexprSpecifier());
5151 else if (getLangOpts().C23)
5152 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5153 else
5154 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5155 << static_cast<int>(DS.getConstexprSpecifier());
5156 // Don't emit warnings after this error.
5157 return TagD;
5158 }
5159
5161
5162 if (DS.isFriendSpecified()) {
5163 // If we're dealing with a decl but not a TagDecl, assume that
5164 // whatever routines created it handled the friendship aspect.
5165 if (TagD && !Tag)
5166 return nullptr;
5167 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5168 }
5169
5170 // Track whether this decl-specifier declares anything.
5171 bool DeclaresAnything = true;
5172
5173 // Handle anonymous struct definitions.
5174 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5175 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5177 if (getLangOpts().CPlusPlus ||
5178 Record->getDeclContext()->isRecord()) {
5179 // If CurContext is a DeclContext that can contain statements,
5180 // RecursiveASTVisitor won't visit the decls that
5181 // BuildAnonymousStructOrUnion() will put into CurContext.
5182 // Also store them here so that they can be part of the
5183 // DeclStmt that gets created in this case.
5184 // FIXME: Also return the IndirectFieldDecls created by
5185 // BuildAnonymousStructOr union, for the same reason?
5187 AnonRecord = Record;
5188 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5190 }
5191
5192 DeclaresAnything = false;
5193 }
5194 }
5195
5196 // C11 6.7.2.1p2:
5197 // A struct-declaration that does not declare an anonymous structure or
5198 // anonymous union shall contain a struct-declarator-list.
5199 //
5200 // This rule also existed in C89 and C99; the grammar for struct-declaration
5201 // did not permit a struct-declaration without a struct-declarator-list.
5204 // Check for Microsoft C extension: anonymous struct/union member.
5205 // Handle 2 kinds of anonymous struct/union:
5206 // struct STRUCT;
5207 // union UNION;
5208 // and
5209 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5210 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5211 if ((Tag && Tag->getDeclName()) ||
5213 RecordDecl *Record = nullptr;
5214 if (Tag)
5215 Record = dyn_cast<RecordDecl>(Tag);
5216 else if (const RecordType *RT =
5218 Record = RT->getDecl();
5219 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5220 Record = UT->getDecl();
5221
5222 if (Record && getLangOpts().MicrosoftExt) {
5223 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5224 << Record->isUnion() << DS.getSourceRange();
5226 }
5227
5228 DeclaresAnything = false;
5229 }
5230 }
5231
5232 // Skip all the checks below if we have a type error.
5234 (TagD && TagD->isInvalidDecl()))
5235 return TagD;
5236
5237 if (getLangOpts().CPlusPlus &&
5239 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5240 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5241 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5242 DeclaresAnything = false;
5243
5244 if (!DS.isMissingDeclaratorOk()) {
5245 // Customize diagnostic for a typedef missing a name.
5247 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5248 << DS.getSourceRange();
5249 else
5250 DeclaresAnything = false;
5251 }
5252
5253 if (DS.isModulePrivateSpecified() &&
5254 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5255 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5256 << llvm::to_underlying(Tag->getTagKind())
5258
5260
5261 // C 6.7/2:
5262 // A declaration [...] shall declare at least a declarator [...], a tag,
5263 // or the members of an enumeration.
5264 // C++ [dcl.dcl]p3:
5265 // [If there are no declarators], and except for the declaration of an
5266 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5267 // names into the program, or shall redeclare a name introduced by a
5268 // previous declaration.
5269 if (!DeclaresAnything) {
5270 // In C, we allow this as a (popular) extension / bug. Don't bother
5271 // producing further diagnostics for redundant qualifiers after this.
5272 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5273 ? diag::err_no_declarators
5274 : diag::ext_no_declarators)
5275 << DS.getSourceRange();
5276 return TagD;
5277 }
5278
5279 // C++ [dcl.stc]p1:
5280 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5281 // init-declarator-list of the declaration shall not be empty.
5282 // C++ [dcl.fct.spec]p1:
5283 // If a cv-qualifier appears in a decl-specifier-seq, the
5284 // init-declarator-list of the declaration shall not be empty.
5285 //
5286 // Spurious qualifiers here appear to be valid in C.
5287 unsigned DiagID = diag::warn_standalone_specifier;
5288 if (getLangOpts().CPlusPlus)
5289 DiagID = diag::ext_standalone_specifier;
5290
5291 // Note that a linkage-specification sets a storage class, but
5292 // 'extern "C" struct foo;' is actually valid and not theoretically
5293 // useless.
5294 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5295 if (SCS == DeclSpec::SCS_mutable)
5296 // Since mutable is not a viable storage class specifier in C, there is
5297 // no reason to treat it as an extension. Instead, diagnose as an error.
5298 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5299 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5300 Diag(DS.getStorageClassSpecLoc(), DiagID)
5302 }
5303
5307 if (DS.getTypeQualifiers()) {
5309 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5311 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5312 // Restrict is covered above.
5314 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5316 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5317 }
5318
5319 // Warn about ignored type attributes, for example:
5320 // __attribute__((aligned)) struct A;
5321 // Attributes should be placed after tag to apply to type declaration.
5322 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5323 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5324 if (TypeSpecType == DeclSpec::TST_class ||
5325 TypeSpecType == DeclSpec::TST_struct ||
5326 TypeSpecType == DeclSpec::TST_interface ||
5327 TypeSpecType == DeclSpec::TST_union ||
5328 TypeSpecType == DeclSpec::TST_enum) {
5329
5330 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5331 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5332 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5333 DiagnosticId = diag::warn_attribute_ignored;
5334 else if (AL.isRegularKeywordAttribute())
5335 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5336 else
5337 DiagnosticId = diag::warn_declspec_attribute_ignored;
5338 Diag(AL.getLoc(), DiagnosticId)
5339 << AL << GetDiagnosticTypeSpecifierID(DS);
5340 };
5341
5342 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5343 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5344 }
5345 }
5346
5347 return TagD;
5348}
5349
5350/// We are trying to inject an anonymous member into the given scope;
5351/// check if there's an existing declaration that can't be overloaded.
5352///
5353/// \return true if this is a forbidden redeclaration
5354static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5355 DeclContext *Owner,
5356 DeclarationName Name,
5357 SourceLocation NameLoc, bool IsUnion,
5358 StorageClass SC) {
5359 LookupResult R(SemaRef, Name, NameLoc,
5363 if (!SemaRef.LookupName(R, S)) return false;
5364
5365 // Pick a representative declaration.
5367 assert(PrevDecl && "Expected a non-null Decl");
5368
5369 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5370 return false;
5371
5372 if (SC == StorageClass::SC_None &&
5373 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5374 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5375 if (!Owner->isRecord())
5376 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5377 return false;
5378 }
5379
5380 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5381 << IsUnion << Name;
5382 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5383
5384 return true;
5385}
5386
5388 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5390}
5391
5392/// Emit diagnostic warnings for placeholder members.
5393/// We can only do that after the class is fully constructed,
5394/// as anonymous union/structs can insert placeholders
5395/// in their parent scope (which might be a Record).
5397 if (!getLangOpts().CPlusPlus)
5398 return;
5399
5400 // This function can be parsed before we have validated the
5401 // structure as an anonymous struct
5402 if (Record->isAnonymousStructOrUnion())
5403 return;
5404
5405 const NamedDecl *First = 0;
5406 for (const Decl *D : Record->decls()) {
5407 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5408 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5409 continue;
5410 if (!First)
5411 First = ND;
5412 else
5414 }
5415}
5416
5417/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5418/// anonymous struct or union AnonRecord into the owning context Owner
5419/// and scope S. This routine will be invoked just after we realize
5420/// that an unnamed union or struct is actually an anonymous union or
5421/// struct, e.g.,
5422///
5423/// @code
5424/// union {
5425/// int i;
5426/// float f;
5427/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5428/// // f into the surrounding scope.x
5429/// @endcode
5430///
5431/// This routine is recursive, injecting the names of nested anonymous
5432/// structs/unions into the owning context and scope as well.
5433static bool
5435 RecordDecl *AnonRecord, AccessSpecifier AS,
5436 StorageClass SC,
5437 SmallVectorImpl<NamedDecl *> &Chaining) {
5438 bool Invalid = false;
5439
5440 // Look every FieldDecl and IndirectFieldDecl with a name.
5441 for (auto *D : AnonRecord->decls()) {
5442 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5443 cast<NamedDecl>(D)->getDeclName()) {
5444 ValueDecl *VD = cast<ValueDecl>(D);
5445 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5446 VD->getLocation(), AnonRecord->isUnion(),
5447 SC)) {
5448 // C++ [class.union]p2:
5449 // The names of the members of an anonymous union shall be
5450 // distinct from the names of any other entity in the
5451 // scope in which the anonymous union is declared.
5452 Invalid = true;
5453 } else {
5454 // C++ [class.union]p2:
5455 // For the purpose of name lookup, after the anonymous union
5456 // definition, the members of the anonymous union are
5457 // considered to have been defined in the scope in which the
5458 // anonymous union is declared.
5459 unsigned OldChainingSize = Chaining.size();
5460 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5461 Chaining.append(IF->chain_begin(), IF->chain_end());
5462 else
5463 Chaining.push_back(VD);
5464
5465 assert(Chaining.size() >= 2);
5466 NamedDecl **NamedChain =
5467 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5468 for (unsigned i = 0; i < Chaining.size(); i++)
5469 NamedChain[i] = Chaining[i];
5470
5472 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5473 VD->getType(), {NamedChain, Chaining.size()});
5474
5475 for (const auto *Attr : VD->attrs())
5476 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5477
5478 IndirectField->setAccess(AS);
5479 IndirectField->setImplicit();
5480 SemaRef.PushOnScopeChains(IndirectField, S);
5481
5482 // That includes picking up the appropriate access specifier.
5483 if (AS != AS_none) IndirectField->setAccess(AS);
5484
5485 Chaining.resize(OldChainingSize);
5486 }
5487 }
5488 }
5489
5490 return Invalid;
5491}
5492
5493/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5494/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5495/// illegal input values are mapped to SC_None.
5496static StorageClass
5498 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5499 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5500 "Parser allowed 'typedef' as storage class VarDecl.");
5501 switch (StorageClassSpec) {
5504 if (DS.isExternInLinkageSpec())
5505 return SC_None;
5506 return SC_Extern;
5507 case DeclSpec::SCS_static: return SC_Static;
5508 case DeclSpec::SCS_auto: return SC_Auto;
5511 // Illegal SCSs map to None: error reporting is up to the caller.
5512 case DeclSpec::SCS_mutable: // Fall through.
5513 case DeclSpec::SCS_typedef: return SC_None;
5514 }
5515 llvm_unreachable("unknown storage class specifier");
5516}
5517
5519 assert(Record->hasInClassInitializer());
5520
5521 for (const auto *I : Record->decls()) {
5522 const auto *FD = dyn_cast<FieldDecl>(I);
5523 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5524 FD = IFD->getAnonField();
5525 if (FD && FD->hasInClassInitializer())
5526 return FD->getLocation();
5527 }
5528
5529 llvm_unreachable("couldn't find in-class initializer");
5530}
5531
5533 SourceLocation DefaultInitLoc) {
5534 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5535 return;
5536
5537 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5538 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5539}
5540
5542 CXXRecordDecl *AnonUnion) {
5543 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5544 return;
5545
5547}
5548
5549/// BuildAnonymousStructOrUnion - Handle the declaration of an
5550/// anonymous structure or union. Anonymous unions are a C++ feature
5551/// (C++ [class.union]) and a C11 feature; anonymous structures
5552/// are a C11 feature and GNU C++ extension.
5554 AccessSpecifier AS,
5556 const PrintingPolicy &Policy) {
5557 DeclContext *Owner = Record->getDeclContext();
5558
5559 // Diagnose whether this anonymous struct/union is an extension.
5560 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5561 Diag(Record->getLocation(), diag::ext_anonymous_union);
5562 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5563 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5564 else if (!Record->isUnion() && !getLangOpts().C11)
5565 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5566
5567 // C and C++ require different kinds of checks for anonymous
5568 // structs/unions.
5569 bool Invalid = false;
5570 if (getLangOpts().CPlusPlus) {
5571 const char *PrevSpec = nullptr;
5572 if (Record->isUnion()) {
5573 // C++ [class.union]p6:
5574 // C++17 [class.union.anon]p2:
5575 // Anonymous unions declared in a named namespace or in the
5576 // global namespace shall be declared static.
5577 unsigned DiagID;
5578 DeclContext *OwnerScope = Owner->getRedeclContext();
5580 (OwnerScope->isTranslationUnit() ||
5581 (OwnerScope->isNamespace() &&
5582 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5583 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5584 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5585
5586 // Recover by adding 'static'.
5588 PrevSpec, DiagID, Policy);
5589 }
5590 // C++ [class.union]p6:
5591 // A storage class is not allowed in a declaration of an
5592 // anonymous union in a class scope.
5594 isa<RecordDecl>(Owner)) {
5596 diag::err_anonymous_union_with_storage_spec)
5598
5599 // Recover by removing the storage specifier.
5602 PrevSpec, DiagID, Context.getPrintingPolicy());
5603 }
5604 }
5605
5606 // Ignore const/volatile/restrict qualifiers.
5607 if (DS.getTypeQualifiers()) {
5609 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5610 << Record->isUnion() << "const"
5614 diag::ext_anonymous_struct_union_qualified)
5615 << Record->isUnion() << "volatile"
5619 diag::ext_anonymous_struct_union_qualified)
5620 << Record->isUnion() << "restrict"
5624 diag::ext_anonymous_struct_union_qualified)
5625 << Record->isUnion() << "_Atomic"
5629 diag::ext_anonymous_struct_union_qualified)
5630 << Record->isUnion() << "__unaligned"
5632
5634 }
5635
5636 // C++ [class.union]p2:
5637 // The member-specification of an anonymous union shall only
5638 // define non-static data members. [Note: nested types and
5639 // functions cannot be declared within an anonymous union. ]
5640 for (auto *Mem : Record->decls()) {
5641 // Ignore invalid declarations; we already diagnosed them.
5642 if (Mem->isInvalidDecl())
5643 continue;
5644
5645 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5646 // C++ [class.union]p3:
5647 // An anonymous union shall not have private or protected
5648 // members (clause 11).
5649 assert(FD->getAccess() != AS_none);
5650 if (FD->getAccess() != AS_public) {
5651 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5652 << Record->isUnion() << (FD->getAccess() == AS_protected);
5653 Invalid = true;
5654 }
5655
5656 // C++ [class.union]p1
5657 // An object of a class with a non-trivial constructor, a non-trivial
5658 // copy constructor, a non-trivial destructor, or a non-trivial copy
5659 // assignment operator cannot be a member of a union, nor can an
5660 // array of such objects.
5661 if (CheckNontrivialField(FD))
5662 Invalid = true;
5663 } else if (Mem->isImplicit()) {
5664 // Any implicit members are fine.
5665 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5666 // This is a type that showed up in an
5667 // elaborated-type-specifier inside the anonymous struct or
5668 // union, but which actually declares a type outside of the
5669 // anonymous struct or union. It's okay.
5670 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5671 if (!MemRecord->isAnonymousStructOrUnion() &&
5672 MemRecord->getDeclName()) {
5673 // Visual C++ allows type definition in anonymous struct or union.
5674 if (getLangOpts().MicrosoftExt)
5675 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5676 << Record->isUnion();
5677 else {
5678 // This is a nested type declaration.
5679 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5680 << Record->isUnion();
5681 Invalid = true;
5682 }
5683 } else {
5684 // This is an anonymous type definition within another anonymous type.
5685 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5686 // not part of standard C++.
5687 Diag(MemRecord->getLocation(),
5688 diag::ext_anonymous_record_with_anonymous_type)
5689 << Record->isUnion();
5690 }
5691 } else if (isa<AccessSpecDecl>(Mem)) {
5692 // Any access specifier is fine.
5693 } else if (isa<StaticAssertDecl>(Mem)) {
5694 // In C++1z, static_assert declarations are also fine.
5695 } else {
5696 // We have something that isn't a non-static data
5697 // member. Complain about it.
5698 unsigned DK = diag::err_anonymous_record_bad_member;
5699 if (isa<TypeDecl>(Mem))
5700 DK = diag::err_anonymous_record_with_type;
5701 else if (isa<FunctionDecl>(Mem))
5702 DK = diag::err_anonymous_record_with_function;
5703 else if (isa<VarDecl>(Mem))
5704 DK = diag::err_anonymous_record_with_static;
5705
5706 // Visual C++ allows type definition in anonymous struct or union.
5707 if (getLangOpts().MicrosoftExt &&
5708 DK == diag::err_anonymous_record_with_type)
5709 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5710 << Record->isUnion();
5711 else {
5712 Diag(Mem->getLocation(), DK) << Record->isUnion();
5713 Invalid = true;
5714 }
5715 }
5716 }
5717
5718 // C++11 [class.union]p8 (DR1460):
5719 // At most one variant member of a union may have a
5720 // brace-or-equal-initializer.
5721 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5722 Owner->isRecord())
5723 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5724 cast<CXXRecordDecl>(Record));
5725 }
5726
5727 if (!Record->isUnion() && !Owner->isRecord()) {
5728 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5729 << getLangOpts().CPlusPlus;
5730 Invalid = true;
5731 }
5732
5733 // C++ [dcl.dcl]p3:
5734 // [If there are no declarators], and except for the declaration of an
5735 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5736 // names into the program
5737 // C++ [class.mem]p2:
5738 // each such member-declaration shall either declare at least one member
5739 // name of the class or declare at least one unnamed bit-field
5740 //
5741 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5742 if (getLangOpts().CPlusPlus && Record->field_empty())
5743 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5744
5745 // Mock up a declarator.
5749 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5750
5751 // Create a declaration for this anonymous struct/union.
5752 NamedDecl *Anon = nullptr;
5753 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5754 Anon = FieldDecl::Create(
5755 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5756 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5757 /*BitWidth=*/nullptr, /*Mutable=*/false,
5758 /*InitStyle=*/ICIS_NoInit);
5759 Anon->setAccess(AS);
5760 ProcessDeclAttributes(S, Anon, Dc);
5761
5762 if (getLangOpts().CPlusPlus)
5763 FieldCollector->Add(cast<FieldDecl>(Anon));
5764 } else {
5765 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5766 if (SCSpec == DeclSpec::SCS_mutable) {
5767 // mutable can only appear on non-static class members, so it's always
5768 // an error here
5769 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5770 Invalid = true;
5771 SC = SC_None;
5772 }
5773
5774 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5775 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5776 Context.getTypeDeclType(Record), TInfo, SC);
5777 ProcessDeclAttributes(S, Anon, Dc);
5778
5779 // Default-initialize the implicit variable. This initialization will be
5780 // trivial in almost all cases, except if a union member has an in-class
5781 // initializer:
5782 // union { int n = 0; };
5784 }
5785 Anon->setImplicit();
5786
5787 // Mark this as an anonymous struct/union type.
5788 Record->setAnonymousStructOrUnion(true);
5789
5790 // Add the anonymous struct/union object to the current
5791 // context. We'll be referencing this object when we refer to one of
5792 // its members.
5793 Owner->addDecl(Anon);
5794
5795 // Inject the members of the anonymous struct/union into the owning
5796 // context and into the identifier resolver chain for name lookup
5797 // purposes.
5799 Chain.push_back(Anon);
5800
5801 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5802 Chain))
5803 Invalid = true;
5804
5805 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5806 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5808 Decl *ManglingContextDecl;
5809 std::tie(MCtx, ManglingContextDecl) =
5810 getCurrentMangleNumberContext(NewVD->getDeclContext());
5811 if (MCtx) {
5813 NewVD, MCtx->getManglingNumber(
5814 NewVD, getMSManglingNumber(getLangOpts(), S)));
5816 }
5817 }
5818 }
5819
5820 if (Invalid)
5821 Anon->setInvalidDecl();
5822
5823 return Anon;
5824}
5825
5826/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5827/// Microsoft C anonymous structure.
5828/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5829/// Example:
5830///
5831/// struct A { int a; };
5832/// struct B { struct A; int b; };
5833///
5834/// void foo() {
5835/// B var;
5836/// var.a = 3;
5837/// }
5838///
5840 RecordDecl *Record) {
5841 assert(Record && "expected a record!");
5842
5843 // Mock up a declarator.
5846 assert(TInfo && "couldn't build declarator info for anonymous struct");
5847
5848 auto *ParentDecl = cast<RecordDecl>(CurContext);
5850
5851 // Create a declaration for this anonymous struct.
5852 NamedDecl *Anon =
5853 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5854 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5855 /*BitWidth=*/nullptr, /*Mutable=*/false,
5856 /*InitStyle=*/ICIS_NoInit);
5857 Anon->setImplicit();
5858
5859 // Add the anonymous struct object to the current context.
5860 CurContext->addDecl(Anon);
5861
5862 // Inject the members of the anonymous struct into the current
5863 // context and into the identifier resolver chain for name lookup
5864 // purposes.
5866 Chain.push_back(Anon);
5867
5868 RecordDecl *RecordDef = Record->getDefinition();
5869 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5870 diag::err_field_incomplete_or_sizeless) ||
5872 *this, S, CurContext, RecordDef, AS_none,
5874 Anon->setInvalidDecl();
5875 ParentDecl->setInvalidDecl();
5876 }
5877
5878 return Anon;
5879}
5880
5881/// GetNameForDeclarator - Determine the full declaration name for the
5882/// given Declarator.
5885}
5886
5887/// Retrieves the declaration name from a parsed unqualified-id.
5890 DeclarationNameInfo NameInfo;
5891 NameInfo.setLoc(Name.StartLocation);
5892
5893 switch (Name.getKind()) {
5894
5897 NameInfo.setName(Name.Identifier);
5898 return NameInfo;
5899
5901 // C++ [temp.deduct.guide]p3:
5902 // The simple-template-id shall name a class template specialization.
5903 // The template-name shall be the same identifier as the template-name
5904 // of the simple-template-id.
5905 // These together intend to imply that the template-name shall name a
5906 // class template.
5907 // FIXME: template<typename T> struct X {};
5908 // template<typename T> using Y = X<T>;
5909 // Y(int) -> Y<int>;
5910 // satisfies these rules but does not name a class template.
5911 TemplateName TN = Name.TemplateName.get().get();
5912 auto *Template = TN.getAsTemplateDecl();
5913 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5914 Diag(Name.StartLocation,
5915 diag::err_deduction_guide_name_not_class_template)
5917 if (Template)
5918 NoteTemplateLocation(*Template);
5919 return DeclarationNameInfo();
5920 }
5921
5922 NameInfo.setName(
5924 return NameInfo;
5925 }
5926
5929 Name.OperatorFunctionId.Operator));
5931 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5932 return NameInfo;
5933
5936 Name.Identifier));
5937 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5938 return NameInfo;
5939
5941 TypeSourceInfo *TInfo;
5942 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5943 if (Ty.isNull())
5944 return DeclarationNameInfo();
5947 NameInfo.setNamedTypeInfo(TInfo);
5948 return NameInfo;
5949 }
5950
5952 TypeSourceInfo *TInfo;
5953 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5954 if (Ty.isNull())
5955 return DeclarationNameInfo();
5958 NameInfo.setNamedTypeInfo(TInfo);
5959 return NameInfo;
5960 }
5961
5963 // In well-formed code, we can only have a constructor
5964 // template-id that refers to the current context, so go there
5965 // to find the actual type being constructed.
5966 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5967 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5968 return DeclarationNameInfo();
5969
5970 // Determine the type of the class being constructed.
5971 QualType CurClassType = Context.getTypeDeclType(CurClass);
5972
5973 // FIXME: Check two things: that the template-id names the same type as
5974 // CurClassType, and that the template-id does not occur when the name
5975 // was qualified.
5976
5978 Context.getCanonicalType(CurClassType)));
5979 // FIXME: should we retrieve TypeSourceInfo?
5980 NameInfo.setNamedTypeInfo(nullptr);
5981 return NameInfo;
5982 }
5983
5985 TypeSourceInfo *TInfo;
5986 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5987 if (Ty.isNull())
5988 return DeclarationNameInfo();
5991 NameInfo.setNamedTypeInfo(TInfo);
5992 return NameInfo;
5993 }
5994
5996 TemplateName TName = Name.TemplateId->Template.get();
5997 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5998 return Context.getNameForTemplate(TName, TNameLoc);
5999 }
6000
6001 } // switch (Name.getKind())
6002
6003 llvm_unreachable("Unknown name kind");
6004}
6005
6007 do {
6008 if (Ty->isPointerType() || Ty->isReferenceType())
6009 Ty = Ty->getPointeeType();
6010 else if (Ty->isArrayType())
6012 else
6013 return Ty.withoutLocalFastQualifiers();
6014 } while (true);
6015}
6016
6017/// hasSimilarParameters - Determine whether the C++ functions Declaration
6018/// and Definition have "nearly" matching parameters. This heuristic is
6019/// used to improve diagnostics in the case where an out-of-line function
6020/// definition doesn't match any declaration within the class or namespace.
6021/// Also sets Params to the list of indices to the parameters that differ
6022/// between the declaration and the definition. If hasSimilarParameters
6023/// returns true and Params is empty, then all of the parameters match.
6027 SmallVectorImpl<unsigned> &Params) {
6028 Params.clear();
6029 if (Declaration->param_size() != Definition->param_size())
6030 return false;
6031 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6032 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6033 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6034
6035 // The parameter types are identical
6036 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6037 continue;
6038
6039 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6040 QualType DefParamBaseTy = getCoreType(DefParamTy);
6041 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6042 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6043
6044 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6045 (DeclTyName && DeclTyName == DefTyName))
6046 Params.push_back(Idx);
6047 else // The two parameters aren't even close
6048 return false;
6049 }
6050
6051 return true;
6052}
6053
6054/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6055/// declarator needs to be rebuilt in the current instantiation.
6056/// Any bits of declarator which appear before the name are valid for
6057/// consideration here. That's specifically the type in the decl spec
6058/// and the base type in any member-pointer chunks.
6060 DeclarationName Name) {
6061 // The types we specifically need to rebuild are:
6062 // - typenames, typeofs, and decltypes
6063 // - types which will become injected class names
6064 // Of course, we also need to rebuild any type referencing such a
6065 // type. It's safest to just say "dependent", but we call out a
6066 // few cases here.
6067
6068 DeclSpec &DS = D.getMutableDeclSpec();
6069 switch (DS.getTypeSpecType()) {
6073#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6074#include "clang/Basic/TransformTypeTraits.def"
6075 case DeclSpec::TST_atomic: {
6076 // Grab the type from the parser.
6077 TypeSourceInfo *TSI = nullptr;
6078 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6079 if (T.isNull() || !T->isInstantiationDependentType()) break;
6080
6081 // Make sure there's a type source info. This isn't really much
6082 // of a waste; most dependent types should have type source info
6083 // attached already.
6084 if (!TSI)
6086
6087 // Rebuild the type in the current instantiation.
6089 if (!TSI) return true;
6090
6091 // Store the new type back in the decl spec.
6092 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6093 DS.UpdateTypeRep(LocType);
6094 break;
6095 }
6096
6100 Expr *E = DS.getRepAsExpr();
6102 if (Result.isInvalid()) return true;
6103 DS.UpdateExprRep(Result.get());
6104 break;
6105 }
6106
6107 default:
6108 // Nothing to do for these decl specs.
6109 break;
6110 }
6111
6112 // It doesn't matter what order we do this in.
6113 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6114 DeclaratorChunk &Chunk = D.getTypeObject(I);
6115
6116 // The only type information in the declarator which can come
6117 // before the declaration name is the base type of a member
6118 // pointer.
6120 continue;
6121
6122 // Rebuild the scope specifier in-place.
6123 CXXScopeSpec &SS = Chunk.Mem.Scope();
6125 return true;
6126 }
6127
6128 return false;
6129}
6130
6131/// Returns true if the declaration is declared in a system header or from a
6132/// system macro.
6133static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6134 return SM.isInSystemHeader(D->getLocation()) ||
6135 SM.isInSystemMacro(D->getLocation());
6136}
6137
6139 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6140 // of system decl.
6141 if (D->getPreviousDecl() || D->isImplicit())
6142 return;
6146 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6147 << D << static_cast<int>(Status);
6148 }
6149}
6150
6153
6154 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6155 // declaration only if the `bind_to_declaration` extension is set.
6158 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6159 implementation_extension_bind_to_declaration))
6161 S, D, MultiTemplateParamsArg(), Bases);
6162
6164
6166 Dcl && Dcl->getDeclContext()->isFileContext())
6168
6169 if (!Bases.empty())
6171
6172 return Dcl;
6173}
6174
6175/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6176/// If T is the name of a class, then each of the following shall have a
6177/// name different from T:
6178/// - every static data member of class T;
6179/// - every member function of class T
6180/// - every member of class T that is itself a type;
6181/// \returns true if the declaration name violates these rules.
6183 DeclarationNameInfo NameInfo) {
6184 DeclarationName Name = NameInfo.getName();
6185
6186 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6187 while (Record && Record->isAnonymousStructOrUnion())
6188 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6189 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6190 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6191 return true;
6192 }
6193
6194 return false;
6195}
6196
6197/// Diagnose a declaration whose declarator-id has the given
6198/// nested-name-specifier.
6199///
6200/// \param SS The nested-name-specifier of the declarator-id.
6201///
6202/// \param DC The declaration context to which the nested-name-specifier
6203/// resolves.
6204///
6205/// \param Name The name of the entity being declared.
6206///
6207/// \param Loc The location of the name of the entity being declared.
6208///
6209/// \param IsMemberSpecialization Whether we are declaring a member
6210/// specialization.
6211///
6212/// \param TemplateId The template-id, if any.
6213///
6214/// \returns true if we cannot safely recover from this error, false otherwise.
6216 DeclarationName Name,
6217 SourceLocation Loc,
6218 TemplateIdAnnotation *TemplateId,
6219 bool IsMemberSpecialization) {
6220 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6221 "without nested-name-specifier");
6222 DeclContext *Cur = CurContext;
6223 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6224 Cur = Cur->getParent();
6225
6226 // If the user provided a superfluous scope specifier that refers back to the
6227 // class in which the entity is already declared, diagnose and ignore it.
6228 //
6229 // class X {
6230 // void X::f();
6231 // };
6232 //
6233 // Note, it was once ill-formed to give redundant qualification in all
6234 // contexts, but that rule was removed by DR482.
6235 if (Cur->Equals(DC)) {
6236 if (Cur->isRecord()) {
6237 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6238 : diag::err_member_extra_qualification)
6239 << Name << FixItHint::CreateRemoval(SS.getRange());
6240 SS.clear();
6241 } else {
6242 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6243 }
6244 return false;
6245 }
6246
6247 // Check whether the qualifying scope encloses the scope of the original
6248 // declaration. For a template-id, we perform the checks in
6249 // CheckTemplateSpecializationScope.
6250 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6251 if (Cur->isRecord())
6252 Diag(Loc, diag::err_member_qualification)
6253 << Name << SS.getRange();
6254 else if (isa<TranslationUnitDecl>(DC))
6255 Diag(Loc, diag::err_invalid_declarator_global_scope)
6256 << Name << SS.getRange();
6257 else if (isa<FunctionDecl>(Cur))
6258 Diag(Loc, diag::err_invalid_declarator_in_function)
6259 << Name << SS.getRange();
6260 else if (isa<BlockDecl>(Cur))
6261 Diag(Loc, diag::err_invalid_declarator_in_block)
6262 << Name << SS.getRange();
6263 else if (isa<ExportDecl>(Cur)) {
6264 if (!isa<NamespaceDecl>(DC))
6265 Diag(Loc, diag::err_export_non_namespace_scope_name)
6266 << Name << SS.getRange();
6267 else
6268 // The cases that DC is not NamespaceDecl should be handled in
6269 // CheckRedeclarationExported.
6270 return false;
6271 } else
6272 Diag(Loc, diag::err_invalid_declarator_scope)
6273 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6274
6275 return true;
6276 }
6277
6278 if (Cur->isRecord()) {
6279 // Cannot qualify members within a class.
6280 Diag(Loc, diag::err_member_qualification)
6281 << Name << SS.getRange();
6282 SS.clear();
6283
6284 // C++ constructors and destructors with incorrect scopes can break
6285 // our AST invariants by having the wrong underlying types. If
6286 // that's the case, then drop this declaration entirely.
6287 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6288 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6289 !Context.hasSameType(Name.getCXXNameType(),
6290 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6291 return true;
6292
6293 return false;
6294 }
6295
6296 // C++23 [temp.names]p5:
6297 // The keyword template shall not appear immediately after a declarative
6298 // nested-name-specifier.
6299 //
6300 // First check the template-id (if any), and then check each component of the
6301 // nested-name-specifier in reverse order.
6302 //
6303 // FIXME: nested-name-specifiers in friend declarations are declarative,
6304 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6305 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6306 Diag(Loc, diag::ext_template_after_declarative_nns)
6308
6310 do {
6311 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6313 Diag(Loc, diag::ext_template_after_declarative_nns)
6315 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6316
6317 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6318 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6319 // C++23 [expr.prim.id.qual]p3:
6320 // [...] If a nested-name-specifier N is declarative and has a
6321 // simple-template-id with a template argument list A that involves a
6322 // template parameter, let T be the template nominated by N without A.
6323 // T shall be a class template.
6324 if (TST->isDependentType() && TST->isTypeAlias())
6325 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6326 << SpecLoc.getLocalSourceRange();
6327 } else if (T->isDecltypeType()) {
6328 // C++23 [expr.prim.id.qual]p2:
6329 // [...] A declarative nested-name-specifier shall not have a
6330 // decltype-specifier.
6331 //
6332 // FIXME: This wording appears to be defective as it does not forbid
6333 // declarative nested-name-specifiers with pack-index-specifiers.
6334 // See https://github.com/cplusplus/CWG/issues/499.
6335 Diag(Loc, diag::err_decltype_in_declarator)
6336 << SpecLoc.getTypeLoc().getSourceRange();
6337 }
6338 }
6339 } while ((SpecLoc = SpecLoc.getPrefix()));
6340
6341 return false;
6342}
6343
6345 MultiTemplateParamsArg TemplateParamLists) {
6346 // TODO: consider using NameInfo for diagnostic.
6348 DeclarationName Name = NameInfo.getName();
6349
6350 // All of these full declarators require an identifier. If it doesn't have
6351 // one, the ParsedFreeStandingDeclSpec action should be used.
6352 if (D.isDecompositionDeclarator()) {
6353 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6354 } else if (!Name) {
6355 if (!D.isInvalidType()) // Reject this if we think it is valid.
6356 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6358 return nullptr;
6360 return nullptr;
6361
6362 DeclContext *DC = CurContext;
6363 if (D.getCXXScopeSpec().isInvalid())
6364 D.setInvalidType();
6365 else if (D.getCXXScopeSpec().isSet()) {
6368 return nullptr;
6369
6370 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6371 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6372 if (!DC || isa<EnumDecl>(DC)) {
6373 // If we could not compute the declaration context, it's because the
6374 // declaration context is dependent but does not refer to a class,
6375 // class template, or class template partial specialization. Complain
6376 // and return early, to avoid the coming semantic disaster.
6378 diag::err_template_qualified_declarator_no_match)
6380 << D.getCXXScopeSpec().getRange();
6381 return nullptr;
6382 }
6383 bool IsDependentContext = DC->isDependentContext();
6384
6385 if (!IsDependentContext &&
6387 return nullptr;
6388
6389 // If a class is incomplete, do not parse entities inside it.
6390 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6392 diag::err_member_def_undefined_record)
6393 << Name << DC << D.getCXXScopeSpec().getRange();
6394 return nullptr;
6395 }
6396 if (!D.getDeclSpec().isFriendSpecified()) {
6397 TemplateIdAnnotation *TemplateId =
6399 ? D.getName().TemplateId
6400 : nullptr;
6402 D.getIdentifierLoc(), TemplateId,
6403 /*IsMemberSpecialization=*/false)) {
6404 if (DC->isRecord())
6405 return nullptr;
6406
6407 D.setInvalidType();
6408 }
6409 }
6410
6411 // Check whether we need to rebuild the type of the given
6412 // declaration in the current instantiation.
6413 if (EnteringContext && IsDependentContext &&
6414 TemplateParamLists.size() != 0) {
6415 ContextRAII SavedContext(*this, DC);
6416 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6417 D.setInvalidType();
6418 }
6419 }
6420
6422 QualType R = TInfo->getType();
6423
6426 D.setInvalidType();
6427
6428 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6430
6431 // See if this is a redefinition of a variable in the same scope.
6432 if (!D.getCXXScopeSpec().isSet()) {
6433 bool IsLinkageLookup = false;
6434 bool CreateBuiltins = false;
6435
6436 // If the declaration we're planning to build will be a function
6437 // or object with linkage, then look for another declaration with
6438 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6439 //
6440 // If the declaration we're planning to build will be declared with
6441 // external linkage in the translation unit, create any builtin with
6442 // the same name.
6444 /* Do nothing*/;
6445 else if (CurContext->isFunctionOrMethod() &&
6447 R->isFunctionType())) {
6448 IsLinkageLookup = true;
6449 CreateBuiltins =
6453 CreateBuiltins = true;
6454
6455 if (IsLinkageLookup) {
6457 Previous.setRedeclarationKind(ForExternalRedeclaration);
6458 }
6459
6460 LookupName(Previous, S, CreateBuiltins);
6461 } else { // Something like "int foo::x;"
6463
6464 // C++ [dcl.meaning]p1:
6465 // When the declarator-id is qualified, the declaration shall refer to a
6466 // previously declared member of the class or namespace to which the
6467 // qualifier refers (or, in the case of a namespace, of an element of the
6468 // inline namespace set of that namespace (7.3.1)) or to a specialization
6469 // thereof; [...]
6470 //
6471 // Note that we already checked the context above, and that we do not have
6472 // enough information to make sure that Previous contains the declaration
6473 // we want to match. For example, given:
6474 //
6475 // class X {
6476 // void f();
6477 // void f(float);
6478 // };
6479 //
6480 // void X::f(int) { } // ill-formed
6481 //
6482 // In this case, Previous will point to the overload set
6483 // containing the two f's declared in X, but neither of them
6484 // matches.
6485
6487 }
6488
6489 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6490 TPD && TPD->isTemplateParameter()) {
6491 // Older versions of clang allowed the names of function/variable templates
6492 // to shadow the names of their template parameters. For the compatibility
6493 // purposes we detect such cases and issue a default-to-error warning that
6494 // can be disabled with -Wno-strict-primary-template-shadow.
6495 if (!D.isInvalidType()) {
6496 bool AllowForCompatibility = false;
6497 if (Scope *DeclParent = S->getDeclParent();
6498 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6499 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6500 TemplateParamParent->isDeclScope(TPD);
6501 }
6503 AllowForCompatibility);
6504 }
6505
6506 // Just pretend that we didn't see the previous declaration.
6507 Previous.clear();
6508 }
6509
6510 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6511 // Forget that the previous declaration is the injected-class-name.
6512 Previous.clear();
6513
6514 // In C++, the previous declaration we find might be a tag type
6515 // (class or enum). In this case, the new declaration will hide the
6516 // tag type. Note that this applies to functions, function templates, and
6517 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6518 if (Previous.isSingleTagDecl() &&
6520 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6521 Previous.clear();
6522
6523 // Check that there are no default arguments other than in the parameters
6524 // of a function declaration (C++ only).
6525 if (getLangOpts().CPlusPlus)
6527
6528 /// Get the innermost enclosing declaration scope.
6529 S = S->getDeclParent();
6530
6531 NamedDecl *New;
6532
6533 bool AddToScope = true;
6535 if (TemplateParamLists.size()) {
6536 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6537 return nullptr;
6538 }
6539
6540 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6541 } else if (R->isFunctionType()) {
6542 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6543 TemplateParamLists,
6544 AddToScope);
6545 } else {
6546 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6547 AddToScope);
6548 }
6549
6550 if (!New)
6551 return nullptr;
6552
6553 // If this has an identifier and is not a function template specialization,
6554 // add it to the scope stack.
6555 if (New->getDeclName() && AddToScope)
6556 PushOnScopeChains(New, S);
6557
6560
6561 return New;
6562}
6563
6564/// Helper method to turn variable array types into constant array
6565/// types in certain situations which would otherwise be errors (for
6566/// GCC compatibility).
6568 ASTContext &Context,
6569 bool &SizeIsNegative,
6570 llvm::APSInt &Oversized) {
6571 // This method tries to turn a variable array into a constant
6572 // array even when the size isn't an ICE. This is necessary
6573 // for compatibility with code that depends on gcc's buggy
6574 // constant expression folding, like struct {char x[(int)(char*)2];}
6575 SizeIsNegative = false;
6576 Oversized = 0;
6577
6578 if (T->isDependentType())
6579 return QualType();
6580
6582 const Type *Ty = Qs.strip(T);
6583
6584 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6585 QualType Pointee = PTy->getPointeeType();
6586 QualType FixedType =
6587 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6588 Oversized);
6589 if (FixedType.isNull()) return FixedType;
6590 FixedType = Context.getPointerType(FixedType);
6591 return Qs.apply(Context, FixedType);
6592 }
6593 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6594 QualType Inner = PTy->getInnerType();
6595 QualType FixedType =
6596 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6597 Oversized);
6598 if (FixedType.isNull()) return FixedType;
6599 FixedType = Context.getParenType(FixedType);
6600 return Qs.apply(Context, FixedType);
6601 }
6602
6603 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6604 if (!VLATy)
6605 return QualType();
6606
6607 QualType ElemTy = VLATy->getElementType();
6608 if (ElemTy->isVariablyModifiedType()) {
6609 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6610 SizeIsNegative, Oversized);
6611 if (ElemTy.isNull())
6612 return QualType();
6613 }
6614
6616 if (!VLATy->getSizeExpr() ||
6617 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6618 return QualType();
6619
6620 llvm::APSInt Res = Result.Val.getInt();
6621
6622 // Check whether the array size is negative.
6623 if (Res.isSigned() && Res.isNegative()) {
6624 SizeIsNegative = true;
6625 return QualType();
6626 }
6627
6628 // Check whether the array is too large to be addressed.
6629 unsigned ActiveSizeBits =
6630 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6631 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6632 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6633 : Res.getActiveBits();
6634 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6635 Oversized = Res;
6636 return QualType();
6637 }
6638
6639 QualType FoldedArrayType = Context.getConstantArrayType(
6640 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6641 return Qs.apply(Context, FoldedArrayType);
6642}
6643
6644static void
6646 SrcTL = SrcTL.getUnqualifiedLoc();
6647 DstTL = DstTL.getUnqualifiedLoc();
6648 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6649 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6650 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6651 DstPTL.getPointeeLoc());
6652 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6653 return;
6654 }
6655 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6656 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6657 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6658 DstPTL.getInnerLoc());
6659 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6660 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6661 return;
6662 }
6663 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6664 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6665 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6666 TypeLoc DstElemTL = DstATL.getElementLoc();
6667 if (VariableArrayTypeLoc SrcElemATL =
6668 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6669 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6670 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6671 } else {
6672 DstElemTL.initializeFullCopy(SrcElemTL);
6673 }
6674 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6675 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6676 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6677}
6678
6679/// Helper method to turn variable array types into constant array
6680/// types in certain situations which would otherwise be errors (for
6681/// GCC compatibility).
6682static TypeSourceInfo*
6684 ASTContext &Context,
6685 bool &SizeIsNegative,
6686 llvm::APSInt &Oversized) {
6687 QualType FixedTy
6688 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6689 SizeIsNegative, Oversized);
6690 if (FixedTy.isNull())
6691 return nullptr;
6692 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6694 FixedTInfo->getTypeLoc());
6695 return FixedTInfo;
6696}
6697
6698/// Attempt to fold a variable-sized type to a constant-sized type, returning
6699/// true if we were successful.
6701 QualType &T, SourceLocation Loc,
6702 unsigned FailedFoldDiagID) {
6703 bool SizeIsNegative;
6704 llvm::APSInt Oversized;
6706 TInfo, Context, SizeIsNegative, Oversized);
6707 if (FixedTInfo) {
6708 Diag(Loc, diag::ext_vla_folded_to_constant);
6709 TInfo = FixedTInfo;
6710 T = FixedTInfo->getType();
6711 return true;
6712 }
6713
6714 if (SizeIsNegative)
6715 Diag(Loc, diag::err_typecheck_negative_array_size);
6716 else if (Oversized.getBoolValue())
6717 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6718 else if (FailedFoldDiagID)
6719 Diag(Loc, FailedFoldDiagID);
6720 return false;
6721}
6722
6723/// Register the given locally-scoped extern "C" declaration so
6724/// that it can be found later for redeclarations. We include any extern "C"
6725/// declaration that is not visible in the translation unit here, not just
6726/// function-scope declarations.
6727void
6729 if (!getLangOpts().CPlusPlus &&
6731 // Don't need to track declarations in the TU in C.
6732 return;
6733
6734 // Note that we have a locally-scoped external with this name.
6736}
6737
6739 // FIXME: We can have multiple results via __attribute__((overloadable)).
6741 return Result.empty() ? nullptr : *Result.begin();
6742}
6743
6744/// Diagnose function specifiers on a declaration of an identifier that
6745/// does not identify a function.
6747 // FIXME: We should probably indicate the identifier in question to avoid
6748 // confusion for constructs like "virtual int a(), b;"
6749 if (DS.isVirtualSpecified())
6751 diag::err_virtual_non_function);
6752
6753 if (DS.hasExplicitSpecifier())
6755 diag::err_explicit_non_function);
6756
6757 if (DS.isNoreturnSpecified())
6759 diag::err_noreturn_non_function);
6760}
6761
6762NamedDecl*
6765 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6766 if (D.getCXXScopeSpec().isSet()) {
6767 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6768 << D.getCXXScopeSpec().getRange();
6769 D.setInvalidType();
6770 // Pretend we didn't see the scope specifier.
6771 DC = CurContext;
6772 Previous.clear();
6773 }
6774
6776
6778 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6779 << getLangOpts().CPlusPlus17;
6781 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6782 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6783
6787 diag::err_deduction_guide_invalid_specifier)
6788 << "typedef";
6789 else
6790 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6791 << D.getName().getSourceRange();
6792 return nullptr;
6793 }
6794
6795 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6796 if (!NewTD) return nullptr;
6797
6798 // Handle attributes prior to checking for duplicates in MergeVarDecl
6799 ProcessDeclAttributes(S, NewTD, D);
6800
6802
6803 bool Redeclaration = D.isRedeclaration();
6804 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6805 D.setRedeclaration(Redeclaration);
6806 return ND;
6807}
6808
6809void
6811 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6812 // then it shall have block scope.
6813 // Note that variably modified types must be fixed before merging the decl so
6814 // that redeclarations will match.
6815 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6816 QualType T = TInfo->getType();
6817 if (T->isVariablyModifiedType()) {
6819
6820 if (S->getFnParent() == nullptr) {
6821 bool SizeIsNegative;
6822 llvm::APSInt Oversized;
6823 TypeSourceInfo *FixedTInfo =
6825 SizeIsNegative,
6826 Oversized);
6827 if (FixedTInfo) {
6828 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6829 NewTD->setTypeSourceInfo(FixedTInfo);
6830 } else {
6831 if (SizeIsNegative)
6832 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6833 else if (T->isVariableArrayType())
6834 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6835 else if (Oversized.getBoolValue())
6836 Diag(NewTD->getLocation(), diag::err_array_too_large)
6837 << toString(Oversized, 10);
6838 else
6839 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6840 NewTD->setInvalidDecl();
6841 }
6842 }
6843 }
6844}
6845
6846/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6847/// declares a typedef-name, either using the 'typedef' type specifier or via
6848/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6849NamedDecl*
6851 LookupResult &Previous, bool &Redeclaration) {
6852
6853 // Find the shadowed declaration before filtering for scope.
6854 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6855
6856 // Merge the decl with the existing one if appropriate. If the decl is
6857 // in an outer scope, it isn't the same thing.
6858 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6859 /*AllowInlineNamespace*/false);
6861 if (!Previous.empty()) {
6862 Redeclaration = true;
6863 MergeTypedefNameDecl(S, NewTD, Previous);
6864 } else {
6866 }
6867
6868 if (ShadowedDecl && !Redeclaration)
6869 CheckShadow(NewTD, ShadowedDecl, Previous);
6870
6871 // If this is the C FILE type, notify the AST context.
6872 if (IdentifierInfo *II = NewTD->getIdentifier())
6873 if (!NewTD->isInvalidDecl() &&
6875 switch (II->getNotableIdentifierID()) {
6876 case tok::NotableIdentifierKind::FILE:
6877 Context.setFILEDecl(NewTD);
6878 break;
6879 case tok::NotableIdentifierKind::jmp_buf:
6880 Context.setjmp_bufDecl(NewTD);
6881 break;
6882 case tok::NotableIdentifierKind::sigjmp_buf:
6884 break;
6885 case tok::NotableIdentifierKind::ucontext_t:
6887 break;
6888 case tok::NotableIdentifierKind::float_t:
6889 case tok::NotableIdentifierKind::double_t:
6890 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6891 break;
6892 default:
6893 break;
6894 }
6895 }
6896
6897 return NewTD;
6898}
6899
6900/// Determines whether the given declaration is an out-of-scope
6901/// previous declaration.
6902///
6903/// This routine should be invoked when name lookup has found a
6904/// previous declaration (PrevDecl) that is not in the scope where a
6905/// new declaration by the same name is being introduced. If the new
6906/// declaration occurs in a local scope, previous declarations with
6907/// linkage may still be considered previous declarations (C99
6908/// 6.2.2p4-5, C++ [basic.link]p6).
6909///
6910/// \param PrevDecl the previous declaration found by name
6911/// lookup
6912///
6913/// \param DC the context in which the new declaration is being
6914/// declared.
6915///
6916/// \returns true if PrevDecl is an out-of-scope previous declaration
6917/// for a new delcaration with the same name.
6918static bool
6920 ASTContext &Context) {
6921 if (!PrevDecl)
6922 return false;
6923
6924 if (!PrevDecl->hasLinkage())
6925 return false;
6926
6927 if (Context.getLangOpts().CPlusPlus) {
6928 // C++ [basic.link]p6:
6929 // If there is a visible declaration of an entity with linkage
6930 // having the same name and type, ignoring entities declared
6931 // outside the innermost enclosing namespace scope, the block
6932 // scope declaration declares that same entity and receives the
6933 // linkage of the previous declaration.
6934 DeclContext *OuterContext = DC->getRedeclContext();
6935 if (!OuterContext->isFunctionOrMethod())
6936 // This rule only applies to block-scope declarations.
6937 return false;
6938
6939 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6940 if (PrevOuterContext->isRecord())
6941 // We found a member function: ignore it.
6942 return false;
6943
6944 // Find the innermost enclosing namespace for the new and
6945 // previous declarations.
6946 OuterContext = OuterContext->getEnclosingNamespaceContext();
6947 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6948
6949 // The previous declaration is in a different namespace, so it
6950 // isn't the same function.
6951 if (!OuterContext->Equals(PrevOuterContext))
6952 return false;
6953 }
6954
6955 return true;
6956}
6957
6959 CXXScopeSpec &SS = D.getCXXScopeSpec();
6960 if (!SS.isSet()) return;
6962}
6963
6965 QualType type = decl->getType();
6966 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6967 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6968 // Various kinds of declaration aren't allowed to be __autoreleasing.
6969 unsigned kind = -1U;
6970 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6971 if (var->hasAttr<BlocksAttr>())
6972 kind = 0; // __block
6973 else if (!var->hasLocalStorage())
6974 kind = 1; // global
6975 } else if (isa<ObjCIvarDecl>(decl)) {
6976 kind = 3; // ivar
6977 } else if (isa<FieldDecl>(decl)) {
6978 kind = 2; // field
6979 }
6980
6981 if (kind != -1U) {
6982 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6983 << kind;
6984 }
6985 } else if (lifetime == Qualifiers::OCL_None) {
6986 // Try to infer lifetime.
6987 if (!type->isObjCLifetimeType())
6988 return false;
6989
6990 lifetime = type->getObjCARCImplicitLifetime();
6992 decl->setType(type);
6993 }
6994
6995 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6996 // Thread-local variables cannot have lifetime.
6997 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6998 var->getTLSKind()) {
6999 Diag(var->getLocation(), diag::err_arc_thread_ownership)
7000 << var->getType();
7001 return true;
7002 }
7003 }
7004
7005 return false;
7006}
7007
7009 if (Decl->getType().hasAddressSpace())
7010 return;
7011 if (Decl->getType()->isDependentType())
7012 return;
7013 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7014 QualType Type = Var->getType();
7015 if (Type->isSamplerT() || Type->isVoidType())
7016 return;
7018 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7019 // __opencl_c_program_scope_global_variables feature, the address space
7020 // for a variable at program scope or a static or extern variable inside
7021 // a function are inferred to be __global.
7022 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7023 Var->hasGlobalStorage())
7024 ImplAS = LangAS::opencl_global;
7025 // If the original type from a decayed type is an array type and that array
7026 // type has no address space yet, deduce it now.
7027 if (auto DT = dyn_cast<DecayedType>(Type)) {
7028 auto OrigTy = DT->getOriginalType();
7029 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7030 // Add the address space to the original array type and then propagate
7031 // that to the element type through `getAsArrayType`.
7032 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7033 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7034 // Re-generate the decayed type.
7035 Type = Context.getDecayedType(OrigTy);
7036 }
7037 }
7039 // Apply any qualifiers (including address space) from the array type to
7040 // the element type. This implements C99 6.7.3p8: "If the specification of
7041 // an array type includes any type qualifiers, the element type is so
7042 // qualified, not the array type."
7043 if (Type->isArrayType())
7045 Decl->setType(Type);
7046 }
7047}
7048
7050 // Ensure that an auto decl is deduced otherwise the checks below might cache
7051 // the wrong linkage.
7052 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7053
7054 // 'weak' only applies to declarations with external linkage.
7055 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7056 if (!ND.isExternallyVisible()) {
7057 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7058 ND.dropAttr<WeakAttr>();
7059 }
7060 }
7061 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7062 if (ND.isExternallyVisible()) {
7063 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7064 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7065 }
7066 }
7067
7068 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7069 if (VD->hasInit()) {
7070 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7071 assert(VD->isThisDeclarationADefinition() &&
7072 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7073 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7074 VD->dropAttr<AliasAttr>();
7075 }
7076 }
7077 }
7078
7079 // 'selectany' only applies to externally visible variable declarations.
7080 // It does not apply to functions.
7081 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7082 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7083 S.Diag(Attr->getLocation(),
7084 diag::err_attribute_selectany_non_extern_data);
7085 ND.dropAttr<SelectAnyAttr>();
7086 }
7087 }
7088
7089 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7090 auto *VD = dyn_cast<VarDecl>(&ND);
7091 bool IsAnonymousNS = false;
7092 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7093 if (VD) {
7094 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7095 while (NS && !IsAnonymousNS) {
7096 IsAnonymousNS = NS->isAnonymousNamespace();
7097 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7098 }
7099 }
7100 // dll attributes require external linkage. Static locals may have external
7101 // linkage but still cannot be explicitly imported or exported.
7102 // In Microsoft mode, a variable defined in anonymous namespace must have
7103 // external linkage in order to be exported.
7104 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7105 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7106 (!AnonNSInMicrosoftMode &&
7107 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7108 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7109 << &ND << Attr;
7110 ND.setInvalidDecl();
7111 }
7112 }
7113
7114 // Check the attributes on the function type, if any.
7115 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7116 // Don't declare this variable in the second operand of the for-statement;
7117 // GCC miscompiles that by ending its lifetime before evaluating the
7118 // third operand. See gcc.gnu.org/PR86769.
7120 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7121 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7122 TL = ATL.getModifiedLoc()) {
7123 // The [[lifetimebound]] attribute can be applied to the implicit object
7124 // parameter of a non-static member function (other than a ctor or dtor)
7125 // by applying it to the function type.
7126 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7127 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7128 if (!MD || MD->isStatic()) {
7129 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7130 << !MD << A->getRange();
7131 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7132 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7133 << isa<CXXDestructorDecl>(MD) << A->getRange();
7134 }
7135 }
7136 }
7137 }
7138}
7139
7141 NamedDecl *NewDecl,
7142 bool IsSpecialization,
7143 bool IsDefinition) {
7144 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7145 return;
7146
7147 bool IsTemplate = false;
7148 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7149 OldDecl = OldTD->getTemplatedDecl();
7150 IsTemplate = true;
7151 if (!IsSpecialization)
7152 IsDefinition = false;
7153 }
7154 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7155 NewDecl = NewTD->getTemplatedDecl();
7156 IsTemplate = true;
7157 }
7158
7159 if (!OldDecl || !NewDecl)
7160 return;
7161
7162 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7163 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7164 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7165 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7166
7167 // dllimport and dllexport are inheritable attributes so we have to exclude
7168 // inherited attribute instances.
7169 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7170 (NewExportAttr && !NewExportAttr->isInherited());
7171
7172 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7173 // the only exception being explicit specializations.
7174 // Implicitly generated declarations are also excluded for now because there
7175 // is no other way to switch these to use dllimport or dllexport.
7176 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7177
7178 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7179 // Allow with a warning for free functions and global variables.
7180 bool JustWarn = false;
7181 if (!OldDecl->isCXXClassMember()) {
7182 auto *VD = dyn_cast<VarDecl>(OldDecl);
7183 if (VD && !VD->getDescribedVarTemplate())
7184 JustWarn = true;
7185 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7186 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7187 JustWarn = true;
7188 }
7189
7190 // We cannot change a declaration that's been used because IR has already
7191 // been emitted. Dllimported functions will still work though (modulo
7192 // address equality) as they can use the thunk.
7193 if (OldDecl->isUsed())
7194 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7195 JustWarn = false;
7196
7197 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7198 : diag::err_attribute_dll_redeclaration;
7199 S.Diag(NewDecl->getLocation(), DiagID)
7200 << NewDecl
7201 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7202 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7203 if (!JustWarn) {
7204 NewDecl->setInvalidDecl();
7205 return;
7206 }
7207 }
7208
7209 // A redeclaration is not allowed to drop a dllimport attribute, the only
7210 // exceptions being inline function definitions (except for function
7211 // templates), local extern declarations, qualified friend declarations or
7212 // special MSVC extension: in the last case, the declaration is treated as if
7213 // it were marked dllexport.
7214 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7215 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7216 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7217 // Ignore static data because out-of-line definitions are diagnosed
7218 // separately.
7219 IsStaticDataMember = VD->isStaticDataMember();
7220 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7222 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7223 IsInline = FD->isInlined();
7224 IsQualifiedFriend = FD->getQualifier() &&
7225 FD->getFriendObjectKind() == Decl::FOK_Declared;
7226 }
7227
7228 if (OldImportAttr && !HasNewAttr &&
7229 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7230 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7231 if (IsMicrosoftABI && IsDefinition) {
7232 if (IsSpecialization) {
7233 S.Diag(
7234 NewDecl->getLocation(),
7235 diag::err_attribute_dllimport_function_specialization_definition);
7236 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7237 NewDecl->dropAttr<DLLImportAttr>();
7238 } else {
7239 S.Diag(NewDecl->getLocation(),
7240 diag::warn_redeclaration_without_import_attribute)
7241 << NewDecl;
7242 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7243 NewDecl->dropAttr<DLLImportAttr>();
7244 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7245 S.Context, NewImportAttr->getRange()));
7246 }
7247 } else if (IsMicrosoftABI && IsSpecialization) {
7248 assert(!IsDefinition);
7249 // MSVC allows this. Keep the inherited attribute.
7250 } else {
7251 S.Diag(NewDecl->getLocation(),
7252 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7253 << NewDecl << OldImportAttr;
7254 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7255 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7256 OldDecl->dropAttr<DLLImportAttr>();
7257 NewDecl->dropAttr<DLLImportAttr>();
7258 }
7259 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7260 // In MinGW, seeing a function declared inline drops the dllimport
7261 // attribute.
7262 OldDecl->dropAttr<DLLImportAttr>();
7263 NewDecl->dropAttr<DLLImportAttr>();
7264 S.Diag(NewDecl->getLocation(),
7265 diag::warn_dllimport_dropped_from_inline_function)
7266 << NewDecl << OldImportAttr;
7267 }
7268
7269 // A specialization of a class template member function is processed here
7270 // since it's a redeclaration. If the parent class is dllexport, the
7271 // specialization inherits that attribute. This doesn't happen automatically
7272 // since the parent class isn't instantiated until later.
7273 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7274 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7275 !NewImportAttr && !NewExportAttr) {
7276 if (const DLLExportAttr *ParentExportAttr =
7277 MD->getParent()->getAttr<DLLExportAttr>()) {
7278 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7279 NewAttr->setInherited(true);
7280 NewDecl->addAttr(NewAttr);
7281 }
7282 }
7283 }
7284}
7285
7286/// Given that we are within the definition of the given function,
7287/// will that definition behave like C99's 'inline', where the
7288/// definition is discarded except for optimization purposes?
7290 // Try to avoid calling GetGVALinkageForFunction.
7291
7292 // All cases of this require the 'inline' keyword.
7293 if (!FD->isInlined()) return false;
7294
7295 // This is only possible in C++ with the gnu_inline attribute.
7296 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7297 return false;
7298
7299 // Okay, go ahead and call the relatively-more-expensive function.
7301}
7302
7303/// Determine whether a variable is extern "C" prior to attaching
7304/// an initializer. We can't just call isExternC() here, because that
7305/// will also compute and cache whether the declaration is externally
7306/// visible, which might change when we attach the initializer.
7307///
7308/// This can only be used if the declaration is known to not be a
7309/// redeclaration of an internal linkage declaration.
7310///
7311/// For instance:
7312///
7313/// auto x = []{};
7314///
7315/// Attaching the initializer here makes this declaration not externally
7316/// visible, because its type has internal linkage.
7317///
7318/// FIXME: This is a hack.
7319template<typename T>
7320static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7321 if (S.getLangOpts().CPlusPlus) {
7322 // In C++, the overloadable attribute negates the effects of extern "C".
7323 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7324 return false;
7325
7326 // So do CUDA's host/device attributes.
7327 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7328 D->template hasAttr<CUDAHostAttr>()))
7329 return false;
7330 }
7331 return D->isExternC();
7332}
7333
7334static bool shouldConsiderLinkage(const VarDecl *VD) {
7335 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7336 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7337 isa<OMPDeclareMapperDecl>(DC))
7338 return VD->hasExternalStorage();
7339 if (DC->isFileContext())
7340 return true;
7341 if (DC->isRecord())
7342 return false;
7343 if (DC->getDeclKind() == Decl::HLSLBuffer)
7344 return false;
7345
7346 if (isa<RequiresExprBodyDecl>(DC))
7347 return false;
7348 llvm_unreachable("Unexpected context");
7349}
7350
7351static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7352 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7353 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7354 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7355 return true;
7356 if (DC->isRecord())
7357 return false;
7358 llvm_unreachable("Unexpected context");
7359}
7360
7361static bool hasParsedAttr(Scope *S, const Declarator &PD,
7362 ParsedAttr::Kind Kind) {
7363 // Check decl attributes on the DeclSpec.
7364 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7365 return true;
7366
7367 // Walk the declarator structure, checking decl attributes that were in a type
7368 // position to the decl itself.
7369 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7370 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7371 return true;
7372 }
7373
7374 // Finally, check attributes on the decl itself.
7375 return PD.getAttributes().hasAttribute(Kind) ||
7377}
7378
7379/// Adjust the \c DeclContext for a function or variable that might be a
7380/// function-local external declaration.
7382 if (!DC->isFunctionOrMethod())
7383 return false;
7384
7385 // If this is a local extern function or variable declared within a function
7386 // template, don't add it into the enclosing namespace scope until it is
7387 // instantiated; it might have a dependent type right now.
7388 if (DC->isDependentContext())
7389 return true;
7390
7391 // C++11 [basic.link]p7:
7392 // When a block scope declaration of an entity with linkage is not found to
7393 // refer to some other declaration, then that entity is a member of the
7394 // innermost enclosing namespace.
7395 //
7396 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7397 // semantically-enclosing namespace, not a lexically-enclosing one.
7398 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7399 DC = DC->getParent();
7400 return true;
7401}
7402
7403/// Returns true if given declaration has external C language linkage.
7404static bool isDeclExternC(const Decl *D) {
7405 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7406 return FD->isExternC();
7407 if (const auto *VD = dyn_cast<VarDecl>(D))
7408 return VD->isExternC();
7409
7410 llvm_unreachable("Unknown type of decl!");
7411}
7412
7413/// Returns true if there hasn't been any invalid type diagnosed.
7414static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7415 DeclContext *DC = NewVD->getDeclContext();
7416 QualType R = NewVD->getType();
7417
7418 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7419 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7420 // argument.
7421 if (R->isImageType() || R->isPipeType()) {
7422 Se.Diag(NewVD->getLocation(),
7423 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7424 << R;
7425 NewVD->setInvalidDecl();
7426 return false;
7427 }
7428
7429 // OpenCL v1.2 s6.9.r:
7430 // The event type cannot be used to declare a program scope variable.
7431 // OpenCL v2.0 s6.9.q:
7432 // The clk_event_t and reserve_id_t types cannot be declared in program
7433 // scope.
7434 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7435 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7436 Se.Diag(NewVD->getLocation(),
7437 diag::err_invalid_type_for_program_scope_var)
7438 << R;
7439 NewVD->setInvalidDecl();
7440 return false;
7441 }
7442 }
7443
7444 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7445 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7446 Se.getLangOpts())) {
7447 QualType NR = R.getCanonicalType();
7448 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7449 NR->isReferenceType()) {
7452 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7453 << NR->isReferenceType();
7454 NewVD->setInvalidDecl();
7455 return false;
7456 }
7457 NR = NR->getPointeeType();
7458 }
7459 }
7460
7461 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7462 Se.getLangOpts())) {
7463 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7464 // half array type (unless the cl_khr_fp16 extension is enabled).
7465 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7466 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7467 NewVD->setInvalidDecl();
7468 return false;
7469 }
7470 }
7471
7472 // OpenCL v1.2 s6.9.r:
7473 // The event type cannot be used with the __local, __constant and __global
7474 // address space qualifiers.
7475 if (R->isEventT()) {
7477 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7478 NewVD->setInvalidDecl();
7479 return false;
7480 }
7481 }
7482
7483 if (R->isSamplerT()) {
7484 // OpenCL v1.2 s6.9.b p4:
7485 // The sampler type cannot be used with the __local and __global address
7486 // space qualifiers.
7489 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7490 NewVD->setInvalidDecl();
7491 }
7492
7493 // OpenCL v1.2 s6.12.14.1:
7494 // A global sampler must be declared with either the constant address
7495 // space qualifier or with the const qualifier.
7496 if (DC->isTranslationUnit() &&
7498 R.isConstQualified())) {
7499 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7500 NewVD->setInvalidDecl();
7501 }
7502 if (NewVD->isInvalidDecl())
7503 return false;
7504 }
7505
7506 return true;
7507}
7508
7509template <typename AttrTy>
7510static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7511 const TypedefNameDecl *TND = TT->getDecl();
7512 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7513 AttrTy *Clone = Attribute->clone(S.Context);
7514 Clone->setInherited(true);
7515 D->addAttr(Clone);
7516 }
7517}
7518
7519// This function emits warning and a corresponding note based on the
7520// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7521// declarations of an annotated type must be const qualified.
7523 QualType VarType = VD->getType().getCanonicalType();
7524
7525 // Ignore local declarations (for now) and those with const qualification.
7526 // TODO: Local variables should not be allowed if their type declaration has
7527 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7528 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7529 return;
7530
7531 if (VarType->isArrayType()) {
7532 // Retrieve element type for array declarations.
7533 VarType = S.getASTContext().getBaseElementType(VarType);
7534 }
7535
7536 const RecordDecl *RD = VarType->getAsRecordDecl();
7537
7538 // Check if the record declaration is present and if it has any attributes.
7539 if (RD == nullptr)
7540 return;
7541
7542 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7543 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7544 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7545 return;
7546 }
7547}
7548
7550 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7551 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7552 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7553 QualType R = TInfo->getType();
7555
7556 IdentifierInfo *II = Name.getAsIdentifierInfo();
7557 bool IsPlaceholderVariable = false;
7558
7559 if (D.isDecompositionDeclarator()) {
7560 // Take the name of the first declarator as our name for diagnostic
7561 // purposes.
7562 auto &Decomp = D.getDecompositionDeclarator();
7563 if (!Decomp.bindings().empty()) {
7564 II = Decomp.bindings()[0].Name;
7565 Name = II;
7566 }
7567 } else if (!II) {
7568 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7569 return nullptr;
7570 }
7571
7572
7575
7576 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7577 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7578 IsPlaceholderVariable = true;
7579 if (!Previous.empty()) {
7580 NamedDecl *PrevDecl = *Previous.begin();
7581 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7582 DC->getRedeclContext());
7583 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7585 }
7586 }
7587
7588 // dllimport globals without explicit storage class are treated as extern. We
7589 // have to change the storage class this early to get the right DeclContext.
7590 if (SC == SC_None && !DC->isRecord() &&
7591 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7592 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7593 SC = SC_Extern;
7594
7595 DeclContext *OriginalDC = DC;
7596 bool IsLocalExternDecl = SC == SC_Extern &&
7598
7599 if (SCSpec == DeclSpec::SCS_mutable) {
7600 // mutable can only appear on non-static class members, so it's always
7601 // an error here
7602 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7603 D.setInvalidType();
7604 SC = SC_None;
7605 }
7606
7607 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7608 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7610 // In C++11, the 'register' storage class specifier is deprecated.
7611 // Suppress the warning in system macros, it's used in macros in some
7612 // popular C system headers, such as in glibc's htonl() macro.
7614 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7615 : diag::warn_deprecated_register)
7617 }
7618
7620
7621 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7622 // C99 6.9p2: The storage-class specifiers auto and register shall not
7623 // appear in the declaration specifiers in an external declaration.
7624 // Global Register+Asm is a GNU extension we support.
7625 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7626 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7627 D.setInvalidType();
7628 }
7629 }
7630
7631 // If this variable has a VLA type and an initializer, try to
7632 // fold to a constant-sized type. This is otherwise invalid.
7633 if (D.hasInitializer() && R->isVariableArrayType())
7635 /*DiagID=*/0);
7636
7637 bool IsMemberSpecialization = false;
7638 bool IsVariableTemplateSpecialization = false;
7639 bool IsPartialSpecialization = false;
7640 bool IsVariableTemplate = false;
7641 VarDecl *NewVD = nullptr;
7642 VarTemplateDecl *NewTemplate = nullptr;
7643 TemplateParameterList *TemplateParams = nullptr;
7644 if (!getLangOpts().CPlusPlus) {
7646 II, R, TInfo, SC);
7647
7648 if (R->getContainedDeducedType())
7649 ParsingInitForAutoVars.insert(NewVD);
7650
7651 if (D.isInvalidType())
7652 NewVD->setInvalidDecl();
7653
7655 NewVD->hasLocalStorage())
7656 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7658 } else {
7659 bool Invalid = false;
7660
7661 if (DC->isRecord() && !CurContext->isRecord()) {
7662 // This is an out-of-line definition of a static data member.
7663 switch (SC) {
7664 case SC_None:
7665 break;
7666 case SC_Static:
7668 diag::err_static_out_of_line)
7670 break;
7671 case SC_Auto:
7672 case SC_Register:
7673 case SC_Extern:
7674 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7675 // to names of variables declared in a block or to function parameters.
7676 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7677 // of class members
7678
7680 diag::err_storage_class_for_static_member)
7682 break;
7683 case SC_PrivateExtern:
7684 llvm_unreachable("C storage class in c++!");
7685 }
7686 }
7687
7688 if (SC == SC_Static && CurContext->isRecord()) {
7689 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7690 // Walk up the enclosing DeclContexts to check for any that are
7691 // incompatible with static data members.
7692 const DeclContext *FunctionOrMethod = nullptr;
7693 const CXXRecordDecl *AnonStruct = nullptr;
7694 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7695 if (Ctxt->isFunctionOrMethod()) {
7696 FunctionOrMethod = Ctxt;
7697 break;
7698 }
7699 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7700 if (ParentDecl && !ParentDecl->getDeclName()) {
7701 AnonStruct = ParentDecl;
7702 break;
7703 }
7704 }
7705 if (FunctionOrMethod) {
7706 // C++ [class.static.data]p5: A local class shall not have static data
7707 // members.
7709 diag::err_static_data_member_not_allowed_in_local_class)
7710 << Name << RD->getDeclName()
7711 << llvm::to_underlying(RD->getTagKind());
7712 } else if (AnonStruct) {
7713 // C++ [class.static.data]p4: Unnamed classes and classes contained
7714 // directly or indirectly within unnamed classes shall not contain
7715 // static data members.
7717 diag::err_static_data_member_not_allowed_in_anon_struct)
7718 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7719 Invalid = true;
7720 } else if (RD->isUnion()) {
7721 // C++98 [class.union]p1: If a union contains a static data member,
7722 // the program is ill-formed. C++11 drops this restriction.
7725 ? diag::warn_cxx98_compat_static_data_member_in_union
7726 : diag::ext_static_data_member_in_union) << Name;
7727 }
7728 }
7729 }
7730
7731 // Match up the template parameter lists with the scope specifier, then
7732 // determine whether we have a template or a template specialization.
7733 bool InvalidScope = false;
7736 D.getCXXScopeSpec(),
7738 ? D.getName().TemplateId
7739 : nullptr,
7740 TemplateParamLists,
7741 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7742 Invalid |= InvalidScope;
7743
7744 if (TemplateParams) {
7745 if (!TemplateParams->size() &&
7747 // There is an extraneous 'template<>' for this variable. Complain
7748 // about it, but allow the declaration of the variable.
7749 Diag(TemplateParams->getTemplateLoc(),
7750 diag::err_template_variable_noparams)
7751 << II
7752 << SourceRange(TemplateParams->getTemplateLoc(),
7753 TemplateParams->getRAngleLoc());
7754 TemplateParams = nullptr;
7755 } else {
7756 // Check that we can declare a template here.
7757 if (CheckTemplateDeclScope(S, TemplateParams))
7758 return nullptr;
7759
7761 // This is an explicit specialization or a partial specialization.
7762 IsVariableTemplateSpecialization = true;
7763 IsPartialSpecialization = TemplateParams->size() > 0;
7764 } else { // if (TemplateParams->size() > 0)
7765 // This is a template declaration.
7766 IsVariableTemplate = true;
7767
7768 // Only C++1y supports variable templates (N3651).
7771 ? diag::warn_cxx11_compat_variable_template
7772 : diag::ext_variable_template);
7773 }
7774 }
7775 } else {
7776 // Check that we can declare a member specialization here.
7777 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7778 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7779 return nullptr;
7780 assert((Invalid ||
7782 "should have a 'template<>' for this decl");
7783 }
7784
7785 if (IsVariableTemplateSpecialization) {
7786 SourceLocation TemplateKWLoc =
7787 TemplateParamLists.size() > 0
7788 ? TemplateParamLists[0]->getTemplateLoc()
7789 : SourceLocation();
7791 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7793 if (Res.isInvalid())
7794 return nullptr;
7795 NewVD = cast<VarDecl>(Res.get());
7796 AddToScope = false;
7797 } else if (D.isDecompositionDeclarator()) {
7799 D.getIdentifierLoc(), R, TInfo, SC,
7800 Bindings);
7801 } else
7802 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7803 D.getIdentifierLoc(), II, R, TInfo, SC);
7804
7805 // If this is supposed to be a variable template, create it as such.
7806 if (IsVariableTemplate) {
7807 NewTemplate =
7809 TemplateParams, NewVD);
7810 NewVD->setDescribedVarTemplate(NewTemplate);
7811 }
7812
7813 // If this decl has an auto type in need of deduction, make a note of the
7814 // Decl so we can diagnose uses of it in its own initializer.
7815 if (R->getContainedDeducedType())
7816 ParsingInitForAutoVars.insert(NewVD);
7817
7818 if (D.isInvalidType() || Invalid) {
7819 NewVD->setInvalidDecl();
7820 if (NewTemplate)
7821 NewTemplate->setInvalidDecl();
7822 }
7823
7824 SetNestedNameSpecifier(*this, NewVD, D);
7825
7826 // If we have any template parameter lists that don't directly belong to
7827 // the variable (matching the scope specifier), store them.
7828 // An explicit variable template specialization does not own any template
7829 // parameter lists.
7830 bool IsExplicitSpecialization =
7831 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7832 unsigned VDTemplateParamLists =
7833 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7834 if (TemplateParamLists.size() > VDTemplateParamLists)
7836 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7837 }
7838
7839 if (D.getDeclSpec().isInlineSpecified()) {
7840 if (!getLangOpts().CPlusPlus) {
7841 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7842 << 0;
7843 } else if (CurContext->isFunctionOrMethod()) {
7844 // 'inline' is not allowed on block scope variable declaration.
7846 diag::err_inline_declaration_block_scope) << Name
7848 } else {
7850 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7851 : diag::ext_inline_variable);
7852 NewVD->setInlineSpecified();
7853 }
7854 }
7855
7856 // Set the lexical context. If the declarator has a C++ scope specifier, the
7857 // lexical context will be different from the semantic context.
7859 if (NewTemplate)
7860 NewTemplate->setLexicalDeclContext(CurContext);
7861
7862 if (IsLocalExternDecl) {
7864 for (auto *B : Bindings)
7865 B->setLocalExternDecl();
7866 else
7867 NewVD->setLocalExternDecl();
7868 }
7869
7870 bool EmitTLSUnsupportedError = false;
7872 // C++11 [dcl.stc]p4:
7873 // When thread_local is applied to a variable of block scope the
7874 // storage-class-specifier static is implied if it does not appear
7875 // explicitly.
7876 // Core issue: 'static' is not implied if the variable is declared
7877 // 'extern'.
7878 if (NewVD->hasLocalStorage() &&
7879 (SCSpec != DeclSpec::SCS_unspecified ||
7881 !DC->isFunctionOrMethod()))
7883 diag::err_thread_non_global)
7885 else if (!Context.getTargetInfo().isTLSSupported()) {
7886 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7887 getLangOpts().SYCLIsDevice) {
7888 // Postpone error emission until we've collected attributes required to
7889 // figure out whether it's a host or device variable and whether the
7890 // error should be ignored.
7891 EmitTLSUnsupportedError = true;
7892 // We still need to mark the variable as TLS so it shows up in AST with
7893 // proper storage class for other tools to use even if we're not going
7894 // to emit any code for it.
7895 NewVD->setTSCSpec(TSCS);
7896 } else
7898 diag::err_thread_unsupported);
7899 } else
7900 NewVD->setTSCSpec(TSCS);
7901 }
7902
7903 switch (D.getDeclSpec().getConstexprSpecifier()) {
7905 break;
7906
7909 diag::err_constexpr_wrong_decl_kind)
7910 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7911 [[fallthrough]];
7912
7914 NewVD->setConstexpr(true);
7915 // C++1z [dcl.spec.constexpr]p1:
7916 // A static data member declared with the constexpr specifier is
7917 // implicitly an inline variable.
7918 if (NewVD->isStaticDataMember() &&
7919 (getLangOpts().CPlusPlus17 ||
7921 NewVD->setImplicitlyInline();
7922 break;
7923
7925 if (!NewVD->hasGlobalStorage())
7927 diag::err_constinit_local_variable);
7928 else
7929 NewVD->addAttr(
7930 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7931 ConstInitAttr::Keyword_constinit));
7932 break;
7933 }
7934
7935 // C99 6.7.4p3
7936 // An inline definition of a function with external linkage shall
7937 // not contain a definition of a modifiable object with static or
7938 // thread storage duration...
7939 // We only apply this when the function is required to be defined
7940 // elsewhere, i.e. when the function is not 'extern inline'. Note
7941 // that a local variable with thread storage duration still has to
7942 // be marked 'static'. Also note that it's possible to get these
7943 // semantics in C++ using __attribute__((gnu_inline)).
7944 if (SC == SC_Static && S->getFnParent() != nullptr &&
7945 !NewVD->getType().isConstQualified()) {
7947 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7949 diag::warn_static_local_in_extern_inline);
7951 }
7952 }
7953
7955 if (IsVariableTemplateSpecialization)
7956 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7957 << (IsPartialSpecialization ? 1 : 0)
7960 else if (IsMemberSpecialization)
7961 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7962 << 2
7964 else if (NewVD->hasLocalStorage())
7965 Diag(NewVD->getLocation(), diag::err_module_private_local)
7966 << 0 << NewVD
7970 else {
7971 NewVD->setModulePrivate();
7972 if (NewTemplate)
7973 NewTemplate->setModulePrivate();
7974 for (auto *B : Bindings)
7975 B->setModulePrivate();
7976 }
7977 }
7978
7979 if (getLangOpts().OpenCL) {
7981
7983 if (TSC != TSCS_unspecified) {
7985 diag::err_opencl_unknown_type_specifier)
7987 << DeclSpec::getSpecifierName(TSC) << 1;
7988 NewVD->setInvalidDecl();
7989 }
7990 }
7991
7992 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7993 // address space if the table has local storage (semantic checks elsewhere
7994 // will produce an error anyway).
7995 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7996 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7997 !NewVD->hasLocalStorage()) {
8000 NewVD->setType(Type);
8001 }
8002 }
8003
8004 // Handle attributes prior to checking for duplicates in MergeVarDecl
8005 ProcessDeclAttributes(S, NewVD, D);
8006
8007 // FIXME: This is probably the wrong location to be doing this and we should
8008 // probably be doing this for more attributes (especially for function
8009 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8010 // the code to copy attributes would be generated by TableGen.
8011 if (R->isFunctionPointerType())
8012 if (const auto *TT = R->getAs<TypedefType>())
8013 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8014
8015 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
8016 getLangOpts().SYCLIsDevice) {
8017 if (EmitTLSUnsupportedError &&
8019 (getLangOpts().OpenMPIsTargetDevice &&
8020 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8022 diag::err_thread_unsupported);
8023
8024 if (EmitTLSUnsupportedError &&
8025 (LangOpts.SYCLIsDevice ||
8026 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8027 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8028 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8029 // storage [duration]."
8030 if (SC == SC_None && S->getFnParent() != nullptr &&
8031 (NewVD->hasAttr<CUDASharedAttr>() ||
8032 NewVD->hasAttr<CUDAConstantAttr>())) {
8033 NewVD->setStorageClass(SC_Static);
8034 }
8035 }
8036
8037 // Ensure that dllimport globals without explicit storage class are treated as
8038 // extern. The storage class is set above using parsed attributes. Now we can
8039 // check the VarDecl itself.
8040 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8041 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8042 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8043
8044 // In auto-retain/release, infer strong retension for variables of
8045 // retainable type.
8046 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8047 NewVD->setInvalidDecl();
8048
8049 // Handle GNU asm-label extension (encoded as an attribute).
8050 if (Expr *E = (Expr*)D.getAsmLabel()) {
8051 // The parser guarantees this is a string.
8052 StringLiteral *SE = cast<StringLiteral>(E);
8053 StringRef Label = SE->getString();
8054 if (S->getFnParent() != nullptr) {
8055 switch (SC) {
8056 case SC_None:
8057 case SC_Auto:
8058 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8059 break;
8060 case SC_Register:
8061 // Local Named register
8064 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8065 break;
8066 case SC_Static:
8067 case SC_Extern:
8068 case SC_PrivateExtern:
8069 break;
8070 }
8071 } else if (SC == SC_Register) {
8072 // Global Named register
8073 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8074 const auto &TI = Context.getTargetInfo();
8075 bool HasSizeMismatch;
8076
8077 if (!TI.isValidGCCRegisterName(Label))
8078 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8079 else if (!TI.validateGlobalRegisterVariable(Label,
8081 HasSizeMismatch))
8082 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8083 else if (HasSizeMismatch)
8084 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8085 }
8086
8087 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8088 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8089 NewVD->setInvalidDecl(true);
8090 }
8091 }
8092
8093 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8094 /*IsLiteralLabel=*/true,
8095 SE->getStrTokenLoc(0)));
8096 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8097 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8099 if (I != ExtnameUndeclaredIdentifiers.end()) {
8100 if (isDeclExternC(NewVD)) {
8101 NewVD->addAttr(I->second);
8103 } else
8104 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8105 << /*Variable*/1 << NewVD;
8106 }
8107 }
8108
8109 // Find the shadowed declaration before filtering for scope.
8110 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8112 : nullptr;
8113
8114 // Don't consider existing declarations that are in a different
8115 // scope and are out-of-semantic-context declarations (if the new
8116 // declaration has linkage).
8119 IsMemberSpecialization ||
8120 IsVariableTemplateSpecialization);
8121
8122 // Check whether the previous declaration is in the same block scope. This
8123 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8124 if (getLangOpts().CPlusPlus &&
8125 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8127 Previous.isSingleResult() && !Previous.isShadowed() &&
8128 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8129
8130 if (!getLangOpts().CPlusPlus) {
8132 } else {
8133 // If this is an explicit specialization of a static data member, check it.
8134 if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
8136 NewVD->setInvalidDecl();
8137
8138 // Merge the decl with the existing one if appropriate.
8139 if (!Previous.empty()) {
8140 if (Previous.isSingleResult() &&
8141 isa<FieldDecl>(Previous.getFoundDecl()) &&
8142 D.getCXXScopeSpec().isSet()) {
8143 // The user tried to define a non-static data member
8144 // out-of-line (C++ [dcl.meaning]p1).
8145 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8146 << D.getCXXScopeSpec().getRange();
8147 Previous.clear();
8148 NewVD->setInvalidDecl();
8149 }
8150 } else if (D.getCXXScopeSpec().isSet() &&
8151 !IsVariableTemplateSpecialization) {
8152 // No previous declaration in the qualifying scope.
8153 Diag(D.getIdentifierLoc(), diag::err_no_member)
8154 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8155 << D.getCXXScopeSpec().getRange();
8156 NewVD->setInvalidDecl();
8157 }
8158
8159 if (!IsPlaceholderVariable)
8161
8162 // CheckVariableDeclaration will set NewVD as invalid if something is in
8163 // error like WebAssembly tables being declared as arrays with a non-zero
8164 // size, but then parsing continues and emits further errors on that line.
8165 // To avoid that we check here if it happened and return nullptr.
8166 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8167 return nullptr;
8168
8169 if (NewTemplate) {
8170 VarTemplateDecl *PrevVarTemplate =
8171 NewVD->getPreviousDecl()
8173 : nullptr;
8174
8175 // Check the template parameter list of this declaration, possibly
8176 // merging in the template parameter list from the previous variable
8177 // template declaration.
8179 TemplateParams,
8180 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8181 : nullptr,
8182 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8183 DC->isDependentContext())
8185 : TPC_VarTemplate))
8186 NewVD->setInvalidDecl();
8187
8188 // If we are providing an explicit specialization of a static variable
8189 // template, make a note of that.
8190 if (PrevVarTemplate &&
8191 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8192 PrevVarTemplate->setMemberSpecialization();
8193 }
8194 }
8195
8196 // Diagnose shadowed variables iff this isn't a redeclaration.
8197 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8198 CheckShadow(NewVD, ShadowedDecl, Previous);
8199
8200 ProcessPragmaWeak(S, NewVD);
8201
8202 // If this is the first declaration of an extern C variable, update
8203 // the map of such variables.
8204 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8205 isIncompleteDeclExternC(*this, NewVD))
8207
8208 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8210 Decl *ManglingContextDecl;
8211 std::tie(MCtx, ManglingContextDecl) =
8213 if (MCtx) {
8215 NewVD, MCtx->getManglingNumber(
8216 NewVD, getMSManglingNumber(getLangOpts(), S)));
8218 }
8219 }
8220
8221 // Special handling of variable named 'main'.
8222 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8224 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8225
8226 // C++ [basic.start.main]p3
8227 // A program that declares a variable main at global scope is ill-formed.
8228 if (getLangOpts().CPlusPlus)
8229 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8230
8231 // In C, and external-linkage variable named main results in undefined
8232 // behavior.
8233 else if (NewVD->hasExternalFormalLinkage())
8234 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8235 }
8236
8237 if (D.isRedeclaration() && !Previous.empty()) {
8238 NamedDecl *Prev = Previous.getRepresentativeDecl();
8239 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8241 }
8242
8243 if (NewTemplate) {
8244 if (NewVD->isInvalidDecl())
8245 NewTemplate->setInvalidDecl();
8246 ActOnDocumentableDecl(NewTemplate);
8247 return NewTemplate;
8248 }
8249
8250 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8252
8254
8255 return NewVD;
8256}
8257
8258/// Enum describing the %select options in diag::warn_decl_shadow.
8268
8269/// Determine what kind of declaration we're shadowing.
8271 const DeclContext *OldDC) {
8272 if (isa<TypeAliasDecl>(ShadowedDecl))
8273 return SDK_Using;
8274 else if (isa<TypedefDecl>(ShadowedDecl))
8275 return SDK_Typedef;
8276 else if (isa<BindingDecl>(ShadowedDecl))
8277 return SDK_StructuredBinding;
8278 else if (isa<RecordDecl>(OldDC))
8279 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8280
8281 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8282}
8283
8284/// Return the location of the capture if the given lambda captures the given
8285/// variable \p VD, or an invalid source location otherwise.
8287 const VarDecl *VD) {
8288 for (const Capture &Capture : LSI->Captures) {
8290 return Capture.getLocation();
8291 }
8292 return SourceLocation();
8293}
8294
8296 const LookupResult &R) {
8297 // Only diagnose if we're shadowing an unambiguous field or variable.
8299 return false;
8300
8301 // Return false if warning is ignored.
8302 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8303}
8304
8305/// Return the declaration shadowed by the given variable \p D, or null
8306/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8308 const LookupResult &R) {
8310 return nullptr;
8311
8312 // Don't diagnose declarations at file scope.
8313 if (D->hasGlobalStorage() && !D->isStaticLocal())
8314 return nullptr;
8315
8316 NamedDecl *ShadowedDecl = R.getFoundDecl();
8317 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8318 : nullptr;
8319}
8320
8321/// Return the declaration shadowed by the given typedef \p D, or null
8322/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8324 const LookupResult &R) {
8325 // Don't warn if typedef declaration is part of a class
8326 if (D->getDeclContext()->isRecord())
8327 return nullptr;
8328
8330 return nullptr;
8331
8332 NamedDecl *ShadowedDecl = R.getFoundDecl();
8333 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8334}
8335
8336/// Return the declaration shadowed by the given variable \p D, or null
8337/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8339 const LookupResult &R) {
8341 return nullptr;
8342
8343 NamedDecl *ShadowedDecl = R.getFoundDecl();
8344 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8345 : nullptr;
8346}
8347
8348/// Diagnose variable or built-in function shadowing. Implements
8349/// -Wshadow.
8350///
8351/// This method is called whenever a VarDecl is added to a "useful"
8352/// scope.
8353///
8354/// \param ShadowedDecl the declaration that is shadowed by the given variable
8355/// \param R the lookup of the name
8356///
8358 const LookupResult &R) {
8359 DeclContext *NewDC = D->getDeclContext();
8360
8361 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8362 // Fields are not shadowed by variables in C++ static methods.
8363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8364 if (MD->isStatic())
8365 return;
8366
8367 // Fields shadowed by constructor parameters are a special case. Usually
8368 // the constructor initializes the field with the parameter.
8369 if (isa<CXXConstructorDecl>(NewDC))
8370 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8371 // Remember that this was shadowed so we can either warn about its
8372 // modification or its existence depending on warning settings.
8373 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8374 return;
8375 }
8376 }
8377
8378 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8379 if (shadowedVar->isExternC()) {
8380 // For shadowing external vars, make sure that we point to the global
8381 // declaration, not a locally scoped extern declaration.
8382 for (auto *I : shadowedVar->redecls())
8383 if (I->isFileVarDecl()) {
8384 ShadowedDecl = I;
8385 break;
8386 }
8387 }
8388
8389 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8390
8391 unsigned WarningDiag = diag::warn_decl_shadow;
8392 SourceLocation CaptureLoc;
8393 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8394 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8395 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8396 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8397 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8398 if (RD->getLambdaCaptureDefault() == LCD_None) {
8399 // Try to avoid warnings for lambdas with an explicit capture
8400 // list. Warn only when the lambda captures the shadowed decl
8401 // explicitly.
8402 CaptureLoc = getCaptureLocation(LSI, VD);
8403 if (CaptureLoc.isInvalid())
8404 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8405 } else {
8406 // Remember that this was shadowed so we can avoid the warning if
8407 // the shadowed decl isn't captured and the warning settings allow
8408 // it.
8409 cast<LambdaScopeInfo>(getCurFunction())
8410 ->ShadowingDecls.push_back({D, VD});
8411 return;
8412 }
8413 }
8414 if (isa<FieldDecl>(ShadowedDecl)) {
8415 // If lambda can capture this, then emit default shadowing warning,
8416 // Otherwise it is not really a shadowing case since field is not
8417 // available in lambda's body.
8418 // At this point we don't know that lambda can capture this, so
8419 // remember that this was shadowed and delay until we know.
8420 cast<LambdaScopeInfo>(getCurFunction())
8421 ->ShadowingDecls.push_back({D, ShadowedDecl});
8422 return;
8423 }
8424 }
8425 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8426 VD && VD->hasLocalStorage()) {
8427 // A variable can't shadow a local variable in an enclosing scope, if
8428 // they are separated by a non-capturing declaration context.
8429 for (DeclContext *ParentDC = NewDC;
8430 ParentDC && !ParentDC->Equals(OldDC);
8431 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8432 // Only block literals, captured statements, and lambda expressions
8433 // can capture; other scopes don't.
8434 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8435 !isLambdaCallOperator(ParentDC)) {
8436 return;
8437 }
8438 }
8439 }
8440 }
8441 }
8442
8443 // Never warn about shadowing a placeholder variable.
8444 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8445 return;
8446
8447 // Only warn about certain kinds of shadowing for class members.
8448 if (NewDC && NewDC->isRecord()) {
8449 // In particular, don't warn about shadowing non-class members.
8450 if (!OldDC->isRecord())
8451 return;
8452
8453 // TODO: should we warn about static data members shadowing
8454 // static data members from base classes?
8455
8456 // TODO: don't diagnose for inaccessible shadowed members.
8457 // This is hard to do perfectly because we might friend the
8458 // shadowing context, but that's just a false negative.
8459 }
8460
8461
8462 DeclarationName Name = R.getLookupName();
8463
8464 // Emit warning and note.
8465 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8466 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8467 if (!CaptureLoc.isInvalid())
8468 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8469 << Name << /*explicitly*/ 1;
8470 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8471}
8472
8473/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8474/// when these variables are captured by the lambda.
8476 for (const auto &Shadow : LSI->ShadowingDecls) {
8477 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8478 // Try to avoid the warning when the shadowed decl isn't captured.
8479 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8480 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8481 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8482 Diag(Shadow.VD->getLocation(),
8483 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8484 : diag::warn_decl_shadow)
8485 << Shadow.VD->getDeclName()
8486 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8487 if (CaptureLoc.isValid())
8488 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8489 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8490 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8491 } else if (isa<FieldDecl>(ShadowedDecl)) {
8492 Diag(Shadow.VD->getLocation(),
8493 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8494 : diag::warn_decl_shadow_uncaptured_local)
8495 << Shadow.VD->getDeclName()
8496 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8497 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8498 }
8499 }
8500}
8501
8502/// Check -Wshadow without the advantage of a previous lookup.
8504 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8505 return;
8506
8507 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8509 LookupName(R, S);
8510 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8511 CheckShadow(D, ShadowedDecl, R);
8512}
8513
8514/// Check if 'E', which is an expression that is about to be modified, refers
8515/// to a constructor parameter that shadows a field.
8517 // Quickly ignore expressions that can't be shadowing ctor parameters.
8518 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8519 return;
8520 E = E->IgnoreParenImpCasts();
8521 auto *DRE = dyn_cast<DeclRefExpr>(E);
8522 if (!DRE)
8523 return;
8524 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8525 auto I = ShadowingDecls.find(D);
8526 if (I == ShadowingDecls.end())
8527 return;
8528 const NamedDecl *ShadowedDecl = I->second;
8529 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8530 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8531 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8532 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8533
8534 // Avoid issuing multiple warnings about the same decl.
8535 ShadowingDecls.erase(I);
8536}
8537
8538/// Check for conflict between this global or extern "C" declaration and
8539/// previous global or extern "C" declarations. This is only used in C++.
8540template<typename T>
8542 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8543 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8544 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8545
8546 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8547 // The common case: this global doesn't conflict with any extern "C"
8548 // declaration.
8549 return false;
8550 }
8551
8552 if (Prev) {
8553 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8554 // Both the old and new declarations have C language linkage. This is a
8555 // redeclaration.
8556 Previous.clear();
8557 Previous.addDecl(Prev);
8558 return true;
8559 }
8560
8561 // This is a global, non-extern "C" declaration, and there is a previous
8562 // non-global extern "C" declaration. Diagnose if this is a variable
8563 // declaration.
8564 if (!isa<VarDecl>(ND))
8565 return false;
8566 } else {
8567 // The declaration is extern "C". Check for any declaration in the
8568 // translation unit which might conflict.
8569 if (IsGlobal) {
8570 // We have already performed the lookup into the translation unit.
8571 IsGlobal = false;
8572 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8573 I != E; ++I) {
8574 if (isa<VarDecl>(*I)) {
8575 Prev = *I;
8576 break;
8577 }
8578 }
8579 } else {
8581 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8582 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8583 I != E; ++I) {
8584 if (isa<VarDecl>(*I)) {
8585 Prev = *I;
8586 break;
8587 }
8588 // FIXME: If we have any other entity with this name in global scope,
8589 // the declaration is ill-formed, but that is a defect: it breaks the
8590 // 'stat' hack, for instance. Only variables can have mangled name
8591 // clashes with extern "C" declarations, so only they deserve a
8592 // diagnostic.
8593 }
8594 }
8595
8596 if (!Prev)
8597 return false;
8598 }
8599
8600 // Use the first declaration's location to ensure we point at something which
8601 // is lexically inside an extern "C" linkage-spec.
8602 assert(Prev && "should have found a previous declaration to diagnose");
8603 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8604 Prev = FD->getFirstDecl();
8605 else
8606 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8607
8608 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8609 << IsGlobal << ND;
8610 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8611 << IsGlobal;
8612 return false;
8613}
8614
8615/// Apply special rules for handling extern "C" declarations. Returns \c true
8616/// if we have found that this is a redeclaration of some prior entity.
8617///
8618/// Per C++ [dcl.link]p6:
8619/// Two declarations [for a function or variable] with C language linkage
8620/// with the same name that appear in different scopes refer to the same
8621/// [entity]. An entity with C language linkage shall not be declared with
8622/// the same name as an entity in global scope.
8623template<typename T>
8626 if (!S.getLangOpts().CPlusPlus) {
8627 // In C, when declaring a global variable, look for a corresponding 'extern'
8628 // variable declared in function scope. We don't need this in C++, because
8629 // we find local extern decls in the surrounding file-scope DeclContext.
8630 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8631 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8632 Previous.clear();
8633 Previous.addDecl(Prev);
8634 return true;
8635 }
8636 }
8637 return false;
8638 }
8639
8640 // A declaration in the translation unit can conflict with an extern "C"
8641 // declaration.
8642 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8643 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8644
8645 // An extern "C" declaration can conflict with a declaration in the
8646 // translation unit or can be a redeclaration of an extern "C" declaration
8647 // in another scope.
8648 if (isIncompleteDeclExternC(S,ND))
8649 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8650
8651 // Neither global nor extern "C": nothing to do.
8652 return false;
8653}
8654
8655static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8656 QualType T) {
8657 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8658 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8659 // any of its members, even recursively, shall not have an atomic type, or a
8660 // variably modified type, or a type that is volatile or restrict qualified.
8661 if (CanonT->isVariablyModifiedType()) {
8662 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8663 return true;
8664 }
8665
8666 // Arrays are qualified by their element type, so get the base type (this
8667 // works on non-arrays as well).
8668 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8669
8670 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8671 CanonT.isRestrictQualified()) {
8672 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8673 return true;
8674 }
8675
8676 if (CanonT->isRecordType()) {
8677 const RecordDecl *RD = CanonT->getAsRecordDecl();
8678 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8679 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8680 }))
8681 return true;
8682 }
8683
8684 return false;
8685}
8686
8688 // If the decl is already known invalid, don't check it.
8689 if (NewVD->isInvalidDecl())
8690 return;
8691
8692 QualType T = NewVD->getType();
8693
8694 // Defer checking an 'auto' type until its initializer is attached.
8695 if (T->isUndeducedType())
8696 return;
8697
8698 if (NewVD->hasAttrs())
8700
8701 if (T->isObjCObjectType()) {
8702 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8703 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8705 NewVD->setType(T);
8706 }
8707
8708 // Emit an error if an address space was applied to decl with local storage.
8709 // This includes arrays of objects with address space qualifiers, but not
8710 // automatic variables that point to other address spaces.
8711 // ISO/IEC TR 18037 S5.1.2
8712 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8714 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8715 NewVD->setInvalidDecl();
8716 return;
8717 }
8718
8719 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8720 // scope.
8721 if (getLangOpts().OpenCLVersion == 120 &&
8722 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8723 getLangOpts()) &&
8724 NewVD->isStaticLocal()) {
8725 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8726 NewVD->setInvalidDecl();
8727 return;
8728 }
8729
8730 if (getLangOpts().OpenCL) {
8731 if (!diagnoseOpenCLTypes(*this, NewVD))
8732 return;
8733
8734 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8735 if (NewVD->hasAttr<BlocksAttr>()) {
8736 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8737 return;
8738 }
8739
8740 if (T->isBlockPointerType()) {
8741 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8742 // can't use 'extern' storage class.
8743 if (!T.isConstQualified()) {
8744 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8745 << 0 /*const*/;
8746 NewVD->setInvalidDecl();
8747 return;
8748 }
8749 if (NewVD->hasExternalStorage()) {
8750 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8751 NewVD->setInvalidDecl();
8752 return;
8753 }
8754 }
8755
8756 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8757 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8758 NewVD->hasExternalStorage()) {
8759 if (!T->isSamplerT() && !T->isDependentType() &&
8762 getOpenCLOptions().areProgramScopeVariablesSupported(
8763 getLangOpts())))) {
8764 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8765 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8766 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8767 << Scope << "global or constant";
8768 else
8769 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8770 << Scope << "constant";
8771 NewVD->setInvalidDecl();
8772 return;
8773 }
8774 } else {
8776 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8777 << 1 /*is any function*/ << "global";
8778 NewVD->setInvalidDecl();
8779 return;
8780 }
8784 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8785 // in functions.
8786 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8788 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8789 << 0 /*non-kernel only*/ << "constant";
8790 else
8791 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8792 << 0 /*non-kernel only*/ << "local";
8793 NewVD->setInvalidDecl();
8794 return;
8795 }
8796 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8797 // in the outermost scope of a kernel function.
8798 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8799 if (!getCurScope()->isFunctionScope()) {
8801 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8802 << "constant";
8803 else
8804 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8805 << "local";
8806 NewVD->setInvalidDecl();
8807 return;
8808 }
8809 }
8810 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8811 // If we are parsing a template we didn't deduce an addr
8812 // space yet.
8814 // Do not allow other address spaces on automatic variable.
8815 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8816 NewVD->setInvalidDecl();
8817 return;
8818 }
8819 }
8820 }
8821
8822 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8823 && !NewVD->hasAttr<BlocksAttr>()) {
8824 if (getLangOpts().getGC() != LangOptions::NonGC)
8825 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8826 else {
8827 assert(!getLangOpts().ObjCAutoRefCount);
8828 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8829 }
8830 }
8831
8832 // WebAssembly tables must be static with a zero length and can't be
8833 // declared within functions.
8834 if (T->isWebAssemblyTableType()) {
8835 if (getCurScope()->getParent()) { // Parent is null at top-level
8836 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8837 NewVD->setInvalidDecl();
8838 return;
8839 }
8840 if (NewVD->getStorageClass() != SC_Static) {
8841 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8842 NewVD->setInvalidDecl();
8843 return;
8844 }
8845 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8846 if (!ATy || ATy->getSize().getSExtValue() != 0) {
8847 Diag(NewVD->getLocation(),
8848 diag::err_typecheck_wasm_table_must_have_zero_length);
8849 NewVD->setInvalidDecl();
8850 return;
8851 }
8852 }
8853
8854 bool isVM = T->isVariablyModifiedType();
8855 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8856 NewVD->hasAttr<BlocksAttr>())
8858
8859 if ((isVM && NewVD->hasLinkage()) ||
8860 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8861 bool SizeIsNegative;
8862 llvm::APSInt Oversized;
8864 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8865 QualType FixedT;
8866 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8867 FixedT = FixedTInfo->getType();
8868 else if (FixedTInfo) {
8869 // Type and type-as-written are canonically different. We need to fix up
8870 // both types separately.
8871 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8872 Oversized);
8873 }
8874 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8876 // FIXME: This won't give the correct result for
8877 // int a[10][n];
8878 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8879
8880 if (NewVD->isFileVarDecl())
8881 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8882 << SizeRange;
8883 else if (NewVD->isStaticLocal())
8884 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8885 << SizeRange;
8886 else
8887 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8888 << SizeRange;
8889 NewVD->setInvalidDecl();
8890 return;
8891 }
8892
8893 if (!FixedTInfo) {
8894 if (NewVD->isFileVarDecl())
8895 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8896 else
8897 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8898 NewVD->setInvalidDecl();
8899 return;
8900 }
8901
8902 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8903 NewVD->setType(FixedT);
8904 NewVD->setTypeSourceInfo(FixedTInfo);
8905 }
8906
8907 if (T->isVoidType()) {
8908 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8909 // of objects and functions.
8911 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8912 << T;
8913 NewVD->setInvalidDecl();
8914 return;
8915 }
8916 }
8917
8918 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8919 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8920 NewVD->setInvalidDecl();
8921 return;
8922 }
8923
8924 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8926 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8927 NewVD->setInvalidDecl();
8928 return;
8929 }
8930
8931 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8932 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8933 NewVD->setInvalidDecl();
8934 return;
8935 }
8936
8937 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8938 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8939 NewVD->setInvalidDecl();
8940 return;
8941 }
8942
8943 if (NewVD->isConstexpr() && !T->isDependentType() &&
8944 RequireLiteralType(NewVD->getLocation(), T,
8945 diag::err_constexpr_var_non_literal)) {
8946 NewVD->setInvalidDecl();
8947 return;
8948 }
8949
8950 // PPC MMA non-pointer types are not allowed as non-local variable types.
8951 if (Context.getTargetInfo().getTriple().isPPC64() &&
8952 !NewVD->isLocalVarDecl() &&
8953 CheckPPCMMAType(T, NewVD->getLocation())) {
8954 NewVD->setInvalidDecl();
8955 return;
8956 }
8957
8958 // Check that SVE types are only used in functions with SVE available.
8959 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8960 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8961 llvm::StringMap<bool> CallerFeatureMap;
8962 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8964 "sve", CallerFeatureMap)) {
8965 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8966 NewVD->setInvalidDecl();
8967 return;
8968 }
8969 }
8970
8971 if (T->isRVVSizelessBuiltinType())
8972 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext));
8973}
8974
8975/// Perform semantic checking on a newly-created variable
8976/// declaration.
8977///
8978/// This routine performs all of the type-checking required for a
8979/// variable declaration once it has been built. It is used both to
8980/// check variables after they have been parsed and their declarators
8981/// have been translated into a declaration, and to check variables
8982/// that have been instantiated from a template.
8983///
8984/// Sets NewVD->isInvalidDecl() if an error was encountered.
8985///
8986/// Returns true if the variable declaration is a redeclaration.
8989
8990 // If the decl is already known invalid, don't check it.
8991 if (NewVD->isInvalidDecl())
8992 return false;
8993
8994 // If we did not find anything by this name, look for a non-visible
8995 // extern "C" declaration with the same name.
8996 if (Previous.empty() &&
8998 Previous.setShadowed();
8999
9000 if (!Previous.empty()) {
9001 MergeVarDecl(NewVD, Previous);
9002 return true;
9003 }
9004 return false;
9005}
9006
9007/// AddOverriddenMethods - See if a method overrides any in the base classes,
9008/// and if so, check that it's a valid override and remember it.
9011
9012 // Look for methods in base classes that this method might override.
9013 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9014 /*DetectVirtual=*/false);
9015 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9016 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9017 DeclarationName Name = MD->getDeclName();
9018
9019 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9020 // We really want to find the base class destructor here.
9021 QualType T = Context.getTypeDeclType(BaseRecord);
9024 }
9025
9026 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9027 CXXMethodDecl *BaseMD =
9028 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9029 if (!BaseMD || !BaseMD->isVirtual() ||
9030 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9031 /*ConsiderCudaAttrs=*/true))
9032 continue;
9033 if (!CheckExplicitObjectOverride(MD, BaseMD))
9034 continue;
9035 if (Overridden.insert(BaseMD).second) {
9036 MD->addOverriddenMethod(BaseMD);
9041 }
9042
9043 // A method can only override one function from each base class. We
9044 // don't track indirectly overridden methods from bases of bases.
9045 return true;
9046 }
9047
9048 return false;
9049 };
9050
9051 DC->lookupInBases(VisitBase, Paths);
9052 return !Overridden.empty();
9053}
9054
9055namespace {
9056 // Struct for holding all of the extra arguments needed by
9057 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9058 struct ActOnFDArgs {
9059 Scope *S;
9060 Declarator &D;
9061 MultiTemplateParamsArg TemplateParamLists;
9062 bool AddToScope;
9063 };
9064} // end anonymous namespace
9065
9066namespace {
9067
9068// Callback to only accept typo corrections that have a non-zero edit distance.
9069// Also only accept corrections that have the same parent decl.
9070class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9071 public:
9072 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9074 : Context(Context), OriginalFD(TypoFD),
9075 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9076
9077 bool ValidateCandidate(const TypoCorrection &candidate) override {
9078 if (candidate.getEditDistance() == 0)
9079 return false;
9080
9081 SmallVector<unsigned, 1> MismatchedParams;
9082 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9083 CDeclEnd = candidate.end();
9084 CDecl != CDeclEnd; ++CDecl) {
9085 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9086
9087 if (FD && !FD->hasBody() &&
9088 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9089 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9090 CXXRecordDecl *Parent = MD->getParent();
9091 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9092 return true;
9093 } else if (!ExpectedParent) {
9094 return true;
9095 }
9096 }
9097 }
9098
9099 return false;
9100 }
9101
9102 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9103 return std::make_unique<DifferentNameValidatorCCC>(*this);
9104 }
9105
9106 private:
9107 ASTContext &Context;
9108 FunctionDecl *OriginalFD;
9109 CXXRecordDecl *ExpectedParent;
9110};
9111
9112} // end anonymous namespace
9113
9116}
9117
9118/// Generate diagnostics for an invalid function redeclaration.
9119///
9120/// This routine handles generating the diagnostic messages for an invalid
9121/// function redeclaration, including finding possible similar declarations
9122/// or performing typo correction if there are no previous declarations with
9123/// the same name.
9124///
9125/// Returns a NamedDecl iff typo correction was performed and substituting in
9126/// the new declaration name does not cause new errors.
9128 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9129 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9130 DeclarationName Name = NewFD->getDeclName();
9131 DeclContext *NewDC = NewFD->getDeclContext();
9132 SmallVector<unsigned, 1> MismatchedParams;
9134 TypoCorrection Correction;
9135 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9136 unsigned DiagMsg =
9137 IsLocalFriend ? diag::err_no_matching_local_friend :
9138 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9139 diag::err_member_decl_does_not_match;
9140 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9141 IsLocalFriend ? Sema::LookupLocalFriendName
9144
9145 NewFD->setInvalidDecl();
9146 if (IsLocalFriend)
9147 SemaRef.LookupName(Prev, S);
9148 else
9149 SemaRef.LookupQualifiedName(Prev, NewDC);
9150 assert(!Prev.isAmbiguous() &&
9151 "Cannot have an ambiguity in previous-declaration lookup");
9152 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9153 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9154 MD ? MD->getParent() : nullptr);
9155 if (!Prev.empty()) {
9156 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9157 Func != FuncEnd; ++Func) {
9158 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9159 if (FD &&
9160 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9161 // Add 1 to the index so that 0 can mean the mismatch didn't
9162 // involve a parameter
9163 unsigned ParamNum =
9164 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9165 NearMatches.push_back(std::make_pair(FD, ParamNum));
9166 }
9167 }
9168 // If the qualified name lookup yielded nothing, try typo correction
9169 } else if ((Correction = SemaRef.CorrectTypo(
9170 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9171 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9172 IsLocalFriend ? nullptr : NewDC))) {
9173 // Set up everything for the call to ActOnFunctionDeclarator
9174 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9175 ExtraArgs.D.getIdentifierLoc());
9176 Previous.clear();
9177 Previous.setLookupName(Correction.getCorrection());
9178 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9179 CDeclEnd = Correction.end();
9180 CDecl != CDeclEnd; ++CDecl) {
9181 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9182 if (FD && !FD->hasBody() &&
9183 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9184 Previous.addDecl(FD);
9185 }
9186 }
9187 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9188
9190 // Retry building the function declaration with the new previous
9191 // declarations, and with errors suppressed.
9192 {
9193 // Trap errors.
9194 Sema::SFINAETrap Trap(SemaRef);
9195
9196 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9197 // pieces need to verify the typo-corrected C++ declaration and hopefully
9198 // eliminate the need for the parameter pack ExtraArgs.
9200 ExtraArgs.S, ExtraArgs.D,
9201 Correction.getCorrectionDecl()->getDeclContext(),
9202 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9203 ExtraArgs.AddToScope);
9204
9205 if (Trap.hasErrorOccurred())
9206 Result = nullptr;
9207 }
9208
9209 if (Result) {
9210 // Determine which correction we picked.
9211 Decl *Canonical = Result->getCanonicalDecl();
9212 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9213 I != E; ++I)
9214 if ((*I)->getCanonicalDecl() == Canonical)
9215 Correction.setCorrectionDecl(*I);
9216
9217 // Let Sema know about the correction.
9219 SemaRef.diagnoseTypo(
9220 Correction,
9221 SemaRef.PDiag(IsLocalFriend
9222 ? diag::err_no_matching_local_friend_suggest
9223 : diag::err_member_decl_does_not_match_suggest)
9224 << Name << NewDC << IsDefinition);
9225 return Result;
9226 }
9227
9228 // Pretend the typo correction never occurred
9229 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9230 ExtraArgs.D.getIdentifierLoc());
9231 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9232 Previous.clear();
9233 Previous.setLookupName(Name);
9234 }
9235
9236 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9237 << Name << NewDC << IsDefinition << NewFD->getLocation();
9238
9239 bool NewFDisConst = false;
9240 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9241 NewFDisConst = NewMD->isConst();
9242
9243 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9244 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9245 NearMatch != NearMatchEnd; ++NearMatch) {
9246 FunctionDecl *FD = NearMatch->first;
9247 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9248 bool FDisConst = MD && MD->isConst();
9249 bool IsMember = MD || !IsLocalFriend;
9250
9251 // FIXME: These notes are poorly worded for the local friend case.
9252 if (unsigned Idx = NearMatch->second) {
9253 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9254 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9255 if (Loc.isInvalid()) Loc = FD->getLocation();
9256 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9257 : diag::note_local_decl_close_param_match)
9258 << Idx << FDParam->getType()
9259 << NewFD->getParamDecl(Idx - 1)->getType();
9260 } else if (FDisConst != NewFDisConst) {
9261 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9262 << NewFDisConst << FD->getSourceRange().getEnd()
9263 << (NewFDisConst
9264 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9265 .getConstQualifierLoc())
9266 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9267 .getRParenLoc()
9268 .getLocWithOffset(1),
9269 " const"));
9270 } else
9271 SemaRef.Diag(FD->getLocation(),
9272 IsMember ? diag::note_member_def_close_match
9273 : diag::note_local_decl_close_match);
9274 }
9275 return nullptr;
9276}
9277
9279 switch (D.getDeclSpec().getStorageClassSpec()) {
9280 default: llvm_unreachable("Unknown storage class!");
9281 case DeclSpec::SCS_auto:
9285 diag::err_typecheck_sclass_func);
9287 D.setInvalidType();
9288 break;
9289 case DeclSpec::SCS_unspecified: break;
9292 return SC_None;
9293 return SC_Extern;
9294 case DeclSpec::SCS_static: {
9296 // C99 6.7.1p5:
9297 // The declaration of an identifier for a function that has
9298 // block scope shall have no explicit storage-class specifier
9299 // other than extern
9300 // See also (C++ [dcl.stc]p4).
9302 diag::err_static_block_func);
9303 break;
9304 } else
9305 return SC_Static;
9306 }
9308 }
9309
9310 // No explicit storage class has already been returned
9311 return SC_None;
9312}
9313
9315 DeclContext *DC, QualType &R,
9316 TypeSourceInfo *TInfo,
9317 StorageClass SC,
9318 bool &IsVirtualOkay) {
9319 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9320 DeclarationName Name = NameInfo.getName();
9321
9322 FunctionDecl *NewFD = nullptr;
9323 bool isInline = D.getDeclSpec().isInlineSpecified();
9324
9326 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9327 (SemaRef.getLangOpts().C23 &&
9328 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9329
9330 if (SemaRef.getLangOpts().C23)
9331 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9332 diag::err_c23_constexpr_not_variable);
9333 else
9334 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9335 diag::err_constexpr_wrong_decl_kind)
9336 << static_cast<int>(ConstexprKind);
9337 ConstexprKind = ConstexprSpecKind::Unspecified;
9339 }
9340
9341 if (!SemaRef.getLangOpts().CPlusPlus) {
9342 // Determine whether the function was written with a prototype. This is
9343 // true when:
9344 // - there is a prototype in the declarator, or
9345 // - the type R of the function is some kind of typedef or other non-
9346 // attributed reference to a type name (which eventually refers to a
9347 // function type). Note, we can't always look at the adjusted type to
9348 // check this case because attributes may cause a non-function
9349 // declarator to still have a function type. e.g.,
9350 // typedef void func(int a);
9351 // __attribute__((noreturn)) func other_func; // This has a prototype
9352 bool HasPrototype =
9354 (D.getDeclSpec().isTypeRep() &&
9355 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9356 ->isFunctionProtoType()) ||
9358 assert(
9359 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9360 "Strict prototypes are required");
9361
9362 NewFD = FunctionDecl::Create(
9363 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9364 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9366 /*TrailingRequiresClause=*/nullptr);
9367 if (D.isInvalidType())
9368 NewFD->setInvalidDecl();
9369
9370 return NewFD;
9371 }
9372
9374 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9375
9376 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9377
9378 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9379 // This is a C++ constructor declaration.
9380 assert(DC->isRecord() &&
9381 "Constructors can only be declared in a member context");
9382
9383 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9385 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9387 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9388 InheritedConstructor(), TrailingRequiresClause);
9389
9390 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9391 // This is a C++ destructor declaration.
9392 if (DC->isRecord()) {
9393 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9394 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9396 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9397 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9398 /*isImplicitlyDeclared=*/false, ConstexprKind,
9399 TrailingRequiresClause);
9400 // User defined destructors start as not selected if the class definition is still
9401 // not done.
9402 if (Record->isBeingDefined())
9403 NewDD->setIneligibleOrNotSelected(true);
9404
9405 // If the destructor needs an implicit exception specification, set it
9406 // now. FIXME: It'd be nice to be able to create the right type to start
9407 // with, but the type needs to reference the destructor declaration.
9408 if (SemaRef.getLangOpts().CPlusPlus11)
9409 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9410
9411 IsVirtualOkay = true;
9412 return NewDD;
9413
9414 } else {
9415 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9416 D.setInvalidType();
9417
9418 // Create a FunctionDecl to satisfy the function definition parsing
9419 // code path.
9420 return FunctionDecl::Create(
9421 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9422 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9423 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9424 }
9425
9426 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9427 if (!DC->isRecord()) {
9428 SemaRef.Diag(D.getIdentifierLoc(),
9429 diag::err_conv_function_not_member);
9430 return nullptr;
9431 }
9432
9433 SemaRef.CheckConversionDeclarator(D, R, SC);
9434 if (D.isInvalidType())
9435 return nullptr;
9436
9437 IsVirtualOkay = true;
9439 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9440 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9441 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9442 TrailingRequiresClause);
9443
9444 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9445 if (TrailingRequiresClause)
9446 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9447 diag::err_trailing_requires_clause_on_deduction_guide)
9448 << TrailingRequiresClause->getSourceRange();
9449 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9450 return nullptr;
9451 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9452 ExplicitSpecifier, NameInfo, R, TInfo,
9453 D.getEndLoc());
9454 } else if (DC->isRecord()) {
9455 // If the name of the function is the same as the name of the record,
9456 // then this must be an invalid constructor that has a return type.
9457 // (The parser checks for a return type and makes the declarator a
9458 // constructor if it has no return type).
9459 if (Name.getAsIdentifierInfo() &&
9460 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9461 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9464 return nullptr;
9465 }
9466
9467 // This is a C++ method declaration.
9469 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9470 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9471 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9472 IsVirtualOkay = !Ret->isStatic();
9473 return Ret;
9474 } else {
9475 bool isFriend =
9476 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9477 if (!isFriend && SemaRef.CurContext->isRecord())
9478 return nullptr;
9479
9480 // Determine whether the function was written with a
9481 // prototype. This true when:
9482 // - we're in C++ (where every function has a prototype),
9483 return FunctionDecl::Create(
9484 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9485 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9486 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9487 }
9488}
9489
9498
9500 // Size dependent types are just typedefs to normal integer types
9501 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9502 // integers other than by their names.
9503 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9504
9505 // Remove typedefs one by one until we reach a typedef
9506 // for a size dependent type.
9507 QualType DesugaredTy = Ty;
9508 do {
9509 ArrayRef<StringRef> Names(SizeTypeNames);
9510 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9511 if (Names.end() != Match)
9512 return true;
9513
9514 Ty = DesugaredTy;
9515 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9516 } while (DesugaredTy != Ty);
9517
9518 return false;
9519}
9520
9522 if (PT->isDependentType())
9523 return InvalidKernelParam;
9524
9525 if (PT->isPointerType() || PT->isReferenceType()) {
9526 QualType PointeeType = PT->getPointeeType();
9527 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9528 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9529 PointeeType.getAddressSpace() == LangAS::Default)
9531
9532 if (PointeeType->isPointerType()) {
9533 // This is a pointer to pointer parameter.
9534 // Recursively check inner type.
9535 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9536 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9537 ParamKind == InvalidKernelParam)
9538 return ParamKind;
9539
9540 // OpenCL v3.0 s6.11.a:
9541 // A restriction to pass pointers to pointers only applies to OpenCL C
9542 // v1.2 or below.
9544 return ValidKernelParam;
9545
9546 return PtrPtrKernelParam;
9547 }
9548
9549 // C++ for OpenCL v1.0 s2.4:
9550 // Moreover the types used in parameters of the kernel functions must be:
9551 // Standard layout types for pointer parameters. The same applies to
9552 // reference if an implementation supports them in kernel parameters.
9553 if (S.getLangOpts().OpenCLCPlusPlus &&
9555 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9556 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9557 bool IsStandardLayoutType = true;
9558 if (CXXRec) {
9559 // If template type is not ODR-used its definition is only available
9560 // in the template definition not its instantiation.
9561 // FIXME: This logic doesn't work for types that depend on template
9562 // parameter (PR58590).
9563 if (!CXXRec->hasDefinition())
9564 CXXRec = CXXRec->getTemplateInstantiationPattern();
9565 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9566 IsStandardLayoutType = false;
9567 }
9568 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9569 !IsStandardLayoutType)
9570 return InvalidKernelParam;
9571 }
9572
9573 // OpenCL v1.2 s6.9.p:
9574 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9576 return ValidKernelParam;
9577
9578 return PtrKernelParam;
9579 }
9580
9581 // OpenCL v1.2 s6.9.k:
9582 // Arguments to kernel functions in a program cannot be declared with the
9583 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9584 // uintptr_t or a struct and/or union that contain fields declared to be one
9585 // of these built-in scalar types.
9587 return InvalidKernelParam;
9588
9589 if (PT->isImageType())
9590 return PtrKernelParam;
9591
9592 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9593 return InvalidKernelParam;
9594
9595 // OpenCL extension spec v1.2 s9.5:
9596 // This extension adds support for half scalar and vector types as built-in
9597 // types that can be used for arithmetic operations, conversions etc.
9598 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9599 PT->isHalfType())
9600 return InvalidKernelParam;
9601
9602 // Look into an array argument to check if it has a forbidden type.
9603 if (PT->isArrayType()) {
9604 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9605 // Call ourself to check an underlying type of an array. Since the
9606 // getPointeeOrArrayElementType returns an innermost type which is not an
9607 // array, this recursive call only happens once.
9608 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9609 }
9610
9611 // C++ for OpenCL v1.0 s2.4:
9612 // Moreover the types used in parameters of the kernel functions must be:
9613 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9614 // types) for parameters passed by value;
9615 if (S.getLangOpts().OpenCLCPlusPlus &&
9617 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9618 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9619 return InvalidKernelParam;
9620
9621 if (PT->isRecordType())
9622 return RecordKernelParam;
9623
9624 return ValidKernelParam;
9625}
9626
9628 Sema &S,
9629 Declarator &D,
9630 ParmVarDecl *Param,
9631 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9632 QualType PT = Param->getType();
9633
9634 // Cache the valid types we encounter to avoid rechecking structs that are
9635 // used again
9636 if (ValidTypes.count(PT.getTypePtr()))
9637 return;
9638
9639 switch (getOpenCLKernelParameterType(S, PT)) {
9640 case PtrPtrKernelParam:
9641 // OpenCL v3.0 s6.11.a:
9642 // A kernel function argument cannot be declared as a pointer to a pointer
9643 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9644 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9645 D.setInvalidType();
9646 return;
9647
9649 // OpenCL v1.0 s6.5:
9650 // __kernel function arguments declared to be a pointer of a type can point
9651 // to one of the following address spaces only : __global, __local or
9652 // __constant.
9653 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9654 D.setInvalidType();
9655 return;
9656
9657 // OpenCL v1.2 s6.9.k:
9658 // Arguments to kernel functions in a program cannot be declared with the
9659 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9660 // uintptr_t or a struct and/or union that contain fields declared to be
9661 // one of these built-in scalar types.
9662
9663 case InvalidKernelParam:
9664 // OpenCL v1.2 s6.8 n:
9665 // A kernel function argument cannot be declared
9666 // of event_t type.
9667 // Do not diagnose half type since it is diagnosed as invalid argument
9668 // type for any function elsewhere.
9669 if (!PT->isHalfType()) {
9670 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9671
9672 // Explain what typedefs are involved.
9673 const TypedefType *Typedef = nullptr;
9674 while ((Typedef = PT->getAs<TypedefType>())) {
9675 SourceLocation Loc = Typedef->getDecl()->getLocation();
9676 // SourceLocation may be invalid for a built-in type.
9677 if (Loc.isValid())
9678 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9679 PT = Typedef->desugar();
9680 }
9681 }
9682
9683 D.setInvalidType();
9684 return;
9685
9686 case PtrKernelParam:
9687 case ValidKernelParam:
9688 ValidTypes.insert(PT.getTypePtr());
9689 return;
9690
9691 case RecordKernelParam:
9692 break;
9693 }
9694
9695 // Track nested structs we will inspect
9697
9698 // Track where we are in the nested structs. Items will migrate from
9699 // VisitStack to HistoryStack as we do the DFS for bad field.
9701 HistoryStack.push_back(nullptr);
9702
9703 // At this point we already handled everything except of a RecordType or
9704 // an ArrayType of a RecordType.
9705 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9706 const RecordType *RecTy =
9708 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9709
9710 VisitStack.push_back(RecTy->getDecl());
9711 assert(VisitStack.back() && "First decl null?");
9712
9713 do {
9714 const Decl *Next = VisitStack.pop_back_val();
9715 if (!Next) {
9716 assert(!HistoryStack.empty());
9717 // Found a marker, we have gone up a level
9718 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9719 ValidTypes.insert(Hist->getType().getTypePtr());
9720
9721 continue;
9722 }
9723
9724 // Adds everything except the original parameter declaration (which is not a
9725 // field itself) to the history stack.
9726 const RecordDecl *RD;
9727 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9728 HistoryStack.push_back(Field);
9729
9730 QualType FieldTy = Field->getType();
9731 // Other field types (known to be valid or invalid) are handled while we
9732 // walk around RecordDecl::fields().
9733 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9734 "Unexpected type.");
9735 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9736
9737 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9738 } else {
9739 RD = cast<RecordDecl>(Next);
9740 }
9741
9742 // Add a null marker so we know when we've gone back up a level
9743 VisitStack.push_back(nullptr);
9744
9745 for (const auto *FD : RD->fields()) {
9746 QualType QT = FD->getType();
9747
9748 if (ValidTypes.count(QT.getTypePtr()))
9749 continue;
9750
9752 if (ParamType == ValidKernelParam)
9753 continue;
9754
9755 if (ParamType == RecordKernelParam) {
9756 VisitStack.push_back(FD);
9757 continue;
9758 }
9759
9760 // OpenCL v1.2 s6.9.p:
9761 // Arguments to kernel functions that are declared to be a struct or union
9762 // do not allow OpenCL objects to be passed as elements of the struct or
9763 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9764 // of SVM.
9765 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9766 ParamType == InvalidAddrSpacePtrKernelParam) {
9767 S.Diag(Param->getLocation(),
9768 diag::err_record_with_pointers_kernel_param)
9769 << PT->isUnionType()
9770 << PT;
9771 } else {
9772 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9773 }
9774
9775 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9776 << OrigRecDecl->getDeclName();
9777
9778 // We have an error, now let's go back up through history and show where
9779 // the offending field came from
9781 I = HistoryStack.begin() + 1,
9782 E = HistoryStack.end();
9783 I != E; ++I) {
9784 const FieldDecl *OuterField = *I;
9785 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9786 << OuterField->getType();
9787 }
9788
9789 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9790 << QT->isPointerType()
9791 << QT;
9792 D.setInvalidType();
9793 return;
9794 }
9795 } while (!VisitStack.empty());
9796}
9797
9798/// Find the DeclContext in which a tag is implicitly declared if we see an
9799/// elaborated type specifier in the specified context, and lookup finds
9800/// nothing.
9802 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9803 DC = DC->getParent();
9804 return DC;
9805}
9806
9807/// Find the Scope in which a tag is implicitly declared if we see an
9808/// elaborated type specifier in the specified context, and lookup finds
9809/// nothing.
9810static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9811 while (S->isClassScope() ||
9812 (LangOpts.CPlusPlus &&
9813 S->isFunctionPrototypeScope()) ||
9814 ((S->getFlags() & Scope::DeclScope) == 0) ||
9815 (S->getEntity() && S->getEntity()->isTransparentContext()))
9816 S = S->getParent();
9817 return S;
9818}
9819
9820/// Determine whether a declaration matches a known function in namespace std.
9822 unsigned BuiltinID) {
9823 switch (BuiltinID) {
9824 case Builtin::BI__GetExceptionInfo:
9825 // No type checking whatsoever.
9826 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9827
9828 case Builtin::BIaddressof:
9829 case Builtin::BI__addressof:
9830 case Builtin::BIforward:
9831 case Builtin::BIforward_like:
9832 case Builtin::BImove:
9833 case Builtin::BImove_if_noexcept:
9834 case Builtin::BIas_const: {
9835 // Ensure that we don't treat the algorithm
9836 // OutputIt std::move(InputIt, InputIt, OutputIt)
9837 // as the builtin std::move.
9838 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9839 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9840 }
9841
9842 default:
9843 return false;
9844 }
9845}
9846
9847NamedDecl*
9850 MultiTemplateParamsArg TemplateParamListsRef,
9851 bool &AddToScope) {
9852 QualType R = TInfo->getType();
9853
9854 assert(R->isFunctionType());
9856 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9857
9858 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9859 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9861 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9862 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9863 TemplateParamLists.back() = Invented;
9864 else
9865 TemplateParamLists.push_back(Invented);
9866 }
9867
9868 // TODO: consider using NameInfo for diagnostic.
9870 DeclarationName Name = NameInfo.getName();
9872
9875 diag::err_invalid_thread)
9877
9882
9883 bool isFriend = false;
9885 bool isMemberSpecialization = false;
9886 bool isFunctionTemplateSpecialization = false;
9887
9888 bool HasExplicitTemplateArgs = false;
9889 TemplateArgumentListInfo TemplateArgs;
9890
9891 bool isVirtualOkay = false;
9892
9893 DeclContext *OriginalDC = DC;
9894 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9895
9896 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9897 isVirtualOkay);
9898 if (!NewFD) return nullptr;
9899
9902
9903 // Set the lexical context. If this is a function-scope declaration, or has a
9904 // C++ scope specifier, or is the object of a friend declaration, the lexical
9905 // context will be different from the semantic context.
9907
9908 if (IsLocalExternDecl)
9909 NewFD->setLocalExternDecl();
9910
9911 if (getLangOpts().CPlusPlus) {
9912 // The rules for implicit inlines changed in C++20 for methods and friends
9913 // with an in-class definition (when such a definition is not attached to
9914 // the global module). User-specified 'inline' overrides this (set when
9915 // the function decl is created above).
9916 // FIXME: We need a better way to separate C++ standard and clang modules.
9917 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9918 !NewFD->getOwningModule() ||
9919 NewFD->getOwningModule()->isGlobalModule() ||
9921 bool isInline = D.getDeclSpec().isInlineSpecified();
9922 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9923 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9924 isFriend = D.getDeclSpec().isFriendSpecified();
9925 if (isFriend && !isInline && D.isFunctionDefinition()) {
9926 // Pre-C++20 [class.friend]p5
9927 // A function can be defined in a friend declaration of a
9928 // class . . . . Such a function is implicitly inline.
9929 // Post C++20 [class.friend]p7
9930 // Such a function is implicitly an inline function if it is attached
9931 // to the global module.
9932 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9933 }
9934
9935 // If this is a method defined in an __interface, and is not a constructor
9936 // or an overloaded operator, then set the pure flag (isVirtual will already
9937 // return true).
9938 if (const CXXRecordDecl *Parent =
9939 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9940 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9941 NewFD->setIsPureVirtual(true);
9942
9943 // C++ [class.union]p2
9944 // A union can have member functions, but not virtual functions.
9945 if (isVirtual && Parent->isUnion()) {
9946 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9947 NewFD->setInvalidDecl();
9948 }
9949 if ((Parent->isClass() || Parent->isStruct()) &&
9950 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9951 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9952 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9953 if (auto *Def = Parent->getDefinition())
9954 Def->setInitMethod(true);
9955 }
9956 }
9957
9958 SetNestedNameSpecifier(*this, NewFD, D);
9959 isMemberSpecialization = false;
9960 isFunctionTemplateSpecialization = false;
9961 if (D.isInvalidType())
9962 NewFD->setInvalidDecl();
9963
9964 // Match up the template parameter lists with the scope specifier, then
9965 // determine whether we have a template or a template specialization.
9966 bool Invalid = false;
9967 TemplateIdAnnotation *TemplateId =
9969 ? D.getName().TemplateId
9970 : nullptr;
9971 TemplateParameterList *TemplateParams =
9974 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9975 isMemberSpecialization, Invalid);
9976 if (TemplateParams) {
9977 // Check that we can declare a template here.
9978 if (CheckTemplateDeclScope(S, TemplateParams))
9979 NewFD->setInvalidDecl();
9980
9981 if (TemplateParams->size() > 0) {
9982 // This is a function template
9983
9984 // A destructor cannot be a template.
9985 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9986 Diag(NewFD->getLocation(), diag::err_destructor_template);
9987 NewFD->setInvalidDecl();
9988 // Function template with explicit template arguments.
9989 } else if (TemplateId) {
9990 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9991 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9992 NewFD->setInvalidDecl();
9993 }
9994
9995 // If we're adding a template to a dependent context, we may need to
9996 // rebuilding some of the types used within the template parameter list,
9997 // now that we know what the current instantiation is.
9998 if (DC->isDependentContext()) {
9999 ContextRAII SavedContext(*this, DC);
10001 Invalid = true;
10002 }
10003
10005 NewFD->getLocation(),
10006 Name, TemplateParams,
10007 NewFD);
10008 FunctionTemplate->setLexicalDeclContext(CurContext);
10010
10011 // For source fidelity, store the other template param lists.
10012 if (TemplateParamLists.size() > 1) {
10014 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10015 .drop_back(1));
10016 }
10017 } else {
10018 // This is a function template specialization.
10019 isFunctionTemplateSpecialization = true;
10020 // For source fidelity, store all the template param lists.
10021 if (TemplateParamLists.size() > 0)
10022 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10023
10024 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10025 if (isFriend) {
10026 // We want to remove the "template<>", found here.
10027 SourceRange RemoveRange = TemplateParams->getSourceRange();
10028
10029 // If we remove the template<> and the name is not a
10030 // template-id, we're actually silently creating a problem:
10031 // the friend declaration will refer to an untemplated decl,
10032 // and clearly the user wants a template specialization. So
10033 // we need to insert '<>' after the name.
10034 SourceLocation InsertLoc;
10036 InsertLoc = D.getName().getSourceRange().getEnd();
10037 InsertLoc = getLocForEndOfToken(InsertLoc);
10038 }
10039
10040 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10041 << Name << RemoveRange
10042 << FixItHint::CreateRemoval(RemoveRange)
10043 << FixItHint::CreateInsertion(InsertLoc, "<>");
10044 Invalid = true;
10045
10046 // Recover by faking up an empty template argument list.
10047 HasExplicitTemplateArgs = true;
10048 TemplateArgs.setLAngleLoc(InsertLoc);
10049 TemplateArgs.setRAngleLoc(InsertLoc);
10050 }
10051 }
10052 } else {
10053 // Check that we can declare a template here.
10054 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10055 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10056 NewFD->setInvalidDecl();
10057
10058 // All template param lists were matched against the scope specifier:
10059 // this is NOT (an explicit specialization of) a template.
10060 if (TemplateParamLists.size() > 0)
10061 // For source fidelity, store all the template param lists.
10062 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10063
10064 // "friend void foo<>(int);" is an implicit specialization decl.
10065 if (isFriend && TemplateId)
10066 isFunctionTemplateSpecialization = true;
10067 }
10068
10069 // If this is a function template specialization and the unqualified-id of
10070 // the declarator-id is a template-id, convert the template argument list
10071 // into our AST format and check for unexpanded packs.
10072 if (isFunctionTemplateSpecialization && TemplateId) {
10073 HasExplicitTemplateArgs = true;
10074
10075 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10076 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10077 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10078 TemplateId->NumArgs);
10079 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10080
10081 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10082 // declaration of a function template partial specialization? Should we
10083 // consider the unexpanded pack context to be a partial specialization?
10084 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10086 ArgLoc, isFriend ? UPPC_FriendDeclaration
10088 NewFD->setInvalidDecl();
10089 }
10090 }
10091
10092 if (Invalid) {
10093 NewFD->setInvalidDecl();
10094 if (FunctionTemplate)
10095 FunctionTemplate->setInvalidDecl();
10096 }
10097
10098 // C++ [dcl.fct.spec]p5:
10099 // The virtual specifier shall only be used in declarations of
10100 // nonstatic class member functions that appear within a
10101 // member-specification of a class declaration; see 10.3.
10102 //
10103 if (isVirtual && !NewFD->isInvalidDecl()) {
10104 if (!isVirtualOkay) {
10106 diag::err_virtual_non_function);
10107 } else if (!CurContext->isRecord()) {
10108 // 'virtual' was specified outside of the class.
10110 diag::err_virtual_out_of_class)
10112 } else if (NewFD->getDescribedFunctionTemplate()) {
10113 // C++ [temp.mem]p3:
10114 // A member function template shall not be virtual.
10116 diag::err_virtual_member_function_template)
10118 } else {
10119 // Okay: Add virtual to the method.
10120 NewFD->setVirtualAsWritten(true);
10121 }
10122
10123 if (getLangOpts().CPlusPlus14 &&
10124 NewFD->getReturnType()->isUndeducedType())
10125 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10126 }
10127
10128 if (getLangOpts().CPlusPlus14 &&
10129 (NewFD->isDependentContext() ||
10130 (isFriend && CurContext->isDependentContext())) &&
10131 NewFD->getReturnType()->isUndeducedType()) {
10132 // If the function template is referenced directly (for instance, as a
10133 // member of the current instantiation), pretend it has a dependent type.
10134 // This is not really justified by the standard, but is the only sane
10135 // thing to do.
10136 // FIXME: For a friend function, we have not marked the function as being
10137 // a friend yet, so 'isDependentContext' on the FD doesn't work.
10138 const FunctionProtoType *FPT =
10139 NewFD->getType()->castAs<FunctionProtoType>();
10142 FPT->getExtProtoInfo()));
10143 }
10144
10145 // C++ [dcl.fct.spec]p3:
10146 // The inline specifier shall not appear on a block scope function
10147 // declaration.
10148 if (isInline && !NewFD->isInvalidDecl()) {
10150 // 'inline' is not allowed on block scope function declaration.
10152 diag::err_inline_declaration_block_scope) << Name
10154 }
10155 }
10156
10157 // C++ [dcl.fct.spec]p6:
10158 // The explicit specifier shall be used only in the declaration of a
10159 // constructor or conversion function within its class definition;
10160 // see 12.3.1 and 12.3.2.
10161 if (hasExplicit && !NewFD->isInvalidDecl() &&
10162 !isa<CXXDeductionGuideDecl>(NewFD)) {
10163 if (!CurContext->isRecord()) {
10164 // 'explicit' was specified outside of the class.
10166 diag::err_explicit_out_of_class)
10168 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10169 !isa<CXXConversionDecl>(NewFD)) {
10170 // 'explicit' was specified on a function that wasn't a constructor
10171 // or conversion function.
10173 diag::err_explicit_non_ctor_or_conv_function)
10175 }
10176 }
10177
10179 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10180 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10181 // are implicitly inline.
10182 NewFD->setImplicitlyInline();
10183
10184 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10185 // be either constructors or to return a literal type. Therefore,
10186 // destructors cannot be declared constexpr.
10187 if (isa<CXXDestructorDecl>(NewFD) &&
10189 ConstexprKind == ConstexprSpecKind::Consteval)) {
10190 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10191 << static_cast<int>(ConstexprKind);
10192 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10195 }
10196 // C++20 [dcl.constexpr]p2: An allocation function, or a
10197 // deallocation function shall not be declared with the consteval
10198 // specifier.
10199 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10200 (NewFD->getOverloadedOperator() == OO_New ||
10201 NewFD->getOverloadedOperator() == OO_Array_New ||
10202 NewFD->getOverloadedOperator() == OO_Delete ||
10203 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10205 diag::err_invalid_consteval_decl_kind)
10206 << NewFD;
10208 }
10209 }
10210
10211 // If __module_private__ was specified, mark the function accordingly.
10213 if (isFunctionTemplateSpecialization) {
10214 SourceLocation ModulePrivateLoc
10216 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10217 << 0
10218 << FixItHint::CreateRemoval(ModulePrivateLoc);
10219 } else {
10220 NewFD->setModulePrivate();
10221 if (FunctionTemplate)
10222 FunctionTemplate->setModulePrivate();
10223 }
10224 }
10225
10226 if (isFriend) {
10227 if (FunctionTemplate) {
10228 FunctionTemplate->setObjectOfFriendDecl();
10229 FunctionTemplate->setAccess(AS_public);
10230 }
10231 NewFD->setObjectOfFriendDecl();
10232 NewFD->setAccess(AS_public);
10233 }
10234
10235 // If a function is defined as defaulted or deleted, mark it as such now.
10236 // We'll do the relevant checks on defaulted / deleted functions later.
10237 switch (D.getFunctionDefinitionKind()) {
10240 break;
10241
10243 NewFD->setDefaulted();
10244 break;
10245
10247 NewFD->setDeletedAsWritten();
10248 break;
10249 }
10250
10251 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10252 D.isFunctionDefinition() && !isInline) {
10253 // Pre C++20 [class.mfct]p2:
10254 // A member function may be defined (8.4) in its class definition, in
10255 // which case it is an inline member function (7.1.2)
10256 // Post C++20 [class.mfct]p1:
10257 // If a member function is attached to the global module and is defined
10258 // in its class definition, it is inline.
10259 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10260 }
10261
10262 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10263 !CurContext->isRecord()) {
10264 // C++ [class.static]p1:
10265 // A data or function member of a class may be declared static
10266 // in a class definition, in which case it is a static member of
10267 // the class.
10268
10269 // Complain about the 'static' specifier if it's on an out-of-line
10270 // member function definition.
10271
10272 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10273 // member function template declaration and class member template
10274 // declaration (MSVC versions before 2015), warn about this.
10276 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10277 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10278 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10279 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10281 }
10282
10283 // C++11 [except.spec]p15:
10284 // A deallocation function with no exception-specification is treated
10285 // as if it were specified with noexcept(true).
10286 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10287 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10288 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10289 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10291 FPT->getReturnType(), FPT->getParamTypes(),
10293
10294 // C++20 [dcl.inline]/7
10295 // If an inline function or variable that is attached to a named module
10296 // is declared in a definition domain, it shall be defined in that
10297 // domain.
10298 // So, if the current declaration does not have a definition, we must
10299 // check at the end of the TU (or when the PMF starts) to see that we
10300 // have a definition at that point.
10301 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10302 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10303 PendingInlineFuncDecls.insert(NewFD);
10304 }
10305 }
10306
10307 // Filter out previous declarations that don't match the scope.
10310 isMemberSpecialization ||
10311 isFunctionTemplateSpecialization);
10312
10313 // Handle GNU asm-label extension (encoded as an attribute).
10314 if (Expr *E = (Expr*) D.getAsmLabel()) {
10315 // The parser guarantees this is a string.
10316 StringLiteral *SE = cast<StringLiteral>(E);
10317 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10318 /*IsLiteralLabel=*/true,
10319 SE->getStrTokenLoc(0)));
10320 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10321 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10323 if (I != ExtnameUndeclaredIdentifiers.end()) {
10324 if (isDeclExternC(NewFD)) {
10325 NewFD->addAttr(I->second);
10327 } else
10328 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10329 << /*Variable*/0 << NewFD;
10330 }
10331 }
10332
10333 // Copy the parameter declarations from the declarator D to the function
10334 // declaration NewFD, if they are available. First scavenge them into Params.
10336 unsigned FTIIdx;
10337 if (D.isFunctionDeclarator(FTIIdx)) {
10339
10340 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10341 // function that takes no arguments, not a function that takes a
10342 // single void argument.
10343 // We let through "const void" here because Sema::GetTypeForDeclarator
10344 // already checks for that case.
10345 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10346 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10347 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10348 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10349 Param->setDeclContext(NewFD);
10350 Params.push_back(Param);
10351
10352 if (Param->isInvalidDecl())
10353 NewFD->setInvalidDecl();
10354 }
10355 }
10356
10357 if (!getLangOpts().CPlusPlus) {
10358 // In C, find all the tag declarations from the prototype and move them
10359 // into the function DeclContext. Remove them from the surrounding tag
10360 // injection context of the function, which is typically but not always
10361 // the TU.
10362 DeclContext *PrototypeTagContext =
10364 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10365 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10366
10367 // We don't want to reparent enumerators. Look at their parent enum
10368 // instead.
10369 if (!TD) {
10370 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10371 TD = cast<EnumDecl>(ECD->getDeclContext());
10372 }
10373 if (!TD)
10374 continue;
10375 DeclContext *TagDC = TD->getLexicalDeclContext();
10376 if (!TagDC->containsDecl(TD))
10377 continue;
10378 TagDC->removeDecl(TD);
10379 TD->setDeclContext(NewFD);
10380 NewFD->addDecl(TD);
10381
10382 // Preserve the lexical DeclContext if it is not the surrounding tag
10383 // injection context of the FD. In this example, the semantic context of
10384 // E will be f and the lexical context will be S, while both the
10385 // semantic and lexical contexts of S will be f:
10386 // void f(struct S { enum E { a } f; } s);
10387 if (TagDC != PrototypeTagContext)
10388 TD->setLexicalDeclContext(TagDC);
10389 }
10390 }
10391 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10392 // When we're declaring a function with a typedef, typeof, etc as in the
10393 // following example, we'll need to synthesize (unnamed)
10394 // parameters for use in the declaration.
10395 //
10396 // @code
10397 // typedef void fn(int);
10398 // fn f;
10399 // @endcode
10400
10401 // Synthesize a parameter for each argument type.
10402 for (const auto &AI : FT->param_types()) {
10403 ParmVarDecl *Param =
10405 Param->setScopeInfo(0, Params.size());
10406 Params.push_back(Param);
10407 }
10408 } else {
10409 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10410 "Should not need args for typedef of non-prototype fn");
10411 }
10412
10413 // Finally, we know we have the right number of parameters, install them.
10414 NewFD->setParams(Params);
10415
10417 NewFD->addAttr(
10418 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10419
10420 // Functions returning a variably modified type violate C99 6.7.5.2p2
10421 // because all functions have linkage.
10422 if (!NewFD->isInvalidDecl() &&
10424 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10425 NewFD->setInvalidDecl();
10426 }
10427
10428 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10430 !NewFD->hasAttr<SectionAttr>())
10431 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10434
10435 // Apply an implicit SectionAttr if #pragma code_seg is active.
10436 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10437 !NewFD->hasAttr<SectionAttr>()) {
10438 NewFD->addAttr(SectionAttr::CreateImplicit(
10439 Context, CodeSegStack.CurrentValue->getString(),
10440 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10441 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10444 NewFD))
10445 NewFD->dropAttr<SectionAttr>();
10446 }
10447
10448 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10449 // active.
10451 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10452 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10454
10455 // Apply an implicit CodeSegAttr from class declspec or
10456 // apply an implicit SectionAttr from #pragma code_seg if active.
10457 if (!NewFD->hasAttr<CodeSegAttr>()) {
10459 D.isFunctionDefinition())) {
10460 NewFD->addAttr(SAttr);
10461 }
10462 }
10463
10464 // Handle attributes.
10465 ProcessDeclAttributes(S, NewFD, D);
10466 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10467 if (NewTVA && !NewTVA->isDefaultVersion() &&
10468 !Context.getTargetInfo().hasFeature("fmv")) {
10469 // Don't add to scope fmv functions declarations if fmv disabled
10470 AddToScope = false;
10471 return NewFD;
10472 }
10473
10474 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10475 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10476 // type.
10477 //
10478 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10479 // type declaration will generate a compilation error.
10480 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10481 if (AddressSpace != LangAS::Default) {
10482 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10483 NewFD->setInvalidDecl();
10484 }
10485 }
10486
10487 if (!getLangOpts().CPlusPlus) {
10488 // Perform semantic checking on the function declaration.
10489 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10490 CheckMain(NewFD, D.getDeclSpec());
10491
10492 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10493 CheckMSVCRTEntryPoint(NewFD);
10494
10495 if (!NewFD->isInvalidDecl())
10497 isMemberSpecialization,
10499 else if (!Previous.empty())
10500 // Recover gracefully from an invalid redeclaration.
10501 D.setRedeclaration(true);
10502 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10503 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10504 "previous declaration set still overloaded");
10505
10506 // Diagnose no-prototype function declarations with calling conventions that
10507 // don't support variadic calls. Only do this in C and do it after merging
10508 // possibly prototyped redeclarations.
10509 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10510 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10511 CallingConv CC = FT->getExtInfo().getCC();
10512 if (!supportsVariadicCall(CC)) {
10513 // Windows system headers sometimes accidentally use stdcall without
10514 // (void) parameters, so we relax this to a warning.
10515 int DiagID =
10516 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10517 Diag(NewFD->getLocation(), DiagID)
10519 }
10520 }
10521
10527 } else {
10528 // C++11 [replacement.functions]p3:
10529 // The program's definitions shall not be specified as inline.
10530 //
10531 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10532 //
10533 // Suppress the diagnostic if the function is __attribute__((used)), since
10534 // that forces an external definition to be emitted.
10535 if (D.getDeclSpec().isInlineSpecified() &&
10537 !NewFD->hasAttr<UsedAttr>())
10539 diag::ext_operator_new_delete_declared_inline)
10540 << NewFD->getDeclName();
10541
10542 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10543 // C++20 [dcl.decl.general]p4:
10544 // The optional requires-clause in an init-declarator or
10545 // member-declarator shall be present only if the declarator declares a
10546 // templated function.
10547 //
10548 // C++20 [temp.pre]p8:
10549 // An entity is templated if it is
10550 // - a template,
10551 // - an entity defined or created in a templated entity,
10552 // - a member of a templated entity,
10553 // - an enumerator for an enumeration that is a templated entity, or
10554 // - the closure type of a lambda-expression appearing in the
10555 // declaration of a templated entity.
10556 //
10557 // [Note 6: A local class, a local or block variable, or a friend
10558 // function defined in a templated entity is a templated entity.
10559 // — end note]
10560 //
10561 // A templated function is a function template or a function that is
10562 // templated. A templated class is a class template or a class that is
10563 // templated. A templated variable is a variable template or a variable
10564 // that is templated.
10565 if (!FunctionTemplate) {
10566 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10567 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10568 // An explicit specialization shall not have a trailing
10569 // requires-clause unless it declares a function template.
10570 //
10571 // Since a friend function template specialization cannot be
10572 // definition, and since a non-template friend declaration with a
10573 // trailing requires-clause must be a definition, we diagnose
10574 // friend function template specializations with trailing
10575 // requires-clauses on the same path as explicit specializations
10576 // even though they aren't necessarily prohibited by the same
10577 // language rule.
10578 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10579 << isFriend;
10580 } else if (isFriend && NewFD->isTemplated() &&
10581 !D.isFunctionDefinition()) {
10582 // C++ [temp.friend]p9:
10583 // A non-template friend declaration with a requires-clause shall be
10584 // a definition.
10585 Diag(NewFD->getBeginLoc(),
10586 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10587 NewFD->setInvalidDecl();
10588 } else if (!NewFD->isTemplated() ||
10589 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10590 Diag(TRC->getBeginLoc(),
10591 diag::err_constrained_non_templated_function);
10592 }
10593 }
10594 }
10595
10596 // We do not add HD attributes to specializations here because
10597 // they may have different constexpr-ness compared to their
10598 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10599 // may end up with different effective targets. Instead, a
10600 // specialization inherits its target attributes from its template
10601 // in the CheckFunctionTemplateSpecialization() call below.
10602 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10604
10605 // Handle explict specializations of function templates
10606 // and friend function declarations with an explicit
10607 // template argument list.
10608 if (isFunctionTemplateSpecialization) {
10609 bool isDependentSpecialization = false;
10610 if (isFriend) {
10611 // For friend function specializations, this is a dependent
10612 // specialization if its semantic context is dependent, its
10613 // type is dependent, or if its template-id is dependent.
10614 isDependentSpecialization =
10615 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10616 (HasExplicitTemplateArgs &&
10619 TemplateArgs.arguments()));
10620 assert((!isDependentSpecialization ||
10621 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10622 "dependent friend function specialization without template "
10623 "args");
10624 } else {
10625 // For class-scope explicit specializations of function templates,
10626 // if the lexical context is dependent, then the specialization
10627 // is dependent.
10628 isDependentSpecialization =
10630 }
10631
10632 TemplateArgumentListInfo *ExplicitTemplateArgs =
10633 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10634 if (isDependentSpecialization) {
10635 // If it's a dependent specialization, it may not be possible
10636 // to determine the primary template (for explicit specializations)
10637 // or befriended declaration (for friends) until the enclosing
10638 // template is instantiated. In such cases, we store the declarations
10639 // found by name lookup and defer resolution until instantiation.
10641 NewFD, ExplicitTemplateArgs, Previous))
10642 NewFD->setInvalidDecl();
10643 } else if (!NewFD->isInvalidDecl()) {
10644 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10645 Previous))
10646 NewFD->setInvalidDecl();
10647 }
10648
10649 // C++ [dcl.stc]p1:
10650 // A storage-class-specifier shall not be specified in an explicit
10651 // specialization (14.7.3)
10652 // FIXME: We should be checking this for dependent specializations.
10655 if (Info && SC != SC_None) {
10656 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10657 Diag(NewFD->getLocation(),
10658 diag::err_explicit_specialization_inconsistent_storage_class)
10659 << SC
10662
10663 else
10664 Diag(NewFD->getLocation(),
10665 diag::ext_explicit_specialization_storage_class)
10668 }
10669 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10671 NewFD->setInvalidDecl();
10672 }
10673
10674 // Perform semantic checking on the function declaration.
10675 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10676 CheckMain(NewFD, D.getDeclSpec());
10677
10678 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10679 CheckMSVCRTEntryPoint(NewFD);
10680
10681 if (!NewFD->isInvalidDecl())
10683 isMemberSpecialization,
10685 else if (!Previous.empty())
10686 // Recover gracefully from an invalid redeclaration.
10687 D.setRedeclaration(true);
10688
10689 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10690 !D.isRedeclaration() ||
10691 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10692 "previous declaration set still overloaded");
10693
10694 NamedDecl *PrincipalDecl = (FunctionTemplate
10695 ? cast<NamedDecl>(FunctionTemplate)
10696 : NewFD);
10697
10698 if (isFriend && NewFD->getPreviousDecl()) {
10699 AccessSpecifier Access = AS_public;
10700 if (!NewFD->isInvalidDecl())
10701 Access = NewFD->getPreviousDecl()->getAccess();
10702
10703 NewFD->setAccess(Access);
10704 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10705 }
10706
10707 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10709 PrincipalDecl->setNonMemberOperator();
10710
10711 // If we have a function template, check the template parameter
10712 // list. This will check and merge default template arguments.
10713 if (FunctionTemplate) {
10714 FunctionTemplateDecl *PrevTemplate =
10715 FunctionTemplate->getPreviousDecl();
10716 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10717 PrevTemplate ? PrevTemplate->getTemplateParameters()
10718 : nullptr,
10723 : (D.getCXXScopeSpec().isSet() &&
10724 DC && DC->isRecord() &&
10725 DC->isDependentContext())
10728 }
10729
10730 if (NewFD->isInvalidDecl()) {
10731 // Ignore all the rest of this.
10732 } else if (!D.isRedeclaration()) {
10733 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10734 AddToScope };
10735 // Fake up an access specifier if it's supposed to be a class member.
10736 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10737 NewFD->setAccess(AS_public);
10738
10739 // Qualified decls generally require a previous declaration.
10740 if (D.getCXXScopeSpec().isSet()) {
10741 // ...with the major exception of templated-scope or
10742 // dependent-scope friend declarations.
10743
10744 // TODO: we currently also suppress this check in dependent
10745 // contexts because (1) the parameter depth will be off when
10746 // matching friend templates and (2) we might actually be
10747 // selecting a friend based on a dependent factor. But there
10748 // are situations where these conditions don't apply and we
10749 // can actually do this check immediately.
10750 //
10751 // Unless the scope is dependent, it's always an error if qualified
10752 // redeclaration lookup found nothing at all. Diagnose that now;
10753 // nothing will diagnose that error later.
10754 if (isFriend &&
10756 (!Previous.empty() && CurContext->isDependentContext()))) {
10757 // ignore these
10758 } else if (NewFD->isCPUDispatchMultiVersion() ||
10759 NewFD->isCPUSpecificMultiVersion()) {
10760 // ignore this, we allow the redeclaration behavior here to create new
10761 // versions of the function.
10762 } else {
10763 // The user tried to provide an out-of-line definition for a
10764 // function that is a member of a class or namespace, but there
10765 // was no such member function declared (C++ [class.mfct]p2,
10766 // C++ [namespace.memdef]p2). For example:
10767 //
10768 // class X {
10769 // void f() const;
10770 // };
10771 //
10772 // void X::f() { } // ill-formed
10773 //
10774 // Complain about this problem, and attempt to suggest close
10775 // matches (e.g., those that differ only in cv-qualifiers and
10776 // whether the parameter types are references).
10777
10779 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10780 AddToScope = ExtraArgs.AddToScope;
10781 return Result;
10782 }
10783 }
10784
10785 // Unqualified local friend declarations are required to resolve
10786 // to something.
10787 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10789 *this, Previous, NewFD, ExtraArgs, true, S)) {
10790 AddToScope = ExtraArgs.AddToScope;
10791 return Result;
10792 }
10793 }
10794 } else if (!D.isFunctionDefinition() &&
10795 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10796 !isFriend && !isFunctionTemplateSpecialization &&
10797 !isMemberSpecialization) {
10798 // An out-of-line member function declaration must also be a
10799 // definition (C++ [class.mfct]p2).
10800 // Note that this is not the case for explicit specializations of
10801 // function templates or member functions of class templates, per
10802 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10803 // extension for compatibility with old SWIG code which likes to
10804 // generate them.
10805 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10806 << D.getCXXScopeSpec().getRange();
10807 }
10808 }
10809
10810 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10811 // Any top level function could potentially be specified as an entry.
10812 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10814
10815 if (NewFD->hasAttr<HLSLShaderAttr>())
10816 CheckHLSLEntryPoint(NewFD);
10817 }
10818
10819 // If this is the first declaration of a library builtin function, add
10820 // attributes as appropriate.
10821 if (!D.isRedeclaration()) {
10822 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10823 if (unsigned BuiltinID = II->getBuiltinID()) {
10824 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10825 if (!InStdNamespace &&
10827 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10828 // Validate the type matches unless this builtin is specified as
10829 // matching regardless of its declared type.
10830 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10831 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10832 } else {
10834 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10835 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10836
10837 if (!Error && !BuiltinType.isNull() &&
10839 NewFD->getType(), BuiltinType))
10840 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10841 }
10842 }
10843 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10844 isStdBuiltin(Context, NewFD, BuiltinID)) {
10845 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10846 }
10847 }
10848 }
10849 }
10850
10851 ProcessPragmaWeak(S, NewFD);
10852 checkAttributesAfterMerging(*this, *NewFD);
10853
10855
10856 if (NewFD->hasAttr<OverloadableAttr>() &&
10857 !NewFD->getType()->getAs<FunctionProtoType>()) {
10858 Diag(NewFD->getLocation(),
10859 diag::err_attribute_overloadable_no_prototype)
10860 << NewFD;
10861 NewFD->dropAttr<OverloadableAttr>();
10862 }
10863
10864 // If there's a #pragma GCC visibility in scope, and this isn't a class
10865 // member, set the visibility of this function.
10866 if (!DC->isRecord() && NewFD->isExternallyVisible())
10868
10869 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10870 // marking the function.
10871 AddCFAuditedAttribute(NewFD);
10872
10873 // If this is a function definition, check if we have to apply any
10874 // attributes (i.e. optnone and no_builtin) due to a pragma.
10875 if (D.isFunctionDefinition()) {
10876 AddRangeBasedOptnone(NewFD);
10878 AddSectionMSAllocText(NewFD);
10880 }
10881
10882 // If this is the first declaration of an extern C variable, update
10883 // the map of such variables.
10884 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10885 isIncompleteDeclExternC(*this, NewFD))
10887
10888 // Set this FunctionDecl's range up to the right paren.
10889 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10890
10891 if (D.isRedeclaration() && !Previous.empty()) {
10892 NamedDecl *Prev = Previous.getRepresentativeDecl();
10893 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10894 isMemberSpecialization ||
10895 isFunctionTemplateSpecialization,
10897 }
10898
10899 if (getLangOpts().CUDA) {
10900 IdentifierInfo *II = NewFD->getIdentifier();
10901 if (II && II->isStr(getCudaConfigureFuncName()) &&
10902 !NewFD->isInvalidDecl() &&
10905 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10908 }
10909
10910 // Variadic functions, other than a *declaration* of printf, are not allowed
10911 // in device-side CUDA code, unless someone passed
10912 // -fcuda-allow-variadic-functions.
10913 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10914 (NewFD->hasAttr<CUDADeviceAttr>() ||
10915 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10916 !(II && II->isStr("printf") && NewFD->isExternC() &&
10917 !D.isFunctionDefinition())) {
10918 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10919 }
10920 }
10921
10923
10924
10925
10926 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10927 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10928 if (SC == SC_Static) {
10929 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10930 D.setInvalidType();
10931 }
10932
10933 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10934 if (!NewFD->getReturnType()->isVoidType()) {
10935 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10936 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10937 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10938 : FixItHint());
10939 D.setInvalidType();
10940 }
10941
10943 for (auto *Param : NewFD->parameters())
10944 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10945
10946 if (getLangOpts().OpenCLCPlusPlus) {
10947 if (DC->isRecord()) {
10948 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10949 D.setInvalidType();
10950 }
10951 if (FunctionTemplate) {
10952 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10953 D.setInvalidType();
10954 }
10955 }
10956 }
10957
10958 if (getLangOpts().CPlusPlus) {
10959 // Precalculate whether this is a friend function template with a constraint
10960 // that depends on an enclosing template, per [temp.friend]p9.
10961 if (isFriend && FunctionTemplate &&
10964
10965 // C++ [temp.friend]p9:
10966 // A friend function template with a constraint that depends on a
10967 // template parameter from an enclosing template shall be a definition.
10968 if (!D.isFunctionDefinition()) {
10969 Diag(NewFD->getBeginLoc(),
10970 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10971 NewFD->setInvalidDecl();
10972 }
10973 }
10974
10975 if (FunctionTemplate) {
10976 if (NewFD->isInvalidDecl())
10977 FunctionTemplate->setInvalidDecl();
10978 return FunctionTemplate;
10979 }
10980
10981 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10983 }
10984
10985 for (const ParmVarDecl *Param : NewFD->parameters()) {
10986 QualType PT = Param->getType();
10987
10988 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10989 // types.
10990 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10991 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10992 QualType ElemTy = PipeTy->getElementType();
10993 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10994 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10995 D.setInvalidType();
10996 }
10997 }
10998 }
10999 // WebAssembly tables can't be used as function parameters.
11000 if (Context.getTargetInfo().getTriple().isWasm()) {
11002 Diag(Param->getTypeSpecStartLoc(),
11003 diag::err_wasm_table_as_function_parameter);
11004 D.setInvalidType();
11005 }
11006 }
11007 }
11008
11009 // Diagnose availability attributes. Availability cannot be used on functions
11010 // that are run during load/unload.
11011 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11012 if (NewFD->hasAttr<ConstructorAttr>()) {
11013 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11014 << 1;
11015 NewFD->dropAttr<AvailabilityAttr>();
11016 }
11017 if (NewFD->hasAttr<DestructorAttr>()) {
11018 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11019 << 2;
11020 NewFD->dropAttr<AvailabilityAttr>();
11021 }
11022 }
11023
11024 // Diagnose no_builtin attribute on function declaration that are not a
11025 // definition.
11026 // FIXME: We should really be doing this in
11027 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11028 // the FunctionDecl and at this point of the code
11029 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11030 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11031 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11032 switch (D.getFunctionDefinitionKind()) {
11035 Diag(NBA->getLocation(),
11036 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11037 << NBA->getSpelling();
11038 break;
11040 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11041 << NBA->getSpelling();
11042 break;
11044 break;
11045 }
11046
11047 return NewFD;
11048}
11049
11050/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11051/// when __declspec(code_seg) "is applied to a class, all member functions of
11052/// the class and nested classes -- this includes compiler-generated special
11053/// member functions -- are put in the specified segment."
11054/// The actual behavior is a little more complicated. The Microsoft compiler
11055/// won't check outer classes if there is an active value from #pragma code_seg.
11056/// The CodeSeg is always applied from the direct parent but only from outer
11057/// classes when the #pragma code_seg stack is empty. See:
11058/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11059/// available since MS has removed the page.
11061 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11062 if (!Method)
11063 return nullptr;
11064 const CXXRecordDecl *Parent = Method->getParent();
11065 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11066 Attr *NewAttr = SAttr->clone(S.getASTContext());
11067 NewAttr->setImplicit(true);
11068 return NewAttr;
11069 }
11070
11071 // The Microsoft compiler won't check outer classes for the CodeSeg
11072 // when the #pragma code_seg stack is active.
11073 if (S.CodeSegStack.CurrentValue)
11074 return nullptr;
11075
11076 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11077 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11078 Attr *NewAttr = SAttr->clone(S.getASTContext());
11079 NewAttr->setImplicit(true);
11080 return NewAttr;
11081 }
11082 }
11083 return nullptr;
11084}
11085
11086/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
11087/// containing class. Otherwise it will return implicit SectionAttr if the
11088/// function is a definition and there is an active value on CodeSegStack
11089/// (from the current #pragma code-seg value).
11090///
11091/// \param FD Function being declared.
11092/// \param IsDefinition Whether it is a definition or just a declaration.
11093/// \returns A CodeSegAttr or SectionAttr to apply to the function or
11094/// nullptr if no attribute should be added.
11096 bool IsDefinition) {
11097 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11098 return A;
11099 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11100 CodeSegStack.CurrentValue)
11101 return SectionAttr::CreateImplicit(
11102 getASTContext(), CodeSegStack.CurrentValue->getString(),
11103 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11104 return nullptr;
11105}
11106
11107/// Determines if we can perform a correct type check for \p D as a
11108/// redeclaration of \p PrevDecl. If not, we can generally still perform a
11109/// best-effort check.
11110///
11111/// \param NewD The new declaration.
11112/// \param OldD The old declaration.
11113/// \param NewT The portion of the type of the new declaration to check.
11114/// \param OldT The portion of the type of the old declaration to check.
11116 QualType NewT, QualType OldT) {
11118 return true;
11119
11120 // For dependently-typed local extern declarations and friends, we can't
11121 // perform a correct type check in general until instantiation:
11122 //
11123 // int f();
11124 // template<typename T> void g() { T f(); }
11125 //
11126 // (valid if g() is only instantiated with T = int).
11127 if (NewT->isDependentType() &&
11128 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11129 return false;
11130
11131 // Similarly, if the previous declaration was a dependent local extern
11132 // declaration, we don't really know its type yet.
11133 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11134 return false;
11135
11136 return true;
11137}
11138
11139/// Checks if the new declaration declared in dependent context must be
11140/// put in the same redeclaration chain as the specified declaration.
11141///
11142/// \param D Declaration that is checked.
11143/// \param PrevDecl Previous declaration found with proper lookup method for the
11144/// same declaration name.
11145/// \returns True if D must be added to the redeclaration chain which PrevDecl
11146/// belongs to.
11147///
11150 return true;
11151
11152 // Don't chain dependent friend function definitions until instantiation, to
11153 // permit cases like
11154 //
11155 // void func();
11156 // template<typename T> class C1 { friend void func() {} };
11157 // template<typename T> class C2 { friend void func() {} };
11158 //
11159 // ... which is valid if only one of C1 and C2 is ever instantiated.
11160 //
11161 // FIXME: This need only apply to function definitions. For now, we proxy
11162 // this by checking for a file-scope function. We do not want this to apply
11163 // to friend declarations nominating member functions, because that gets in
11164 // the way of access checks.
11166 return false;
11167
11168 auto *VD = dyn_cast<ValueDecl>(D);
11169 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11170 return !VD || !PrevVD ||
11171 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11172 PrevVD->getType());
11173}
11174
11175/// Check the target or target_version attribute of the function for
11176/// MultiVersion validity.
11177///
11178/// Returns true if there was an error, false otherwise.
11179static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11180 const auto *TA = FD->getAttr<TargetAttr>();
11181 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11182 assert(
11183 (TA || TVA) &&
11184 "MultiVersion candidate requires a target or target_version attribute");
11186 enum ErrType { Feature = 0, Architecture = 1 };
11187
11188 if (TA) {
11189 ParsedTargetAttr ParseInfo =
11190 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11191 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11192 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11193 << Architecture << ParseInfo.CPU;
11194 return true;
11195 }
11196 for (const auto &Feat : ParseInfo.Features) {
11197 auto BareFeat = StringRef{Feat}.substr(1);
11198 if (Feat[0] == '-') {
11199 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11200 << Feature << ("no-" + BareFeat).str();
11201 return true;
11202 }
11203
11204 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11205 !TargetInfo.isValidFeatureName(BareFeat)) {
11206 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11207 << Feature << BareFeat;
11208 return true;
11209 }
11210 }
11211 }
11212
11213 if (TVA) {
11215 TVA->getFeatures(Feats);
11216 for (const auto &Feat : Feats) {
11217 if (!TargetInfo.validateCpuSupports(Feat)) {
11218 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11219 << Feature << Feat;
11220 return true;
11221 }
11222 }
11223 }
11224 return false;
11225}
11226
11227// Provide a white-list of attributes that are allowed to be combined with
11228// multiversion functions.
11230 MultiVersionKind MVKind) {
11231 // Note: this list/diagnosis must match the list in
11232 // checkMultiversionAttributesAllSame.
11233 switch (Kind) {
11234 default:
11235 return false;
11236 case attr::Used:
11237 return MVKind == MultiVersionKind::Target;
11238 case attr::NonNull:
11239 case attr::NoThrow:
11240 return true;
11241 }
11242}
11243
11245 const FunctionDecl *FD,
11246 const FunctionDecl *CausedFD,
11247 MultiVersionKind MVKind) {
11248 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11249 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11250 << static_cast<unsigned>(MVKind) << A;
11251 if (CausedFD)
11252 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11253 return true;
11254 };
11255
11256 for (const Attr *A : FD->attrs()) {
11257 switch (A->getKind()) {
11258 case attr::CPUDispatch:
11259 case attr::CPUSpecific:
11260 if (MVKind != MultiVersionKind::CPUDispatch &&
11262 return Diagnose(S, A);
11263 break;
11264 case attr::Target:
11265 if (MVKind != MultiVersionKind::Target)
11266 return Diagnose(S, A);
11267 break;
11268 case attr::TargetVersion:
11269 if (MVKind != MultiVersionKind::TargetVersion)
11270 return Diagnose(S, A);
11271 break;
11272 case attr::TargetClones:
11273 if (MVKind != MultiVersionKind::TargetClones)
11274 return Diagnose(S, A);
11275 break;
11276 default:
11277 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11278 return Diagnose(S, A);
11279 break;
11280 }
11281 }
11282 return false;
11283}
11284
11286 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11287 const PartialDiagnostic &NoProtoDiagID,
11288 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11289 const PartialDiagnosticAt &NoSupportDiagIDAt,
11290 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11291 bool ConstexprSupported, bool CLinkageMayDiffer) {
11292 enum DoesntSupport {
11293 FuncTemplates = 0,
11294 VirtFuncs = 1,
11295 DeducedReturn = 2,
11296 Constructors = 3,
11297 Destructors = 4,
11298 DeletedFuncs = 5,
11299 DefaultedFuncs = 6,
11300 ConstexprFuncs = 7,
11301 ConstevalFuncs = 8,
11302 Lambda = 9,
11303 };
11304 enum Different {
11305 CallingConv = 0,
11306 ReturnType = 1,
11307 ConstexprSpec = 2,
11308 InlineSpec = 3,
11309 Linkage = 4,
11310 LanguageLinkage = 5,
11311 };
11312
11313 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11314 !OldFD->getType()->getAs<FunctionProtoType>()) {
11315 Diag(OldFD->getLocation(), NoProtoDiagID);
11316 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11317 return true;
11318 }
11319
11320 if (NoProtoDiagID.getDiagID() != 0 &&
11321 !NewFD->getType()->getAs<FunctionProtoType>())
11322 return Diag(NewFD->getLocation(), NoProtoDiagID);
11323
11324 if (!TemplatesSupported &&
11326 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11327 << FuncTemplates;
11328
11329 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11330 if (NewCXXFD->isVirtual())
11331 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11332 << VirtFuncs;
11333
11334 if (isa<CXXConstructorDecl>(NewCXXFD))
11335 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11336 << Constructors;
11337
11338 if (isa<CXXDestructorDecl>(NewCXXFD))
11339 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11340 << Destructors;
11341 }
11342
11343 if (NewFD->isDeleted())
11344 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11345 << DeletedFuncs;
11346
11347 if (NewFD->isDefaulted())
11348 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11349 << DefaultedFuncs;
11350
11351 if (!ConstexprSupported && NewFD->isConstexpr())
11352 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11353 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11354
11355 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11356 const auto *NewType = cast<FunctionType>(NewQType);
11357 QualType NewReturnType = NewType->getReturnType();
11358
11359 if (NewReturnType->isUndeducedType())
11360 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11361 << DeducedReturn;
11362
11363 // Ensure the return type is identical.
11364 if (OldFD) {
11365 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11366 const auto *OldType = cast<FunctionType>(OldQType);
11367 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11368 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11369
11370 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11371 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11372
11373 QualType OldReturnType = OldType->getReturnType();
11374
11375 if (OldReturnType != NewReturnType)
11376 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11377
11378 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11379 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11380
11381 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11382 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11383
11384 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11385 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11386
11387 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11388 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11389
11391 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11392 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11393 return true;
11394 }
11395 return false;
11396}
11397
11399 const FunctionDecl *NewFD,
11400 bool CausesMV,
11401 MultiVersionKind MVKind) {
11403 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11404 if (OldFD)
11405 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11406 return true;
11407 }
11408
11409 bool IsCPUSpecificCPUDispatchMVKind =
11412
11413 if (CausesMV && OldFD &&
11414 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11415 return true;
11416
11417 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11418 return true;
11419
11420 // Only allow transition to MultiVersion if it hasn't been used.
11421 if (OldFD && CausesMV && OldFD->isUsed(false))
11422 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11423
11425 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11427 S.PDiag(diag::note_multiversioning_caused_here)),
11429 S.PDiag(diag::err_multiversion_doesnt_support)
11430 << static_cast<unsigned>(MVKind)),
11432 S.PDiag(diag::err_multiversion_diff)),
11433 /*TemplatesSupported=*/false,
11434 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11435 /*CLinkageMayDiffer=*/false);
11436}
11437
11438/// Check the validity of a multiversion function declaration that is the
11439/// first of its kind. Also sets the multiversion'ness' of the function itself.
11440///
11441/// This sets NewFD->isInvalidDecl() to true if there was an error.
11442///
11443/// Returns true if there was an error, false otherwise.
11446 assert(MVKind != MultiVersionKind::None &&
11447 "Function lacks multiversion attribute");
11448 const auto *TA = FD->getAttr<TargetAttr>();
11449 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11450 // Target and target_version only causes MV if it is default, otherwise this
11451 // is a normal function.
11452 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11453 return false;
11454
11455 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11456 FD->setInvalidDecl();
11457 return true;
11458 }
11459
11460 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11461 FD->setInvalidDecl();
11462 return true;
11463 }
11464
11465 FD->setIsMultiVersion();
11466 return false;
11467}
11468
11470 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11472 return true;
11473 }
11474
11475 return false;
11476}
11477
11479 FunctionDecl *NewFD,
11480 bool &Redeclaration,
11481 NamedDecl *&OldDecl,
11483 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11484
11485 // The definitions should be allowed in any order. If we have discovered
11486 // a new target version and the preceeding was the default, then add the
11487 // corresponding attribute to it.
11490 OldFD->addAttr(TargetVersionAttr::CreateImplicit(S.Context, "default",
11491 OldFD->getSourceRange()));
11492
11493 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11494 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11495 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11496 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11497 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11498 // to change, this is a simple redeclaration.
11499 if ((NewTA && !NewTA->isDefaultVersion() &&
11500 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11501 (NewTVA && !NewTVA->isDefaultVersion() &&
11502 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11503 return false;
11504
11505 // Otherwise, this decl causes MultiVersioning.
11506 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11509 NewFD->setInvalidDecl();
11510 return true;
11511 }
11512
11513 if (CheckMultiVersionValue(S, NewFD)) {
11514 NewFD->setInvalidDecl();
11515 return true;
11516 }
11517
11518 // If this is 'default', permit the forward declaration.
11519 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11520 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11521 Redeclaration = true;
11522 OldDecl = OldFD;
11523 OldFD->setIsMultiVersion();
11524 NewFD->setIsMultiVersion();
11525 return false;
11526 }
11527
11528 if (CheckMultiVersionValue(S, OldFD)) {
11529 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11530 NewFD->setInvalidDecl();
11531 return true;
11532 }
11533
11534 if (NewTA) {
11535 ParsedTargetAttr OldParsed =
11537 OldTA->getFeaturesStr());
11538 llvm::sort(OldParsed.Features);
11539 ParsedTargetAttr NewParsed =
11541 NewTA->getFeaturesStr());
11542 // Sort order doesn't matter, it just needs to be consistent.
11543 llvm::sort(NewParsed.Features);
11544 if (OldParsed == NewParsed) {
11545 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11546 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11547 NewFD->setInvalidDecl();
11548 return true;
11549 }
11550 }
11551
11552 if (NewTVA) {
11554 OldTVA->getFeatures(Feats);
11555 llvm::sort(Feats);
11557 NewTVA->getFeatures(NewFeats);
11558 llvm::sort(NewFeats);
11559
11560 if (Feats == NewFeats) {
11561 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11562 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11563 NewFD->setInvalidDecl();
11564 return true;
11565 }
11566 }
11567
11568 for (const auto *FD : OldFD->redecls()) {
11569 const auto *CurTA = FD->getAttr<TargetAttr>();
11570 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11571 // We allow forward declarations before ANY multiversioning attributes, but
11572 // nothing after the fact.
11574 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11575 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11576 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11577 << (NewTA ? 0 : 2);
11578 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11579 NewFD->setInvalidDecl();
11580 return true;
11581 }
11582 }
11583
11584 OldFD->setIsMultiVersion();
11585 NewFD->setIsMultiVersion();
11586 Redeclaration = false;
11587 OldDecl = nullptr;
11588 Previous.clear();
11589 return false;
11590}
11591
11593 MultiVersionKind New) {
11594 if (Old == New || Old == MultiVersionKind::None ||
11596 return true;
11597
11598 return (Old == MultiVersionKind::CPUDispatch &&
11602}
11603
11604/// Check the validity of a new function declaration being added to an existing
11605/// multiversioned declaration collection.
11607 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11608 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11609 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11610 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11611 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11612 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11613 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11614 // Disallow mixing of multiversioning types.
11615 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11616 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11617 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11618 NewFD->setInvalidDecl();
11619 return true;
11620 }
11621
11622 ParsedTargetAttr NewParsed;
11623 if (NewTA) {
11625 NewTA->getFeaturesStr());
11626 llvm::sort(NewParsed.Features);
11627 }
11629 if (NewTVA) {
11630 NewTVA->getFeatures(NewFeats);
11631 llvm::sort(NewFeats);
11632 }
11633
11634 bool UseMemberUsingDeclRules =
11635 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11636
11637 bool MayNeedOverloadableChecks =
11639
11640 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11641 // of a previous member of the MultiVersion set.
11642 for (NamedDecl *ND : Previous) {
11643 FunctionDecl *CurFD = ND->getAsFunction();
11644 if (!CurFD || CurFD->isInvalidDecl())
11645 continue;
11646 if (MayNeedOverloadableChecks &&
11647 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11648 continue;
11649
11650 if (NewMVKind == MultiVersionKind::None &&
11651 OldMVKind == MultiVersionKind::TargetVersion) {
11652 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11653 S.Context, "default", NewFD->getSourceRange()));
11654 NewFD->setIsMultiVersion();
11656 if (!NewTVA) {
11657 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11658 NewTVA->getFeatures(NewFeats);
11659 llvm::sort(NewFeats);
11660 }
11661 }
11662
11663 switch (NewMVKind) {
11665 assert(OldMVKind == MultiVersionKind::TargetClones &&
11666 "Only target_clones can be omitted in subsequent declarations");
11667 break;
11669 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11670 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11671 NewFD->setIsMultiVersion();
11672 Redeclaration = true;
11673 OldDecl = ND;
11674 return false;
11675 }
11676
11677 ParsedTargetAttr CurParsed =
11679 CurTA->getFeaturesStr());
11680 llvm::sort(CurParsed.Features);
11681 if (CurParsed == NewParsed) {
11682 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11683 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11684 NewFD->setInvalidDecl();
11685 return true;
11686 }
11687 break;
11688 }
11690 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11691 if (CurTVA->getName() == NewTVA->getName()) {
11692 NewFD->setIsMultiVersion();
11693 Redeclaration = true;
11694 OldDecl = ND;
11695 return false;
11696 }
11698 if (CurTVA) {
11699 CurTVA->getFeatures(CurFeats);
11700 llvm::sort(CurFeats);
11701 }
11702 if (CurFeats == NewFeats) {
11703 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11704 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11705 NewFD->setInvalidDecl();
11706 return true;
11707 }
11708 break;
11709 }
11711 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11712 Redeclaration = true;
11713 OldDecl = CurFD;
11714 NewFD->setIsMultiVersion();
11715
11716 if (CurClones && NewClones &&
11717 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11718 !std::equal(CurClones->featuresStrs_begin(),
11719 CurClones->featuresStrs_end(),
11720 NewClones->featuresStrs_begin()))) {
11721 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11722 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11723 NewFD->setInvalidDecl();
11724 return true;
11725 }
11726
11727 return false;
11728 }
11731 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11732 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11733 // Handle CPUDispatch/CPUSpecific versions.
11734 // Only 1 CPUDispatch function is allowed, this will make it go through
11735 // the redeclaration errors.
11736 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11737 CurFD->hasAttr<CPUDispatchAttr>()) {
11738 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11739 std::equal(
11740 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11741 NewCPUDisp->cpus_begin(),
11742 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11743 return Cur->getName() == New->getName();
11744 })) {
11745 NewFD->setIsMultiVersion();
11746 Redeclaration = true;
11747 OldDecl = ND;
11748 return false;
11749 }
11750
11751 // If the declarations don't match, this is an error condition.
11752 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11753 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11754 NewFD->setInvalidDecl();
11755 return true;
11756 }
11757 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11758 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11759 std::equal(
11760 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11761 NewCPUSpec->cpus_begin(),
11762 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11763 return Cur->getName() == New->getName();
11764 })) {
11765 NewFD->setIsMultiVersion();
11766 Redeclaration = true;
11767 OldDecl = ND;
11768 return false;
11769 }
11770
11771 // Only 1 version of CPUSpecific is allowed for each CPU.
11772 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11773 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11774 if (CurII == NewII) {
11775 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11776 << NewII;
11777 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11778 NewFD->setInvalidDecl();
11779 return true;
11780 }
11781 }
11782 }
11783 }
11784 break;
11785 }
11786 }
11787 }
11788
11789 // Else, this is simply a non-redecl case. Checking the 'value' is only
11790 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11791 // handled in the attribute adding step.
11792 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11793 NewMVKind == MultiVersionKind::Target) &&
11794 CheckMultiVersionValue(S, NewFD)) {
11795 NewFD->setInvalidDecl();
11796 return true;
11797 }
11798
11799 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11800 !OldFD->isMultiVersion(), NewMVKind)) {
11801 NewFD->setInvalidDecl();
11802 return true;
11803 }
11804
11805 // Permit forward declarations in the case where these two are compatible.
11806 if (!OldFD->isMultiVersion()) {
11807 OldFD->setIsMultiVersion();
11808 NewFD->setIsMultiVersion();
11809 Redeclaration = true;
11810 OldDecl = OldFD;
11811 return false;
11812 }
11813
11814 NewFD->setIsMultiVersion();
11815 Redeclaration = false;
11816 OldDecl = nullptr;
11817 Previous.clear();
11818 return false;
11819}
11820
11821/// Check the validity of a mulitversion function declaration.
11822/// Also sets the multiversion'ness' of the function itself.
11823///
11824/// This sets NewFD->isInvalidDecl() to true if there was an error.
11825///
11826/// Returns true if there was an error, false otherwise.
11828 bool &Redeclaration, NamedDecl *&OldDecl,
11830 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11831 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11832 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11833 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11834 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11835 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11836
11837 // Main isn't allowed to become a multiversion function, however it IS
11838 // permitted to have 'main' be marked with the 'target' optimization hint,
11839 // for 'target_version' only default is allowed.
11840 if (NewFD->isMain()) {
11841 if (MVKind != MultiVersionKind::None &&
11842 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11843 !(MVKind == MultiVersionKind::TargetVersion &&
11844 NewTVA->isDefaultVersion())) {
11845 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11846 NewFD->setInvalidDecl();
11847 return true;
11848 }
11849 return false;
11850 }
11851
11852 // Target attribute on AArch64 is not used for multiversioning
11853 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11854 return false;
11855
11856 if (!OldDecl || !OldDecl->getAsFunction() ||
11857 OldDecl->getDeclContext()->getRedeclContext() !=
11858 NewFD->getDeclContext()->getRedeclContext()) {
11859 // If there's no previous declaration, AND this isn't attempting to cause
11860 // multiversioning, this isn't an error condition.
11861 if (MVKind == MultiVersionKind::None)
11862 return false;
11863 return CheckMultiVersionFirstFunction(S, NewFD);
11864 }
11865
11866 FunctionDecl *OldFD = OldDecl->getAsFunction();
11867
11868 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11869 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11870 return false;
11871 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11872 // Multiversion declaration doesn't have prototype.
11873 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11874 NewFD->setInvalidDecl();
11875 } else {
11876 // No "target_version" attribute is equivalent to "default" attribute.
11877 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11878 S.Context, "default", NewFD->getSourceRange()));
11879 NewFD->setIsMultiVersion();
11880 OldFD->setIsMultiVersion();
11881 OldDecl = OldFD;
11882 Redeclaration = true;
11883 }
11884 return true;
11885 }
11886
11887 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11888 // for target_clones and target_version.
11889 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11892 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11894 NewFD->setInvalidDecl();
11895 return true;
11896 }
11897
11898 if (!OldFD->isMultiVersion()) {
11899 switch (MVKind) {
11902 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11903 OldDecl, Previous);
11905 if (OldFD->isUsed(false)) {
11906 NewFD->setInvalidDecl();
11907 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11908 }
11909 OldFD->setIsMultiVersion();
11910 break;
11911
11915 break;
11916 }
11917 }
11918
11919 // At this point, we have a multiversion function decl (in OldFD) AND an
11920 // appropriate attribute in the current function decl. Resolve that these are
11921 // still compatible with previous declarations.
11922 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11923 NewCPUSpec, NewClones, Redeclaration,
11924 OldDecl, Previous);
11925}
11926
11928 bool IsPure = NewFD->hasAttr<PureAttr>();
11929 bool IsConst = NewFD->hasAttr<ConstAttr>();
11930
11931 // If there are no pure or const attributes, there's nothing to check.
11932 if (!IsPure && !IsConst)
11933 return;
11934
11935 // If the function is marked both pure and const, we retain the const
11936 // attribute because it makes stronger guarantees than the pure attribute, and
11937 // we drop the pure attribute explicitly to prevent later confusion about
11938 // semantics.
11939 if (IsPure && IsConst) {
11940 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11941 NewFD->dropAttrs<PureAttr>();
11942 }
11943
11944 // Constructors and destructors are functions which return void, so are
11945 // handled here as well.
11946 if (NewFD->getReturnType()->isVoidType()) {
11947 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11948 << IsConst;
11949 NewFD->dropAttrs<PureAttr, ConstAttr>();
11950 }
11951}
11952
11953/// Perform semantic checking of a new function declaration.
11954///
11955/// Performs semantic analysis of the new function declaration
11956/// NewFD. This routine performs all semantic checking that does not
11957/// require the actual declarator involved in the declaration, and is
11958/// used both for the declaration of functions as they are parsed
11959/// (called via ActOnDeclarator) and for the declaration of functions
11960/// that have been instantiated via C++ template instantiation (called
11961/// via InstantiateDecl).
11962///
11963/// \param IsMemberSpecialization whether this new function declaration is
11964/// a member specialization (that replaces any definition provided by the
11965/// previous declaration).
11966///
11967/// This sets NewFD->isInvalidDecl() to true if there was an error.
11968///
11969/// \returns true if the function declaration is a redeclaration.
11972 bool IsMemberSpecialization,
11973 bool DeclIsDefn) {
11974 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11975 "Variably modified return types are not handled here");
11976
11977 // Determine whether the type of this function should be merged with
11978 // a previous visible declaration. This never happens for functions in C++,
11979 // and always happens in C if the previous declaration was visible.
11980 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11981 !Previous.isShadowed();
11982
11983 bool Redeclaration = false;
11984 NamedDecl *OldDecl = nullptr;
11985 bool MayNeedOverloadableChecks = false;
11986
11987 // Merge or overload the declaration with an existing declaration of
11988 // the same name, if appropriate.
11989 if (!Previous.empty()) {
11990 // Determine whether NewFD is an overload of PrevDecl or
11991 // a declaration that requires merging. If it's an overload,
11992 // there's no more work to do here; we'll just add the new
11993 // function to the scope.
11995 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11996 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11997 Redeclaration = true;
11998 OldDecl = Candidate;
11999 }
12000 } else {
12001 MayNeedOverloadableChecks = true;
12002 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12003 /*NewIsUsingDecl*/ false)) {
12004 case Ovl_Match:
12005 Redeclaration = true;
12006 break;
12007
12008 case Ovl_NonFunction:
12009 Redeclaration = true;
12010 break;
12011
12012 case Ovl_Overload:
12013 Redeclaration = false;
12014 break;
12015 }
12016 }
12017 }
12018
12019 // Check for a previous extern "C" declaration with this name.
12020 if (!Redeclaration &&
12022 if (!Previous.empty()) {
12023 // This is an extern "C" declaration with the same name as a previous
12024 // declaration, and thus redeclares that entity...
12025 Redeclaration = true;
12026 OldDecl = Previous.getFoundDecl();
12027 MergeTypeWithPrevious = false;
12028
12029 // ... except in the presence of __attribute__((overloadable)).
12030 if (OldDecl->hasAttr<OverloadableAttr>() ||
12031 NewFD->hasAttr<OverloadableAttr>()) {
12032 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12033 MayNeedOverloadableChecks = true;
12034 Redeclaration = false;
12035 OldDecl = nullptr;
12036 }
12037 }
12038 }
12039 }
12040
12041 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12042 return Redeclaration;
12043
12044 // PPC MMA non-pointer types are not allowed as function return types.
12045 if (Context.getTargetInfo().getTriple().isPPC64() &&
12046 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12047 NewFD->setInvalidDecl();
12048 }
12049
12050 CheckConstPureAttributesUsage(*this, NewFD);
12051
12052 // C++11 [dcl.constexpr]p8:
12053 // A constexpr specifier for a non-static member function that is not
12054 // a constructor declares that member function to be const.
12055 //
12056 // This needs to be delayed until we know whether this is an out-of-line
12057 // definition of a static member function.
12058 //
12059 // This rule is not present in C++1y, so we produce a backwards
12060 // compatibility warning whenever it happens in C++11.
12061 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12062 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12063 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12064 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12065 CXXMethodDecl *OldMD = nullptr;
12066 if (OldDecl)
12067 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12068 if (!OldMD || !OldMD->isStatic()) {
12069 const FunctionProtoType *FPT =
12072 EPI.TypeQuals.addConst();
12074 FPT->getParamTypes(), EPI));
12075
12076 // Warn that we did this, if we're not performing template instantiation.
12077 // In that case, we'll have warned already when the template was defined.
12078 if (!inTemplateInstantiation()) {
12079 SourceLocation AddConstLoc;
12082 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12083
12084 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12085 << FixItHint::CreateInsertion(AddConstLoc, " const");
12086 }
12087 }
12088 }
12089
12090 if (Redeclaration) {
12091 // NewFD and OldDecl represent declarations that need to be
12092 // merged.
12093 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12094 DeclIsDefn)) {
12095 NewFD->setInvalidDecl();
12096 return Redeclaration;
12097 }
12098
12099 Previous.clear();
12100 Previous.addDecl(OldDecl);
12101
12102 if (FunctionTemplateDecl *OldTemplateDecl =
12103 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12104 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12105 FunctionTemplateDecl *NewTemplateDecl
12107 assert(NewTemplateDecl && "Template/non-template mismatch");
12108
12109 // The call to MergeFunctionDecl above may have created some state in
12110 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12111 // can add it as a redeclaration.
12112 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12113
12114 NewFD->setPreviousDeclaration(OldFD);
12115 if (NewFD->isCXXClassMember()) {
12116 NewFD->setAccess(OldTemplateDecl->getAccess());
12117 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12118 }
12119
12120 // If this is an explicit specialization of a member that is a function
12121 // template, mark it as a member specialization.
12122 if (IsMemberSpecialization &&
12123 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12124 NewTemplateDecl->setMemberSpecialization();
12125 assert(OldTemplateDecl->isMemberSpecialization());
12126 // Explicit specializations of a member template do not inherit deleted
12127 // status from the parent member template that they are specializing.
12128 if (OldFD->isDeleted()) {
12129 // FIXME: This assert will not hold in the presence of modules.
12130 assert(OldFD->getCanonicalDecl() == OldFD);
12131 // FIXME: We need an update record for this AST mutation.
12132 OldFD->setDeletedAsWritten(false);
12133 }
12134 }
12135
12136 } else {
12137 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12138 auto *OldFD = cast<FunctionDecl>(OldDecl);
12139 // This needs to happen first so that 'inline' propagates.
12140 NewFD->setPreviousDeclaration(OldFD);
12141 if (NewFD->isCXXClassMember())
12142 NewFD->setAccess(OldFD->getAccess());
12143 }
12144 }
12145 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12146 !NewFD->getAttr<OverloadableAttr>()) {
12147 assert((Previous.empty() ||
12148 llvm::any_of(Previous,
12149 [](const NamedDecl *ND) {
12150 return ND->hasAttr<OverloadableAttr>();
12151 })) &&
12152 "Non-redecls shouldn't happen without overloadable present");
12153
12154 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12155 const auto *FD = dyn_cast<FunctionDecl>(ND);
12156 return FD && !FD->hasAttr<OverloadableAttr>();
12157 });
12158
12159 if (OtherUnmarkedIter != Previous.end()) {
12160 Diag(NewFD->getLocation(),
12161 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12162 Diag((*OtherUnmarkedIter)->getLocation(),
12163 diag::note_attribute_overloadable_prev_overload)
12164 << false;
12165
12166 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12167 }
12168 }
12169
12170 if (LangOpts.OpenMP)
12172
12173 // Semantic checking for this function declaration (in isolation).
12174
12175 if (getLangOpts().CPlusPlus) {
12176 // C++-specific checks.
12177 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12178 CheckConstructor(Constructor);
12179 } else if (CXXDestructorDecl *Destructor =
12180 dyn_cast<CXXDestructorDecl>(NewFD)) {
12181 // We check here for invalid destructor names.
12182 // If we have a friend destructor declaration that is dependent, we can't
12183 // diagnose right away because cases like this are still valid:
12184 // template <class T> struct A { friend T::X::~Y(); };
12185 // struct B { struct Y { ~Y(); }; using X = Y; };
12186 // template struct A<B>;
12188 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12189 CXXRecordDecl *Record = Destructor->getParent();
12191
12193 Context.getCanonicalType(ClassType));
12194 if (NewFD->getDeclName() != Name) {
12195 Diag(NewFD->getLocation(), diag::err_destructor_name);
12196 NewFD->setInvalidDecl();
12197 return Redeclaration;
12198 }
12199 }
12200 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12201 if (auto *TD = Guide->getDescribedFunctionTemplate())
12203
12204 // A deduction guide is not on the list of entities that can be
12205 // explicitly specialized.
12206 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12207 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12208 << /*explicit specialization*/ 1;
12209 }
12210
12211 // Find any virtual functions that this function overrides.
12212 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12213 if (!Method->isFunctionTemplateSpecialization() &&
12214 !Method->getDescribedFunctionTemplate() &&
12215 Method->isCanonicalDecl()) {
12216 AddOverriddenMethods(Method->getParent(), Method);
12217 }
12218 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12219 // C++2a [class.virtual]p6
12220 // A virtual method shall not have a requires-clause.
12222 diag::err_constrained_virtual_method);
12223
12224 if (Method->isStatic())
12226 }
12227
12228 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12229 ActOnConversionDeclarator(Conversion);
12230
12231 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12232 if (NewFD->isOverloadedOperator() &&
12234 NewFD->setInvalidDecl();
12235 return Redeclaration;
12236 }
12237
12238 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12239 if (NewFD->getLiteralIdentifier() &&
12241 NewFD->setInvalidDecl();
12242 return Redeclaration;
12243 }
12244
12245 // In C++, check default arguments now that we have merged decls. Unless
12246 // the lexical context is the class, because in this case this is done
12247 // during delayed parsing anyway.
12248 if (!CurContext->isRecord())
12250
12251 // If this function is declared as being extern "C", then check to see if
12252 // the function returns a UDT (class, struct, or union type) that is not C
12253 // compatible, and if it does, warn the user.
12254 // But, issue any diagnostic on the first declaration only.
12255 if (Previous.empty() && NewFD->isExternC()) {
12256 QualType R = NewFD->getReturnType();
12257 if (R->isIncompleteType() && !R->isVoidType())
12258 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12259 << NewFD << R;
12260 else if (!R.isPODType(Context) && !R->isVoidType() &&
12262 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12263 }
12264
12265 // C++1z [dcl.fct]p6:
12266 // [...] whether the function has a non-throwing exception-specification
12267 // [is] part of the function type
12268 //
12269 // This results in an ABI break between C++14 and C++17 for functions whose
12270 // declared type includes an exception-specification in a parameter or
12271 // return type. (Exception specifications on the function itself are OK in
12272 // most cases, and exception specifications are not permitted in most other
12273 // contexts where they could make it into a mangling.)
12274 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12275 auto HasNoexcept = [&](QualType T) -> bool {
12276 // Strip off declarator chunks that could be between us and a function
12277 // type. We don't need to look far, exception specifications are very
12278 // restricted prior to C++17.
12279 if (auto *RT = T->getAs<ReferenceType>())
12280 T = RT->getPointeeType();
12281 else if (T->isAnyPointerType())
12282 T = T->getPointeeType();
12283 else if (auto *MPT = T->getAs<MemberPointerType>())
12284 T = MPT->getPointeeType();
12285 if (auto *FPT = T->getAs<FunctionProtoType>())
12286 if (FPT->isNothrow())
12287 return true;
12288 return false;
12289 };
12290
12291 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12292 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12293 for (QualType T : FPT->param_types())
12294 AnyNoexcept |= HasNoexcept(T);
12295 if (AnyNoexcept)
12296 Diag(NewFD->getLocation(),
12297 diag::warn_cxx17_compat_exception_spec_in_signature)
12298 << NewFD;
12299 }
12300
12301 if (!Redeclaration && LangOpts.CUDA)
12303 }
12304
12305 // Check if the function definition uses any AArch64 SME features without
12306 // having the '+sme' feature enabled.
12307 if (DeclIsDefn) {
12308 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12309 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12310 bool UsesZA = Attr && Attr->isNewZA();
12311 bool UsesZT0 = Attr && Attr->isNewZT0();
12312 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12313 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12314 UsesSM |=
12320 }
12321
12322 if (UsesSM || UsesZA) {
12323 llvm::StringMap<bool> FeatureMap;
12324 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12325 if (!FeatureMap.contains("sme")) {
12326 if (UsesSM)
12327 Diag(NewFD->getLocation(),
12328 diag::err_sme_definition_using_sm_in_non_sme_target);
12329 else
12330 Diag(NewFD->getLocation(),
12331 diag::err_sme_definition_using_za_in_non_sme_target);
12332 }
12333 }
12334 if (UsesZT0) {
12335 llvm::StringMap<bool> FeatureMap;
12336 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12337 if (!FeatureMap.contains("sme2")) {
12338 Diag(NewFD->getLocation(),
12339 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12340 }
12341 }
12342 }
12343
12344 return Redeclaration;
12345}
12346
12348 // C++11 [basic.start.main]p3:
12349 // A program that [...] declares main to be inline, static or
12350 // constexpr is ill-formed.
12351 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12352 // appear in a declaration of main.
12353 // static main is not an error under C99, but we should warn about it.
12354 // We accept _Noreturn main as an extension.
12355 if (FD->getStorageClass() == SC_Static)
12357 ? diag::err_static_main : diag::warn_static_main)
12359 if (FD->isInlineSpecified())
12360 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12362 if (DS.isNoreturnSpecified()) {
12363 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12364 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12365 Diag(NoreturnLoc, diag::ext_noreturn_main);
12366 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12367 << FixItHint::CreateRemoval(NoreturnRange);
12368 }
12369 if (FD->isConstexpr()) {
12370 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12371 << FD->isConsteval()
12374 }
12375
12376 if (getLangOpts().OpenCL) {
12377 Diag(FD->getLocation(), diag::err_opencl_no_main)
12378 << FD->hasAttr<OpenCLKernelAttr>();
12379 FD->setInvalidDecl();
12380 return;
12381 }
12382
12383 // Functions named main in hlsl are default entries, but don't have specific
12384 // signatures they are required to conform to.
12385 if (getLangOpts().HLSL)
12386 return;
12387
12388 QualType T = FD->getType();
12389 assert(T->isFunctionType() && "function decl is not of function type");
12390 const FunctionType* FT = T->castAs<FunctionType>();
12391
12392 // Set default calling convention for main()
12393 if (FT->getCallConv() != CC_C) {
12395 FD->setType(QualType(FT, 0));
12396 T = Context.getCanonicalType(FD->getType());
12397 }
12398
12399 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12400 // In C with GNU extensions we allow main() to have non-integer return
12401 // type, but we should warn about the extension, and we disable the
12402 // implicit-return-zero rule.
12403
12404 // GCC in C mode accepts qualified 'int'.
12406 FD->setHasImplicitReturnZero(true);
12407 else {
12408 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12409 SourceRange RTRange = FD->getReturnTypeSourceRange();
12410 if (RTRange.isValid())
12411 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12412 << FixItHint::CreateReplacement(RTRange, "int");
12413 }
12414 } else {
12415 // In C and C++, main magically returns 0 if you fall off the end;
12416 // set the flag which tells us that.
12417 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12418
12419 // All the standards say that main() should return 'int'.
12421 FD->setHasImplicitReturnZero(true);
12422 else {
12423 // Otherwise, this is just a flat-out error.
12424 SourceRange RTRange = FD->getReturnTypeSourceRange();
12425 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12426 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12427 : FixItHint());
12428 FD->setInvalidDecl(true);
12429 }
12430 }
12431
12432 // Treat protoless main() as nullary.
12433 if (isa<FunctionNoProtoType>(FT)) return;
12434
12435 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12436 unsigned nparams = FTP->getNumParams();
12437 assert(FD->getNumParams() == nparams);
12438
12439 bool HasExtraParameters = (nparams > 3);
12440
12441 if (FTP->isVariadic()) {
12442 Diag(FD->getLocation(), diag::ext_variadic_main);
12443 // FIXME: if we had information about the location of the ellipsis, we
12444 // could add a FixIt hint to remove it as a parameter.
12445 }
12446
12447 // Darwin passes an undocumented fourth argument of type char**. If
12448 // other platforms start sprouting these, the logic below will start
12449 // getting shifty.
12450 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12451 HasExtraParameters = false;
12452
12453 if (HasExtraParameters) {
12454 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12455 FD->setInvalidDecl(true);
12456 nparams = 3;
12457 }
12458
12459 // FIXME: a lot of the following diagnostics would be improved
12460 // if we had some location information about types.
12461
12462 QualType CharPP =
12464 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12465
12466 for (unsigned i = 0; i < nparams; ++i) {
12467 QualType AT = FTP->getParamType(i);
12468
12469 bool mismatch = true;
12470
12472 mismatch = false;
12473 else if (Expected[i] == CharPP) {
12474 // As an extension, the following forms are okay:
12475 // char const **
12476 // char const * const *
12477 // char * const *
12478
12480 const PointerType* PT;
12481 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12482 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12484 Context.CharTy)) {
12485 qs.removeConst();
12486 mismatch = !qs.empty();
12487 }
12488 }
12489
12490 if (mismatch) {
12491 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12492 // TODO: suggest replacing given type with expected type
12493 FD->setInvalidDecl(true);
12494 }
12495 }
12496
12497 if (nparams == 1 && !FD->isInvalidDecl()) {
12498 Diag(FD->getLocation(), diag::warn_main_one_arg);
12499 }
12500
12501 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12502 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12503 FD->setInvalidDecl();
12504 }
12505}
12506
12507static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12508
12509 // Default calling convention for main and wmain is __cdecl
12510 if (FD->getName() == "main" || FD->getName() == "wmain")
12511 return false;
12512
12513 // Default calling convention for MinGW is __cdecl
12514 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12515 if (T.isWindowsGNUEnvironment())
12516 return false;
12517
12518 // Default calling convention for WinMain, wWinMain and DllMain
12519 // is __stdcall on 32 bit Windows
12520 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12521 return true;
12522
12523 return false;
12524}
12525
12527 QualType T = FD->getType();
12528 assert(T->isFunctionType() && "function decl is not of function type");
12529 const FunctionType *FT = T->castAs<FunctionType>();
12530
12531 // Set an implicit return of 'zero' if the function can return some integral,
12532 // enumeration, pointer or nullptr type.
12536 // DllMain is exempt because a return value of zero means it failed.
12537 if (FD->getName() != "DllMain")
12538 FD->setHasImplicitReturnZero(true);
12539
12540 // Explicity specified calling conventions are applied to MSVC entry points
12541 if (!hasExplicitCallingConv(T)) {
12542 if (isDefaultStdCall(FD, *this)) {
12543 if (FT->getCallConv() != CC_X86StdCall) {
12546 FD->setType(QualType(FT, 0));
12547 }
12548 } else if (FT->getCallConv() != CC_C) {
12551 FD->setType(QualType(FT, 0));
12552 }
12553 }
12554
12555 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12556 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12557 FD->setInvalidDecl();
12558 }
12559}
12560
12563
12565 return;
12566
12567 StringRef Env = TargetInfo.getTriple().getEnvironmentName();
12568 HLSLShaderAttr::ShaderType ShaderType;
12569 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) {
12570 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
12571 // The entry point is already annotated - check that it matches the
12572 // triple.
12573 if (Shader->getType() != ShaderType) {
12574 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
12575 << Shader;
12576 FD->setInvalidDecl();
12577 }
12578 } else {
12579 // Implicitly add the shader attribute if the entry function isn't
12580 // explicitly annotated.
12581 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType,
12582 FD->getBeginLoc()));
12583 }
12584 } else {
12585 switch (TargetInfo.getTriple().getEnvironment()) {
12586 case llvm::Triple::UnknownEnvironment:
12587 case llvm::Triple::Library:
12588 break;
12589 default:
12590 llvm_unreachable("Unhandled environment in triple");
12591 }
12592 }
12593}
12594
12596 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
12597 assert(ShaderAttr && "Entry point has no shader attribute");
12598 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12599
12600 switch (ST) {
12601 case HLSLShaderAttr::Pixel:
12602 case HLSLShaderAttr::Vertex:
12603 case HLSLShaderAttr::Geometry:
12604 case HLSLShaderAttr::Hull:
12605 case HLSLShaderAttr::Domain:
12606 case HLSLShaderAttr::RayGeneration:
12607 case HLSLShaderAttr::Intersection:
12608 case HLSLShaderAttr::AnyHit:
12609 case HLSLShaderAttr::ClosestHit:
12610 case HLSLShaderAttr::Miss:
12611 case HLSLShaderAttr::Callable:
12612 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
12614 {HLSLShaderAttr::Compute,
12615 HLSLShaderAttr::Amplification,
12616 HLSLShaderAttr::Mesh});
12617 FD->setInvalidDecl();
12618 }
12619 break;
12620
12621 case HLSLShaderAttr::Compute:
12622 case HLSLShaderAttr::Amplification:
12623 case HLSLShaderAttr::Mesh:
12624 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12625 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12626 << HLSLShaderAttr::ConvertShaderTypeToStr(ST);
12627 FD->setInvalidDecl();
12628 }
12629 break;
12630 }
12631
12632 for (ParmVarDecl *Param : FD->parameters()) {
12633 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) {
12634 CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr);
12635 } else {
12636 // FIXME: Handle struct parameters where annotations are on struct fields.
12637 // See: https://github.com/llvm/llvm-project/issues/57875
12638 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12639 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12640 FD->setInvalidDecl();
12641 }
12642 }
12643 // FIXME: Verify return type semantic annotation.
12644}
12645
12647 FunctionDecl *EntryPoint, const Decl *Param,
12648 const HLSLAnnotationAttr *AnnotationAttr) {
12649 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
12650 assert(ShaderAttr && "Entry point has no shader attribute");
12651 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12652
12653 switch (AnnotationAttr->getKind()) {
12654 case attr::HLSLSV_DispatchThreadID:
12655 case attr::HLSLSV_GroupIndex:
12656 if (ST == HLSLShaderAttr::Compute)
12657 return;
12658 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST,
12659 {HLSLShaderAttr::Compute});
12660 break;
12661 default:
12662 llvm_unreachable("Unknown HLSLAnnotationAttr");
12663 }
12664}
12665
12667 const Attr *A, HLSLShaderAttr::ShaderType Stage,
12668 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) {
12669 SmallVector<StringRef, 8> StageStrings;
12670 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
12671 [](HLSLShaderAttr::ShaderType ST) {
12672 return StringRef(
12673 HLSLShaderAttr::ConvertShaderTypeToStr(ST));
12674 });
12675 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
12676 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage)
12677 << (AllowedStages.size() != 1) << join(StageStrings, ", ");
12678}
12679
12681 // FIXME: Need strict checking. In C89, we need to check for
12682 // any assignment, increment, decrement, function-calls, or
12683 // commas outside of a sizeof. In C99, it's the same list,
12684 // except that the aforementioned are allowed in unevaluated
12685 // expressions. Everything else falls under the
12686 // "may accept other forms of constant expressions" exception.
12687 //
12688 // Regular C++ code will not end up here (exceptions: language extensions,
12689 // OpenCL C++ etc), so the constant expression rules there don't matter.
12690 if (Init->isValueDependent()) {
12691 assert(Init->containsErrors() &&
12692 "Dependent code should only occur in error-recovery path.");
12693 return true;
12694 }
12695 const Expr *Culprit;
12696 if (Init->isConstantInitializer(Context, false, &Culprit))
12697 return false;
12698 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12699 << Culprit->getSourceRange();
12700 return true;
12701}
12702
12703namespace {
12704 // Visits an initialization expression to see if OrigDecl is evaluated in
12705 // its own initialization and throws a warning if it does.
12706 class SelfReferenceChecker
12707 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12708 Sema &S;
12709 Decl *OrigDecl;
12710 bool isRecordType;
12711 bool isPODType;
12712 bool isReferenceType;
12713
12714 bool isInitList;
12715 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12716
12717 public:
12719
12720 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12721 S(S), OrigDecl(OrigDecl) {
12722 isPODType = false;
12723 isRecordType = false;
12724 isReferenceType = false;
12725 isInitList = false;
12726 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12727 isPODType = VD->getType().isPODType(S.Context);
12728 isRecordType = VD->getType()->isRecordType();
12729 isReferenceType = VD->getType()->isReferenceType();
12730 }
12731 }
12732
12733 // For most expressions, just call the visitor. For initializer lists,
12734 // track the index of the field being initialized since fields are
12735 // initialized in order allowing use of previously initialized fields.
12736 void CheckExpr(Expr *E) {
12737 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12738 if (!InitList) {
12739 Visit(E);
12740 return;
12741 }
12742
12743 // Track and increment the index here.
12744 isInitList = true;
12745 InitFieldIndex.push_back(0);
12746 for (auto *Child : InitList->children()) {
12747 CheckExpr(cast<Expr>(Child));
12748 ++InitFieldIndex.back();
12749 }
12750 InitFieldIndex.pop_back();
12751 }
12752
12753 // Returns true if MemberExpr is checked and no further checking is needed.
12754 // Returns false if additional checking is required.
12755 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12757 Expr *Base = E;
12758 bool ReferenceField = false;
12759
12760 // Get the field members used.
12761 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12762 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12763 if (!FD)
12764 return false;
12765 Fields.push_back(FD);
12766 if (FD->getType()->isReferenceType())
12767 ReferenceField = true;
12768 Base = ME->getBase()->IgnoreParenImpCasts();
12769 }
12770
12771 // Keep checking only if the base Decl is the same.
12772 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12773 if (!DRE || DRE->getDecl() != OrigDecl)
12774 return false;
12775
12776 // A reference field can be bound to an unininitialized field.
12777 if (CheckReference && !ReferenceField)
12778 return true;
12779
12780 // Convert FieldDecls to their index number.
12781 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12782 for (const FieldDecl *I : llvm::reverse(Fields))
12783 UsedFieldIndex.push_back(I->getFieldIndex());
12784
12785 // See if a warning is needed by checking the first difference in index
12786 // numbers. If field being used has index less than the field being
12787 // initialized, then the use is safe.
12788 for (auto UsedIter = UsedFieldIndex.begin(),
12789 UsedEnd = UsedFieldIndex.end(),
12790 OrigIter = InitFieldIndex.begin(),
12791 OrigEnd = InitFieldIndex.end();
12792 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12793 if (*UsedIter < *OrigIter)
12794 return true;
12795 if (*UsedIter > *OrigIter)
12796 break;
12797 }
12798
12799 // TODO: Add a different warning which will print the field names.
12800 HandleDeclRefExpr(DRE);
12801 return true;
12802 }
12803
12804 // For most expressions, the cast is directly above the DeclRefExpr.
12805 // For conditional operators, the cast can be outside the conditional
12806 // operator if both expressions are DeclRefExpr's.
12807 void HandleValue(Expr *E) {
12808 E = E->IgnoreParens();
12809 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12810 HandleDeclRefExpr(DRE);
12811 return;
12812 }
12813
12814 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12815 Visit(CO->getCond());
12816 HandleValue(CO->getTrueExpr());
12817 HandleValue(CO->getFalseExpr());
12818 return;
12819 }
12820
12821 if (BinaryConditionalOperator *BCO =
12822 dyn_cast<BinaryConditionalOperator>(E)) {
12823 Visit(BCO->getCond());
12824 HandleValue(BCO->getFalseExpr());
12825 return;
12826 }
12827
12828 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12829 if (Expr *SE = OVE->getSourceExpr())
12830 HandleValue(SE);
12831 return;
12832 }
12833
12834 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12835 if (BO->getOpcode() == BO_Comma) {
12836 Visit(BO->getLHS());
12837 HandleValue(BO->getRHS());
12838 return;
12839 }
12840 }
12841
12842 if (isa<MemberExpr>(E)) {
12843 if (isInitList) {
12844 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12845 false /*CheckReference*/))
12846 return;
12847 }
12848
12850 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12851 // Check for static member variables and don't warn on them.
12852 if (!isa<FieldDecl>(ME->getMemberDecl()))
12853 return;
12854 Base = ME->getBase()->IgnoreParenImpCasts();
12855 }
12856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12857 HandleDeclRefExpr(DRE);
12858 return;
12859 }
12860
12861 Visit(E);
12862 }
12863
12864 // Reference types not handled in HandleValue are handled here since all
12865 // uses of references are bad, not just r-value uses.
12866 void VisitDeclRefExpr(DeclRefExpr *E) {
12867 if (isReferenceType)
12868 HandleDeclRefExpr(E);
12869 }
12870
12871 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12872 if (E->getCastKind() == CK_LValueToRValue) {
12873 HandleValue(E->getSubExpr());
12874 return;
12875 }
12876
12877 Inherited::VisitImplicitCastExpr(E);
12878 }
12879
12880 void VisitMemberExpr(MemberExpr *E) {
12881 if (isInitList) {
12882 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12883 return;
12884 }
12885
12886 // Don't warn on arrays since they can be treated as pointers.
12887 if (E->getType()->canDecayToPointerType()) return;
12888
12889 // Warn when a non-static method call is followed by non-static member
12890 // field accesses, which is followed by a DeclRefExpr.
12891 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12892 bool Warn = (MD && !MD->isStatic());
12894 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12895 if (!isa<FieldDecl>(ME->getMemberDecl()))
12896 Warn = false;
12897 Base = ME->getBase()->IgnoreParenImpCasts();
12898 }
12899
12900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12901 if (Warn)
12902 HandleDeclRefExpr(DRE);
12903 return;
12904 }
12905
12906 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12907 // Visit that expression.
12908 Visit(Base);
12909 }
12910
12911 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12912 Expr *Callee = E->getCallee();
12913
12914 if (isa<UnresolvedLookupExpr>(Callee))
12915 return Inherited::VisitCXXOperatorCallExpr(E);
12916
12917 Visit(Callee);
12918 for (auto Arg: E->arguments())
12919 HandleValue(Arg->IgnoreParenImpCasts());
12920 }
12921
12922 void VisitUnaryOperator(UnaryOperator *E) {
12923 // For POD record types, addresses of its own members are well-defined.
12924 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12925 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12926 if (!isPODType)
12927 HandleValue(E->getSubExpr());
12928 return;
12929 }
12930
12931 if (E->isIncrementDecrementOp()) {
12932 HandleValue(E->getSubExpr());
12933 return;
12934 }
12935
12936 Inherited::VisitUnaryOperator(E);
12937 }
12938
12939 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12940
12941 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12942 if (E->getConstructor()->isCopyConstructor()) {
12943 Expr *ArgExpr = E->getArg(0);
12944 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12945 if (ILE->getNumInits() == 1)
12946 ArgExpr = ILE->getInit(0);
12947 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12948 if (ICE->getCastKind() == CK_NoOp)
12949 ArgExpr = ICE->getSubExpr();
12950 HandleValue(ArgExpr);
12951 return;
12952 }
12953 Inherited::VisitCXXConstructExpr(E);
12954 }
12955
12956 void VisitCallExpr(CallExpr *E) {
12957 // Treat std::move as a use.
12958 if (E->isCallToStdMove()) {
12959 HandleValue(E->getArg(0));
12960 return;
12961 }
12962
12963 Inherited::VisitCallExpr(E);
12964 }
12965
12966 void VisitBinaryOperator(BinaryOperator *E) {
12967 if (E->isCompoundAssignmentOp()) {
12968 HandleValue(E->getLHS());
12969 Visit(E->getRHS());
12970 return;
12971 }
12972
12973 Inherited::VisitBinaryOperator(E);
12974 }
12975
12976 // A custom visitor for BinaryConditionalOperator is needed because the
12977 // regular visitor would check the condition and true expression separately
12978 // but both point to the same place giving duplicate diagnostics.
12979 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12980 Visit(E->getCond());
12981 Visit(E->getFalseExpr());
12982 }
12983
12984 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12985 Decl* ReferenceDecl = DRE->getDecl();
12986 if (OrigDecl != ReferenceDecl) return;
12987 unsigned diag;
12988 if (isReferenceType) {
12989 diag = diag::warn_uninit_self_reference_in_reference_init;
12990 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12991 diag = diag::warn_static_self_reference_in_init;
12992 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12993 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12994 DRE->getDecl()->getType()->isRecordType()) {
12995 diag = diag::warn_uninit_self_reference_in_init;
12996 } else {
12997 // Local variables will be handled by the CFG analysis.
12998 return;
12999 }
13000
13001 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13002 S.PDiag(diag)
13003 << DRE->getDecl() << OrigDecl->getLocation()
13004 << DRE->getSourceRange());
13005 }
13006 };
13007
13008 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13009 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13010 bool DirectInit) {
13011 // Parameters arguments are occassionially constructed with itself,
13012 // for instance, in recursive functions. Skip them.
13013 if (isa<ParmVarDecl>(OrigDecl))
13014 return;
13015
13016 E = E->IgnoreParens();
13017
13018 // Skip checking T a = a where T is not a record or reference type.
13019 // Doing so is a way to silence uninitialized warnings.
13020 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13021 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13022 if (ICE->getCastKind() == CK_LValueToRValue)
13023 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13024 if (DRE->getDecl() == OrigDecl)
13025 return;
13026
13027 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13028 }
13029} // end anonymous namespace
13030
13031namespace {
13032 // Simple wrapper to add the name of a variable or (if no variable is
13033 // available) a DeclarationName into a diagnostic.
13034 struct VarDeclOrName {
13035 VarDecl *VDecl;
13036 DeclarationName Name;
13037
13038 friend const Sema::SemaDiagnosticBuilder &
13039 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13040 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13041 }
13042 };
13043} // end anonymous namespace
13044
13047 TypeSourceInfo *TSI,
13048 SourceRange Range, bool DirectInit,
13049 Expr *Init) {
13050 bool IsInitCapture = !VDecl;
13051 assert((!VDecl || !VDecl->isInitCapture()) &&
13052 "init captures are expected to be deduced prior to initialization");
13053
13054 VarDeclOrName VN{VDecl, Name};
13055
13057 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13058
13059 // Diagnose auto array declarations in C23, unless it's a supported extension.
13060 if (getLangOpts().C23 && Type->isArrayType() &&
13061 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13062 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13063 << (int)Deduced->getContainedAutoType()->getKeyword()
13064 << /*in array decl*/ 23 << Range;
13065 return QualType();
13066 }
13067
13068 // C++11 [dcl.spec.auto]p3
13069 if (!Init) {
13070 assert(VDecl && "no init for init capture deduction?");
13071
13072 // Except for class argument deduction, and then for an initializing
13073 // declaration only, i.e. no static at class scope or extern.
13074 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
13075 VDecl->hasExternalStorage() ||
13076 VDecl->isStaticDataMember()) {
13077 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13078 << VDecl->getDeclName() << Type;
13079 return QualType();
13080 }
13081 }
13082
13083 ArrayRef<Expr*> DeduceInits;
13084 if (Init)
13085 DeduceInits = Init;
13086
13087 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13088 if (DirectInit && PL)
13089 DeduceInits = PL->exprs();
13090
13091 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
13092 assert(VDecl && "non-auto type for init capture deduction?");
13095 VDecl->getLocation(), DirectInit, Init);
13096 // FIXME: Initialization should not be taking a mutable list of inits.
13097 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
13098 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13099 InitsCopy);
13100 }
13101
13102 if (DirectInit) {
13103 if (auto *IL = dyn_cast<InitListExpr>(Init))
13104 DeduceInits = IL->inits();
13105 }
13106
13107 // Deduction only works if we have exactly one source expression.
13108 if (DeduceInits.empty()) {
13109 // It isn't possible to write this directly, but it is possible to
13110 // end up in this situation with "auto x(some_pack...);"
13111 Diag(Init->getBeginLoc(), IsInitCapture
13112 ? diag::err_init_capture_no_expression
13113 : diag::err_auto_var_init_no_expression)
13114 << VN << Type << Range;
13115 return QualType();
13116 }
13117
13118 if (DeduceInits.size() > 1) {
13119 Diag(DeduceInits[1]->getBeginLoc(),
13120 IsInitCapture ? diag::err_init_capture_multiple_expressions
13121 : diag::err_auto_var_init_multiple_expressions)
13122 << VN << Type << Range;
13123 return QualType();
13124 }
13125
13126 Expr *DeduceInit = DeduceInits[0];
13127 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13128 Diag(Init->getBeginLoc(), IsInitCapture
13129 ? diag::err_init_capture_paren_braces
13130 : diag::err_auto_var_init_paren_braces)
13131 << isa<InitListExpr>(Init) << VN << Type << Range;
13132 return QualType();
13133 }
13134
13135 // Expressions default to 'id' when we're in a debugger.
13136 bool DefaultedAnyToId = false;
13137 if (getLangOpts().DebuggerCastResultToId &&
13138 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13140 if (Result.isInvalid()) {
13141 return QualType();
13142 }
13143 Init = Result.get();
13144 DefaultedAnyToId = true;
13145 }
13146
13147 // C++ [dcl.decomp]p1:
13148 // If the assignment-expression [...] has array type A and no ref-qualifier
13149 // is present, e has type cv A
13150 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13152 DeduceInit->getType()->isConstantArrayType())
13153 return Context.getQualifiedType(DeduceInit->getType(),
13154 Type.getQualifiers());
13155
13157 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13159 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13162 if (!IsInitCapture)
13163 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13164 else if (isa<InitListExpr>(Init))
13165 Diag(Range.getBegin(),
13166 diag::err_init_capture_deduction_failure_from_init_list)
13167 << VN
13168 << (DeduceInit->getType().isNull() ? TSI->getType()
13169 : DeduceInit->getType())
13170 << DeduceInit->getSourceRange();
13171 else
13172 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13173 << VN << TSI->getType()
13174 << (DeduceInit->getType().isNull() ? TSI->getType()
13175 : DeduceInit->getType())
13176 << DeduceInit->getSourceRange();
13177 }
13178
13179 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13180 // 'id' instead of a specific object type prevents most of our usual
13181 // checks.
13182 // We only want to warn outside of template instantiations, though:
13183 // inside a template, the 'id' could have come from a parameter.
13184 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13185 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13186 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13187 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13188 }
13189
13190 return DeducedType;
13191}
13192
13194 Expr *Init) {
13195 assert(!Init || !Init->containsErrors());
13197 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13198 VDecl->getSourceRange(), DirectInit, Init);
13199 if (DeducedType.isNull()) {
13200 VDecl->setInvalidDecl();
13201 return true;
13202 }
13203
13204 VDecl->setType(DeducedType);
13205 assert(VDecl->isLinkageValid());
13206
13207 // In ARC, infer lifetime.
13208 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13209 VDecl->setInvalidDecl();
13210
13211 if (getLangOpts().OpenCL)
13213
13214 // If this is a redeclaration, check that the type we just deduced matches
13215 // the previously declared type.
13216 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13217 // We never need to merge the type, because we cannot form an incomplete
13218 // array of auto, nor deduce such a type.
13219 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13220 }
13221
13222 // Check the deduced type is valid for a variable declaration.
13224 return VDecl->isInvalidDecl();
13225}
13226
13228 SourceLocation Loc) {
13229 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13230 Init = EWC->getSubExpr();
13231
13232 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13233 Init = CE->getSubExpr();
13234
13235 QualType InitType = Init->getType();
13238 "shouldn't be called if type doesn't have a non-trivial C struct");
13239 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13240 for (auto *I : ILE->inits()) {
13241 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13242 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13243 continue;
13244 SourceLocation SL = I->getExprLoc();
13245 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13246 }
13247 return;
13248 }
13249
13250 if (isa<ImplicitValueInitExpr>(Init)) {
13253 NTCUK_Init);
13254 } else {
13255 // Assume all other explicit initializers involving copying some existing
13256 // object.
13257 // TODO: ignore any explicit initializers where we can guarantee
13258 // copy-elision.
13261 }
13262}
13263
13264namespace {
13265
13266bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13267 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13268 // in the source code or implicitly by the compiler if it is in a union
13269 // defined in a system header and has non-trivial ObjC ownership
13270 // qualifications. We don't want those fields to participate in determining
13271 // whether the containing union is non-trivial.
13272 return FD->hasAttr<UnavailableAttr>();
13273}
13274
13275struct DiagNonTrivalCUnionDefaultInitializeVisitor
13276 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13277 void> {
13278 using Super =
13279 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13280 void>;
13281
13282 DiagNonTrivalCUnionDefaultInitializeVisitor(
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::PrimitiveDefaultInitializeKind PDIK, 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(PDIK, 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 << 0 << 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 << 0 << 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 << 0 << 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 << 0 << 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
13334 // The non-trivial C union type or the struct/union type that contains a
13335 // non-trivial C union.
13336 QualType OrigTy;
13337 SourceLocation OrigLoc;
13339 Sema &S;
13340};
13341
13342struct DiagNonTrivalCUnionDestructedTypeVisitor
13343 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13344 using Super =
13346
13347 DiagNonTrivalCUnionDestructedTypeVisitor(
13348 QualType OrigTy, SourceLocation OrigLoc,
13349 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13350 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13351
13352 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13353 const FieldDecl *FD, bool InNonTrivialUnion) {
13354 if (const auto *AT = S.Context.getAsArrayType(QT))
13355 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13356 InNonTrivialUnion);
13357 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13358 }
13359
13360 void visitARCStrong(QualType QT, const FieldDecl *FD,
13361 bool InNonTrivialUnion) {
13362 if (InNonTrivialUnion)
13363 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13364 << 1 << 1 << QT << FD->getName();
13365 }
13366
13367 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13368 if (InNonTrivialUnion)
13369 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13370 << 1 << 1 << QT << FD->getName();
13371 }
13372
13373 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13374 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13375 if (RD->isUnion()) {
13376 if (OrigLoc.isValid()) {
13377 bool IsUnion = false;
13378 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13379 IsUnion = OrigRD->isUnion();
13380 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13381 << 1 << OrigTy << IsUnion << UseContext;
13382 // Reset OrigLoc so that this diagnostic is emitted only once.
13383 OrigLoc = SourceLocation();
13384 }
13385 InNonTrivialUnion = true;
13386 }
13387
13388 if (InNonTrivialUnion)
13389 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13390 << 0 << 1 << QT.getUnqualifiedType() << "";
13391
13392 for (const FieldDecl *FD : RD->fields())
13393 if (!shouldIgnoreForRecordTriviality(FD))
13394 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13395 }
13396
13397 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13398 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13399 bool InNonTrivialUnion) {}
13400
13401 // The non-trivial C union type or the struct/union type that contains a
13402 // non-trivial C union.
13403 QualType OrigTy;
13404 SourceLocation OrigLoc;
13406 Sema &S;
13407};
13408
13409struct DiagNonTrivalCUnionCopyVisitor
13410 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13412
13413 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13415 Sema &S)
13416 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13417
13418 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13419 const FieldDecl *FD, bool InNonTrivialUnion) {
13420 if (const auto *AT = S.Context.getAsArrayType(QT))
13421 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13422 InNonTrivialUnion);
13423 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13424 }
13425
13426 void visitARCStrong(QualType QT, const FieldDecl *FD,
13427 bool InNonTrivialUnion) {
13428 if (InNonTrivialUnion)
13429 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13430 << 1 << 2 << QT << FD->getName();
13431 }
13432
13433 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13434 if (InNonTrivialUnion)
13435 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13436 << 1 << 2 << QT << FD->getName();
13437 }
13438
13439 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13440 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13441 if (RD->isUnion()) {
13442 if (OrigLoc.isValid()) {
13443 bool IsUnion = false;
13444 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13445 IsUnion = OrigRD->isUnion();
13446 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13447 << 2 << OrigTy << IsUnion << UseContext;
13448 // Reset OrigLoc so that this diagnostic is emitted only once.
13449 OrigLoc = SourceLocation();
13450 }
13451 InNonTrivialUnion = true;
13452 }
13453
13454 if (InNonTrivialUnion)
13455 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13456 << 0 << 2 << QT.getUnqualifiedType() << "";
13457
13458 for (const FieldDecl *FD : RD->fields())
13459 if (!shouldIgnoreForRecordTriviality(FD))
13460 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13461 }
13462
13463 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13464 const FieldDecl *FD, bool InNonTrivialUnion) {}
13465 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13466 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13467 bool InNonTrivialUnion) {}
13468
13469 // The non-trivial C union type or the struct/union type that contains a
13470 // non-trivial C union.
13471 QualType OrigTy;
13472 SourceLocation OrigLoc;
13474 Sema &S;
13475};
13476
13477} // namespace
13478
13480 NonTrivialCUnionContext UseContext,
13481 unsigned NonTrivialKind) {
13485 "shouldn't be called if type doesn't have a non-trivial C union");
13486
13487 if ((NonTrivialKind & NTCUK_Init) &&
13489 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13490 .visit(QT, nullptr, false);
13491 if ((NonTrivialKind & NTCUK_Destruct) &&
13493 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13494 .visit(QT, nullptr, false);
13495 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13496 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13497 .visit(QT, nullptr, false);
13498}
13499
13500/// AddInitializerToDecl - Adds the initializer Init to the
13501/// declaration dcl. If DirectInit is true, this is C++ direct
13502/// initialization rather than copy initialization.
13504 // If there is no declaration, there was an error parsing it. Just ignore
13505 // the initializer.
13506 if (!RealDecl || RealDecl->isInvalidDecl()) {
13507 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13508 return;
13509 }
13510
13511 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13512 // Pure-specifiers are handled in ActOnPureSpecifier.
13513 Diag(Method->getLocation(), diag::err_member_function_initialization)
13514 << Method->getDeclName() << Init->getSourceRange();
13515 Method->setInvalidDecl();
13516 return;
13517 }
13518
13519 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13520 if (!VDecl) {
13521 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13522 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13523 RealDecl->setInvalidDecl();
13524 return;
13525 }
13526
13527 // WebAssembly tables can't be used to initialise a variable.
13528 if (Init && !Init->getType().isNull() &&
13529 Init->getType()->isWebAssemblyTableType()) {
13530 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13531 VDecl->setInvalidDecl();
13532 return;
13533 }
13534
13535 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13536 if (VDecl->getType()->isUndeducedType()) {
13537 // Attempt typo correction early so that the type of the init expression can
13538 // be deduced based on the chosen correction if the original init contains a
13539 // TypoExpr.
13541 if (!Res.isUsable()) {
13542 // There are unresolved typos in Init, just drop them.
13543 // FIXME: improve the recovery strategy to preserve the Init.
13544 RealDecl->setInvalidDecl();
13545 return;
13546 }
13547 if (Res.get()->containsErrors()) {
13548 // Invalidate the decl as we don't know the type for recovery-expr yet.
13549 RealDecl->setInvalidDecl();
13550 VDecl->setInit(Res.get());
13551 return;
13552 }
13553 Init = Res.get();
13554
13556 return;
13557 }
13558
13559 // dllimport cannot be used on variable definitions.
13560 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13561 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13562 VDecl->setInvalidDecl();
13563 return;
13564 }
13565
13566 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13567 // the identifier has external or internal linkage, the declaration shall
13568 // have no initializer for the identifier.
13569 // C++14 [dcl.init]p5 is the same restriction for C++.
13570 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13571 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13572 VDecl->setInvalidDecl();
13573 return;
13574 }
13575
13576 if (!VDecl->getType()->isDependentType()) {
13577 // A definition must end up with a complete type, which means it must be
13578 // complete with the restriction that an array type might be completed by
13579 // the initializer; note that later code assumes this restriction.
13580 QualType BaseDeclType = VDecl->getType();
13581 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13582 BaseDeclType = Array->getElementType();
13583 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13584 diag::err_typecheck_decl_incomplete_type)) {
13585 RealDecl->setInvalidDecl();
13586 return;
13587 }
13588
13589 // The variable can not have an abstract class type.
13590 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13591 diag::err_abstract_type_in_decl,
13593 VDecl->setInvalidDecl();
13594 }
13595
13596 // C++ [module.import/6] external definitions are not permitted in header
13597 // units.
13598 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13599 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13600 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13601 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13602 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13603 VDecl->setInvalidDecl();
13604 }
13605
13606 // If adding the initializer will turn this declaration into a definition,
13607 // and we already have a definition for this variable, diagnose or otherwise
13608 // handle the situation.
13609 if (VarDecl *Def = VDecl->getDefinition())
13610 if (Def != VDecl &&
13611 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13613 checkVarDeclRedefinition(Def, VDecl))
13614 return;
13615
13616 if (getLangOpts().CPlusPlus) {
13617 // C++ [class.static.data]p4
13618 // If a static data member is of const integral or const
13619 // enumeration type, its declaration in the class definition can
13620 // specify a constant-initializer which shall be an integral
13621 // constant expression (5.19). In that case, the member can appear
13622 // in integral constant expressions. The member shall still be
13623 // defined in a namespace scope if it is used in the program and the
13624 // namespace scope definition shall not contain an initializer.
13625 //
13626 // We already performed a redefinition check above, but for static
13627 // data members we also need to check whether there was an in-class
13628 // declaration with an initializer.
13629 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13630 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13631 << VDecl->getDeclName();
13632 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13633 diag::note_previous_initializer)
13634 << 0;
13635 return;
13636 }
13637
13638 if (VDecl->hasLocalStorage())
13640
13642 VDecl->setInvalidDecl();
13643 return;
13644 }
13645 }
13646
13647 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13648 // a kernel function cannot be initialized."
13649 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13650 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13651 VDecl->setInvalidDecl();
13652 return;
13653 }
13654
13655 // The LoaderUninitialized attribute acts as a definition (of undef).
13656 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13657 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13658 VDecl->setInvalidDecl();
13659 return;
13660 }
13661
13662 // Get the decls type and save a reference for later, since
13663 // CheckInitializerTypes may change it.
13664 QualType DclT = VDecl->getType(), SavT = DclT;
13665
13666 // Expressions default to 'id' when we're in a debugger
13667 // and we are assigning it to a variable of Objective-C pointer type.
13668 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13669 Init->getType() == Context.UnknownAnyTy) {
13671 if (Result.isInvalid()) {
13672 VDecl->setInvalidDecl();
13673 return;
13674 }
13675 Init = Result.get();
13676 }
13677
13678 // Perform the initialization.
13679 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13680 bool IsParenListInit = false;
13681 if (!VDecl->isInvalidDecl()) {
13684 VDecl->getLocation(), DirectInit, Init);
13685
13686 MultiExprArg Args = Init;
13687 if (CXXDirectInit)
13688 Args = MultiExprArg(CXXDirectInit->getExprs(),
13689 CXXDirectInit->getNumExprs());
13690
13691 // Try to correct any TypoExprs in the initialization arguments.
13692 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13694 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13695 [this, Entity, Kind](Expr *E) {
13696 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13697 return Init.Failed() ? ExprError() : E;
13698 });
13699 if (Res.isInvalid()) {
13700 VDecl->setInvalidDecl();
13701 } else if (Res.get() != Args[Idx]) {
13702 Args[Idx] = Res.get();
13703 }
13704 }
13705 if (VDecl->isInvalidDecl())
13706 return;
13707
13708 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13709 /*TopLevelOfInitList=*/false,
13710 /*TreatUnavailableAsInvalid=*/false);
13711 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13712 if (Result.isInvalid()) {
13713 // If the provided initializer fails to initialize the var decl,
13714 // we attach a recovery expr for better recovery.
13715 auto RecoveryExpr =
13716 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13717 if (RecoveryExpr.get())
13718 VDecl->setInit(RecoveryExpr.get());
13719 // In general, for error recovery purposes, the initalizer doesn't play
13720 // part in the valid bit of the declaration. There are a few exceptions:
13721 // 1) if the var decl has a deduced auto type, and the type cannot be
13722 // deduced by an invalid initializer;
13723 // 2) if the var decl is decompsition decl with a non-deduced type, and
13724 // the initialization fails (e.g. `int [a] = {1, 2};`);
13725 // Case 1) was already handled elsewhere.
13726 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13727 VDecl->setInvalidDecl();
13728 return;
13729 }
13730
13731 Init = Result.getAs<Expr>();
13732 IsParenListInit = !InitSeq.steps().empty() &&
13733 InitSeq.step_begin()->Kind ==
13735 QualType VDeclType = VDecl->getType();
13736 if (Init && !Init->getType().isNull() &&
13737 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13738 Context.getAsIncompleteArrayType(VDeclType) &&
13740 // Bail out if it is not possible to deduce array size from the
13741 // initializer.
13742 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13743 << VDeclType;
13744 VDecl->setInvalidDecl();
13745 return;
13746 }
13747 }
13748
13749 // Check for self-references within variable initializers.
13750 // Variables declared within a function/method body (except for references)
13751 // are handled by a dataflow analysis.
13752 // This is undefined behavior in C++, but valid in C.
13753 if (getLangOpts().CPlusPlus)
13754 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13755 VDecl->getType()->isReferenceType())
13756 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13757
13758 // If the type changed, it means we had an incomplete type that was
13759 // completed by the initializer. For example:
13760 // int ary[] = { 1, 3, 5 };
13761 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13762 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13763 VDecl->setType(DclT);
13764
13765 if (!VDecl->isInvalidDecl()) {
13766 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13767
13768 if (VDecl->hasAttr<BlocksAttr>())
13769 checkRetainCycles(VDecl, Init);
13770
13771 // It is safe to assign a weak reference into a strong variable.
13772 // Although this code can still have problems:
13773 // id x = self.weakProp;
13774 // id y = self.weakProp;
13775 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13776 // paths through the function. This should be revisited if
13777 // -Wrepeated-use-of-weak is made flow-sensitive.
13778 if (FunctionScopeInfo *FSI = getCurFunction())
13779 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13781 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13782 Init->getBeginLoc()))
13783 FSI->markSafeWeakUse(Init);
13784 }
13785
13786 // The initialization is usually a full-expression.
13787 //
13788 // FIXME: If this is a braced initialization of an aggregate, it is not
13789 // an expression, and each individual field initializer is a separate
13790 // full-expression. For instance, in:
13791 //
13792 // struct Temp { ~Temp(); };
13793 // struct S { S(Temp); };
13794 // struct T { S a, b; } t = { Temp(), Temp() }
13795 //
13796 // we should destroy the first Temp before constructing the second.
13799 /*DiscardedValue*/ false, VDecl->isConstexpr());
13800 if (Result.isInvalid()) {
13801 VDecl->setInvalidDecl();
13802 return;
13803 }
13804 Init = Result.get();
13805
13806 // Attach the initializer to the decl.
13807 VDecl->setInit(Init);
13808
13809 if (VDecl->isLocalVarDecl()) {
13810 // Don't check the initializer if the declaration is malformed.
13811 if (VDecl->isInvalidDecl()) {
13812 // do nothing
13813
13814 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13815 // This is true even in C++ for OpenCL.
13816 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13818
13819 // Otherwise, C++ does not restrict the initializer.
13820 } else if (getLangOpts().CPlusPlus) {
13821 // do nothing
13822
13823 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13824 // static storage duration shall be constant expressions or string literals.
13825 } else if (VDecl->getStorageClass() == SC_Static) {
13827
13828 // C89 is stricter than C99 for aggregate initializers.
13829 // C89 6.5.7p3: All the expressions [...] in an initializer list
13830 // for an object that has aggregate or union type shall be
13831 // constant expressions.
13832 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13833 isa<InitListExpr>(Init)) {
13834 const Expr *Culprit;
13835 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13836 Diag(Culprit->getExprLoc(),
13837 diag::ext_aggregate_init_not_constant)
13838 << Culprit->getSourceRange();
13839 }
13840 }
13841
13842 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13843 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13844 if (VDecl->hasLocalStorage())
13845 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13846 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13847 VDecl->getLexicalDeclContext()->isRecord()) {
13848 // This is an in-class initialization for a static data member, e.g.,
13849 //
13850 // struct S {
13851 // static const int value = 17;
13852 // };
13853
13854 // C++ [class.mem]p4:
13855 // A member-declarator can contain a constant-initializer only
13856 // if it declares a static member (9.4) of const integral or
13857 // const enumeration type, see 9.4.2.
13858 //
13859 // C++11 [class.static.data]p3:
13860 // If a non-volatile non-inline const static data member is of integral
13861 // or enumeration type, its declaration in the class definition can
13862 // specify a brace-or-equal-initializer in which every initializer-clause
13863 // that is an assignment-expression is a constant expression. A static
13864 // data member of literal type can be declared in the class definition
13865 // with the constexpr specifier; if so, its declaration shall specify a
13866 // brace-or-equal-initializer in which every initializer-clause that is
13867 // an assignment-expression is a constant expression.
13868
13869 // Do nothing on dependent types.
13870 if (DclT->isDependentType()) {
13871
13872 // Allow any 'static constexpr' members, whether or not they are of literal
13873 // type. We separately check that every constexpr variable is of literal
13874 // type.
13875 } else if (VDecl->isConstexpr()) {
13876
13877 // Require constness.
13878 } else if (!DclT.isConstQualified()) {
13879 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13880 << Init->getSourceRange();
13881 VDecl->setInvalidDecl();
13882
13883 // We allow integer constant expressions in all cases.
13884 } else if (DclT->isIntegralOrEnumerationType()) {
13885 // Check whether the expression is a constant expression.
13886 SourceLocation Loc;
13888 // In C++11, a non-constexpr const static data member with an
13889 // in-class initializer cannot be volatile.
13890 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13891 else if (Init->isValueDependent())
13892 ; // Nothing to check.
13893 else if (Init->isIntegerConstantExpr(Context, &Loc))
13894 ; // Ok, it's an ICE!
13895 else if (Init->getType()->isScopedEnumeralType() &&
13896 Init->isCXX11ConstantExpr(Context))
13897 ; // Ok, it is a scoped-enum constant expression.
13898 else if (Init->isEvaluatable(Context)) {
13899 // If we can constant fold the initializer through heroics, accept it,
13900 // but report this as a use of an extension for -pedantic.
13901 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13902 << Init->getSourceRange();
13903 } else {
13904 // Otherwise, this is some crazy unknown case. Report the issue at the
13905 // location provided by the isIntegerConstantExpr failed check.
13906 Diag(Loc, diag::err_in_class_initializer_non_constant)
13907 << Init->getSourceRange();
13908 VDecl->setInvalidDecl();
13909 }
13910
13911 // We allow foldable floating-point constants as an extension.
13912 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13913 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13914 // it anyway and provide a fixit to add the 'constexpr'.
13915 if (getLangOpts().CPlusPlus11) {
13916 Diag(VDecl->getLocation(),
13917 diag::ext_in_class_initializer_float_type_cxx11)
13918 << DclT << Init->getSourceRange();
13919 Diag(VDecl->getBeginLoc(),
13920 diag::note_in_class_initializer_float_type_cxx11)
13921 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13922 } else {
13923 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13924 << DclT << Init->getSourceRange();
13925
13926 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13927 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13928 << Init->getSourceRange();
13929 VDecl->setInvalidDecl();
13930 }
13931 }
13932
13933 // Suggest adding 'constexpr' in C++11 for literal types.
13934 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13935 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13936 << DclT << Init->getSourceRange()
13937 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13938 VDecl->setConstexpr(true);
13939
13940 } else {
13941 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13942 << DclT << Init->getSourceRange();
13943 VDecl->setInvalidDecl();
13944 }
13945 } else if (VDecl->isFileVarDecl()) {
13946 // In C, extern is typically used to avoid tentative definitions when
13947 // declaring variables in headers, but adding an intializer makes it a
13948 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13949 // In C++, extern is often used to give implictly static const variables
13950 // external linkage, so don't warn in that case. If selectany is present,
13951 // this might be header code intended for C and C++ inclusion, so apply the
13952 // C++ rules.
13953 if (VDecl->getStorageClass() == SC_Extern &&
13954 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13956 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13958 Diag(VDecl->getLocation(), diag::warn_extern_init);
13959
13960 // In Microsoft C++ mode, a const variable defined in namespace scope has
13961 // external linkage by default if the variable is declared with
13962 // __declspec(dllexport).
13965 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13966 VDecl->setStorageClass(SC_Extern);
13967
13968 // C99 6.7.8p4. All file scoped initializers need to be constant.
13969 // Avoid duplicate diagnostics for constexpr variables.
13970 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13971 !VDecl->isConstexpr())
13973 }
13974
13975 QualType InitType = Init->getType();
13976 if (!InitType.isNull() &&
13980
13981 // We will represent direct-initialization similarly to copy-initialization:
13982 // int x(1); -as-> int x = 1;
13983 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13984 //
13985 // Clients that want to distinguish between the two forms, can check for
13986 // direct initializer using VarDecl::getInitStyle().
13987 // A major benefit is that clients that don't particularly care about which
13988 // exactly form was it (like the CodeGen) can handle both cases without
13989 // special case code.
13990
13991 // C++ 8.5p11:
13992 // The form of initialization (using parentheses or '=') is generally
13993 // insignificant, but does matter when the entity being initialized has a
13994 // class type.
13995 if (CXXDirectInit) {
13996 assert(DirectInit && "Call-style initializer must be direct init.");
13997 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13999 } else if (DirectInit) {
14000 // This must be list-initialization. No other way is direct-initialization.
14002 }
14003
14004 if (LangOpts.OpenMP &&
14005 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14006 VDecl->isFileVarDecl())
14007 DeclsToCheckForDeferredDiags.insert(VDecl);
14009}
14010
14011/// ActOnInitializerError - Given that there was an error parsing an
14012/// initializer for the given declaration, try to at least re-establish
14013/// invariants such as whether a variable's type is either dependent or
14014/// complete.
14016 // Our main concern here is re-establishing invariants like "a
14017 // variable's type is either dependent or complete".
14018 if (!D || D->isInvalidDecl()) return;
14019
14020 VarDecl *VD = dyn_cast<VarDecl>(D);
14021 if (!VD) return;
14022
14023 // Bindings are not usable if we can't make sense of the initializer.
14024 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14025 for (auto *BD : DD->bindings())
14026 BD->setInvalidDecl();
14027
14028 // Auto types are meaningless if we can't make sense of the initializer.
14029 if (VD->getType()->isUndeducedType()) {
14030 D->setInvalidDecl();
14031 return;
14032 }
14033
14034 QualType Ty = VD->getType();
14035 if (Ty->isDependentType()) return;
14036
14037 // Require a complete type.
14040 diag::err_typecheck_decl_incomplete_type)) {
14041 VD->setInvalidDecl();
14042 return;
14043 }
14044
14045 // Require a non-abstract type.
14046 if (RequireNonAbstractType(VD->getLocation(), Ty,
14047 diag::err_abstract_type_in_decl,
14049 VD->setInvalidDecl();
14050 return;
14051 }
14052
14053 // Don't bother complaining about constructors or destructors,
14054 // though.
14055}
14056
14058 // If there is no declaration, there was an error parsing it. Just ignore it.
14059 if (!RealDecl)
14060 return;
14061
14062 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14063 QualType Type = Var->getType();
14064
14065 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14066 if (isa<DecompositionDecl>(RealDecl)) {
14067 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14068 Var->setInvalidDecl();
14069 return;
14070 }
14071
14072 if (Type->isUndeducedType() &&
14073 DeduceVariableDeclarationType(Var, false, nullptr))
14074 return;
14075
14076 // C++11 [class.static.data]p3: A static data member can be declared with
14077 // the constexpr specifier; if so, its declaration shall specify
14078 // a brace-or-equal-initializer.
14079 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14080 // the definition of a variable [...] or the declaration of a static data
14081 // member.
14082 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14083 !Var->isThisDeclarationADemotedDefinition()) {
14084 if (Var->isStaticDataMember()) {
14085 // C++1z removes the relevant rule; the in-class declaration is always
14086 // a definition there.
14087 if (!getLangOpts().CPlusPlus17 &&
14089 Diag(Var->getLocation(),
14090 diag::err_constexpr_static_mem_var_requires_init)
14091 << Var;
14092 Var->setInvalidDecl();
14093 return;
14094 }
14095 } else {
14096 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14097 Var->setInvalidDecl();
14098 return;
14099 }
14100 }
14101
14102 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14103 // be initialized.
14104 if (!Var->isInvalidDecl() &&
14105 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14106 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14107 bool HasConstExprDefaultConstructor = false;
14108 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14109 for (auto *Ctor : RD->ctors()) {
14110 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14111 Ctor->getMethodQualifiers().getAddressSpace() ==
14113 HasConstExprDefaultConstructor = true;
14114 }
14115 }
14116 }
14117 if (!HasConstExprDefaultConstructor) {
14118 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14119 Var->setInvalidDecl();
14120 return;
14121 }
14122 }
14123
14124 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14125 if (Var->getStorageClass() == SC_Extern) {
14126 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14127 << Var;
14128 Var->setInvalidDecl();
14129 return;
14130 }
14131 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14132 diag::err_typecheck_decl_incomplete_type)) {
14133 Var->setInvalidDecl();
14134 return;
14135 }
14136 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14137 if (!RD->hasTrivialDefaultConstructor()) {
14138 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14139 Var->setInvalidDecl();
14140 return;
14141 }
14142 }
14143 // The declaration is unitialized, no need for further checks.
14144 return;
14145 }
14146
14147 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14148 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14149 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14150 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14152
14153
14154 switch (DefKind) {
14156 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14157 break;
14158
14159 // We have an out-of-line definition of a static data member
14160 // that has an in-class initializer, so we type-check this like
14161 // a declaration.
14162 //
14163 [[fallthrough]];
14164
14166 // It's only a declaration.
14167
14168 // Block scope. C99 6.7p7: If an identifier for an object is
14169 // declared with no linkage (C99 6.2.2p6), the type for the
14170 // object shall be complete.
14171 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14172 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14173 RequireCompleteType(Var->getLocation(), Type,
14174 diag::err_typecheck_decl_incomplete_type))
14175 Var->setInvalidDecl();
14176
14177 // Make sure that the type is not abstract.
14178 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14179 RequireNonAbstractType(Var->getLocation(), Type,
14180 diag::err_abstract_type_in_decl,
14182 Var->setInvalidDecl();
14183 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14184 Var->getStorageClass() == SC_PrivateExtern) {
14185 Diag(Var->getLocation(), diag::warn_private_extern);
14186 Diag(Var->getLocation(), diag::note_private_extern);
14187 }
14188
14190 !Var->isInvalidDecl())
14191 ExternalDeclarations.push_back(Var);
14192
14193 return;
14194
14196 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14197 // object that has file scope without an initializer, and without a
14198 // storage-class specifier or with the storage-class specifier "static",
14199 // constitutes a tentative definition. Note: A tentative definition with
14200 // external linkage is valid (C99 6.2.2p5).
14201 if (!Var->isInvalidDecl()) {
14202 if (const IncompleteArrayType *ArrayT
14205 Var->getLocation(), ArrayT->getElementType(),
14206 diag::err_array_incomplete_or_sizeless_type))
14207 Var->setInvalidDecl();
14208 } else if (Var->getStorageClass() == SC_Static) {
14209 // C99 6.9.2p3: If the declaration of an identifier for an object is
14210 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14211 // declared type shall not be an incomplete type.
14212 // NOTE: code such as the following
14213 // static struct s;
14214 // struct s { int a; };
14215 // is accepted by gcc. Hence here we issue a warning instead of
14216 // an error and we do not invalidate the static declaration.
14217 // NOTE: to avoid multiple warnings, only check the first declaration.
14218 if (Var->isFirstDecl())
14219 RequireCompleteType(Var->getLocation(), Type,
14220 diag::ext_typecheck_decl_incomplete_type);
14221 }
14222 }
14223
14224 // Record the tentative definition; we're done.
14225 if (!Var->isInvalidDecl())
14227 return;
14228 }
14229
14230 // Provide a specific diagnostic for uninitialized variable
14231 // definitions with incomplete array type.
14232 if (Type->isIncompleteArrayType()) {
14233 if (Var->isConstexpr())
14234 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14235 << Var;
14236 else
14237 Diag(Var->getLocation(),
14238 diag::err_typecheck_incomplete_array_needs_initializer);
14239 Var->setInvalidDecl();
14240 return;
14241 }
14242
14243 // Provide a specific diagnostic for uninitialized variable
14244 // definitions with reference type.
14245 if (Type->isReferenceType()) {
14246 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14247 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14248 return;
14249 }
14250
14251 // Do not attempt to type-check the default initializer for a
14252 // variable with dependent type.
14253 if (Type->isDependentType())
14254 return;
14255
14256 if (Var->isInvalidDecl())
14257 return;
14258
14259 if (!Var->hasAttr<AliasAttr>()) {
14260 if (RequireCompleteType(Var->getLocation(),
14262 diag::err_typecheck_decl_incomplete_type)) {
14263 Var->setInvalidDecl();
14264 return;
14265 }
14266 } else {
14267 return;
14268 }
14269
14270 // The variable can not have an abstract class type.
14271 if (RequireNonAbstractType(Var->getLocation(), Type,
14272 diag::err_abstract_type_in_decl,
14274 Var->setInvalidDecl();
14275 return;
14276 }
14277
14278 // Check for jumps past the implicit initializer. C++0x
14279 // clarifies that this applies to a "variable with automatic
14280 // storage duration", not a "local variable".
14281 // C++11 [stmt.dcl]p3
14282 // A program that jumps from a point where a variable with automatic
14283 // storage duration is not in scope to a point where it is in scope is
14284 // ill-formed unless the variable has scalar type, class type with a
14285 // trivial default constructor and a trivial destructor, a cv-qualified
14286 // version of one of these types, or an array of one of the preceding
14287 // types and is declared without an initializer.
14288 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14289 if (const RecordType *Record
14291 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14292 // Mark the function (if we're in one) for further checking even if the
14293 // looser rules of C++11 do not require such checks, so that we can
14294 // diagnose incompatibilities with C++98.
14295 if (!CXXRecord->isPOD())
14297 }
14298 }
14299 // In OpenCL, we can't initialize objects in the __local address space,
14300 // even implicitly, so don't synthesize an implicit initializer.
14301 if (getLangOpts().OpenCL &&
14302 Var->getType().getAddressSpace() == LangAS::opencl_local)
14303 return;
14304 // C++03 [dcl.init]p9:
14305 // If no initializer is specified for an object, and the
14306 // object is of (possibly cv-qualified) non-POD class type (or
14307 // array thereof), the object shall be default-initialized; if
14308 // the object is of const-qualified type, the underlying class
14309 // type shall have a user-declared default
14310 // constructor. Otherwise, if no initializer is specified for
14311 // a non- static object, the object and its subobjects, if
14312 // any, have an indeterminate initial value); if the object
14313 // or any of its subobjects are of const-qualified type, the
14314 // program is ill-formed.
14315 // C++0x [dcl.init]p11:
14316 // If no initializer is specified for an object, the object is
14317 // default-initialized; [...].
14320 = InitializationKind::CreateDefault(Var->getLocation());
14321
14322 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14323 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14324
14325 if (Init.get()) {
14326 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14327 // This is important for template substitution.
14328 Var->setInitStyle(VarDecl::CallInit);
14329 } else if (Init.isInvalid()) {
14330 // If default-init fails, attach a recovery-expr initializer to track
14331 // that initialization was attempted and failed.
14332 auto RecoveryExpr =
14333 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14334 if (RecoveryExpr.get())
14335 Var->setInit(RecoveryExpr.get());
14336 }
14337
14339 }
14340}
14341
14343 // If there is no declaration, there was an error parsing it. Ignore it.
14344 if (!D)
14345 return;
14346
14347 VarDecl *VD = dyn_cast<VarDecl>(D);
14348 if (!VD) {
14349 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14350 D->setInvalidDecl();
14351 return;
14352 }
14353
14354 VD->setCXXForRangeDecl(true);
14355
14356 // for-range-declaration cannot be given a storage class specifier.
14357 int Error = -1;
14358 switch (VD->getStorageClass()) {
14359 case SC_None:
14360 break;
14361 case SC_Extern:
14362 Error = 0;
14363 break;
14364 case SC_Static:
14365 Error = 1;
14366 break;
14367 case SC_PrivateExtern:
14368 Error = 2;
14369 break;
14370 case SC_Auto:
14371 Error = 3;
14372 break;
14373 case SC_Register:
14374 Error = 4;
14375 break;
14376 }
14377
14378 // for-range-declaration cannot be given a storage class specifier con't.
14379 switch (VD->getTSCSpec()) {
14380 case TSCS_thread_local:
14381 Error = 6;
14382 break;
14383 case TSCS___thread:
14384 case TSCS__Thread_local:
14385 case TSCS_unspecified:
14386 break;
14387 }
14388
14389 if (Error != -1) {
14390 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14391 << VD << Error;
14392 D->setInvalidDecl();
14393 }
14394}
14395
14397 IdentifierInfo *Ident,
14398 ParsedAttributes &Attrs) {
14399 // C++1y [stmt.iter]p1:
14400 // A range-based for statement of the form
14401 // for ( for-range-identifier : for-range-initializer ) statement
14402 // is equivalent to
14403 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14404 DeclSpec DS(Attrs.getPool().getFactory());
14405
14406 const char *PrevSpec;
14407 unsigned DiagID;
14408 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14410
14412 D.SetIdentifier(Ident, IdentLoc);
14413 D.takeAttributes(Attrs);
14414
14415 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14416 IdentLoc);
14417 Decl *Var = ActOnDeclarator(S, D);
14418 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14420 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14421 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14422 : IdentLoc);
14423}
14424
14426 if (var->isInvalidDecl()) return;
14427
14429
14430 if (getLangOpts().OpenCL) {
14431 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14432 // initialiser
14433 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14434 !var->hasInit()) {
14435 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14436 << 1 /*Init*/;
14437 var->setInvalidDecl();
14438 return;
14439 }
14440 }
14441
14442 // In Objective-C, don't allow jumps past the implicit initialization of a
14443 // local retaining variable.
14444 if (getLangOpts().ObjC &&
14445 var->hasLocalStorage()) {
14446 switch (var->getType().getObjCLifetime()) {
14450 break;
14451
14455 break;
14456 }
14457 }
14458
14459 if (var->hasLocalStorage() &&
14462
14463 // Warn about externally-visible variables being defined without a
14464 // prior declaration. We only want to do this for global
14465 // declarations, but we also specifically need to avoid doing it for
14466 // class members because the linkage of an anonymous class can
14467 // change if it's later given a typedef name.
14468 if (var->isThisDeclarationADefinition() &&
14470 var->isExternallyVisible() && var->hasLinkage() &&
14471 !var->isInline() && !var->getDescribedVarTemplate() &&
14472 var->getStorageClass() != SC_Register &&
14473 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14475 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14476 var->getLocation())) {
14477 // Find a previous declaration that's not a definition.
14478 VarDecl *prev = var->getPreviousDecl();
14479 while (prev && prev->isThisDeclarationADefinition())
14480 prev = prev->getPreviousDecl();
14481
14482 if (!prev) {
14483 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14484 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14485 << /* variable */ 0;
14486 }
14487 }
14488
14489 // Cache the result of checking for constant initialization.
14490 std::optional<bool> CacheHasConstInit;
14491 const Expr *CacheCulprit = nullptr;
14492 auto checkConstInit = [&]() mutable {
14493 if (!CacheHasConstInit)
14494 CacheHasConstInit = var->getInit()->isConstantInitializer(
14495 Context, var->getType()->isReferenceType(), &CacheCulprit);
14496 return *CacheHasConstInit;
14497 };
14498
14499 if (var->getTLSKind() == VarDecl::TLS_Static) {
14500 if (var->getType().isDestructedType()) {
14501 // GNU C++98 edits for __thread, [basic.start.term]p3:
14502 // The type of an object with thread storage duration shall not
14503 // have a non-trivial destructor.
14504 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14506 Diag(var->getLocation(), diag::note_use_thread_local);
14507 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14508 if (!checkConstInit()) {
14509 // GNU C++98 edits for __thread, [basic.start.init]p4:
14510 // An object of thread storage duration shall not require dynamic
14511 // initialization.
14512 // FIXME: Need strict checking here.
14513 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14514 << CacheCulprit->getSourceRange();
14516 Diag(var->getLocation(), diag::note_use_thread_local);
14517 }
14518 }
14519 }
14520
14521
14522 if (!var->getType()->isStructureType() && var->hasInit() &&
14523 isa<InitListExpr>(var->getInit())) {
14524 const auto *ILE = cast<InitListExpr>(var->getInit());
14525 unsigned NumInits = ILE->getNumInits();
14526 if (NumInits > 2)
14527 for (unsigned I = 0; I < NumInits; ++I) {
14528 const auto *Init = ILE->getInit(I);
14529 if (!Init)
14530 break;
14531 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14532 if (!SL)
14533 break;
14534
14535 unsigned NumConcat = SL->getNumConcatenated();
14536 // Diagnose missing comma in string array initialization.
14537 // Do not warn when all the elements in the initializer are concatenated
14538 // together. Do not warn for macros too.
14539 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14540 bool OnlyOneMissingComma = true;
14541 for (unsigned J = I + 1; J < NumInits; ++J) {
14542 const auto *Init = ILE->getInit(J);
14543 if (!Init)
14544 break;
14545 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14546 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14547 OnlyOneMissingComma = false;
14548 break;
14549 }
14550 }
14551
14552 if (OnlyOneMissingComma) {
14554 for (unsigned i = 0; i < NumConcat - 1; ++i)
14555 Hints.push_back(FixItHint::CreateInsertion(
14556 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14557
14558 Diag(SL->getStrTokenLoc(1),
14559 diag::warn_concatenated_literal_array_init)
14560 << Hints;
14561 Diag(SL->getBeginLoc(),
14562 diag::note_concatenated_string_literal_silence);
14563 }
14564 // In any case, stop now.
14565 break;
14566 }
14567 }
14568 }
14569
14570
14571 QualType type = var->getType();
14572
14573 if (var->hasAttr<BlocksAttr>())
14575
14576 Expr *Init = var->getInit();
14577 bool GlobalStorage = var->hasGlobalStorage();
14578 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14580 bool HasConstInit = true;
14581
14582 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14583 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14584 << var;
14585
14586 // Check whether the initializer is sufficiently constant.
14587 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14588 !type->isDependentType() && Init && !Init->isValueDependent() &&
14589 (GlobalStorage || var->isConstexpr() ||
14591 // If this variable might have a constant initializer or might be usable in
14592 // constant expressions, check whether or not it actually is now. We can't
14593 // do this lazily, because the result might depend on things that change
14594 // later, such as which constexpr functions happen to be defined.
14596 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14597 // Prior to C++11, in contexts where a constant initializer is required,
14598 // the set of valid constant initializers is described by syntactic rules
14599 // in [expr.const]p2-6.
14600 // FIXME: Stricter checking for these rules would be useful for constinit /
14601 // -Wglobal-constructors.
14602 HasConstInit = checkConstInit();
14603
14604 // Compute and cache the constant value, and remember that we have a
14605 // constant initializer.
14606 if (HasConstInit) {
14607 (void)var->checkForConstantInitialization(Notes);
14608 Notes.clear();
14609 } else if (CacheCulprit) {
14610 Notes.emplace_back(CacheCulprit->getExprLoc(),
14611 PDiag(diag::note_invalid_subexpr_in_const_expr));
14612 Notes.back().second << CacheCulprit->getSourceRange();
14613 }
14614 } else {
14615 // Evaluate the initializer to see if it's a constant initializer.
14616 HasConstInit = var->checkForConstantInitialization(Notes);
14617 }
14618
14619 if (HasConstInit) {
14620 // FIXME: Consider replacing the initializer with a ConstantExpr.
14621 } else if (var->isConstexpr()) {
14622 SourceLocation DiagLoc = var->getLocation();
14623 // If the note doesn't add any useful information other than a source
14624 // location, fold it into the primary diagnostic.
14625 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14626 diag::note_invalid_subexpr_in_const_expr) {
14627 DiagLoc = Notes[0].first;
14628 Notes.clear();
14629 }
14630 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14631 << var << Init->getSourceRange();
14632 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14633 Diag(Notes[I].first, Notes[I].second);
14634 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14635 auto *Attr = var->getAttr<ConstInitAttr>();
14636 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14637 << Init->getSourceRange();
14638 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14639 << Attr->getRange() << Attr->isConstinit();
14640 for (auto &it : Notes)
14641 Diag(it.first, it.second);
14642 } else if (IsGlobal &&
14643 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14644 var->getLocation())) {
14645 // Warn about globals which don't have a constant initializer. Don't
14646 // warn about globals with a non-trivial destructor because we already
14647 // warned about them.
14648 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14649 if (!(RD && !RD->hasTrivialDestructor())) {
14650 // checkConstInit() here permits trivial default initialization even in
14651 // C++11 onwards, where such an initializer is not a constant initializer
14652 // but nonetheless doesn't require a global constructor.
14653 if (!checkConstInit())
14654 Diag(var->getLocation(), diag::warn_global_constructor)
14655 << Init->getSourceRange();
14656 }
14657 }
14658 }
14659
14660 // Apply section attributes and pragmas to global variables.
14661 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14663 PragmaStack<StringLiteral *> *Stack = nullptr;
14664 int SectionFlags = ASTContext::PSF_Read;
14665 bool MSVCEnv =
14666 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14667 std::optional<QualType::NonConstantStorageReason> Reason;
14668 if (HasConstInit &&
14669 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14670 Stack = &ConstSegStack;
14671 } else {
14672 SectionFlags |= ASTContext::PSF_Write;
14673 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14674 }
14675 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14676 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14677 SectionFlags |= ASTContext::PSF_Implicit;
14678 UnifySection(SA->getName(), SectionFlags, var);
14679 } else if (Stack->CurrentValue) {
14680 if (Stack != &ConstSegStack && MSVCEnv &&
14681 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14682 var->getType().isConstQualified()) {
14683 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14684 NonConstNonReferenceType) &&
14685 "This case should've already been handled elsewhere");
14686 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14687 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14689 : *Reason);
14690 }
14691 SectionFlags |= ASTContext::PSF_Implicit;
14692 auto SectionName = Stack->CurrentValue->getString();
14693 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14694 Stack->CurrentPragmaLocation,
14695 SectionAttr::Declspec_allocate));
14696 if (UnifySection(SectionName, SectionFlags, var))
14697 var->dropAttr<SectionAttr>();
14698 }
14699
14700 // Apply the init_seg attribute if this has an initializer. If the
14701 // initializer turns out to not be dynamic, we'll end up ignoring this
14702 // attribute.
14703 if (CurInitSeg && var->getInit())
14704 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14705 CurInitSegLoc));
14706 }
14707
14708 // All the following checks are C++ only.
14709 if (!getLangOpts().CPlusPlus) {
14710 // If this variable must be emitted, add it as an initializer for the
14711 // current module.
14712 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14713 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14714 return;
14715 }
14716
14717 // Require the destructor.
14718 if (!type->isDependentType())
14719 if (const RecordType *recordType = baseType->getAs<RecordType>())
14721
14722 // If this variable must be emitted, add it as an initializer for the current
14723 // module.
14724 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14725 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14726
14727 // Build the bindings if this is a structured binding declaration.
14728 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14730}
14731
14732/// Check if VD needs to be dllexport/dllimport due to being in a
14733/// dllexport/import function.
14735 assert(VD->isStaticLocal());
14736
14737 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14738
14739 // Find outermost function when VD is in lambda function.
14740 while (FD && !getDLLAttr(FD) &&
14741 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14742 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14743 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14744 }
14745
14746 if (!FD)
14747 return;
14748
14749 // Static locals inherit dll attributes from their function.
14750 if (Attr *A = getDLLAttr(FD)) {
14751 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14752 NewAttr->setInherited(true);
14753 VD->addAttr(NewAttr);
14754 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14755 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14756 NewAttr->setInherited(true);
14757 VD->addAttr(NewAttr);
14758
14759 // Export this function to enforce exporting this static variable even
14760 // if it is not used in this compilation unit.
14761 if (!FD->hasAttr<DLLExportAttr>())
14762 FD->addAttr(NewAttr);
14763
14764 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14765 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14766 NewAttr->setInherited(true);
14767 VD->addAttr(NewAttr);
14768 }
14769}
14770
14772 assert(VD->getTLSKind());
14773
14774 // Perform TLS alignment check here after attributes attached to the variable
14775 // which may affect the alignment have been processed. Only perform the check
14776 // if the target has a maximum TLS alignment (zero means no constraints).
14777 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14778 // Protect the check so that it's not performed on dependent types and
14779 // dependent alignments (we can't determine the alignment in that case).
14780 if (!VD->hasDependentAlignment()) {
14781 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14782 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14783 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14785 << (unsigned)MaxAlignChars.getQuantity();
14786 }
14787 }
14788 }
14789}
14790
14791/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14792/// any semantic actions necessary after any initializer has been attached.
14794 // Note that we are no longer parsing the initializer for this declaration.
14795 ParsingInitForAutoVars.erase(ThisDecl);
14796
14797 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14798 if (!VD)
14799 return;
14800
14801 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14803 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14805 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14809 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14813 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14817 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14820 }
14821
14822 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14823 for (auto *BD : DD->bindings()) {
14825 }
14826 }
14827
14828 checkAttributesAfterMerging(*this, *VD);
14829
14830 if (VD->isStaticLocal())
14832
14833 if (VD->getTLSKind())
14835
14836 // Perform check for initializers of device-side global variables.
14837 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14838 // 7.5). We must also apply the same checks to all __shared__
14839 // variables whether they are local or not. CUDA also allows
14840 // constant initializers for __constant__ and __device__ variables.
14841 if (getLangOpts().CUDA)
14843
14844 // Grab the dllimport or dllexport attribute off of the VarDecl.
14845 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14846
14847 // Imported static data members cannot be defined out-of-line.
14848 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14849 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14851 // We allow definitions of dllimport class template static data members
14852 // with a warning.
14854 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14855 bool IsClassTemplateMember =
14856 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14857 Context->getDescribedClassTemplate();
14858
14859 Diag(VD->getLocation(),
14860 IsClassTemplateMember
14861 ? diag::warn_attribute_dllimport_static_field_definition
14862 : diag::err_attribute_dllimport_static_field_definition);
14863 Diag(IA->getLocation(), diag::note_attribute);
14864 if (!IsClassTemplateMember)
14865 VD->setInvalidDecl();
14866 }
14867 }
14868
14869 // dllimport/dllexport variables cannot be thread local, their TLS index
14870 // isn't exported with the variable.
14871 if (DLLAttr && VD->getTLSKind()) {
14872 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14873 if (F && getDLLAttr(F)) {
14874 assert(VD->isStaticLocal());
14875 // But if this is a static local in a dlimport/dllexport function, the
14876 // function will never be inlined, which means the var would never be
14877 // imported, so having it marked import/export is safe.
14878 } else {
14879 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14880 << DLLAttr;
14881 VD->setInvalidDecl();
14882 }
14883 }
14884
14885 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14886 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14887 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14888 << Attr;
14889 VD->dropAttr<UsedAttr>();
14890 }
14891 }
14892 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14893 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14894 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14895 << Attr;
14896 VD->dropAttr<RetainAttr>();
14897 }
14898 }
14899
14900 const DeclContext *DC = VD->getDeclContext();
14901 // If there's a #pragma GCC visibility in scope, and this isn't a class
14902 // member, set the visibility of this variable.
14905
14906 // FIXME: Warn on unused var template partial specializations.
14907 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14909
14910 // Now we have parsed the initializer and can update the table of magic
14911 // tag values.
14912 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14914 return;
14915
14916 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14917 const Expr *MagicValueExpr = VD->getInit();
14918 if (!MagicValueExpr) {
14919 continue;
14920 }
14921 std::optional<llvm::APSInt> MagicValueInt;
14922 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14923 Diag(I->getRange().getBegin(),
14924 diag::err_type_tag_for_datatype_not_ice)
14925 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14926 continue;
14927 }
14928 if (MagicValueInt->getActiveBits() > 64) {
14929 Diag(I->getRange().getBegin(),
14930 diag::err_type_tag_for_datatype_too_large)
14931 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14932 continue;
14933 }
14934 uint64_t MagicValue = MagicValueInt->getZExtValue();
14935 RegisterTypeTagForDatatype(I->getArgumentKind(),
14936 MagicValue,
14937 I->getMatchingCType(),
14938 I->getLayoutCompatible(),
14939 I->getMustBeNull());
14940 }
14941}
14942
14944 auto *VD = dyn_cast<VarDecl>(DD);
14945 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14946}
14947
14949 ArrayRef<Decl *> Group) {
14951
14952 if (DS.isTypeSpecOwned())
14953 Decls.push_back(DS.getRepAsDecl());
14954
14955 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14956 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14957 bool DiagnosedMultipleDecomps = false;
14958 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14959 bool DiagnosedNonDeducedAuto = false;
14960
14961 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14962 if (Decl *D = Group[i]) {
14963 // Check if the Decl has been declared in '#pragma omp declare target'
14964 // directive and has static storage duration.
14965 if (auto *VD = dyn_cast<VarDecl>(D);
14966 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14967 VD->hasGlobalStorage())
14969 // For declarators, there are some additional syntactic-ish checks we need
14970 // to perform.
14971 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14972 if (!FirstDeclaratorInGroup)
14973 FirstDeclaratorInGroup = DD;
14974 if (!FirstDecompDeclaratorInGroup)
14975 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14976 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14977 !hasDeducedAuto(DD))
14978 FirstNonDeducedAutoInGroup = DD;
14979
14980 if (FirstDeclaratorInGroup != DD) {
14981 // A decomposition declaration cannot be combined with any other
14982 // declaration in the same group.
14983 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14984 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14985 diag::err_decomp_decl_not_alone)
14986 << FirstDeclaratorInGroup->getSourceRange()
14987 << DD->getSourceRange();
14988 DiagnosedMultipleDecomps = true;
14989 }
14990
14991 // A declarator that uses 'auto' in any way other than to declare a
14992 // variable with a deduced type cannot be combined with any other
14993 // declarator in the same group.
14994 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14995 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14996 diag::err_auto_non_deduced_not_alone)
14997 << FirstNonDeducedAutoInGroup->getType()
14999 << FirstDeclaratorInGroup->getSourceRange()
15000 << DD->getSourceRange();
15001 DiagnosedNonDeducedAuto = true;
15002 }
15003 }
15004 }
15005
15006 Decls.push_back(D);
15007 }
15008 }
15009
15011 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15012 handleTagNumbering(Tag, S);
15013 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15015 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15016 }
15017 }
15018
15019 return BuildDeclaratorGroup(Decls);
15020}
15021
15022/// BuildDeclaratorGroup - convert a list of declarations into a declaration
15023/// group, performing any necessary semantic checking.
15026 // C++14 [dcl.spec.auto]p7: (DR1347)
15027 // If the type that replaces the placeholder type is not the same in each
15028 // deduction, the program is ill-formed.
15029 if (Group.size() > 1) {
15030 QualType Deduced;
15031 VarDecl *DeducedDecl = nullptr;
15032 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15033 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15034 if (!D || D->isInvalidDecl())
15035 break;
15037 if (!DT || DT->getDeducedType().isNull())
15038 continue;
15039 if (Deduced.isNull()) {
15040 Deduced = DT->getDeducedType();
15041 DeducedDecl = D;
15042 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15043 auto *AT = dyn_cast<AutoType>(DT);
15044 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15045 diag::err_auto_different_deductions)
15046 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15047 << DeducedDecl->getDeclName() << DT->getDeducedType()
15048 << D->getDeclName();
15049 if (DeducedDecl->hasInit())
15050 Dia << DeducedDecl->getInit()->getSourceRange();
15051 if (D->getInit())
15052 Dia << D->getInit()->getSourceRange();
15053 D->setInvalidDecl();
15054 break;
15055 }
15056 }
15057 }
15058
15060
15061 return DeclGroupPtrTy::make(
15062 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15063}
15064
15067}
15068
15070 // Don't parse the comment if Doxygen diagnostics are ignored.
15071 if (Group.empty() || !Group[0])
15072 return;
15073
15074 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15075 Group[0]->getLocation()) &&
15076 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15077 Group[0]->getLocation()))
15078 return;
15079
15080 if (Group.size() >= 2) {
15081 // This is a decl group. Normally it will contain only declarations
15082 // produced from declarator list. But in case we have any definitions or
15083 // additional declaration references:
15084 // 'typedef struct S {} S;'
15085 // 'typedef struct S *S;'
15086 // 'struct S *pS;'
15087 // FinalizeDeclaratorGroup adds these as separate declarations.
15088 Decl *MaybeTagDecl = Group[0];
15089 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15090 Group = Group.slice(1);
15091 }
15092 }
15093
15094 // FIMXE: We assume every Decl in the group is in the same file.
15095 // This is false when preprocessor constructs the group from decls in
15096 // different files (e. g. macros or #include).
15098}
15099
15100/// Common checks for a parameter-declaration that should apply to both function
15101/// parameters and non-type template parameters.
15103 // Check that there are no default arguments inside the type of this
15104 // parameter.
15105 if (getLangOpts().CPlusPlus)
15107
15108 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15109 if (D.getCXXScopeSpec().isSet()) {
15110 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15111 << D.getCXXScopeSpec().getRange();
15112 }
15113
15114 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15115 // simple identifier except [...irrelevant cases...].
15116 switch (D.getName().getKind()) {
15118 break;
15119
15127 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15129 break;
15130
15133 // GetNameForDeclarator would not produce a useful name in this case.
15134 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15135 break;
15136 }
15137}
15138
15140 SourceLocation ExplicitThisLoc) {
15141 if (!ExplicitThisLoc.isValid())
15142 return;
15143 assert(S.getLangOpts().CPlusPlus &&
15144 "explicit parameter in non-cplusplus mode");
15145 if (!S.getLangOpts().CPlusPlus23)
15146 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15147 << P->getSourceRange();
15148
15149 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15150 // parameter pack.
15151 if (P->isParameterPack()) {
15152 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15153 << P->getSourceRange();
15154 return;
15155 }
15156 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15157 if (LambdaScopeInfo *LSI = S.getCurLambda())
15158 LSI->ExplicitObjectParameter = P;
15159}
15160
15161/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15162/// to introduce parameters into function prototype scope.
15164 SourceLocation ExplicitThisLoc) {
15165 const DeclSpec &DS = D.getDeclSpec();
15166
15167 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15168
15169 // C++03 [dcl.stc]p2 also permits 'auto'.
15170 StorageClass SC = SC_None;
15172 SC = SC_Register;
15173 // In C++11, the 'register' storage class specifier is deprecated.
15174 // In C++17, it is not allowed, but we tolerate it as an extension.
15175 if (getLangOpts().CPlusPlus11) {
15177 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15178 : diag::warn_deprecated_register)
15180 }
15181 } else if (getLangOpts().CPlusPlus &&
15183 SC = SC_Auto;
15186 diag::err_invalid_storage_class_in_func_decl);
15188 }
15189
15191 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15193 if (DS.isInlineSpecified())
15194 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15195 << getLangOpts().CPlusPlus17;
15196 if (DS.hasConstexprSpecifier())
15197 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15198 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15199
15201
15203
15205 QualType parmDeclType = TInfo->getType();
15206
15207 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15208 IdentifierInfo *II = D.getIdentifier();
15209 if (II) {
15212 LookupName(R, S);
15213 if (!R.empty()) {
15214 NamedDecl *PrevDecl = *R.begin();
15215 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15216 // Maybe we will complain about the shadowed template parameter.
15218 // Just pretend that we didn't see the previous declaration.
15219 PrevDecl = nullptr;
15220 }
15221 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15222 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15223 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15224 // Recover by removing the name
15225 II = nullptr;
15226 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15227 D.setInvalidType(true);
15228 }
15229 }
15230 }
15231
15232 // Temporarily put parameter variables in the translation unit, not
15233 // the enclosing context. This prevents them from accidentally
15234 // looking like class members in C++.
15235 ParmVarDecl *New =
15237 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15238
15239 if (D.isInvalidType())
15240 New->setInvalidDecl();
15241
15242 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15243
15244 assert(S->isFunctionPrototypeScope());
15245 assert(S->getFunctionPrototypeDepth() >= 1);
15246 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15247 S->getNextFunctionPrototypeIndex());
15248
15249 // Add the parameter declaration into this scope.
15250 S->AddDecl(New);
15251 if (II)
15252 IdResolver.AddDecl(New);
15253
15254 ProcessDeclAttributes(S, New, D);
15255
15257 Diag(New->getLocation(), diag::err_module_private_local)
15258 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15260
15261 if (New->hasAttr<BlocksAttr>()) {
15262 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15263 }
15264
15265 if (getLangOpts().OpenCL)
15267
15268 return New;
15269}
15270
15271/// Synthesizes a variable for a parameter arising from a
15272/// typedef.
15274 SourceLocation Loc,
15275 QualType T) {
15276 /* FIXME: setting StartLoc == Loc.
15277 Would it be worth to modify callers so as to provide proper source
15278 location for the unnamed parameters, embedding the parameter's type? */
15279 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15281 SC_None, nullptr);
15282 Param->setImplicit();
15283 return Param;
15284}
15285
15287 // Don't diagnose unused-parameter errors in template instantiations; we
15288 // will already have done so in the template itself.
15290 return;
15291
15292 for (const ParmVarDecl *Parameter : Parameters) {
15293 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15294 !Parameter->hasAttr<UnusedAttr>() &&
15295 !Parameter->getIdentifier()->isPlaceholder()) {
15296 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15297 << Parameter->getDeclName();
15298 }
15299 }
15300}
15301
15303 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15304 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15305 return;
15306
15307 // Warn if the return value is pass-by-value and larger than the specified
15308 // threshold.
15309 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15310 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15311 if (Size > LangOpts.NumLargeByValueCopy)
15312 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15313 }
15314
15315 // Warn if any parameter is pass-by-value and larger than the specified
15316 // threshold.
15317 for (const ParmVarDecl *Parameter : Parameters) {
15318 QualType T = Parameter->getType();
15319 if (T->isDependentType() || !T.isPODType(Context))
15320 continue;
15321 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15322 if (Size > LangOpts.NumLargeByValueCopy)
15323 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15324 << Parameter << Size;
15325 }
15326}
15327
15329 SourceLocation NameLoc,
15330 TypeSourceInfo *TSInfo) {
15331 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15332 if (!getLangOpts().ObjCAutoRefCount ||
15334 return T;
15335
15336 Qualifiers::ObjCLifetime Lifetime;
15337
15338 // Special cases for arrays:
15339 // - if it's const, use __unsafe_unretained
15340 // - otherwise, it's an error
15341 if (T->isArrayType()) {
15342 if (!T.isConstQualified()) {
15345 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15346 else
15347 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15348 << TSInfo->getTypeLoc().getSourceRange();
15349 }
15351 } else {
15352 Lifetime = T->getObjCARCImplicitLifetime();
15353 }
15354 T = Context.getLifetimeQualifiedType(T, Lifetime);
15355
15356 return T;
15357}
15358
15360 SourceLocation NameLoc, IdentifierInfo *Name,
15361 QualType T, TypeSourceInfo *TSInfo,
15362 StorageClass SC) {
15363 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15364 if (getLangOpts().ObjCAutoRefCount &&
15366 T->isObjCLifetimeType()) {
15367
15368 Qualifiers::ObjCLifetime lifetime;
15369
15370 // Special cases for arrays:
15371 // - if it's const, use __unsafe_unretained
15372 // - otherwise, it's an error
15373 if (T->isArrayType()) {
15374 if (!T.isConstQualified()) {
15378 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15379 else
15380 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15381 << TSInfo->getTypeLoc().getSourceRange();
15382 }
15384 } else {
15385 lifetime = T->getObjCARCImplicitLifetime();
15386 }
15387 T = Context.getLifetimeQualifiedType(T, lifetime);
15388 }
15389
15390 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15392 TSInfo, SC, nullptr);
15393
15394 // Make a note if we created a new pack in the scope of a lambda, so that
15395 // we know that references to that pack must also be expanded within the
15396 // lambda scope.
15397 if (New->isParameterPack())
15398 if (auto *LSI = getEnclosingLambda())
15399 LSI->LocalPacks.push_back(New);
15400
15405
15406 // Parameter declarators cannot be interface types. All ObjC objects are
15407 // passed by reference.
15408 if (T->isObjCObjectType()) {
15409 SourceLocation TypeEndLoc =
15411 Diag(NameLoc,
15412 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15413 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15415 New->setType(T);
15416 }
15417
15418 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15419 // duration shall not be qualified by an address-space qualifier."
15420 // Since all parameters have automatic store duration, they can not have
15421 // an address space.
15422 if (T.getAddressSpace() != LangAS::Default &&
15423 // OpenCL allows function arguments declared to be an array of a type
15424 // to be qualified with an address space.
15425 !(getLangOpts().OpenCL &&
15427 // WebAssembly allows reference types as parameters. Funcref in particular
15428 // lives in a different address space.
15429 !(T->isFunctionPointerType() &&
15431 Diag(NameLoc, diag::err_arg_with_address_space);
15432 New->setInvalidDecl();
15433 }
15434
15435 // PPC MMA non-pointer types are not allowed as function argument types.
15436 if (Context.getTargetInfo().getTriple().isPPC64() &&
15437 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15438 New->setInvalidDecl();
15439 }
15440
15441 return New;
15442}
15443
15445 SourceLocation LocAfterDecls) {
15447
15448 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15449 // in the declaration list shall have at least one declarator, those
15450 // declarators shall only declare identifiers from the identifier list, and
15451 // every identifier in the identifier list shall be declared.
15452 //
15453 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15454 // identifiers it names shall be declared in the declaration list."
15455 //
15456 // This is why we only diagnose in C99 and later. Note, the other conditions
15457 // listed are checked elsewhere.
15458 if (!FTI.hasPrototype) {
15459 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15460 --i;
15461 if (FTI.Params[i].Param == nullptr) {
15462 if (getLangOpts().C99) {
15463 SmallString<256> Code;
15464 llvm::raw_svector_ostream(Code)
15465 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15466 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15467 << FTI.Params[i].Ident
15468 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15469 }
15470
15471 // Implicitly declare the argument as type 'int' for lack of a better
15472 // type.
15473 AttributeFactory attrs;
15474 DeclSpec DS(attrs);
15475 const char* PrevSpec; // unused
15476 unsigned DiagID; // unused
15477 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15478 DiagID, Context.getPrintingPolicy());
15479 // Use the identifier location for the type source range.
15480 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15481 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15484 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15485 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15486 }
15487 }
15488 }
15489}
15490
15491Decl *
15493 MultiTemplateParamsArg TemplateParameterLists,
15494 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15495 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15496 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15497 Scope *ParentScope = FnBodyScope->getParent();
15498
15499 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15500 // we define a non-templated function definition, we will create a declaration
15501 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15502 // The base function declaration will have the equivalent of an `omp declare
15503 // variant` annotation which specifies the mangled definition as a
15504 // specialization function under the OpenMP context defined as part of the
15505 // `omp begin declare variant`.
15509 ParentScope, D, TemplateParameterLists, Bases);
15510
15512 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15513 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15514
15515 if (!Bases.empty())
15517
15518 return Dcl;
15519}
15520
15523}
15524
15526 const FunctionDecl *&PossiblePrototype) {
15527 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15528 Prev = Prev->getPreviousDecl()) {
15529 // Ignore any declarations that occur in function or method
15530 // scope, because they aren't visible from the header.
15531 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15532 continue;
15533
15534 PossiblePrototype = Prev;
15535 return Prev->getType()->isFunctionProtoType();
15536 }
15537 return false;
15538}
15539
15540static bool
15542 const FunctionDecl *&PossiblePrototype) {
15543 // Don't warn about invalid declarations.
15544 if (FD->isInvalidDecl())
15545 return false;
15546
15547 // Or declarations that aren't global.
15548 if (!FD->isGlobal())
15549 return false;
15550
15551 // Don't warn about C++ member functions.
15552 if (isa<CXXMethodDecl>(FD))
15553 return false;
15554
15555 // Don't warn about 'main'.
15556 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15557 if (IdentifierInfo *II = FD->getIdentifier())
15558 if (II->isStr("main") || II->isStr("efi_main"))
15559 return false;
15560
15561 // Don't warn about inline functions.
15562 if (FD->isInlined())
15563 return false;
15564
15565 // Don't warn about function templates.
15567 return false;
15568
15569 // Don't warn about function template specializations.
15571 return false;
15572
15573 // Don't warn for OpenCL kernels.
15574 if (FD->hasAttr<OpenCLKernelAttr>())
15575 return false;
15576
15577 // Don't warn on explicitly deleted functions.
15578 if (FD->isDeleted())
15579 return false;
15580
15581 // Don't warn on implicitly local functions (such as having local-typed
15582 // parameters).
15583 if (!FD->isExternallyVisible())
15584 return false;
15585
15586 // If we were able to find a potential prototype, don't warn.
15587 if (FindPossiblePrototype(FD, PossiblePrototype))
15588 return false;
15589
15590 return true;
15591}
15592
15593void
15595 const FunctionDecl *EffectiveDefinition,
15596 SkipBodyInfo *SkipBody) {
15597 const FunctionDecl *Definition = EffectiveDefinition;
15598 if (!Definition &&
15599 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15600 return;
15601
15602 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15603 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15604 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15605 // A merged copy of the same function, instantiated as a member of
15606 // the same class, is OK.
15607 if (declaresSameEntity(OrigFD, OrigDef) &&
15608 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15609 cast<Decl>(FD->getLexicalDeclContext())))
15610 return;
15611 }
15612 }
15613 }
15614
15616 return;
15617
15618 // Don't emit an error when this is redefinition of a typo-corrected
15619 // definition.
15621 return;
15622
15623 // If we don't have a visible definition of the function, and it's inline or
15624 // a template, skip the new definition.
15625 if (SkipBody && !hasVisibleDefinition(Definition) &&
15626 (Definition->getFormalLinkage() == Linkage::Internal ||
15627 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15628 Definition->getNumTemplateParameterLists())) {
15629 SkipBody->ShouldSkip = true;
15630 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15631 if (auto *TD = Definition->getDescribedFunctionTemplate())
15634 return;
15635 }
15636
15637 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15638 Definition->getStorageClass() == SC_Extern)
15639 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15640 << FD << getLangOpts().CPlusPlus;
15641 else
15642 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15643
15644 Diag(Definition->getLocation(), diag::note_previous_definition);
15645 FD->setInvalidDecl();
15646}
15647
15649 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15650
15652 LSI->CallOperator = CallOperator;
15653 LSI->Lambda = LambdaClass;
15654 LSI->ReturnType = CallOperator->getReturnType();
15655 // This function in calls in situation where the context of the call operator
15656 // is not entered, so we set AfterParameterList to false, so that
15657 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15658 LSI->AfterParameterList = false;
15659 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15660
15661 if (LCD == LCD_None)
15663 else if (LCD == LCD_ByCopy)
15665 else if (LCD == LCD_ByRef)
15667 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15668
15670 LSI->Mutable = !CallOperator->isConst();
15671 if (CallOperator->isExplicitObjectMemberFunction())
15672 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15673
15674 // Add the captures to the LSI so they can be noted as already
15675 // captured within tryCaptureVar.
15676 auto I = LambdaClass->field_begin();
15677 for (const auto &C : LambdaClass->captures()) {
15678 if (C.capturesVariable()) {
15679 ValueDecl *VD = C.getCapturedVar();
15680 if (VD->isInitCapture())
15682 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15683 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15684 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15685 /*EllipsisLoc*/C.isPackExpansion()
15686 ? C.getEllipsisLoc() : SourceLocation(),
15687 I->getType(), /*Invalid*/false);
15688
15689 } else if (C.capturesThis()) {
15690 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15691 C.getCaptureKind() == LCK_StarThis);
15692 } else {
15693 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15694 I->getType());
15695 }
15696 ++I;
15697 }
15698 return LSI;
15699}
15700
15702 SkipBodyInfo *SkipBody,
15703 FnBodyKind BodyKind) {
15704 if (!D) {
15705 // Parsing the function declaration failed in some way. Push on a fake scope
15706 // anyway so we can try to parse the function body.
15709 return D;
15710 }
15711
15712 FunctionDecl *FD = nullptr;
15713
15714 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15715 FD = FunTmpl->getTemplatedDecl();
15716 else
15717 FD = cast<FunctionDecl>(D);
15718
15719 // Do not push if it is a lambda because one is already pushed when building
15720 // the lambda in ActOnStartOfLambdaDefinition().
15721 if (!isLambdaCallOperator(FD))
15722 // [expr.const]/p14.1
15723 // An expression or conversion is in an immediate function context if it is
15724 // potentially evaluated and either: its innermost enclosing non-block scope
15725 // is a function parameter scope of an immediate function.
15728 : ExprEvalContexts.back().Context);
15729
15730 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15731 // context is nested in an immediate function context, so smaller contexts
15732 // that appear inside immediate functions (like variable initializers) are
15733 // considered to be inside an immediate function context even though by
15734 // themselves they are not immediate function contexts. But when a new
15735 // function is entered, we need to reset this tracking, since the entered
15736 // function might be not an immediate function.
15737 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15738 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15739 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15740
15741 // Check for defining attributes before the check for redefinition.
15742 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15743 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15744 FD->dropAttr<AliasAttr>();
15745 FD->setInvalidDecl();
15746 }
15747 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15748 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15749 FD->dropAttr<IFuncAttr>();
15750 FD->setInvalidDecl();
15751 }
15752 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15753 if (!Context.getTargetInfo().hasFeature("fmv") &&
15754 !Attr->isDefaultVersion()) {
15755 // If function multi versioning disabled skip parsing function body
15756 // defined with non-default target_version attribute
15757 if (SkipBody)
15758 SkipBody->ShouldSkip = true;
15759 return nullptr;
15760 }
15761 }
15762
15763 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15764 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15765 Ctor->isDefaultConstructor() &&
15767 // If this is an MS ABI dllexport default constructor, instantiate any
15768 // default arguments.
15770 }
15771 }
15772
15773 // See if this is a redefinition. If 'will have body' (or similar) is already
15774 // set, then these checks were already performed when it was set.
15775 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15777 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15778
15779 // If we're skipping the body, we're done. Don't enter the scope.
15780 if (SkipBody && SkipBody->ShouldSkip)
15781 return D;
15782 }
15783
15784 // Mark this function as "will have a body eventually". This lets users to
15785 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15786 // this function.
15787 FD->setWillHaveBody();
15788
15789 // If we are instantiating a generic lambda call operator, push
15790 // a LambdaScopeInfo onto the function stack. But use the information
15791 // that's already been calculated (ActOnLambdaExpr) to prime the current
15792 // LambdaScopeInfo.
15793 // When the template operator is being specialized, the LambdaScopeInfo,
15794 // has to be properly restored so that tryCaptureVariable doesn't try
15795 // and capture any new variables. In addition when calculating potential
15796 // captures during transformation of nested lambdas, it is necessary to
15797 // have the LSI properly restored.
15799 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15800 // instantiated, explicitly specialized.
15803 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15804 FD->setInvalidDecl();
15806 } else {
15807 assert(inTemplateInstantiation() &&
15808 "There should be an active template instantiation on the stack "
15809 "when instantiating a generic lambda!");
15810 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15811 }
15812 } else {
15813 // Enter a new function scope
15815 }
15816
15817 // Builtin functions cannot be defined.
15818 if (unsigned BuiltinID = FD->getBuiltinID()) {
15821 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15822 FD->setInvalidDecl();
15823 }
15824 }
15825
15826 // The return type of a function definition must be complete (C99 6.9.1p3).
15827 // C++23 [dcl.fct.def.general]/p2
15828 // The type of [...] the return for a function definition
15829 // shall not be a (possibly cv-qualified) class type that is incomplete
15830 // or abstract within the function body unless the function is deleted.
15831 QualType ResultType = FD->getReturnType();
15832 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15833 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15834 (RequireCompleteType(FD->getLocation(), ResultType,
15835 diag::err_func_def_incomplete_result) ||
15837 diag::err_abstract_type_in_decl,
15839 FD->setInvalidDecl();
15840
15841 if (FnBodyScope)
15842 PushDeclContext(FnBodyScope, FD);
15843
15844 // Check the validity of our function parameters
15845 if (BodyKind != FnBodyKind::Delete)
15847 /*CheckParameterNames=*/true);
15848
15849 // Add non-parameter declarations already in the function to the current
15850 // scope.
15851 if (FnBodyScope) {
15852 for (Decl *NPD : FD->decls()) {
15853 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15854 if (!NonParmDecl)
15855 continue;
15856 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15857 "parameters should not be in newly created FD yet");
15858
15859 // If the decl has a name, make it accessible in the current scope.
15860 if (NonParmDecl->getDeclName())
15861 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15862
15863 // Similarly, dive into enums and fish their constants out, making them
15864 // accessible in this scope.
15865 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15866 for (auto *EI : ED->enumerators())
15867 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15868 }
15869 }
15870 }
15871
15872 // Introduce our parameters into the function scope
15873 for (auto *Param : FD->parameters()) {
15874 Param->setOwningFunction(FD);
15875
15876 // If this has an identifier, add it to the scope stack.
15877 if (Param->getIdentifier() && FnBodyScope) {
15878 CheckShadow(FnBodyScope, Param);
15879
15880 PushOnScopeChains(Param, FnBodyScope);
15881 }
15882 }
15883
15884 // C++ [module.import/6] external definitions are not permitted in header
15885 // units. Deleted and Defaulted functions are implicitly inline (but the
15886 // inline state is not set at this point, so check the BodyKind explicitly).
15887 // FIXME: Consider an alternate location for the test where the inlined()
15888 // state is complete.
15889 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15890 !FD->isInvalidDecl() && !FD->isInlined() &&
15891 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15892 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15893 !FD->isTemplateInstantiation()) {
15894 assert(FD->isThisDeclarationADefinition());
15895 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15896 FD->setInvalidDecl();
15897 }
15898
15899 // Ensure that the function's exception specification is instantiated.
15900 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15902
15903 // dllimport cannot be applied to non-inline function definitions.
15904 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15905 !FD->isTemplateInstantiation()) {
15906 assert(!FD->hasAttr<DLLExportAttr>());
15907 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15908 FD->setInvalidDecl();
15909 return D;
15910 }
15911 // We want to attach documentation to original Decl (which might be
15912 // a function template).
15914 if (getCurLexicalContext()->isObjCContainer() &&
15915 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15916 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15917 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15918
15919 return D;
15920}
15921
15922/// Given the set of return statements within a function body,
15923/// compute the variables that are subject to the named return value
15924/// optimization.
15925///
15926/// Each of the variables that is subject to the named return value
15927/// optimization will be marked as NRVO variables in the AST, and any
15928/// return statement that has a marked NRVO variable as its NRVO candidate can
15929/// use the named return value optimization.
15930///
15931/// This function applies a very simplistic algorithm for NRVO: if every return
15932/// statement in the scope of a variable has the same NRVO candidate, that
15933/// candidate is an NRVO variable.
15935 ReturnStmt **Returns = Scope->Returns.data();
15936
15937 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15938 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15939 if (!NRVOCandidate->isNRVOVariable())
15940 Returns[I]->setNRVOCandidate(nullptr);
15941 }
15942 }
15943}
15944
15946 // We can't delay parsing the body of a constexpr function template (yet).
15948 return false;
15949
15950 // We can't delay parsing the body of a function template with a deduced
15951 // return type (yet).
15952 if (D.getDeclSpec().hasAutoTypeSpec()) {
15953 // If the placeholder introduces a non-deduced trailing return type,
15954 // we can still delay parsing it.
15955 if (D.getNumTypeObjects()) {
15956 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15957 if (Outer.Kind == DeclaratorChunk::Function &&
15958 Outer.Fun.hasTrailingReturnType()) {
15959 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15960 return Ty.isNull() || !Ty->isUndeducedType();
15961 }
15962 }
15963 return false;
15964 }
15965
15966 return true;
15967}
15968
15970 // We cannot skip the body of a function (or function template) which is
15971 // constexpr, since we may need to evaluate its body in order to parse the
15972 // rest of the file.
15973 // We cannot skip the body of a function with an undeduced return type,
15974 // because any callers of that function need to know the type.
15975 if (const FunctionDecl *FD = D->getAsFunction()) {
15976 if (FD->isConstexpr())
15977 return false;
15978 // We can't simply call Type::isUndeducedType here, because inside template
15979 // auto can be deduced to a dependent type, which is not considered
15980 // "undeduced".
15981 if (FD->getReturnType()->getContainedDeducedType())
15982 return false;
15983 }
15985}
15986
15988 if (!Decl)
15989 return nullptr;
15990 if (FunctionDecl *FD = Decl->getAsFunction())
15991 FD->setHasSkippedBody();
15992 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15993 MD->setHasSkippedBody();
15994 return Decl;
15995}
15996
15998 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15999}
16000
16001/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16002/// body.
16004public:
16005 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16007 if (!IsLambda)
16009 }
16010
16011private:
16012 Sema &S;
16013 bool IsLambda = false;
16014};
16015
16017 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16018
16019 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16020 if (EscapeInfo.count(BD))
16021 return EscapeInfo[BD];
16022
16023 bool R = false;
16024 const BlockDecl *CurBD = BD;
16025
16026 do {
16027 R = !CurBD->doesNotEscape();
16028 if (R)
16029 break;
16030 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16031 } while (CurBD);
16032
16033 return EscapeInfo[BD] = R;
16034 };
16035
16036 // If the location where 'self' is implicitly retained is inside a escaping
16037 // block, emit a diagnostic.
16038 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16040 if (IsOrNestedInEscapingBlock(P.second))
16041 S.Diag(P.first, diag::warn_implicitly_retains_self)
16042 << FixItHint::CreateInsertion(P.first, "self->");
16043}
16044
16045static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16046 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16047 FD->getDeclName().isIdentifier() && FD->getName().equals(Name);
16048}
16049
16051 return methodHasName(FD, "get_return_object");
16052}
16053
16055 return FD->isStatic() &&
16056 methodHasName(FD, "get_return_object_on_allocation_failure");
16057}
16058
16061 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16062 return;
16063 // Allow some_promise_type::get_return_object().
16065 return;
16066 if (!FD->hasAttr<CoroWrapperAttr>())
16067 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16068}
16069
16071 bool IsInstantiation) {
16073 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16074
16075 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16076 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16077
16079 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16080
16081 // If we skip function body, we can't tell if a function is a coroutine.
16082 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16083 if (FSI->isCoroutine())
16085 else
16087 }
16088
16089 {
16090 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16091 // one is already popped when finishing the lambda in BuildLambdaExpr().
16092 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16093 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16094 if (FD) {
16095 FD->setBody(Body);
16096 FD->setWillHaveBody(false);
16098
16099 if (getLangOpts().CPlusPlus14) {
16100 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16101 FD->getReturnType()->isUndeducedType()) {
16102 // For a function with a deduced result type to return void,
16103 // the result type as written must be 'auto' or 'decltype(auto)',
16104 // possibly cv-qualified or constrained, but not ref-qualified.
16105 if (!FD->getReturnType()->getAs<AutoType>()) {
16106 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16107 << FD->getReturnType();
16108 FD->setInvalidDecl();
16109 } else {
16110 // Falling off the end of the function is the same as 'return;'.
16111 Expr *Dummy = nullptr;
16113 FD, dcl->getLocation(), Dummy,
16114 FD->getReturnType()->getAs<AutoType>()))
16115 FD->setInvalidDecl();
16116 }
16117 }
16118 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
16119 // In C++11, we don't use 'auto' deduction rules for lambda call
16120 // operators because we don't support return type deduction.
16121 auto *LSI = getCurLambda();
16122 if (LSI->HasImplicitReturnType) {
16124
16125 // C++11 [expr.prim.lambda]p4:
16126 // [...] if there are no return statements in the compound-statement
16127 // [the deduced type is] the type void
16128 QualType RetType =
16129 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16130
16131 // Update the return type to the deduced type.
16132 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16133 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16134 Proto->getExtProtoInfo()));
16135 }
16136 }
16137
16138 // If the function implicitly returns zero (like 'main') or is naked,
16139 // don't complain about missing return statements.
16140 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16142
16143 // MSVC permits the use of pure specifier (=0) on function definition,
16144 // defined at class scope, warn about this non-standard construct.
16145 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16146 !FD->isOutOfLine())
16147 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16148
16149 if (!FD->isInvalidDecl()) {
16150 // Don't diagnose unused parameters of defaulted, deleted or naked
16151 // functions.
16152 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16153 !FD->hasAttr<NakedAttr>())
16156 FD->getReturnType(), FD);
16157
16158 // If this is a structor, we need a vtable.
16159 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16160 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16161 else if (CXXDestructorDecl *Destructor =
16162 dyn_cast<CXXDestructorDecl>(FD))
16163 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16164
16165 // Try to apply the named return value optimization. We have to check
16166 // if we can do this here because lambdas keep return statements around
16167 // to deduce an implicit return type.
16168 if (FD->getReturnType()->isRecordType() &&
16170 computeNRVO(Body, FSI);
16171 }
16172
16173 // GNU warning -Wmissing-prototypes:
16174 // Warn if a global function is defined without a previous
16175 // prototype declaration. This warning is issued even if the
16176 // definition itself provides a prototype. The aim is to detect
16177 // global functions that fail to be declared in header files.
16178 const FunctionDecl *PossiblePrototype = nullptr;
16179 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16180 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16181
16182 if (PossiblePrototype) {
16183 // We found a declaration that is not a prototype,
16184 // but that could be a zero-parameter prototype
16185 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16186 TypeLoc TL = TI->getTypeLoc();
16188 Diag(PossiblePrototype->getLocation(),
16189 diag::note_declaration_not_a_prototype)
16190 << (FD->getNumParams() != 0)
16192 FTL.getRParenLoc(), "void")
16193 : FixItHint{});
16194 }
16195 } else {
16196 // Returns true if the token beginning at this Loc is `const`.
16197 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16198 const LangOptions &LangOpts) {
16199 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16200 if (LocInfo.first.isInvalid())
16201 return false;
16202
16203 bool Invalid = false;
16204 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16205 if (Invalid)
16206 return false;
16207
16208 if (LocInfo.second > Buffer.size())
16209 return false;
16210
16211 const char *LexStart = Buffer.data() + LocInfo.second;
16212 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16213
16214 return StartTok.consume_front("const") &&
16215 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16216 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16217 };
16218
16219 auto findBeginLoc = [&]() {
16220 // If the return type has `const` qualifier, we want to insert
16221 // `static` before `const` (and not before the typename).
16222 if ((FD->getReturnType()->isAnyPointerType() &&
16225 // But only do this if we can determine where the `const` is.
16226
16227 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16228 getLangOpts()))
16229
16230 return FD->getBeginLoc();
16231 }
16232 return FD->getTypeSpecStartLoc();
16233 };
16235 diag::note_static_for_internal_linkage)
16236 << /* function */ 1
16237 << (FD->getStorageClass() == SC_None
16238 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16239 : FixItHint{});
16240 }
16241 }
16242
16243 // We might not have found a prototype because we didn't wish to warn on
16244 // the lack of a missing prototype. Try again without the checks for
16245 // whether we want to warn on the missing prototype.
16246 if (!PossiblePrototype)
16247 (void)FindPossiblePrototype(FD, PossiblePrototype);
16248
16249 // If the function being defined does not have a prototype, then we may
16250 // need to diagnose it as changing behavior in C23 because we now know
16251 // whether the function accepts arguments or not. This only handles the
16252 // case where the definition has no prototype but does have parameters
16253 // and either there is no previous potential prototype, or the previous
16254 // potential prototype also has no actual prototype. This handles cases
16255 // like:
16256 // void f(); void f(a) int a; {}
16257 // void g(a) int a; {}
16258 // See MergeFunctionDecl() for other cases of the behavior change
16259 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16260 // type without a prototype.
16261 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16262 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16263 !PossiblePrototype->isImplicit()))) {
16264 // The function definition has parameters, so this will change behavior
16265 // in C23. If there is a possible prototype, it comes before the
16266 // function definition.
16267 // FIXME: The declaration may have already been diagnosed as being
16268 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16269 // there's no way to test for the "changes behavior" condition in
16270 // SemaType.cpp when forming the declaration's function type. So, we do
16271 // this awkward dance instead.
16272 //
16273 // If we have a possible prototype and it declares a function with a
16274 // prototype, we don't want to diagnose it; if we have a possible
16275 // prototype and it has no prototype, it may have already been
16276 // diagnosed in SemaType.cpp as deprecated depending on whether
16277 // -Wstrict-prototypes is enabled. If we already warned about it being
16278 // deprecated, add a note that it also changes behavior. If we didn't
16279 // warn about it being deprecated (because the diagnostic is not
16280 // enabled), warn now that it is deprecated and changes behavior.
16281
16282 // This K&R C function definition definitely changes behavior in C23,
16283 // so diagnose it.
16284 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16285 << /*definition*/ 1 << /* not supported in C23 */ 0;
16286
16287 // If we have a possible prototype for the function which is a user-
16288 // visible declaration, we already tested that it has no prototype.
16289 // This will change behavior in C23. This gets a warning rather than a
16290 // note because it's the same behavior-changing problem as with the
16291 // definition.
16292 if (PossiblePrototype)
16293 Diag(PossiblePrototype->getLocation(),
16294 diag::warn_non_prototype_changes_behavior)
16295 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16296 << /*definition*/ 1;
16297 }
16298
16299 // Warn on CPUDispatch with an actual body.
16300 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16301 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16302 if (!CmpndBody->body_empty())
16303 Diag(CmpndBody->body_front()->getBeginLoc(),
16304 diag::warn_dispatch_body_ignored);
16305
16306 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16307 const CXXMethodDecl *KeyFunction;
16308 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16309 MD->isVirtual() &&
16310 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16311 MD == KeyFunction->getCanonicalDecl()) {
16312 // Update the key-function state if necessary for this ABI.
16313 if (FD->isInlined() &&
16316
16317 // If the newly-chosen key function is already defined, then we
16318 // need to mark the vtable as used retroactively.
16319 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16320 const FunctionDecl *Definition;
16321 if (KeyFunction && KeyFunction->isDefined(Definition))
16322 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16323 } else {
16324 // We just defined they key function; mark the vtable as used.
16325 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16326 }
16327 }
16328 }
16329
16330 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16331 "Function parsing confused");
16332 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16333 assert(MD == getCurMethodDecl() && "Method parsing confused");
16334 MD->setBody(Body);
16335 if (!MD->isInvalidDecl()) {
16337 MD->getReturnType(), MD);
16338
16339 if (Body)
16340 computeNRVO(Body, FSI);
16341 }
16342 if (FSI->ObjCShouldCallSuper) {
16343 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16344 << MD->getSelector().getAsString();
16345 FSI->ObjCShouldCallSuper = false;
16346 }
16348 const ObjCMethodDecl *InitMethod = nullptr;
16349 bool isDesignated =
16350 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16351 assert(isDesignated && InitMethod);
16352 (void)isDesignated;
16353
16354 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16355 auto IFace = MD->getClassInterface();
16356 if (!IFace)
16357 return false;
16358 auto SuperD = IFace->getSuperClass();
16359 if (!SuperD)
16360 return false;
16361 return SuperD->getIdentifier() ==
16362 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16363 };
16364 // Don't issue this warning for unavailable inits or direct subclasses
16365 // of NSObject.
16366 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16367 Diag(MD->getLocation(),
16368 diag::warn_objc_designated_init_missing_super_call);
16369 Diag(InitMethod->getLocation(),
16370 diag::note_objc_designated_init_marked_here);
16371 }
16373 }
16374 if (FSI->ObjCWarnForNoInitDelegation) {
16375 // Don't issue this warning for unavaialable inits.
16376 if (!MD->isUnavailable())
16377 Diag(MD->getLocation(),
16378 diag::warn_objc_secondary_init_missing_init_call);
16379 FSI->ObjCWarnForNoInitDelegation = false;
16380 }
16381
16383 } else {
16384 // Parsing the function declaration failed in some way. Pop the fake scope
16385 // we pushed on.
16386 PopFunctionScopeInfo(ActivePolicy, dcl);
16387 return nullptr;
16388 }
16389
16390 if (Body && FSI->HasPotentialAvailabilityViolations)
16392
16393 assert(!FSI->ObjCShouldCallSuper &&
16394 "This should only be set for ObjC methods, which should have been "
16395 "handled in the block above.");
16396
16397 // Verify and clean out per-function state.
16398 if (Body && (!FD || !FD->isDefaulted())) {
16399 // C++ constructors that have function-try-blocks can't have return
16400 // statements in the handlers of that block. (C++ [except.handle]p14)
16401 // Verify this.
16402 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16403 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16404
16405 // Verify that gotos and switch cases don't jump into scopes illegally.
16408
16409 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16410 if (!Destructor->getParent()->isDependentType())
16411 CheckDestructor(Destructor);
16412
16413 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16414 Destructor->getParent());
16415 }
16416
16417 // If any errors have occurred, clear out any temporaries that may have
16418 // been leftover. This ensures that these temporaries won't be picked up
16419 // for deletion in some later function.
16422 getDiagnostics().getSuppressAllDiagnostics()) {
16424 }
16425 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16426 // Since the body is valid, issue any analysis-based warnings that are
16427 // enabled.
16428 ActivePolicy = &WP;
16429 }
16430
16431 if (!IsInstantiation && FD &&
16432 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16433 !FD->isInvalidDecl() &&
16435 FD->setInvalidDecl();
16436
16437 if (FD && FD->hasAttr<NakedAttr>()) {
16438 for (const Stmt *S : Body->children()) {
16439 // Allow local register variables without initializer as they don't
16440 // require prologue.
16441 bool RegisterVariables = false;
16442 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16443 for (const auto *Decl : DS->decls()) {
16444 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16445 RegisterVariables =
16446 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16447 if (!RegisterVariables)
16448 break;
16449 }
16450 }
16451 }
16452 if (RegisterVariables)
16453 continue;
16454 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16455 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16456 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16457 FD->setInvalidDecl();
16458 break;
16459 }
16460 }
16461 }
16462
16463 assert(ExprCleanupObjects.size() ==
16464 ExprEvalContexts.back().NumCleanupObjects &&
16465 "Leftover temporaries in function");
16466 assert(!Cleanup.exprNeedsCleanups() &&
16467 "Unaccounted cleanups in function");
16468 assert(MaybeODRUseExprs.empty() &&
16469 "Leftover expressions for odr-use checking");
16470 }
16471 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16472 // the declaration context below. Otherwise, we're unable to transform
16473 // 'this' expressions when transforming immediate context functions.
16474
16475 if (!IsInstantiation)
16477
16478 PopFunctionScopeInfo(ActivePolicy, dcl);
16479 // If any errors have occurred, clear out any temporaries that may have
16480 // been leftover. This ensures that these temporaries won't be picked up for
16481 // deletion in some later function.
16484 }
16485
16486 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16487 !LangOpts.OMPTargetTriples.empty())) ||
16488 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16489 auto ES = getEmissionStatus(FD);
16492 DeclsToCheckForDeferredDiags.insert(FD);
16493 }
16494
16495 if (FD && !FD->isDeleted())
16496 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16497
16498 return dcl;
16499}
16500
16501/// When we finish delayed parsing of an attribute, we must attach it to the
16502/// relevant Decl.
16504 ParsedAttributes &Attrs) {
16505 // Always attach attributes to the underlying decl.
16506 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16507 D = TD->getTemplatedDecl();
16508 ProcessDeclAttributeList(S, D, Attrs);
16509 ProcessAPINotes(D);
16510
16511 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16512 if (Method->isStatic())
16514}
16515
16516/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16517/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16519 IdentifierInfo &II, Scope *S) {
16520 // It is not valid to implicitly define a function in C23.
16522 "Implicit function declarations aren't allowed in this language mode");
16523
16524 // Find the scope in which the identifier is injected and the corresponding
16525 // DeclContext.
16526 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16527 // In that case, we inject the declaration into the translation unit scope
16528 // instead.
16529 Scope *BlockScope = S;
16530 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16531 BlockScope = BlockScope->getParent();
16532
16533 // Loop until we find a DeclContext that is either a function/method or the
16534 // translation unit, which are the only two valid places to implicitly define
16535 // a function. This avoids accidentally defining the function within a tag
16536 // declaration, for example.
16537 Scope *ContextScope = BlockScope;
16538 while (!ContextScope->getEntity() ||
16539 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16540 !ContextScope->getEntity()->isTranslationUnit()))
16541 ContextScope = ContextScope->getParent();
16542 ContextRAII SavedContext(*this, ContextScope->getEntity());
16543
16544 // Before we produce a declaration for an implicitly defined
16545 // function, see whether there was a locally-scoped declaration of
16546 // this name as a function or variable. If so, use that
16547 // (non-visible) declaration, and complain about it.
16548 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16549 if (ExternCPrev) {
16550 // We still need to inject the function into the enclosing block scope so
16551 // that later (non-call) uses can see it.
16552 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16553
16554 // C89 footnote 38:
16555 // If in fact it is not defined as having type "function returning int",
16556 // the behavior is undefined.
16557 if (!isa<FunctionDecl>(ExternCPrev) ||
16559 cast<FunctionDecl>(ExternCPrev)->getType(),
16561 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16562 << ExternCPrev << !getLangOpts().C99;
16563 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16564 return ExternCPrev;
16565 }
16566 }
16567
16568 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16569 unsigned diag_id;
16570 if (II.getName().starts_with("__builtin_"))
16571 diag_id = diag::warn_builtin_unknown;
16572 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16573 else if (getLangOpts().C99)
16574 diag_id = diag::ext_implicit_function_decl_c99;
16575 else
16576 diag_id = diag::warn_implicit_function_decl;
16577
16578 TypoCorrection Corrected;
16579 // Because typo correction is expensive, only do it if the implicit
16580 // function declaration is going to be treated as an error.
16581 //
16582 // Perform the correction before issuing the main diagnostic, as some
16583 // consumers use typo-correction callbacks to enhance the main diagnostic.
16584 if (S && !ExternCPrev &&
16587 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16588 S, nullptr, CCC, CTK_NonError);
16589 }
16590
16591 Diag(Loc, diag_id) << &II;
16592 if (Corrected) {
16593 // If the correction is going to suggest an implicitly defined function,
16594 // skip the correction as not being a particularly good idea.
16595 bool Diagnose = true;
16596 if (const auto *D = Corrected.getCorrectionDecl())
16597 Diagnose = !D->isImplicit();
16598 if (Diagnose)
16599 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16600 /*ErrorRecovery*/ false);
16601 }
16602
16603 // If we found a prior declaration of this function, don't bother building
16604 // another one. We've already pushed that one into scope, so there's nothing
16605 // more to do.
16606 if (ExternCPrev)
16607 return ExternCPrev;
16608
16609 // Set a Declarator for the implicit definition: int foo();
16610 const char *Dummy;
16611 AttributeFactory attrFactory;
16612 DeclSpec DS(attrFactory);
16613 unsigned DiagID;
16614 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16616 (void)Error; // Silence warning.
16617 assert(!Error && "Error setting up implicit decl!");
16618 SourceLocation NoLoc;
16620 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16621 /*IsAmbiguous=*/false,
16622 /*LParenLoc=*/NoLoc,
16623 /*Params=*/nullptr,
16624 /*NumParams=*/0,
16625 /*EllipsisLoc=*/NoLoc,
16626 /*RParenLoc=*/NoLoc,
16627 /*RefQualifierIsLvalueRef=*/true,
16628 /*RefQualifierLoc=*/NoLoc,
16629 /*MutableLoc=*/NoLoc, EST_None,
16630 /*ESpecRange=*/SourceRange(),
16631 /*Exceptions=*/nullptr,
16632 /*ExceptionRanges=*/nullptr,
16633 /*NumExceptions=*/0,
16634 /*NoexceptExpr=*/nullptr,
16635 /*ExceptionSpecTokens=*/nullptr,
16636 /*DeclsInPrototype=*/std::nullopt,
16637 Loc, Loc, D),
16638 std::move(DS.getAttributes()), SourceLocation());
16639 D.SetIdentifier(&II, Loc);
16640
16641 // Insert this function into the enclosing block scope.
16642 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16643 FD->setImplicit();
16644
16646
16647 return FD;
16648}
16649
16650/// If this function is a C++ replaceable global allocation function
16651/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16652/// adds any function attributes that we know a priori based on the standard.
16653///
16654/// We need to check for duplicate attributes both here and where user-written
16655/// attributes are applied to declarations.
16657 FunctionDecl *FD) {
16658 if (FD->isInvalidDecl())
16659 return;
16660
16661 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16662 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16663 return;
16664
16665 std::optional<unsigned> AlignmentParam;
16666 bool IsNothrow = false;
16667 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16668 return;
16669
16670 // C++2a [basic.stc.dynamic.allocation]p4:
16671 // An allocation function that has a non-throwing exception specification
16672 // indicates failure by returning a null pointer value. Any other allocation
16673 // function never returns a null pointer value and indicates failure only by
16674 // throwing an exception [...]
16675 //
16676 // However, -fcheck-new invalidates this possible assumption, so don't add
16677 // NonNull when that is enabled.
16678 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16679 !getLangOpts().CheckNew)
16680 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16681
16682 // C++2a [basic.stc.dynamic.allocation]p2:
16683 // An allocation function attempts to allocate the requested amount of
16684 // storage. [...] If the request succeeds, the value returned by a
16685 // replaceable allocation function is a [...] pointer value p0 different
16686 // from any previously returned value p1 [...]
16687 //
16688 // However, this particular information is being added in codegen,
16689 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16690
16691 // C++2a [basic.stc.dynamic.allocation]p2:
16692 // An allocation function attempts to allocate the requested amount of
16693 // storage. If it is successful, it returns the address of the start of a
16694 // block of storage whose length in bytes is at least as large as the
16695 // requested size.
16696 if (!FD->hasAttr<AllocSizeAttr>()) {
16697 FD->addAttr(AllocSizeAttr::CreateImplicit(
16698 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16699 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16700 }
16701
16702 // C++2a [basic.stc.dynamic.allocation]p3:
16703 // For an allocation function [...], the pointer returned on a successful
16704 // call shall represent the address of storage that is aligned as follows:
16705 // (3.1) If the allocation function takes an argument of type
16706 // std​::​align_­val_­t, the storage will have the alignment
16707 // specified by the value of this argument.
16708 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16709 FD->addAttr(AllocAlignAttr::CreateImplicit(
16710 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16711 }
16712
16713 // FIXME:
16714 // C++2a [basic.stc.dynamic.allocation]p3:
16715 // For an allocation function [...], the pointer returned on a successful
16716 // call shall represent the address of storage that is aligned as follows:
16717 // (3.2) Otherwise, if the allocation function is named operator new[],
16718 // the storage is aligned for any object that does not have
16719 // new-extended alignment ([basic.align]) and is no larger than the
16720 // requested size.
16721 // (3.3) Otherwise, the storage is aligned for any object that does not
16722 // have new-extended alignment and is of the requested size.
16723}
16724
16725/// Adds any function attributes that we know a priori based on
16726/// the declaration of this function.
16727///
16728/// These attributes can apply both to implicitly-declared builtins
16729/// (like __builtin___printf_chk) or to library-declared functions
16730/// like NSLog or printf.
16731///
16732/// We need to check for duplicate attributes both here and where user-written
16733/// attributes are applied to declarations.
16735 if (FD->isInvalidDecl())
16736 return;
16737
16738 // If this is a built-in function, map its builtin attributes to
16739 // actual attributes.
16740 if (unsigned BuiltinID = FD->getBuiltinID()) {
16741 // Handle printf-formatting attributes.
16742 unsigned FormatIdx;
16743 bool HasVAListArg;
16744 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16745 if (!FD->hasAttr<FormatAttr>()) {
16746 const char *fmt = "printf";
16747 unsigned int NumParams = FD->getNumParams();
16748 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16749 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16750 fmt = "NSString";
16751 FD->addAttr(FormatAttr::CreateImplicit(Context,
16752 &Context.Idents.get(fmt),
16753 FormatIdx+1,
16754 HasVAListArg ? 0 : FormatIdx+2,
16755 FD->getLocation()));
16756 }
16757 }
16758 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16759 HasVAListArg)) {
16760 if (!FD->hasAttr<FormatAttr>())
16761 FD->addAttr(FormatAttr::CreateImplicit(Context,
16762 &Context.Idents.get("scanf"),
16763 FormatIdx+1,
16764 HasVAListArg ? 0 : FormatIdx+2,
16765 FD->getLocation()));
16766 }
16767
16768 // Handle automatically recognized callbacks.
16769 SmallVector<int, 4> Encoding;
16770 if (!FD->hasAttr<CallbackAttr>() &&
16771 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16772 FD->addAttr(CallbackAttr::CreateImplicit(
16773 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16774
16775 // Mark const if we don't care about errno and/or floating point exceptions
16776 // that are the only thing preventing the function from being const. This
16777 // allows IRgen to use LLVM intrinsics for such functions.
16778 bool NoExceptions =
16780 bool ConstWithoutErrnoAndExceptions =
16782 bool ConstWithoutExceptions =
16784 if (!FD->hasAttr<ConstAttr>() &&
16785 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16786 (!ConstWithoutErrnoAndExceptions ||
16787 (!getLangOpts().MathErrno && NoExceptions)) &&
16788 (!ConstWithoutExceptions || NoExceptions))
16789 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16790
16791 // We make "fma" on GNU or Windows const because we know it does not set
16792 // errno in those environments even though it could set errno based on the
16793 // C standard.
16794 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16795 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16796 !FD->hasAttr<ConstAttr>()) {
16797 switch (BuiltinID) {
16798 case Builtin::BI__builtin_fma:
16799 case Builtin::BI__builtin_fmaf:
16800 case Builtin::BI__builtin_fmal:
16801 case Builtin::BIfma:
16802 case Builtin::BIfmaf:
16803 case Builtin::BIfmal:
16804 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16805 break;
16806 default:
16807 break;
16808 }
16809 }
16810
16811 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16812 !FD->hasAttr<ReturnsTwiceAttr>())
16813 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16814 FD->getLocation()));
16815 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16816 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16817 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16818 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16819 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16820 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16821 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16822 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16823 // Add the appropriate attribute, depending on the CUDA compilation mode
16824 // and which target the builtin belongs to. For example, during host
16825 // compilation, aux builtins are __device__, while the rest are __host__.
16826 if (getLangOpts().CUDAIsDevice !=
16828 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16829 else
16830 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16831 }
16832
16833 // Add known guaranteed alignment for allocation functions.
16834 switch (BuiltinID) {
16835 case Builtin::BImemalign:
16836 case Builtin::BIaligned_alloc:
16837 if (!FD->hasAttr<AllocAlignAttr>())
16838 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16839 FD->getLocation()));
16840 break;
16841 default:
16842 break;
16843 }
16844
16845 // Add allocsize attribute for allocation functions.
16846 switch (BuiltinID) {
16847 case Builtin::BIcalloc:
16848 FD->addAttr(AllocSizeAttr::CreateImplicit(
16849 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16850 break;
16851 case Builtin::BImemalign:
16852 case Builtin::BIaligned_alloc:
16853 case Builtin::BIrealloc:
16854 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16855 ParamIdx(), FD->getLocation()));
16856 break;
16857 case Builtin::BImalloc:
16858 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16859 ParamIdx(), FD->getLocation()));
16860 break;
16861 default:
16862 break;
16863 }
16864
16865 // Add lifetime attribute to std::move, std::fowrard et al.
16866 switch (BuiltinID) {
16867 case Builtin::BIaddressof:
16868 case Builtin::BI__addressof:
16869 case Builtin::BI__builtin_addressof:
16870 case Builtin::BIas_const:
16871 case Builtin::BIforward:
16872 case Builtin::BIforward_like:
16873 case Builtin::BImove:
16874 case Builtin::BImove_if_noexcept:
16875 if (ParmVarDecl *P = FD->getParamDecl(0u);
16876 !P->hasAttr<LifetimeBoundAttr>())
16877 P->addAttr(
16878 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16879 break;
16880 default:
16881 break;
16882 }
16883 }
16884
16886
16887 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16888 // throw, add an implicit nothrow attribute to any extern "C" function we come
16889 // across.
16890 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16891 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16892 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16893 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16894 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16895 }
16896
16897 IdentifierInfo *Name = FD->getIdentifier();
16898 if (!Name)
16899 return;
16901 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16902 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16904 // Okay: this could be a libc/libm/Objective-C function we know
16905 // about.
16906 } else
16907 return;
16908
16909 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16910 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16911 // target-specific builtins, perhaps?
16912 if (!FD->hasAttr<FormatAttr>())
16913 FD->addAttr(FormatAttr::CreateImplicit(Context,
16914 &Context.Idents.get("printf"), 2,
16915 Name->isStr("vasprintf") ? 0 : 3,
16916 FD->getLocation()));
16917 }
16918
16919 if (Name->isStr("__CFStringMakeConstantString")) {
16920 // We already have a __builtin___CFStringMakeConstantString,
16921 // but builds that use -fno-constant-cfstrings don't go through that.
16922 if (!FD->hasAttr<FormatArgAttr>())
16923 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16924 FD->getLocation()));
16925 }
16926}
16927
16929 TypeSourceInfo *TInfo) {
16930 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16931 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16932
16933 if (!TInfo) {
16934 assert(D.isInvalidType() && "no declarator info for valid type");
16936 }
16937
16938 // Scope manipulation handled by caller.
16939 TypedefDecl *NewTD =
16941 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16942
16943 // Bail out immediately if we have an invalid declaration.
16944 if (D.isInvalidType()) {
16945 NewTD->setInvalidDecl();
16946 return NewTD;
16947 }
16948
16951 Diag(NewTD->getLocation(), diag::err_module_private_local)
16952 << 2 << NewTD
16956 else
16957 NewTD->setModulePrivate();
16958 }
16959
16960 // C++ [dcl.typedef]p8:
16961 // If the typedef declaration defines an unnamed class (or
16962 // enum), the first typedef-name declared by the declaration
16963 // to be that class type (or enum type) is used to denote the
16964 // class type (or enum type) for linkage purposes only.
16965 // We need to check whether the type was declared in the declaration.
16966 switch (D.getDeclSpec().getTypeSpecType()) {
16967 case TST_enum:
16968 case TST_struct:
16969 case TST_interface:
16970 case TST_union:
16971 case TST_class: {
16972 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16973 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16974 break;
16975 }
16976
16977 default:
16978 break;
16979 }
16980
16981 return NewTD;
16982}
16983
16984/// Check that this is a valid underlying type for an enum declaration.
16986 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16987 QualType T = TI->getType();
16988
16989 if (T->isDependentType())
16990 return false;
16991
16992 // This doesn't use 'isIntegralType' despite the error message mentioning
16993 // integral type because isIntegralType would also allow enum types in C.
16994 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16995 if (BT->isInteger())
16996 return false;
16997
16998 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16999 << T << T->isBitIntType();
17000}
17001
17002/// Check whether this is a valid redeclaration of a previous enumeration.
17003/// \return true if the redeclaration was invalid.
17005 QualType EnumUnderlyingTy, bool IsFixed,
17006 const EnumDecl *Prev) {
17007 if (IsScoped != Prev->isScoped()) {
17008 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17009 << Prev->isScoped();
17010 Diag(Prev->getLocation(), diag::note_previous_declaration);
17011 return true;
17012 }
17013
17014 if (IsFixed && Prev->isFixed()) {
17015 if (!EnumUnderlyingTy->isDependentType() &&
17016 !Prev->getIntegerType()->isDependentType() &&
17017 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17018 Prev->getIntegerType())) {
17019 // TODO: Highlight the underlying type of the redeclaration.
17020 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17021 << EnumUnderlyingTy << Prev->getIntegerType();
17022 Diag(Prev->getLocation(), diag::note_previous_declaration)
17023 << Prev->getIntegerTypeRange();
17024 return true;
17025 }
17026 } else if (IsFixed != Prev->isFixed()) {
17027 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17028 << Prev->isFixed();
17029 Diag(Prev->getLocation(), diag::note_previous_declaration);
17030 return true;
17031 }
17032
17033 return false;
17034}
17035
17036/// Get diagnostic %select index for tag kind for
17037/// redeclaration diagnostic message.
17038/// WARNING: Indexes apply to particular diagnostics only!
17039///
17040/// \returns diagnostic %select index.
17042 switch (Tag) {
17044 return 0;
17046 return 1;
17047 case TagTypeKind::Class:
17048 return 2;
17049 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17050 }
17051}
17052
17053/// Determine if tag kind is a class-key compatible with
17054/// class for redeclaration (class, struct, or __interface).
17055///
17056/// \returns true iff the tag kind is compatible.
17058{
17059 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17061}
17062
17064 TagTypeKind TTK) {
17065 if (isa<TypedefDecl>(PrevDecl))
17066 return NTK_Typedef;
17067 else if (isa<TypeAliasDecl>(PrevDecl))
17068 return NTK_TypeAlias;
17069 else if (isa<ClassTemplateDecl>(PrevDecl))
17070 return NTK_Template;
17071 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17072 return NTK_TypeAliasTemplate;
17073 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17075 switch (TTK) {
17078 case TagTypeKind::Class:
17079 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
17080 case TagTypeKind::Union:
17081 return NTK_NonUnion;
17082 case TagTypeKind::Enum:
17083 return NTK_NonEnum;
17084 }
17085 llvm_unreachable("invalid TTK");
17086}
17087
17088/// Determine whether a tag with a given kind is acceptable
17089/// as a redeclaration of the given tag declaration.
17090///
17091/// \returns true if the new tag kind is acceptable, false otherwise.
17093 TagTypeKind NewTag, bool isDefinition,
17094 SourceLocation NewTagLoc,
17095 const IdentifierInfo *Name) {
17096 // C++ [dcl.type.elab]p3:
17097 // The class-key or enum keyword present in the
17098 // elaborated-type-specifier shall agree in kind with the
17099 // declaration to which the name in the elaborated-type-specifier
17100 // refers. This rule also applies to the form of
17101 // elaborated-type-specifier that declares a class-name or
17102 // friend class since it can be construed as referring to the
17103 // definition of the class. Thus, in any
17104 // elaborated-type-specifier, the enum keyword shall be used to
17105 // refer to an enumeration (7.2), the union class-key shall be
17106 // used to refer to a union (clause 9), and either the class or
17107 // struct class-key shall be used to refer to a class (clause 9)
17108 // declared using the class or struct class-key.
17109 TagTypeKind OldTag = Previous->getTagKind();
17110 if (OldTag != NewTag &&
17111 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
17112 return false;
17113
17114 // Tags are compatible, but we might still want to warn on mismatched tags.
17115 // Non-class tags can't be mismatched at this point.
17116 if (!isClassCompatTagKind(NewTag))
17117 return true;
17118
17119 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17120 // by our warning analysis. We don't want to warn about mismatches with (eg)
17121 // declarations in system headers that are designed to be specialized, but if
17122 // a user asks us to warn, we should warn if their code contains mismatched
17123 // declarations.
17124 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17125 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17126 Loc);
17127 };
17128 if (IsIgnoredLoc(NewTagLoc))
17129 return true;
17130
17131 auto IsIgnored = [&](const TagDecl *Tag) {
17132 return IsIgnoredLoc(Tag->getLocation());
17133 };
17134 while (IsIgnored(Previous)) {
17135 Previous = Previous->getPreviousDecl();
17136 if (!Previous)
17137 return true;
17138 OldTag = Previous->getTagKind();
17139 }
17140
17141 bool isTemplate = false;
17142 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17143 isTemplate = Record->getDescribedClassTemplate();
17144
17146 if (OldTag != NewTag) {
17147 // In a template instantiation, do not offer fix-its for tag mismatches
17148 // since they usually mess up the template instead of fixing the problem.
17149 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17150 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17151 << getRedeclDiagFromTagKind(OldTag);
17152 // FIXME: Note previous location?
17153 }
17154 return true;
17155 }
17156
17157 if (isDefinition) {
17158 // On definitions, check all previous tags and issue a fix-it for each
17159 // one that doesn't match the current tag.
17160 if (Previous->getDefinition()) {
17161 // Don't suggest fix-its for redefinitions.
17162 return true;
17163 }
17164
17165 bool previousMismatch = false;
17166 for (const TagDecl *I : Previous->redecls()) {
17167 if (I->getTagKind() != NewTag) {
17168 // Ignore previous declarations for which the warning was disabled.
17169 if (IsIgnored(I))
17170 continue;
17171
17172 if (!previousMismatch) {
17173 previousMismatch = true;
17174 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17175 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17176 << getRedeclDiagFromTagKind(I->getTagKind());
17177 }
17178 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17179 << getRedeclDiagFromTagKind(NewTag)
17180 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17182 }
17183 }
17184 return true;
17185 }
17186
17187 // Identify the prevailing tag kind: this is the kind of the definition (if
17188 // there is a non-ignored definition), or otherwise the kind of the prior
17189 // (non-ignored) declaration.
17190 const TagDecl *PrevDef = Previous->getDefinition();
17191 if (PrevDef && IsIgnored(PrevDef))
17192 PrevDef = nullptr;
17193 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17194 if (Redecl->getTagKind() != NewTag) {
17195 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17196 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17197 << getRedeclDiagFromTagKind(OldTag);
17198 Diag(Redecl->getLocation(), diag::note_previous_use);
17199
17200 // If there is a previous definition, suggest a fix-it.
17201 if (PrevDef) {
17202 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17206 }
17207 }
17208
17209 return true;
17210}
17211
17212/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17213/// from an outer enclosing namespace or file scope inside a friend declaration.
17214/// This should provide the commented out code in the following snippet:
17215/// namespace N {
17216/// struct X;
17217/// namespace M {
17218/// struct Y { friend struct /*N::*/ X; };
17219/// }
17220/// }
17222 SourceLocation NameLoc) {
17223 // While the decl is in a namespace, do repeated lookup of that name and see
17224 // if we get the same namespace back. If we do not, continue until
17225 // translation unit scope, at which point we have a fully qualified NNS.
17228 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17229 // This tag should be declared in a namespace, which can only be enclosed by
17230 // other namespaces. Bail if there's an anonymous namespace in the chain.
17231 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17232 if (!Namespace || Namespace->isAnonymousNamespace())
17233 return FixItHint();
17234 IdentifierInfo *II = Namespace->getIdentifier();
17235 Namespaces.push_back(II);
17236 NamedDecl *Lookup = SemaRef.LookupSingleName(
17237 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17238 if (Lookup == Namespace)
17239 break;
17240 }
17241
17242 // Once we have all the namespaces, reverse them to go outermost first, and
17243 // build an NNS.
17244 SmallString<64> Insertion;
17245 llvm::raw_svector_ostream OS(Insertion);
17246 if (DC->isTranslationUnit())
17247 OS << "::";
17248 std::reverse(Namespaces.begin(), Namespaces.end());
17249 for (auto *II : Namespaces)
17250 OS << II->getName() << "::";
17251 return FixItHint::CreateInsertion(NameLoc, Insertion);
17252}
17253
17254/// Determine whether a tag originally declared in context \p OldDC can
17255/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17256/// found a declaration in \p OldDC as a previous decl, perhaps through a
17257/// using-declaration).
17259 DeclContext *NewDC) {
17260 OldDC = OldDC->getRedeclContext();
17261 NewDC = NewDC->getRedeclContext();
17262
17263 if (OldDC->Equals(NewDC))
17264 return true;
17265
17266 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17267 // encloses the other).
17268 if (S.getLangOpts().MSVCCompat &&
17269 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17270 return true;
17271
17272 return false;
17273}
17274
17275/// This is invoked when we see 'struct foo' or 'struct {'. In the
17276/// former case, Name will be non-null. In the later case, Name will be null.
17277/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17278/// reference/declaration/definition of a tag.
17279///
17280/// \param IsTypeSpecifier \c true if this is a type-specifier (or
17281/// trailing-type-specifier) other than one in an alias-declaration.
17282///
17283/// \param SkipBody If non-null, will be set to indicate if the caller should
17284/// skip the definition of this tag and treat it as if it were a declaration.
17286Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17287 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17288 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17289 SourceLocation ModulePrivateLoc,
17290 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17291 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17292 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17293 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17294 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17295 // If this is not a definition, it must have a name.
17296 IdentifierInfo *OrigName = Name;
17297 assert((Name != nullptr || TUK == TUK_Definition) &&
17298 "Nameless record must be a definition!");
17299 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17300
17301 OwnedDecl = false;
17303 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17304
17305 // FIXME: Check member specializations more carefully.
17306 bool isMemberSpecialization = false;
17307 bool Invalid = false;
17308
17309 // We only need to do this matching if we have template parameters
17310 // or a scope specifier, which also conveniently avoids this work
17311 // for non-C++ cases.
17312 if (TemplateParameterLists.size() > 0 ||
17313 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17314 TemplateParameterList *TemplateParams =
17316 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17317 TUK == TUK_Friend, isMemberSpecialization, Invalid);
17318
17319 // C++23 [dcl.type.elab] p2:
17320 // If an elaborated-type-specifier is the sole constituent of a
17321 // declaration, the declaration is ill-formed unless it is an explicit
17322 // specialization, an explicit instantiation or it has one of the
17323 // following forms: [...]
17324 // C++23 [dcl.enum] p1:
17325 // If the enum-head-name of an opaque-enum-declaration contains a
17326 // nested-name-specifier, the declaration shall be an explicit
17327 // specialization.
17328 //
17329 // FIXME: Class template partial specializations can be forward declared
17330 // per CWG2213, but the resolution failed to allow qualified forward
17331 // declarations. This is almost certainly unintentional, so we allow them.
17332 if (TUK == TUK_Declaration && SS.isNotEmpty() && !isMemberSpecialization)
17333 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17335
17336 if (TemplateParams) {
17337 if (Kind == TagTypeKind::Enum) {
17338 Diag(KWLoc, diag::err_enum_template);
17339 return true;
17340 }
17341
17342 if (TemplateParams->size() > 0) {
17343 // This is a declaration or definition of a class template (which may
17344 // be a member of another template).
17345
17346 if (Invalid)
17347 return true;
17348
17349 OwnedDecl = false;
17351 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17352 AS, ModulePrivateLoc,
17353 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17354 TemplateParameterLists.data(), SkipBody);
17355 return Result.get();
17356 } else {
17357 // The "template<>" header is extraneous.
17358 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17359 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17360 isMemberSpecialization = true;
17361 }
17362 }
17363
17364 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17365 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17366 return true;
17367 }
17368
17369 if (TUK == TUK_Friend && Kind == TagTypeKind::Enum) {
17370 // C++23 [dcl.type.elab]p4:
17371 // If an elaborated-type-specifier appears with the friend specifier as
17372 // an entire member-declaration, the member-declaration shall have one
17373 // of the following forms:
17374 // friend class-key nested-name-specifier(opt) identifier ;
17375 // friend class-key simple-template-id ;
17376 // friend class-key nested-name-specifier template(opt)
17377 // simple-template-id ;
17378 //
17379 // Since enum is not a class-key, so declarations like "friend enum E;"
17380 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17381 // invalid, most implementations accept so we issue a pedantic warning.
17382 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17383 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17384 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17385 Diag(KWLoc, diag::note_enum_friend)
17386 << (ScopedEnum + ScopedEnumUsesClassTag);
17387 }
17388
17389 // Figure out the underlying type if this a enum declaration. We need to do
17390 // this early, because it's needed to detect if this is an incompatible
17391 // redeclaration.
17392 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17393 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17394
17395 if (Kind == TagTypeKind::Enum) {
17396 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17397 // No underlying type explicitly specified, or we failed to parse the
17398 // type, default to int.
17399 EnumUnderlying = Context.IntTy.getTypePtr();
17400 } else if (UnderlyingType.get()) {
17401 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17402 // integral type; any cv-qualification is ignored.
17403 TypeSourceInfo *TI = nullptr;
17404 GetTypeFromParser(UnderlyingType.get(), &TI);
17405 EnumUnderlying = TI;
17406
17408 // Recover by falling back to int.
17409 EnumUnderlying = Context.IntTy.getTypePtr();
17410
17413 EnumUnderlying = Context.IntTy.getTypePtr();
17414
17415 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17416 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17417 // of 'int'. However, if this is an unfixed forward declaration, don't set
17418 // the underlying type unless the user enables -fms-compatibility. This
17419 // makes unfixed forward declared enums incomplete and is more conforming.
17420 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17421 EnumUnderlying = Context.IntTy.getTypePtr();
17422 }
17423 }
17424
17425 DeclContext *SearchDC = CurContext;
17426 DeclContext *DC = CurContext;
17427 bool isStdBadAlloc = false;
17428 bool isStdAlignValT = false;
17429
17431 if (TUK == TUK_Friend || TUK == TUK_Reference)
17432 Redecl = NotForRedeclaration;
17433
17434 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17435 /// implemented asks for structural equivalence checking, the returned decl
17436 /// here is passed back to the parser, allowing the tag body to be parsed.
17437 auto createTagFromNewDecl = [&]() -> TagDecl * {
17438 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17439 // If there is an identifier, use the location of the identifier as the
17440 // location of the decl, otherwise use the location of the struct/union
17441 // keyword.
17442 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17443 TagDecl *New = nullptr;
17444
17445 if (Kind == TagTypeKind::Enum) {
17446 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17447 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17448 // If this is an undefined enum, bail.
17449 if (TUK != TUK_Definition && !Invalid)
17450 return nullptr;
17451 if (EnumUnderlying) {
17452 EnumDecl *ED = cast<EnumDecl>(New);
17453 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17455 else
17456 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17457 QualType EnumTy = ED->getIntegerType();
17460 : EnumTy);
17461 }
17462 } else { // struct/union
17463 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17464 nullptr);
17465 }
17466
17467 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17468 // Add alignment attributes if necessary; these attributes are checked
17469 // when the ASTContext lays out the structure.
17470 //
17471 // It is important for implementing the correct semantics that this
17472 // happen here (in ActOnTag). The #pragma pack stack is
17473 // maintained as a result of parser callbacks which can occur at
17474 // many points during the parsing of a struct declaration (because
17475 // the #pragma tokens are effectively skipped over during the
17476 // parsing of the struct).
17477 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17480 }
17481 }
17483 return New;
17484 };
17485
17486 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17487 if (Name && SS.isNotEmpty()) {
17488 // We have a nested-name tag ('struct foo::bar').
17489
17490 // Check for invalid 'foo::'.
17491 if (SS.isInvalid()) {
17492 Name = nullptr;
17493 goto CreateNewDecl;
17494 }
17495
17496 // If this is a friend or a reference to a class in a dependent
17497 // context, don't try to make a decl for it.
17498 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17499 DC = computeDeclContext(SS, false);
17500 if (!DC) {
17501 IsDependent = true;
17502 return true;
17503 }
17504 } else {
17505 DC = computeDeclContext(SS, true);
17506 if (!DC) {
17507 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17508 << SS.getRange();
17509 return true;
17510 }
17511 }
17512
17513 if (RequireCompleteDeclContext(SS, DC))
17514 return true;
17515
17516 SearchDC = DC;
17517 // Look-up name inside 'foo::'.
17519
17520 if (Previous.isAmbiguous())
17521 return true;
17522
17523 if (Previous.empty()) {
17524 // Name lookup did not find anything. However, if the
17525 // nested-name-specifier refers to the current instantiation,
17526 // and that current instantiation has any dependent base
17527 // classes, we might find something at instantiation time: treat
17528 // this as a dependent elaborated-type-specifier.
17529 // But this only makes any sense for reference-like lookups.
17530 if (Previous.wasNotFoundInCurrentInstantiation() &&
17531 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17532 IsDependent = true;
17533 return true;
17534 }
17535
17536 // A tag 'foo::bar' must already exist.
17537 Diag(NameLoc, diag::err_not_tag_in_scope)
17538 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17539 Name = nullptr;
17540 Invalid = true;
17541 goto CreateNewDecl;
17542 }
17543 } else if (Name) {
17544 // C++14 [class.mem]p14:
17545 // If T is the name of a class, then each of the following shall have a
17546 // name different from T:
17547 // -- every member of class T that is itself a type
17548 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17549 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17550 return true;
17551
17552 // If this is a named struct, check to see if there was a previous forward
17553 // declaration or definition.
17554 // FIXME: We're looking into outer scopes here, even when we
17555 // shouldn't be. Doing so can result in ambiguities that we
17556 // shouldn't be diagnosing.
17557 LookupName(Previous, S);
17558
17559 // When declaring or defining a tag, ignore ambiguities introduced
17560 // by types using'ed into this scope.
17561 if (Previous.isAmbiguous() &&
17562 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17563 LookupResult::Filter F = Previous.makeFilter();
17564 while (F.hasNext()) {
17565 NamedDecl *ND = F.next();
17566 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17567 SearchDC->getRedeclContext()))
17568 F.erase();
17569 }
17570 F.done();
17571 }
17572
17573 // C++11 [namespace.memdef]p3:
17574 // If the name in a friend declaration is neither qualified nor
17575 // a template-id and the declaration is a function or an
17576 // elaborated-type-specifier, the lookup to determine whether
17577 // the entity has been previously declared shall not consider
17578 // any scopes outside the innermost enclosing namespace.
17579 //
17580 // MSVC doesn't implement the above rule for types, so a friend tag
17581 // declaration may be a redeclaration of a type declared in an enclosing
17582 // scope. They do implement this rule for friend functions.
17583 //
17584 // Does it matter that this should be by scope instead of by
17585 // semantic context?
17586 if (!Previous.empty() && TUK == TUK_Friend) {
17587 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17588 LookupResult::Filter F = Previous.makeFilter();
17589 bool FriendSawTagOutsideEnclosingNamespace = false;
17590 while (F.hasNext()) {
17591 NamedDecl *ND = F.next();
17593 if (DC->isFileContext() &&
17594 !EnclosingNS->Encloses(ND->getDeclContext())) {
17595 if (getLangOpts().MSVCCompat)
17596 FriendSawTagOutsideEnclosingNamespace = true;
17597 else
17598 F.erase();
17599 }
17600 }
17601 F.done();
17602
17603 // Diagnose this MSVC extension in the easy case where lookup would have
17604 // unambiguously found something outside the enclosing namespace.
17605 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17606 NamedDecl *ND = Previous.getFoundDecl();
17607 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17608 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17609 }
17610 }
17611
17612 // Note: there used to be some attempt at recovery here.
17613 if (Previous.isAmbiguous())
17614 return true;
17615
17616 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17617 // FIXME: This makes sure that we ignore the contexts associated
17618 // with C structs, unions, and enums when looking for a matching
17619 // tag declaration or definition. See the similar lookup tweak
17620 // in Sema::LookupName; is there a better way to deal with this?
17621 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17622 SearchDC = SearchDC->getParent();
17623 } else if (getLangOpts().CPlusPlus) {
17624 // Inside ObjCContainer want to keep it as a lexical decl context but go
17625 // past it (most often to TranslationUnit) to find the semantic decl
17626 // context.
17627 while (isa<ObjCContainerDecl>(SearchDC))
17628 SearchDC = SearchDC->getParent();
17629 }
17630 } else if (getLangOpts().CPlusPlus) {
17631 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17632 // TagDecl the same way as we skip it for named TagDecl.
17633 while (isa<ObjCContainerDecl>(SearchDC))
17634 SearchDC = SearchDC->getParent();
17635 }
17636
17637 if (Previous.isSingleResult() &&
17638 Previous.getFoundDecl()->isTemplateParameter()) {
17639 // Maybe we will complain about the shadowed template parameter.
17640 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17641 // Just pretend that we didn't see the previous declaration.
17642 Previous.clear();
17643 }
17644
17645 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17646 DC->Equals(getStdNamespace())) {
17647 if (Name->isStr("bad_alloc")) {
17648 // This is a declaration of or a reference to "std::bad_alloc".
17649 isStdBadAlloc = true;
17650
17651 // If std::bad_alloc has been implicitly declared (but made invisible to
17652 // name lookup), fill in this implicit declaration as the previous
17653 // declaration, so that the declarations get chained appropriately.
17654 if (Previous.empty() && StdBadAlloc)
17655 Previous.addDecl(getStdBadAlloc());
17656 } else if (Name->isStr("align_val_t")) {
17657 isStdAlignValT = true;
17658 if (Previous.empty() && StdAlignValT)
17659 Previous.addDecl(getStdAlignValT());
17660 }
17661 }
17662
17663 // If we didn't find a previous declaration, and this is a reference
17664 // (or friend reference), move to the correct scope. In C++, we
17665 // also need to do a redeclaration lookup there, just in case
17666 // there's a shadow friend decl.
17667 if (Name && Previous.empty() &&
17668 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17669 if (Invalid) goto CreateNewDecl;
17670 assert(SS.isEmpty());
17671
17672 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17673 // C++ [basic.scope.pdecl]p5:
17674 // -- for an elaborated-type-specifier of the form
17675 //
17676 // class-key identifier
17677 //
17678 // if the elaborated-type-specifier is used in the
17679 // decl-specifier-seq or parameter-declaration-clause of a
17680 // function defined in namespace scope, the identifier is
17681 // declared as a class-name in the namespace that contains
17682 // the declaration; otherwise, except as a friend
17683 // declaration, the identifier is declared in the smallest
17684 // non-class, non-function-prototype scope that contains the
17685 // declaration.
17686 //
17687 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17688 // C structs and unions.
17689 //
17690 // It is an error in C++ to declare (rather than define) an enum
17691 // type, including via an elaborated type specifier. We'll
17692 // diagnose that later; for now, declare the enum in the same
17693 // scope as we would have picked for any other tag type.
17694 //
17695 // GNU C also supports this behavior as part of its incomplete
17696 // enum types extension, while GNU C++ does not.
17697 //
17698 // Find the context where we'll be declaring the tag.
17699 // FIXME: We would like to maintain the current DeclContext as the
17700 // lexical context,
17701 SearchDC = getTagInjectionContext(SearchDC);
17702
17703 // Find the scope where we'll be declaring the tag.
17705 } else {
17706 assert(TUK == TUK_Friend);
17707 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17708
17709 // C++ [namespace.memdef]p3:
17710 // If a friend declaration in a non-local class first declares a
17711 // class or function, the friend class or function is a member of
17712 // the innermost enclosing namespace.
17713 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17714 : SearchDC->getEnclosingNamespaceContext();
17715 }
17716
17717 // In C++, we need to do a redeclaration lookup to properly
17718 // diagnose some problems.
17719 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17720 // hidden declaration so that we don't get ambiguity errors when using a
17721 // type declared by an elaborated-type-specifier. In C that is not correct
17722 // and we should instead merge compatible types found by lookup.
17723 if (getLangOpts().CPlusPlus) {
17724 // FIXME: This can perform qualified lookups into function contexts,
17725 // which are meaningless.
17726 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17727 LookupQualifiedName(Previous, SearchDC);
17728 } else {
17729 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17730 LookupName(Previous, S);
17731 }
17732 }
17733
17734 // If we have a known previous declaration to use, then use it.
17735 if (Previous.empty() && SkipBody && SkipBody->Previous)
17736 Previous.addDecl(SkipBody->Previous);
17737
17738 if (!Previous.empty()) {
17739 NamedDecl *PrevDecl = Previous.getFoundDecl();
17740 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17741
17742 // It's okay to have a tag decl in the same scope as a typedef
17743 // which hides a tag decl in the same scope. Finding this
17744 // with a redeclaration lookup can only actually happen in C++.
17745 //
17746 // This is also okay for elaborated-type-specifiers, which is
17747 // technically forbidden by the current standard but which is
17748 // okay according to the likely resolution of an open issue;
17749 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17750 if (getLangOpts().CPlusPlus) {
17751 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17752 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17753 TagDecl *Tag = TT->getDecl();
17754 if (Tag->getDeclName() == Name &&
17756 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17757 PrevDecl = Tag;
17758 Previous.clear();
17759 Previous.addDecl(Tag);
17760 Previous.resolveKind();
17761 }
17762 }
17763 }
17764 }
17765
17766 // If this is a redeclaration of a using shadow declaration, it must
17767 // declare a tag in the same context. In MSVC mode, we allow a
17768 // redefinition if either context is within the other.
17769 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17770 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17771 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17772 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17773 !(OldTag && isAcceptableTagRedeclContext(
17774 *this, OldTag->getDeclContext(), SearchDC))) {
17775 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17776 Diag(Shadow->getTargetDecl()->getLocation(),
17777 diag::note_using_decl_target);
17778 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17779 << 0;
17780 // Recover by ignoring the old declaration.
17781 Previous.clear();
17782 goto CreateNewDecl;
17783 }
17784 }
17785
17786 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17787 // If this is a use of a previous tag, or if the tag is already declared
17788 // in the same scope (so that the definition/declaration completes or
17789 // rementions the tag), reuse the decl.
17790 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17791 isDeclInScope(DirectPrevDecl, SearchDC, S,
17792 SS.isNotEmpty() || isMemberSpecialization)) {
17793 // Make sure that this wasn't declared as an enum and now used as a
17794 // struct or something similar.
17795 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17796 TUK == TUK_Definition, KWLoc,
17797 Name)) {
17798 bool SafeToContinue =
17799 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17800 Kind != TagTypeKind::Enum);
17801 if (SafeToContinue)
17802 Diag(KWLoc, diag::err_use_with_wrong_tag)
17803 << Name
17805 PrevTagDecl->getKindName());
17806 else
17807 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17808 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17809
17810 if (SafeToContinue)
17811 Kind = PrevTagDecl->getTagKind();
17812 else {
17813 // Recover by making this an anonymous redefinition.
17814 Name = nullptr;
17815 Previous.clear();
17816 Invalid = true;
17817 }
17818 }
17819
17820 if (Kind == TagTypeKind::Enum &&
17821 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17822 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17823 if (TUK == TUK_Reference || TUK == TUK_Friend)
17824 return PrevTagDecl;
17825
17826 QualType EnumUnderlyingTy;
17827 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17828 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17829 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17830 EnumUnderlyingTy = QualType(T, 0);
17831
17832 // All conflicts with previous declarations are recovered by
17833 // returning the previous declaration, unless this is a definition,
17834 // in which case we want the caller to bail out.
17835 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17836 ScopedEnum, EnumUnderlyingTy,
17837 IsFixed, PrevEnum))
17838 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17839 }
17840
17841 // C++11 [class.mem]p1:
17842 // A member shall not be declared twice in the member-specification,
17843 // except that a nested class or member class template can be declared
17844 // and then later defined.
17845 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17846 S->isDeclScope(PrevDecl)) {
17847 Diag(NameLoc, diag::ext_member_redeclared);
17848 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17849 }
17850
17851 if (!Invalid) {
17852 // If this is a use, just return the declaration we found, unless
17853 // we have attributes.
17854 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17855 if (!Attrs.empty()) {
17856 // FIXME: Diagnose these attributes. For now, we create a new
17857 // declaration to hold them.
17858 } else if (TUK == TUK_Reference &&
17859 (PrevTagDecl->getFriendObjectKind() ==
17861 PrevDecl->getOwningModule() != getCurrentModule()) &&
17862 SS.isEmpty()) {
17863 // This declaration is a reference to an existing entity, but
17864 // has different visibility from that entity: it either makes
17865 // a friend visible or it makes a type visible in a new module.
17866 // In either case, create a new declaration. We only do this if
17867 // the declaration would have meant the same thing if no prior
17868 // declaration were found, that is, if it was found in the same
17869 // scope where we would have injected a declaration.
17870 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17871 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17872 return PrevTagDecl;
17873 // This is in the injected scope, create a new declaration in
17874 // that scope.
17876 } else {
17877 return PrevTagDecl;
17878 }
17879 }
17880
17881 // Diagnose attempts to redefine a tag.
17882 if (TUK == TUK_Definition) {
17883 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17884 // If we're defining a specialization and the previous definition
17885 // is from an implicit instantiation, don't emit an error
17886 // here; we'll catch this in the general case below.
17887 bool IsExplicitSpecializationAfterInstantiation = false;
17888 if (isMemberSpecialization) {
17889 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17890 IsExplicitSpecializationAfterInstantiation =
17891 RD->getTemplateSpecializationKind() !=
17893 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17894 IsExplicitSpecializationAfterInstantiation =
17895 ED->getTemplateSpecializationKind() !=
17897 }
17898
17899 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17900 // not keep more that one definition around (merge them). However,
17901 // ensure the decl passes the structural compatibility check in
17902 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17903 NamedDecl *Hidden = nullptr;
17904 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17905 // There is a definition of this tag, but it is not visible. We
17906 // explicitly make use of C++'s one definition rule here, and
17907 // assume that this definition is identical to the hidden one
17908 // we already have. Make the existing definition visible and
17909 // use it in place of this one.
17910 if (!getLangOpts().CPlusPlus) {
17911 // Postpone making the old definition visible until after we
17912 // complete parsing the new one and do the structural
17913 // comparison.
17914 SkipBody->CheckSameAsPrevious = true;
17915 SkipBody->New = createTagFromNewDecl();
17916 SkipBody->Previous = Def;
17917 return Def;
17918 } else {
17919 SkipBody->ShouldSkip = true;
17920 SkipBody->Previous = Def;
17922 // Carry on and handle it like a normal definition. We'll
17923 // skip starting the definitiion later.
17924 }
17925 } else if (!IsExplicitSpecializationAfterInstantiation) {
17926 // A redeclaration in function prototype scope in C isn't
17927 // visible elsewhere, so merely issue a warning.
17928 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17929 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17930 else
17931 Diag(NameLoc, diag::err_redefinition) << Name;
17933 NameLoc.isValid() ? NameLoc : KWLoc);
17934 // If this is a redefinition, recover by making this
17935 // struct be anonymous, which will make any later
17936 // references get the previous definition.
17937 Name = nullptr;
17938 Previous.clear();
17939 Invalid = true;
17940 }
17941 } else {
17942 // If the type is currently being defined, complain
17943 // about a nested redefinition.
17944 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17945 if (TD->isBeingDefined()) {
17946 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17947 Diag(PrevTagDecl->getLocation(),
17948 diag::note_previous_definition);
17949 Name = nullptr;
17950 Previous.clear();
17951 Invalid = true;
17952 }
17953 }
17954
17955 // Okay, this is definition of a previously declared or referenced
17956 // tag. We're going to create a new Decl for it.
17957 }
17958
17959 // Okay, we're going to make a redeclaration. If this is some kind
17960 // of reference, make sure we build the redeclaration in the same DC
17961 // as the original, and ignore the current access specifier.
17962 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17963 SearchDC = PrevTagDecl->getDeclContext();
17964 AS = AS_none;
17965 }
17966 }
17967 // If we get here we have (another) forward declaration or we
17968 // have a definition. Just create a new decl.
17969
17970 } else {
17971 // If we get here, this is a definition of a new tag type in a nested
17972 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17973 // new decl/type. We set PrevDecl to NULL so that the entities
17974 // have distinct types.
17975 Previous.clear();
17976 }
17977 // If we get here, we're going to create a new Decl. If PrevDecl
17978 // is non-NULL, it's a definition of the tag declared by
17979 // PrevDecl. If it's NULL, we have a new definition.
17980
17981 // Otherwise, PrevDecl is not a tag, but was found with tag
17982 // lookup. This is only actually possible in C++, where a few
17983 // things like templates still live in the tag namespace.
17984 } else {
17985 // Use a better diagnostic if an elaborated-type-specifier
17986 // found the wrong kind of type on the first
17987 // (non-redeclaration) lookup.
17988 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17989 !Previous.isForRedeclaration()) {
17990 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17991 Diag(NameLoc, diag::err_tag_reference_non_tag)
17992 << PrevDecl << NTK << llvm::to_underlying(Kind);
17993 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17994 Invalid = true;
17995
17996 // Otherwise, only diagnose if the declaration is in scope.
17997 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17998 SS.isNotEmpty() || isMemberSpecialization)) {
17999 // do nothing
18000
18001 // Diagnose implicit declarations introduced by elaborated types.
18002 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
18003 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18004 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18005 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18006 Invalid = true;
18007
18008 // Otherwise it's a declaration. Call out a particularly common
18009 // case here.
18010 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18011 unsigned Kind = 0;
18012 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18013 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18014 << Name << Kind << TND->getUnderlyingType();
18015 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18016 Invalid = true;
18017
18018 // Otherwise, diagnose.
18019 } else {
18020 // The tag name clashes with something else in the target scope,
18021 // issue an error and recover by making this tag be anonymous.
18022 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18023 notePreviousDefinition(PrevDecl, NameLoc);
18024 Name = nullptr;
18025 Invalid = true;
18026 }
18027
18028 // The existing declaration isn't relevant to us; we're in a
18029 // new scope, so clear out the previous declaration.
18030 Previous.clear();
18031 }
18032 }
18033
18034CreateNewDecl:
18035
18036 TagDecl *PrevDecl = nullptr;
18037 if (Previous.isSingleResult())
18038 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18039
18040 // If there is an identifier, use the location of the identifier as the
18041 // location of the decl, otherwise use the location of the struct/union
18042 // keyword.
18043 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18044
18045 // Otherwise, create a new declaration. If there is a previous
18046 // declaration of the same entity, the two will be linked via
18047 // PrevDecl.
18048 TagDecl *New;
18049
18050 if (Kind == TagTypeKind::Enum) {
18051 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18052 // enum X { A, B, C } D; D should chain to X.
18053 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18054 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18055 ScopedEnumUsesClassTag, IsFixed);
18056
18057 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18058 StdAlignValT = cast<EnumDecl>(New);
18059
18060 // If this is an undefined enum, warn.
18061 if (TUK != TUK_Definition && !Invalid) {
18062 TagDecl *Def;
18063 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
18064 // C++0x: 7.2p2: opaque-enum-declaration.
18065 // Conflicts are diagnosed above. Do nothing.
18066 }
18067 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18068 Diag(Loc, diag::ext_forward_ref_enum_def)
18069 << New;
18070 Diag(Def->getLocation(), diag::note_previous_definition);
18071 } else {
18072 unsigned DiagID = diag::ext_forward_ref_enum;
18073 if (getLangOpts().MSVCCompat)
18074 DiagID = diag::ext_ms_forward_ref_enum;
18075 else if (getLangOpts().CPlusPlus)
18076 DiagID = diag::err_forward_ref_enum;
18077 Diag(Loc, DiagID);
18078 }
18079 }
18080
18081 if (EnumUnderlying) {
18082 EnumDecl *ED = cast<EnumDecl>(New);
18083 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
18085 else
18086 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
18087 QualType EnumTy = ED->getIntegerType();
18090 : EnumTy);
18091 assert(ED->isComplete() && "enum with type should be complete");
18092 }
18093 } else {
18094 // struct/union/class
18095
18096 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18097 // struct X { int A; } D; D should chain to X.
18098 if (getLangOpts().CPlusPlus) {
18099 // FIXME: Look for a way to use RecordDecl for simple structs.
18100 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18101 cast_or_null<CXXRecordDecl>(PrevDecl));
18102
18103 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18104 StdBadAlloc = cast<CXXRecordDecl>(New);
18105 } else
18106 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18107 cast_or_null<RecordDecl>(PrevDecl));
18108 }
18109
18110 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
18111 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18112 << (OOK == OOK_Macro) << New->getSourceRange();
18113
18114 // C++11 [dcl.type]p3:
18115 // A type-specifier-seq shall not define a class or enumeration [...].
18116 if (!Invalid && getLangOpts().CPlusPlus &&
18117 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
18118 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18119 << Context.getTagDeclType(New);
18120 Invalid = true;
18121 }
18122
18123 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
18124 DC->getDeclKind() == Decl::Enum) {
18125 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18126 << Context.getTagDeclType(New);
18127 Invalid = true;
18128 }
18129
18130 // Maybe add qualifier info.
18131 if (SS.isNotEmpty()) {
18132 if (SS.isSet()) {
18133 // If this is either a declaration or a definition, check the
18134 // nested-name-specifier against the current context.
18135 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
18136 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18137 /*TemplateId=*/nullptr,
18138 isMemberSpecialization))
18139 Invalid = true;
18140
18142 if (TemplateParameterLists.size() > 0) {
18143 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18144 }
18145 }
18146 else
18147 Invalid = true;
18148 }
18149
18150 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18151 // Add alignment attributes if necessary; these attributes are checked when
18152 // the ASTContext lays out the structure.
18153 //
18154 // It is important for implementing the correct semantics that this
18155 // happen here (in ActOnTag). The #pragma pack stack is
18156 // maintained as a result of parser callbacks which can occur at
18157 // many points during the parsing of a struct declaration (because
18158 // the #pragma tokens are effectively skipped over during the
18159 // parsing of the struct).
18160 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18163 }
18164 }
18165
18166 if (ModulePrivateLoc.isValid()) {
18167 if (isMemberSpecialization)
18168 Diag(New->getLocation(), diag::err_module_private_specialization)
18169 << 2
18170 << FixItHint::CreateRemoval(ModulePrivateLoc);
18171 // __module_private__ does not apply to local classes. However, we only
18172 // diagnose this as an error when the declaration specifiers are
18173 // freestanding. Here, we just ignore the __module_private__.
18174 else if (!SearchDC->isFunctionOrMethod())
18175 New->setModulePrivate();
18176 }
18177
18178 // If this is a specialization of a member class (of a class template),
18179 // check the specialization.
18180 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18181 Invalid = true;
18182
18183 // If we're declaring or defining a tag in function prototype scope in C,
18184 // note that this type can only be used within the function and add it to
18185 // the list of decls to inject into the function definition scope.
18186 if ((Name || Kind == TagTypeKind::Enum) &&
18187 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18188 if (getLangOpts().CPlusPlus) {
18189 // C++ [dcl.fct]p6:
18190 // Types shall not be defined in return or parameter types.
18191 if (TUK == TUK_Definition && !IsTypeSpecifier) {
18192 Diag(Loc, diag::err_type_defined_in_param_type)
18193 << Name;
18194 Invalid = true;
18195 }
18196 } else if (!PrevDecl) {
18197 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18198 }
18199 }
18200
18201 if (Invalid)
18202 New->setInvalidDecl();
18203
18204 // Set the lexical context. If the tag has a C++ scope specifier, the
18205 // lexical context will be different from the semantic context.
18207
18208 // Mark this as a friend decl if applicable.
18209 // In Microsoft mode, a friend declaration also acts as a forward
18210 // declaration so we always pass true to setObjectOfFriendDecl to make
18211 // the tag name visible.
18212 if (TUK == TUK_Friend)
18213 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18214
18215 // Set the access specifier.
18216 if (!Invalid && SearchDC->isRecord())
18217 SetMemberAccessSpecifier(New, PrevDecl, AS);
18218
18219 if (PrevDecl)
18220 CheckRedeclarationInModule(New, PrevDecl);
18221
18222 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
18223 New->startDefinition();
18224
18225 ProcessDeclAttributeList(S, New, Attrs);
18226 AddPragmaAttributes(S, New);
18227
18228 // If this has an identifier, add it to the scope stack.
18229 if (TUK == TUK_Friend) {
18230 // We might be replacing an existing declaration in the lookup tables;
18231 // if so, borrow its access specifier.
18232 if (PrevDecl)
18233 New->setAccess(PrevDecl->getAccess());
18234
18236 DC->makeDeclVisibleInContext(New);
18237 if (Name) // can be null along some error paths
18238 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18239 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18240 } else if (Name) {
18241 S = getNonFieldDeclScope(S);
18242 PushOnScopeChains(New, S, true);
18243 } else {
18244 CurContext->addDecl(New);
18245 }
18246
18247 // If this is the C FILE type, notify the AST context.
18248 if (IdentifierInfo *II = New->getIdentifier())
18249 if (!New->isInvalidDecl() &&
18251 II->isStr("FILE"))
18252 Context.setFILEDecl(New);
18253
18254 if (PrevDecl)
18255 mergeDeclAttributes(New, PrevDecl);
18256
18257 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
18259
18260 // If there's a #pragma GCC visibility in scope, set the visibility of this
18261 // record.
18263
18264 if (isMemberSpecialization && !New->isInvalidDecl())
18266
18267 OwnedDecl = true;
18268 // In C++, don't return an invalid declaration. We can't recover well from
18269 // the cases where we make the type anonymous.
18270 if (Invalid && getLangOpts().CPlusPlus) {
18271 if (New->isBeingDefined())
18272 if (auto RD = dyn_cast<RecordDecl>(New))
18273 RD->completeDefinition();
18274 return true;
18275 } else if (SkipBody && SkipBody->ShouldSkip) {
18276 return SkipBody->Previous;
18277 } else {
18278 return New;
18279 }
18280}
18281
18284 TagDecl *Tag = cast<TagDecl>(TagD);
18285
18286 // Enter the tag context.
18287 PushDeclContext(S, Tag);
18288
18290
18291 // If there's a #pragma GCC visibility in scope, set the visibility of this
18292 // record.
18294}
18295
18297 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18298 return false;
18299
18300 // Make the previous decl visible.
18302 return true;
18303}
18304
18306 assert(IDecl->getLexicalParent() == CurContext &&
18307 "The next DeclContext should be lexically contained in the current one.");
18308 CurContext = IDecl;
18309}
18310
18312 SourceLocation FinalLoc,
18313 bool IsFinalSpelledSealed,
18314 bool IsAbstract,
18315 SourceLocation LBraceLoc) {
18317 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18318
18319 FieldCollector->StartClass();
18320
18321 if (!Record->getIdentifier())
18322 return;
18323
18324 if (IsAbstract)
18325 Record->markAbstract();
18326
18327 if (FinalLoc.isValid()) {
18328 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18329 IsFinalSpelledSealed
18330 ? FinalAttr::Keyword_sealed
18331 : FinalAttr::Keyword_final));
18332 }
18333 // C++ [class]p2:
18334 // [...] The class-name is also inserted into the scope of the
18335 // class itself; this is known as the injected-class-name. For
18336 // purposes of access checking, the injected-class-name is treated
18337 // as if it were a public member name.
18338 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18339 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18340 Record->getLocation(), Record->getIdentifier(),
18341 /*PrevDecl=*/nullptr,
18342 /*DelayTypeCreation=*/true);
18343 Context.getTypeDeclType(InjectedClassName, Record);
18344 InjectedClassName->setImplicit();
18345 InjectedClassName->setAccess(AS_public);
18346 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18347 InjectedClassName->setDescribedClassTemplate(Template);
18348 PushOnScopeChains(InjectedClassName, S);
18349 assert(InjectedClassName->isInjectedClassName() &&
18350 "Broken injected-class-name");
18351}
18352
18354 SourceRange BraceRange) {
18356 TagDecl *Tag = cast<TagDecl>(TagD);
18357 Tag->setBraceRange(BraceRange);
18358
18359 // Make sure we "complete" the definition even it is invalid.
18360 if (Tag->isBeingDefined()) {
18361 assert(Tag->isInvalidDecl() && "We should already have completed it");
18362 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18363 RD->completeDefinition();
18364 }
18365
18366 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18367 FieldCollector->FinishClass();
18368 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18369 auto *Def = RD->getDefinition();
18370 assert(Def && "The record is expected to have a completed definition");
18371 unsigned NumInitMethods = 0;
18372 for (auto *Method : Def->methods()) {
18373 if (!Method->getIdentifier())
18374 continue;
18375 if (Method->getName() == "__init")
18376 NumInitMethods++;
18377 }
18378 if (NumInitMethods > 1 || !Def->hasInitMethod())
18379 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18380 }
18381 }
18382
18383 // Exit this scope of this tag's definition.
18385
18386 if (getCurLexicalContext()->isObjCContainer() &&
18387 Tag->getDeclContext()->isFileContext())
18389
18390 // Notify the consumer that we've defined a tag.
18391 if (!Tag->isInvalidDecl())
18393
18394 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18395 // from XLs and instead matches the XL #pragma pack(1) behavior.
18396 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18397 AlignPackStack.hasValue()) {
18398 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18399 // Only diagnose #pragma align(packed).
18400 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18401 return;
18402 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18403 if (!RD)
18404 return;
18405 // Only warn if there is at least 1 bitfield member.
18406 if (llvm::any_of(RD->fields(),
18407 [](const FieldDecl *FD) { return FD->isBitField(); }))
18408 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18409 }
18410}
18411
18413 // Exit this scope of this interface definition.
18415}
18416
18418 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18419 OriginalLexicalContext = ObjCCtx;
18421}
18422
18425 OriginalLexicalContext = nullptr;
18426}
18427
18430 TagDecl *Tag = cast<TagDecl>(TagD);
18431 Tag->setInvalidDecl();
18432
18433 // Make sure we "complete" the definition even it is invalid.
18434 if (Tag->isBeingDefined()) {
18435 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18436 RD->completeDefinition();
18437 }
18438
18439 // We're undoing ActOnTagStartDefinition here, not
18440 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18441 // the FieldCollector.
18442
18444}
18445
18446// Note that FieldName may be null for anonymous bitfields.
18448 IdentifierInfo *FieldName, QualType FieldTy,
18449 bool IsMsStruct, Expr *BitWidth) {
18450 assert(BitWidth);
18451 if (BitWidth->containsErrors())
18452 return ExprError();
18453
18454 // C99 6.7.2.1p4 - verify the field type.
18455 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18456 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18457 // Handle incomplete and sizeless types with a specific error.
18458 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18459 diag::err_field_incomplete_or_sizeless))
18460 return ExprError();
18461 if (FieldName)
18462 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18463 << FieldName << FieldTy << BitWidth->getSourceRange();
18464 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18465 << FieldTy << BitWidth->getSourceRange();
18466 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18468 return ExprError();
18469
18470 // If the bit-width is type- or value-dependent, don't try to check
18471 // it now.
18472 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18473 return BitWidth;
18474
18475 llvm::APSInt Value;
18477 if (ICE.isInvalid())
18478 return ICE;
18479 BitWidth = ICE.get();
18480
18481 // Zero-width bitfield is ok for anonymous field.
18482 if (Value == 0 && FieldName)
18483 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18484 << FieldName << BitWidth->getSourceRange();
18485
18486 if (Value.isSigned() && Value.isNegative()) {
18487 if (FieldName)
18488 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18489 << FieldName << toString(Value, 10);
18490 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18491 << toString(Value, 10);
18492 }
18493
18494 // The size of the bit-field must not exceed our maximum permitted object
18495 // size.
18496 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18497 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18498 << !FieldName << FieldName << toString(Value, 10);
18499 }
18500
18501 if (!FieldTy->isDependentType()) {
18502 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18503 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18504 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18505
18506 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18507 // ABI.
18508 bool CStdConstraintViolation =
18509 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18510 bool MSBitfieldViolation =
18511 Value.ugt(TypeStorageSize) &&
18512 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18513 if (CStdConstraintViolation || MSBitfieldViolation) {
18514 unsigned DiagWidth =
18515 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18516 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18517 << (bool)FieldName << FieldName << toString(Value, 10)
18518 << !CStdConstraintViolation << DiagWidth;
18519 }
18520
18521 // Warn on types where the user might conceivably expect to get all
18522 // specified bits as value bits: that's all integral types other than
18523 // 'bool'.
18524 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18525 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18526 << FieldName << toString(Value, 10)
18527 << (unsigned)TypeWidth;
18528 }
18529 }
18530
18531 return BitWidth;
18532}
18533
18534/// ActOnField - Each field of a C struct/union is passed into this in order
18535/// to create a FieldDecl object for it.
18537 Declarator &D, Expr *BitfieldWidth) {
18538 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18539 D, BitfieldWidth,
18540 /*InitStyle=*/ICIS_NoInit, AS_public);
18541 return Res;
18542}
18543
18544/// HandleField - Analyze a field of a C struct or a C++ data member.
18545///
18547 SourceLocation DeclStart,
18548 Declarator &D, Expr *BitWidth,
18549 InClassInitStyle InitStyle,
18550 AccessSpecifier AS) {
18551 if (D.isDecompositionDeclarator()) {
18553 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18554 << Decomp.getSourceRange();
18555 return nullptr;
18556 }
18557
18558 IdentifierInfo *II = D.getIdentifier();
18559 SourceLocation Loc = DeclStart;
18560 if (II) Loc = D.getIdentifierLoc();
18561
18563 QualType T = TInfo->getType();
18564 if (getLangOpts().CPlusPlus) {
18566
18569 D.setInvalidType();
18570 T = Context.IntTy;
18571 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18572 }
18573 }
18574
18576
18578 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18579 << getLangOpts().CPlusPlus17;
18582 diag::err_invalid_thread)
18584
18585 // Check to see if this name was declared as a member previously
18586 NamedDecl *PrevDecl = nullptr;
18587 LookupResult Previous(*this, II, Loc, LookupMemberName,
18589 LookupName(Previous, S);
18590 switch (Previous.getResultKind()) {
18593 PrevDecl = Previous.getAsSingle<NamedDecl>();
18594 break;
18595
18597 PrevDecl = Previous.getRepresentativeDecl();
18598 break;
18599
18603 break;
18604 }
18605 Previous.suppressDiagnostics();
18606
18607 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18608 // Maybe we will complain about the shadowed template parameter.
18610 // Just pretend that we didn't see the previous declaration.
18611 PrevDecl = nullptr;
18612 }
18613
18614 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18615 PrevDecl = nullptr;
18616
18617 bool Mutable
18619 SourceLocation TSSL = D.getBeginLoc();
18620 FieldDecl *NewFD
18621 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18622 TSSL, AS, PrevDecl, &D);
18623
18624 if (NewFD->isInvalidDecl())
18625 Record->setInvalidDecl();
18626
18628 NewFD->setModulePrivate();
18629
18630 if (NewFD->isInvalidDecl() && PrevDecl) {
18631 // Don't introduce NewFD into scope; there's already something
18632 // with the same name in the same scope.
18633 } else if (II) {
18634 PushOnScopeChains(NewFD, S);
18635 } else
18636 Record->addDecl(NewFD);
18637
18638 return NewFD;
18639}
18640
18641/// Build a new FieldDecl and check its well-formedness.
18642///
18643/// This routine builds a new FieldDecl given the fields name, type,
18644/// record, etc. \p PrevDecl should refer to any previous declaration
18645/// with the same name and in the same scope as the field to be
18646/// created.
18647///
18648/// \returns a new FieldDecl.
18649///
18650/// \todo The Declarator argument is a hack. It will be removed once
18652 TypeSourceInfo *TInfo,
18654 bool Mutable, Expr *BitWidth,
18655 InClassInitStyle InitStyle,
18656 SourceLocation TSSL,
18657 AccessSpecifier AS, NamedDecl *PrevDecl,
18658 Declarator *D) {
18659 IdentifierInfo *II = Name.getAsIdentifierInfo();
18660 bool InvalidDecl = false;
18661 if (D) InvalidDecl = D->isInvalidType();
18662
18663 // If we receive a broken type, recover by assuming 'int' and
18664 // marking this declaration as invalid.
18665 if (T.isNull() || T->containsErrors()) {
18666 InvalidDecl = true;
18667 T = Context.IntTy;
18668 }
18669
18671 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18672 if (RequireCompleteSizedType(Loc, EltTy,
18673 diag::err_field_incomplete_or_sizeless)) {
18674 // Fields of incomplete type force their record to be invalid.
18675 Record->setInvalidDecl();
18676 InvalidDecl = true;
18677 } else {
18678 NamedDecl *Def;
18679 EltTy->isIncompleteType(&Def);
18680 if (Def && Def->isInvalidDecl()) {
18681 Record->setInvalidDecl();
18682 InvalidDecl = true;
18683 }
18684 }
18685 }
18686
18687 // TR 18037 does not allow fields to be declared with address space
18690 Diag(Loc, diag::err_field_with_address_space);
18691 Record->setInvalidDecl();
18692 InvalidDecl = true;
18693 }
18694
18695 if (LangOpts.OpenCL) {
18696 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18697 // used as structure or union field: image, sampler, event or block types.
18698 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18699 T->isBlockPointerType()) {
18700 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18701 Record->setInvalidDecl();
18702 InvalidDecl = true;
18703 }
18704 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18705 // is enabled.
18706 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18707 "__cl_clang_bitfields", LangOpts)) {
18708 Diag(Loc, diag::err_opencl_bitfields);
18709 InvalidDecl = true;
18710 }
18711 }
18712
18713 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18714 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18715 T.hasQualifiers()) {
18716 InvalidDecl = true;
18717 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18718 }
18719
18720 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18721 // than a variably modified type.
18722 if (!InvalidDecl && T->isVariablyModifiedType()) {
18724 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18725 InvalidDecl = true;
18726 }
18727
18728 // Fields can not have abstract class types
18729 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18730 diag::err_abstract_type_in_decl,
18732 InvalidDecl = true;
18733
18734 if (InvalidDecl)
18735 BitWidth = nullptr;
18736 // If this is declared as a bit-field, check the bit-field.
18737 if (BitWidth) {
18738 BitWidth =
18739 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18740 if (!BitWidth) {
18741 InvalidDecl = true;
18742 BitWidth = nullptr;
18743 }
18744 }
18745
18746 // Check that 'mutable' is consistent with the type of the declaration.
18747 if (!InvalidDecl && Mutable) {
18748 unsigned DiagID = 0;
18749 if (T->isReferenceType())
18750 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18751 : diag::err_mutable_reference;
18752 else if (T.isConstQualified())
18753 DiagID = diag::err_mutable_const;
18754
18755 if (DiagID) {
18756 SourceLocation ErrLoc = Loc;
18757 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18758 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18759 Diag(ErrLoc, DiagID);
18760 if (DiagID != diag::ext_mutable_reference) {
18761 Mutable = false;
18762 InvalidDecl = true;
18763 }
18764 }
18765 }
18766
18767 // C++11 [class.union]p8 (DR1460):
18768 // At most one variant member of a union may have a
18769 // brace-or-equal-initializer.
18770 if (InitStyle != ICIS_NoInit)
18771 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18772
18773 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18774 BitWidth, Mutable, InitStyle);
18775 if (InvalidDecl)
18776 NewFD->setInvalidDecl();
18777
18778 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18779 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18780 Diag(Loc, diag::err_duplicate_member) << II;
18781 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18782 NewFD->setInvalidDecl();
18783 }
18784
18785 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18786 if (Record->isUnion()) {
18787 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18788 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18789 if (RDecl->getDefinition()) {
18790 // C++ [class.union]p1: An object of a class with a non-trivial
18791 // constructor, a non-trivial copy constructor, a non-trivial
18792 // destructor, or a non-trivial copy assignment operator
18793 // cannot be a member of a union, nor can an array of such
18794 // objects.
18795 if (CheckNontrivialField(NewFD))
18796 NewFD->setInvalidDecl();
18797 }
18798 }
18799
18800 // C++ [class.union]p1: If a union contains a member of reference type,
18801 // the program is ill-formed, except when compiling with MSVC extensions
18802 // enabled.
18803 if (EltTy->isReferenceType()) {
18804 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18805 diag::ext_union_member_of_reference_type :
18806 diag::err_union_member_of_reference_type)
18807 << NewFD->getDeclName() << EltTy;
18808 if (!getLangOpts().MicrosoftExt)
18809 NewFD->setInvalidDecl();
18810 }
18811 }
18812 }
18813
18814 // FIXME: We need to pass in the attributes given an AST
18815 // representation, not a parser representation.
18816 if (D) {
18817 // FIXME: The current scope is almost... but not entirely... correct here.
18818 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18819
18820 if (NewFD->hasAttrs())
18822 }
18823
18824 // In auto-retain/release, infer strong retension for fields of
18825 // retainable type.
18826 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18827 NewFD->setInvalidDecl();
18828
18829 if (T.isObjCGCWeak())
18830 Diag(Loc, diag::warn_attribute_weak_on_field);
18831
18832 // PPC MMA non-pointer types are not allowed as field types.
18833 if (Context.getTargetInfo().getTriple().isPPC64() &&
18834 CheckPPCMMAType(T, NewFD->getLocation()))
18835 NewFD->setInvalidDecl();
18836
18837 NewFD->setAccess(AS);
18838 return NewFD;
18839}
18840
18842 assert(FD);
18843 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18844
18845 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18846 return false;
18847
18849 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18850 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18851 if (RDecl->getDefinition()) {
18852 // We check for copy constructors before constructors
18853 // because otherwise we'll never get complaints about
18854 // copy constructors.
18855
18857 // We're required to check for any non-trivial constructors. Since the
18858 // implicit default constructor is suppressed if there are any
18859 // user-declared constructors, we just need to check that there is a
18860 // trivial default constructor and a trivial copy constructor. (We don't
18861 // worry about move constructors here, since this is a C++98 check.)
18862 if (RDecl->hasNonTrivialCopyConstructor())
18863 member = CXXCopyConstructor;
18864 else if (!RDecl->hasTrivialDefaultConstructor())
18865 member = CXXDefaultConstructor;
18866 else if (RDecl->hasNonTrivialCopyAssignment())
18867 member = CXXCopyAssignment;
18868 else if (RDecl->hasNonTrivialDestructor())
18869 member = CXXDestructor;
18870
18871 if (member != CXXInvalid) {
18872 if (!getLangOpts().CPlusPlus11 &&
18873 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18874 // Objective-C++ ARC: it is an error to have a non-trivial field of
18875 // a union. However, system headers in Objective-C programs
18876 // occasionally have Objective-C lifetime objects within unions,
18877 // and rather than cause the program to fail, we make those
18878 // members unavailable.
18879 SourceLocation Loc = FD->getLocation();
18880 if (getSourceManager().isInSystemHeader(Loc)) {
18881 if (!FD->hasAttr<UnavailableAttr>())
18882 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18883 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18884 return false;
18885 }
18886 }
18887
18889 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18890 diag::err_illegal_union_or_anon_struct_member)
18891 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18892 DiagnoseNontrivial(RDecl, member);
18893 return !getLangOpts().CPlusPlus11;
18894 }
18895 }
18896 }
18897
18898 return false;
18899}
18900
18901/// TranslateIvarVisibility - Translate visibility from a token ID to an
18902/// AST enum value.
18905 switch (ivarVisibility) {
18906 default: llvm_unreachable("Unknown visitibility kind");
18907 case tok::objc_private: return ObjCIvarDecl::Private;
18908 case tok::objc_public: return ObjCIvarDecl::Public;
18909 case tok::objc_protected: return ObjCIvarDecl::Protected;
18910 case tok::objc_package: return ObjCIvarDecl::Package;
18911 }
18912}
18913
18914/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18915/// in order to create an IvarDecl object for it.
18918
18919 IdentifierInfo *II = D.getIdentifier();
18920 SourceLocation Loc = DeclStart;
18921 if (II) Loc = D.getIdentifierLoc();
18922
18923 // FIXME: Unnamed fields can be handled in various different ways, for
18924 // example, unnamed unions inject all members into the struct namespace!
18925
18927 QualType T = TInfo->getType();
18928
18929 if (BitWidth) {
18930 // 6.7.2.1p3, 6.7.2.1p4
18931 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18932 if (!BitWidth)
18933 D.setInvalidType();
18934 } else {
18935 // Not a bitfield.
18936
18937 // validate II.
18938
18939 }
18940 if (T->isReferenceType()) {
18941 Diag(Loc, diag::err_ivar_reference_type);
18942 D.setInvalidType();
18943 }
18944 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18945 // than a variably modified type.
18946 else if (T->isVariablyModifiedType()) {
18948 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18949 D.setInvalidType();
18950 }
18951
18952 // Get the visibility (access control) for this ivar.
18954 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18956 // Must set ivar's DeclContext to its enclosing interface.
18957 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18958 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18959 return nullptr;
18960 ObjCContainerDecl *EnclosingContext;
18961 if (ObjCImplementationDecl *IMPDecl =
18962 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18964 // Case of ivar declared in an implementation. Context is that of its class.
18965 EnclosingContext = IMPDecl->getClassInterface();
18966 assert(EnclosingContext && "Implementation has no class interface!");
18967 }
18968 else
18969 EnclosingContext = EnclosingDecl;
18970 } else {
18971 if (ObjCCategoryDecl *CDecl =
18972 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18973 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18974 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18975 return nullptr;
18976 }
18977 }
18978 EnclosingContext = EnclosingDecl;
18979 }
18980
18981 // Construct the decl.
18983 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
18984
18985 if (T->containsErrors())
18986 NewID->setInvalidDecl();
18987
18988 if (II) {
18989 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18991 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18992 && !isa<TagDecl>(PrevDecl)) {
18993 Diag(Loc, diag::err_duplicate_member) << II;
18994 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18995 NewID->setInvalidDecl();
18996 }
18997 }
18998
18999 // Process attributes attached to the ivar.
19000 ProcessDeclAttributes(S, NewID, D);
19001
19002 if (D.isInvalidType())
19003 NewID->setInvalidDecl();
19004
19005 // In ARC, infer 'retaining' for ivars of retainable type.
19006 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
19007 NewID->setInvalidDecl();
19008
19010 NewID->setModulePrivate();
19011
19012 if (II) {
19013 // FIXME: When interfaces are DeclContexts, we'll need to add
19014 // these to the interface.
19015 S->AddDecl(NewID);
19016 IdResolver.AddDecl(NewID);
19017 }
19018
19020 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
19021 Diag(Loc, diag::warn_ivars_in_interface);
19022
19023 return NewID;
19024}
19025
19026/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
19027/// class and class extensions. For every class \@interface and class
19028/// extension \@interface, if the last ivar is a bitfield of any type,
19029/// then add an implicit `char :0` ivar to the end of that interface.
19031 SmallVectorImpl<Decl *> &AllIvarDecls) {
19032 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19033 return;
19034
19035 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19036 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19037
19038 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
19039 return;
19040 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19041 if (!ID) {
19042 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19043 if (!CD->IsClassExtension())
19044 return;
19045 }
19046 // No need to add this to end of @implementation.
19047 else
19048 return;
19049 }
19050 // All conditions are met. Add a new bitfield to the tail end of ivars.
19051 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19052 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19053
19054 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
19055 DeclLoc, DeclLoc, nullptr,
19058 DeclLoc),
19060 true);
19061 AllIvarDecls.push_back(Ivar);
19062}
19063
19064/// [class.dtor]p4:
19065/// At the end of the definition of a class, overload resolution is
19066/// performed among the prospective destructors declared in that class with
19067/// an empty argument list to select the destructor for the class, also
19068/// known as the selected destructor.
19069///
19070/// We do the overload resolution here, then mark the selected constructor in the AST.
19071/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19073 if (!Record->hasUserDeclaredDestructor()) {
19074 return;
19075 }
19076
19077 SourceLocation Loc = Record->getLocation();
19079
19080 for (auto *Decl : Record->decls()) {
19081 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19082 if (DD->isInvalidDecl())
19083 continue;
19084 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19085 OCS);
19086 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19087 }
19088 }
19089
19090 if (OCS.empty()) {
19091 return;
19092 }
19094 unsigned Msg = 0;
19095 OverloadCandidateDisplayKind DisplayKind;
19096
19097 switch (OCS.BestViableFunction(S, Loc, Best)) {
19098 case OR_Success:
19099 case OR_Deleted:
19100 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19101 break;
19102
19103 case OR_Ambiguous:
19104 Msg = diag::err_ambiguous_destructor;
19105 DisplayKind = OCD_AmbiguousCandidates;
19106 break;
19107
19109 Msg = diag::err_no_viable_destructor;
19110 DisplayKind = OCD_AllCandidates;
19111 break;
19112 }
19113
19114 if (Msg) {
19115 // OpenCL have got their own thing going with destructors. It's slightly broken,
19116 // but we allow it.
19117 if (!S.LangOpts.OpenCL) {
19118 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19119 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19120 Record->setInvalidDecl();
19121 }
19122 // It's a bit hacky: At this point we've raised an error but we want the
19123 // rest of the compiler to continue somehow working. However almost
19124 // everything we'll try to do with the class will depend on there being a
19125 // destructor. So let's pretend the first one is selected and hope for the
19126 // best.
19127 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19128 }
19129}
19130
19131/// [class.mem.special]p5
19132/// Two special member functions are of the same kind if:
19133/// - they are both default constructors,
19134/// - they are both copy or move constructors with the same first parameter
19135/// type, or
19136/// - they are both copy or move assignment operators with the same first
19137/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19139 CXXMethodDecl *M1,
19140 CXXMethodDecl *M2,
19142 // We don't want to compare templates to non-templates: See
19143 // https://github.com/llvm/llvm-project/issues/59206
19144 if (CSM == Sema::CXXDefaultConstructor)
19145 return bool(M1->getDescribedFunctionTemplate()) ==
19147 // FIXME: better resolve CWG
19148 // https://cplusplus.github.io/CWG/issues/2787.html
19149 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19150 M2->getNonObjectParameter(0)->getType()))
19151 return false;
19154 return false;
19155
19156 return true;
19157}
19158
19159/// [class.mem.special]p6:
19160/// An eligible special member function is a special member function for which:
19161/// - the function is not deleted,
19162/// - the associated constraints, if any, are satisfied, and
19163/// - no special member function of the same kind whose associated constraints
19164/// [CWG2595], if any, are satisfied is more constrained.
19168 SmallVector<bool, 4> SatisfactionStatus;
19169
19170 for (CXXMethodDecl *Method : Methods) {
19171 const Expr *Constraints = Method->getTrailingRequiresClause();
19172 if (!Constraints)
19173 SatisfactionStatus.push_back(true);
19174 else {
19175 ConstraintSatisfaction Satisfaction;
19176 if (S.CheckFunctionConstraints(Method, Satisfaction))
19177 SatisfactionStatus.push_back(false);
19178 else
19179 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19180 }
19181 }
19182
19183 for (size_t i = 0; i < Methods.size(); i++) {
19184 if (!SatisfactionStatus[i])
19185 continue;
19186 CXXMethodDecl *Method = Methods[i];
19187 CXXMethodDecl *OrigMethod = Method;
19188 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19189 OrigMethod = cast<CXXMethodDecl>(MF);
19190
19191 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
19192 bool AnotherMethodIsMoreConstrained = false;
19193 for (size_t j = 0; j < Methods.size(); j++) {
19194 if (i == j || !SatisfactionStatus[j])
19195 continue;
19196 CXXMethodDecl *OtherMethod = Methods[j];
19197 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19198 OtherMethod = cast<CXXMethodDecl>(MF);
19199
19200 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19201 CSM))
19202 continue;
19203
19204 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
19205 if (!OtherConstraints)
19206 continue;
19207 if (!Constraints) {
19208 AnotherMethodIsMoreConstrained = true;
19209 break;
19210 }
19211 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
19212 {Constraints},
19213 AnotherMethodIsMoreConstrained)) {
19214 // There was an error with the constraints comparison. Exit the loop
19215 // and don't consider this function eligible.
19216 AnotherMethodIsMoreConstrained = true;
19217 }
19218 if (AnotherMethodIsMoreConstrained)
19219 break;
19220 }
19221 // FIXME: Do not consider deleted methods as eligible after implementing
19222 // DR1734 and DR1496.
19223 if (!AnotherMethodIsMoreConstrained) {
19224 Method->setIneligibleOrNotSelected(false);
19225 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
19226 }
19227 }
19228}
19229
19232 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19233 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19234 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19235 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19236 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19237
19238 for (auto *Decl : Record->decls()) {
19239 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19240 if (!MD) {
19241 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19242 if (FTD)
19243 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19244 }
19245 if (!MD)
19246 continue;
19247 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19248 if (CD->isInvalidDecl())
19249 continue;
19250 if (CD->isDefaultConstructor())
19251 DefaultConstructors.push_back(MD);
19252 else if (CD->isCopyConstructor())
19253 CopyConstructors.push_back(MD);
19254 else if (CD->isMoveConstructor())
19255 MoveConstructors.push_back(MD);
19256 } else if (MD->isCopyAssignmentOperator()) {
19257 CopyAssignmentOperators.push_back(MD);
19258 } else if (MD->isMoveAssignmentOperator()) {
19259 MoveAssignmentOperators.push_back(MD);
19260 }
19261 }
19262
19263 SetEligibleMethods(S, Record, DefaultConstructors,
19265 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
19266 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
19267 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19269 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19271}
19272
19273void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19274 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19275 SourceLocation RBrac,
19276 const ParsedAttributesView &Attrs) {
19277 assert(EnclosingDecl && "missing record or interface decl");
19278
19279 // If this is an Objective-C @implementation or category and we have
19280 // new fields here we should reset the layout of the interface since
19281 // it will now change.
19282 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19283 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19284 switch (DC->getKind()) {
19285 default: break;
19286 case Decl::ObjCCategory:
19287 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19288 break;
19289 case Decl::ObjCImplementation:
19290 Context.
19291 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19292 break;
19293 }
19294 }
19295
19296 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19297 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19298
19299 // Start counting up the number of named members; make sure to include
19300 // members of anonymous structs and unions in the total.
19301 unsigned NumNamedMembers = 0;
19302 if (Record) {
19303 for (const auto *I : Record->decls()) {
19304 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19305 if (IFD->getDeclName())
19306 ++NumNamedMembers;
19307 }
19308 }
19309
19310 // Verify that all the fields are okay.
19312
19313 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19314 i != end; ++i) {
19315 FieldDecl *FD = cast<FieldDecl>(*i);
19316
19317 // Get the type for the field.
19318 const Type *FDTy = FD->getType().getTypePtr();
19319
19320 if (!FD->isAnonymousStructOrUnion()) {
19321 // Remember all fields written by the user.
19322 RecFields.push_back(FD);
19323 }
19324
19325 // If the field is already invalid for some reason, don't emit more
19326 // diagnostics about it.
19327 if (FD->isInvalidDecl()) {
19328 EnclosingDecl->setInvalidDecl();
19329 continue;
19330 }
19331
19332 // C99 6.7.2.1p2:
19333 // A structure or union shall not contain a member with
19334 // incomplete or function type (hence, a structure shall not
19335 // contain an instance of itself, but may contain a pointer to
19336 // an instance of itself), except that the last member of a
19337 // structure with more than one named member may have incomplete
19338 // array type; such a structure (and any union containing,
19339 // possibly recursively, a member that is such a structure)
19340 // shall not be a member of a structure or an element of an
19341 // array.
19342 bool IsLastField = (i + 1 == Fields.end());
19343 if (FDTy->isFunctionType()) {
19344 // Field declared as a function.
19345 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19346 << FD->getDeclName();
19347 FD->setInvalidDecl();
19348 EnclosingDecl->setInvalidDecl();
19349 continue;
19350 } else if (FDTy->isIncompleteArrayType() &&
19351 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19352 if (Record) {
19353 // Flexible array member.
19354 // Microsoft and g++ is more permissive regarding flexible array.
19355 // It will accept flexible array in union and also
19356 // as the sole element of a struct/class.
19357 unsigned DiagID = 0;
19358 if (!Record->isUnion() && !IsLastField) {
19359 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19360 << FD->getDeclName() << FD->getType()
19361 << llvm::to_underlying(Record->getTagKind());
19362 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19363 FD->setInvalidDecl();
19364 EnclosingDecl->setInvalidDecl();
19365 continue;
19366 } else if (Record->isUnion())
19367 DiagID = getLangOpts().MicrosoftExt
19368 ? diag::ext_flexible_array_union_ms
19369 : getLangOpts().CPlusPlus
19370 ? diag::ext_flexible_array_union_gnu
19371 : diag::err_flexible_array_union;
19372 else if (NumNamedMembers < 1)
19373 DiagID = getLangOpts().MicrosoftExt
19374 ? diag::ext_flexible_array_empty_aggregate_ms
19375 : getLangOpts().CPlusPlus
19376 ? diag::ext_flexible_array_empty_aggregate_gnu
19377 : diag::err_flexible_array_empty_aggregate;
19378
19379 if (DiagID)
19380 Diag(FD->getLocation(), DiagID)
19381 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19382 // While the layout of types that contain virtual bases is not specified
19383 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19384 // virtual bases after the derived members. This would make a flexible
19385 // array member declared at the end of an object not adjacent to the end
19386 // of the type.
19387 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19388 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19389 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19390 if (!getLangOpts().C99)
19391 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19392 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19393
19394 // If the element type has a non-trivial destructor, we would not
19395 // implicitly destroy the elements, so disallow it for now.
19396 //
19397 // FIXME: GCC allows this. We should probably either implicitly delete
19398 // the destructor of the containing class, or just allow this.
19399 QualType BaseElem = Context.getBaseElementType(FD->getType());
19400 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19401 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19402 << FD->getDeclName() << FD->getType();
19403 FD->setInvalidDecl();
19404 EnclosingDecl->setInvalidDecl();
19405 continue;
19406 }
19407 // Okay, we have a legal flexible array member at the end of the struct.
19408 Record->setHasFlexibleArrayMember(true);
19409 } else {
19410 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19411 // unless they are followed by another ivar. That check is done
19412 // elsewhere, after synthesized ivars are known.
19413 }
19414 } else if (!FDTy->isDependentType() &&
19416 FD->getLocation(), FD->getType(),
19417 diag::err_field_incomplete_or_sizeless)) {
19418 // Incomplete type
19419 FD->setInvalidDecl();
19420 EnclosingDecl->setInvalidDecl();
19421 continue;
19422 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19423 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19424 // A type which contains a flexible array member is considered to be a
19425 // flexible array member.
19426 Record->setHasFlexibleArrayMember(true);
19427 if (!Record->isUnion()) {
19428 // If this is a struct/class and this is not the last element, reject
19429 // it. Note that GCC supports variable sized arrays in the middle of
19430 // structures.
19431 if (!IsLastField)
19432 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19433 << FD->getDeclName() << FD->getType();
19434 else {
19435 // We support flexible arrays at the end of structs in
19436 // other structs as an extension.
19437 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19438 << FD->getDeclName();
19439 }
19440 }
19441 }
19442 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19444 diag::err_abstract_type_in_decl,
19446 // Ivars can not have abstract class types
19447 FD->setInvalidDecl();
19448 }
19449 if (Record && FDTTy->getDecl()->hasObjectMember())
19450 Record->setHasObjectMember(true);
19451 if (Record && FDTTy->getDecl()->hasVolatileMember())
19452 Record->setHasVolatileMember(true);
19453 } else if (FDTy->isObjCObjectType()) {
19454 /// A field cannot be an Objective-c object
19455 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19458 FD->setType(T);
19459 } else if (Record && Record->isUnion() &&
19461 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19462 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19465 // For backward compatibility, fields of C unions declared in system
19466 // headers that have non-trivial ObjC ownership qualifications are marked
19467 // as unavailable unless the qualifier is explicit and __strong. This can
19468 // break ABI compatibility between programs compiled with ARC and MRR, but
19469 // is a better option than rejecting programs using those unions under
19470 // ARC.
19471 FD->addAttr(UnavailableAttr::CreateImplicit(
19472 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19473 FD->getLocation()));
19474 } else if (getLangOpts().ObjC &&
19475 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19476 !Record->hasObjectMember()) {
19477 if (FD->getType()->isObjCObjectPointerType() ||
19478 FD->getType().isObjCGCStrong())
19479 Record->setHasObjectMember(true);
19480 else if (Context.getAsArrayType(FD->getType())) {
19481 QualType BaseType = Context.getBaseElementType(FD->getType());
19482 if (BaseType->isRecordType() &&
19483 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19484 Record->setHasObjectMember(true);
19485 else if (BaseType->isObjCObjectPointerType() ||
19486 BaseType.isObjCGCStrong())
19487 Record->setHasObjectMember(true);
19488 }
19489 }
19490
19491 if (Record && !getLangOpts().CPlusPlus &&
19492 !shouldIgnoreForRecordTriviality(FD)) {
19493 QualType FT = FD->getType();
19495 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19497 Record->isUnion())
19498 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19499 }
19502 Record->setNonTrivialToPrimitiveCopy(true);
19503 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19504 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19505 }
19506 if (FT.isDestructedType()) {
19507 Record->setNonTrivialToPrimitiveDestroy(true);
19508 Record->setParamDestroyedInCallee(true);
19509 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19510 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19511 }
19512
19513 if (const auto *RT = FT->getAs<RecordType>()) {
19514 if (RT->getDecl()->getArgPassingRestrictions() ==
19516 Record->setArgPassingRestrictions(
19519 Record->setArgPassingRestrictions(
19521 }
19522
19523 if (Record && FD->getType().isVolatileQualified())
19524 Record->setHasVolatileMember(true);
19525 // Keep track of the number of named members.
19526 if (FD->getIdentifier())
19527 ++NumNamedMembers;
19528 }
19529
19530 // Okay, we successfully defined 'Record'.
19531 if (Record) {
19532 bool Completed = false;
19533 if (CXXRecord) {
19534 if (!CXXRecord->isInvalidDecl()) {
19535 // Set access bits correctly on the directly-declared conversions.
19537 I = CXXRecord->conversion_begin(),
19538 E = CXXRecord->conversion_end(); I != E; ++I)
19539 I.setAccess((*I)->getAccess());
19540 }
19541
19542 // Add any implicitly-declared members to this class.
19544
19545 if (!CXXRecord->isDependentType()) {
19546 if (!CXXRecord->isInvalidDecl()) {
19547 // If we have virtual base classes, we may end up finding multiple
19548 // final overriders for a given virtual function. Check for this
19549 // problem now.
19550 if (CXXRecord->getNumVBases()) {
19551 CXXFinalOverriderMap FinalOverriders;
19552 CXXRecord->getFinalOverriders(FinalOverriders);
19553
19554 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19555 MEnd = FinalOverriders.end();
19556 M != MEnd; ++M) {
19557 for (OverridingMethods::iterator SO = M->second.begin(),
19558 SOEnd = M->second.end();
19559 SO != SOEnd; ++SO) {
19560 assert(SO->second.size() > 0 &&
19561 "Virtual function without overriding functions?");
19562 if (SO->second.size() == 1)
19563 continue;
19564
19565 // C++ [class.virtual]p2:
19566 // In a derived class, if a virtual member function of a base
19567 // class subobject has more than one final overrider the
19568 // program is ill-formed.
19569 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19570 << (const NamedDecl *)M->first << Record;
19571 Diag(M->first->getLocation(),
19572 diag::note_overridden_virtual_function);
19574 OM = SO->second.begin(),
19575 OMEnd = SO->second.end();
19576 OM != OMEnd; ++OM)
19577 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19578 << (const NamedDecl *)M->first << OM->Method->getParent();
19579
19580 Record->setInvalidDecl();
19581 }
19582 }
19583 CXXRecord->completeDefinition(&FinalOverriders);
19584 Completed = true;
19585 }
19586 }
19587 ComputeSelectedDestructor(*this, CXXRecord);
19589 }
19590 }
19591
19592 if (!Completed)
19593 Record->completeDefinition();
19594
19595 // Handle attributes before checking the layout.
19597
19598 // Check to see if a FieldDecl is a pointer to a function.
19599 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19600 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19601 if (!FD) {
19602 // Check whether this is a forward declaration that was inserted by
19603 // Clang. This happens when a non-forward declared / defined type is
19604 // used, e.g.:
19605 //
19606 // struct foo {
19607 // struct bar *(*f)();
19608 // struct bar *(*g)();
19609 // };
19610 //
19611 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19612 // incomplete definition.
19613 if (const auto *TD = dyn_cast<TagDecl>(D))
19614 return !TD->isCompleteDefinition();
19615 return false;
19616 }
19617 QualType FieldType = FD->getType().getDesugaredType(Context);
19618 if (isa<PointerType>(FieldType)) {
19619 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19620 return PointeeType.getDesugaredType(Context)->isFunctionType();
19621 }
19622 return false;
19623 };
19624
19625 // Maybe randomize the record's decls. We automatically randomize a record
19626 // of function pointers, unless it has the "no_randomize_layout" attribute.
19627 if (!getLangOpts().CPlusPlus &&
19628 (Record->hasAttr<RandomizeLayoutAttr>() ||
19629 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19630 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19631 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19632 !Record->isRandomized()) {
19633 SmallVector<Decl *, 32> NewDeclOrdering;
19635 NewDeclOrdering))
19636 Record->reorderDecls(NewDeclOrdering);
19637 }
19638
19639 // We may have deferred checking for a deleted destructor. Check now.
19640 if (CXXRecord) {
19641 auto *Dtor = CXXRecord->getDestructor();
19642 if (Dtor && Dtor->isImplicit() &&
19644 CXXRecord->setImplicitDestructorIsDeleted();
19645 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19646 }
19647 }
19648
19649 if (Record->hasAttrs()) {
19651
19652 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19653 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19654 IA->getRange(), IA->getBestCase(),
19655 IA->getInheritanceModel());
19656 }
19657
19658 // Check if the structure/union declaration is a type that can have zero
19659 // size in C. For C this is a language extension, for C++ it may cause
19660 // compatibility problems.
19661 bool CheckForZeroSize;
19662 if (!getLangOpts().CPlusPlus) {
19663 CheckForZeroSize = true;
19664 } else {
19665 // For C++ filter out types that cannot be referenced in C code.
19666 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19667 CheckForZeroSize =
19668 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19669 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19670 CXXRecord->isCLike();
19671 }
19672 if (CheckForZeroSize) {
19673 bool ZeroSize = true;
19674 bool IsEmpty = true;
19675 unsigned NonBitFields = 0;
19676 for (RecordDecl::field_iterator I = Record->field_begin(),
19677 E = Record->field_end();
19678 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19679 IsEmpty = false;
19680 if (I->isUnnamedBitfield()) {
19681 if (!I->isZeroLengthBitField(Context))
19682 ZeroSize = false;
19683 } else {
19684 ++NonBitFields;
19685 QualType FieldType = I->getType();
19686 if (FieldType->isIncompleteType() ||
19687 !Context.getTypeSizeInChars(FieldType).isZero())
19688 ZeroSize = false;
19689 }
19690 }
19691
19692 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19693 // allowed in C++, but warn if its declaration is inside
19694 // extern "C" block.
19695 if (ZeroSize) {
19696 Diag(RecLoc, getLangOpts().CPlusPlus ?
19697 diag::warn_zero_size_struct_union_in_extern_c :
19698 diag::warn_zero_size_struct_union_compat)
19699 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19700 }
19701
19702 // Structs without named members are extension in C (C99 6.7.2.1p7),
19703 // but are accepted by GCC.
19704 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19705 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19706 diag::ext_no_named_members_in_struct_union)
19707 << Record->isUnion();
19708 }
19709 }
19710 } else {
19711 ObjCIvarDecl **ClsFields =
19712 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19713 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19714 ID->setEndOfDefinitionLoc(RBrac);
19715 // Add ivar's to class's DeclContext.
19716 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19717 ClsFields[i]->setLexicalDeclContext(ID);
19718 ID->addDecl(ClsFields[i]);
19719 }
19720 // Must enforce the rule that ivars in the base classes may not be
19721 // duplicates.
19722 if (ID->getSuperClass())
19723 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19724 } else if (ObjCImplementationDecl *IMPDecl =
19725 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19726 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19727 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19728 // Ivar declared in @implementation never belongs to the implementation.
19729 // Only it is in implementation's lexical context.
19730 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19731 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19732 IMPDecl->setIvarLBraceLoc(LBrac);
19733 IMPDecl->setIvarRBraceLoc(RBrac);
19734 } else if (ObjCCategoryDecl *CDecl =
19735 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19736 // case of ivars in class extension; all other cases have been
19737 // reported as errors elsewhere.
19738 // FIXME. Class extension does not have a LocEnd field.
19739 // CDecl->setLocEnd(RBrac);
19740 // Add ivar's to class extension's DeclContext.
19741 // Diagnose redeclaration of private ivars.
19742 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19743 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19744 if (IDecl) {
19745 if (const ObjCIvarDecl *ClsIvar =
19746 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19747 Diag(ClsFields[i]->getLocation(),
19748 diag::err_duplicate_ivar_declaration);
19749 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19750 continue;
19751 }
19752 for (const auto *Ext : IDecl->known_extensions()) {
19753 if (const ObjCIvarDecl *ClsExtIvar
19754 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19755 Diag(ClsFields[i]->getLocation(),
19756 diag::err_duplicate_ivar_declaration);
19757 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19758 continue;
19759 }
19760 }
19761 }
19762 ClsFields[i]->setLexicalDeclContext(CDecl);
19763 CDecl->addDecl(ClsFields[i]);
19764 }
19765 CDecl->setIvarLBraceLoc(LBrac);
19766 CDecl->setIvarRBraceLoc(RBrac);
19767 }
19768 }
19770}
19771
19772/// Determine whether the given integral value is representable within
19773/// the given type T.
19775 llvm::APSInt &Value,
19776 QualType T) {
19777 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19778 "Integral type required!");
19779 unsigned BitWidth = Context.getIntWidth(T);
19780
19781 if (Value.isUnsigned() || Value.isNonNegative()) {
19783 --BitWidth;
19784 return Value.getActiveBits() <= BitWidth;
19785 }
19786 return Value.getSignificantBits() <= BitWidth;
19787}
19788
19789// Given an integral type, return the next larger integral type
19790// (or a NULL type of no such type exists).
19792 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19793 // enum checking below.
19794 assert((T->isIntegralType(Context) ||
19795 T->isEnumeralType()) && "Integral type required!");
19796 const unsigned NumTypes = 4;
19797 QualType SignedIntegralTypes[NumTypes] = {
19798 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19799 };
19800 QualType UnsignedIntegralTypes[NumTypes] = {
19801 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19802 Context.UnsignedLongLongTy
19803 };
19804
19805 unsigned BitWidth = Context.getTypeSize(T);
19806 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19807 : UnsignedIntegralTypes;
19808 for (unsigned I = 0; I != NumTypes; ++I)
19809 if (Context.getTypeSize(Types[I]) > BitWidth)
19810 return Types[I];
19811
19812 return QualType();
19813}
19814
19816 EnumConstantDecl *LastEnumConst,
19817 SourceLocation IdLoc,
19819 Expr *Val) {
19820 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19821 llvm::APSInt EnumVal(IntWidth);
19822 QualType EltTy;
19823
19825 Val = nullptr;
19826
19827 if (Val)
19828 Val = DefaultLvalueConversion(Val).get();
19829
19830 if (Val) {
19831 if (Enum->isDependentType() || Val->isTypeDependent() ||
19832 Val->containsErrors())
19833 EltTy = Context.DependentTy;
19834 else {
19835 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19836 // underlying type, but do allow it in all other contexts.
19837 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19838 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19839 // constant-expression in the enumerator-definition shall be a converted
19840 // constant expression of the underlying type.
19841 EltTy = Enum->getIntegerType();
19842 ExprResult Converted =
19843 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19845 if (Converted.isInvalid())
19846 Val = nullptr;
19847 else
19848 Val = Converted.get();
19849 } else if (!Val->isValueDependent() &&
19850 !(Val =
19852 .get())) {
19853 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19854 } else {
19855 if (Enum->isComplete()) {
19856 EltTy = Enum->getIntegerType();
19857
19858 // In Obj-C and Microsoft mode, require the enumeration value to be
19859 // representable in the underlying type of the enumeration. In C++11,
19860 // we perform a non-narrowing conversion as part of converted constant
19861 // expression checking.
19862 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19864 .getTriple()
19865 .isWindowsMSVCEnvironment()) {
19866 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19867 } else {
19868 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19869 }
19870 }
19871
19872 // Cast to the underlying type.
19873 Val = ImpCastExprToType(Val, EltTy,
19874 EltTy->isBooleanType() ? CK_IntegralToBoolean
19875 : CK_IntegralCast)
19876 .get();
19877 } else if (getLangOpts().CPlusPlus) {
19878 // C++11 [dcl.enum]p5:
19879 // If the underlying type is not fixed, the type of each enumerator
19880 // is the type of its initializing value:
19881 // - If an initializer is specified for an enumerator, the
19882 // initializing value has the same type as the expression.
19883 EltTy = Val->getType();
19884 } else {
19885 // C99 6.7.2.2p2:
19886 // The expression that defines the value of an enumeration constant
19887 // shall be an integer constant expression that has a value
19888 // representable as an int.
19889
19890 // Complain if the value is not representable in an int.
19892 Diag(IdLoc, diag::ext_enum_value_not_int)
19893 << toString(EnumVal, 10) << Val->getSourceRange()
19894 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19895 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19896 // Force the type of the expression to 'int'.
19897 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19898 }
19899 EltTy = Val->getType();
19900 }
19901 }
19902 }
19903 }
19904
19905 if (!Val) {
19906 if (Enum->isDependentType())
19907 EltTy = Context.DependentTy;
19908 else if (!LastEnumConst) {
19909 // C++0x [dcl.enum]p5:
19910 // If the underlying type is not fixed, the type of each enumerator
19911 // is the type of its initializing value:
19912 // - If no initializer is specified for the first enumerator, the
19913 // initializing value has an unspecified integral type.
19914 //
19915 // GCC uses 'int' for its unspecified integral type, as does
19916 // C99 6.7.2.2p3.
19917 if (Enum->isFixed()) {
19918 EltTy = Enum->getIntegerType();
19919 }
19920 else {
19921 EltTy = Context.IntTy;
19922 }
19923 } else {
19924 // Assign the last value + 1.
19925 EnumVal = LastEnumConst->getInitVal();
19926 ++EnumVal;
19927 EltTy = LastEnumConst->getType();
19928
19929 // Check for overflow on increment.
19930 if (EnumVal < LastEnumConst->getInitVal()) {
19931 // C++0x [dcl.enum]p5:
19932 // If the underlying type is not fixed, the type of each enumerator
19933 // is the type of its initializing value:
19934 //
19935 // - Otherwise the type of the initializing value is the same as
19936 // the type of the initializing value of the preceding enumerator
19937 // unless the incremented value is not representable in that type,
19938 // in which case the type is an unspecified integral type
19939 // sufficient to contain the incremented value. If no such type
19940 // exists, the program is ill-formed.
19942 if (T.isNull() || Enum->isFixed()) {
19943 // There is no integral type larger enough to represent this
19944 // value. Complain, then allow the value to wrap around.
19945 EnumVal = LastEnumConst->getInitVal();
19946 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19947 ++EnumVal;
19948 if (Enum->isFixed())
19949 // When the underlying type is fixed, this is ill-formed.
19950 Diag(IdLoc, diag::err_enumerator_wrapped)
19951 << toString(EnumVal, 10)
19952 << EltTy;
19953 else
19954 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19955 << toString(EnumVal, 10);
19956 } else {
19957 EltTy = T;
19958 }
19959
19960 // Retrieve the last enumerator's value, extent that type to the
19961 // type that is supposed to be large enough to represent the incremented
19962 // value, then increment.
19963 EnumVal = LastEnumConst->getInitVal();
19964 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19965 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19966 ++EnumVal;
19967
19968 // If we're not in C++, diagnose the overflow of enumerator values,
19969 // which in C99 means that the enumerator value is not representable in
19970 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19971 // permits enumerator values that are representable in some larger
19972 // integral type.
19973 if (!getLangOpts().CPlusPlus && !T.isNull())
19974 Diag(IdLoc, diag::warn_enum_value_overflow);
19975 } else if (!getLangOpts().CPlusPlus &&
19976 !EltTy->isDependentType() &&
19977 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19978 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19979 Diag(IdLoc, diag::ext_enum_value_not_int)
19980 << toString(EnumVal, 10) << 1;
19981 }
19982 }
19983 }
19984
19985 if (!EltTy->isDependentType()) {
19986 // Make the enumerator value match the signedness and size of the
19987 // enumerator's type.
19988 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19989 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19990 }
19991
19992 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19993 Val, EnumVal);
19994}
19995
19997 SourceLocation IILoc) {
19998 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20000 return SkipBodyInfo();
20001
20002 // We have an anonymous enum definition. Look up the first enumerator to
20003 // determine if we should merge the definition with an existing one and
20004 // skip the body.
20005 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20007 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20008 if (!PrevECD)
20009 return SkipBodyInfo();
20010
20011 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20012 NamedDecl *Hidden;
20013 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20014 SkipBodyInfo Skip;
20015 Skip.Previous = Hidden;
20016 return Skip;
20017 }
20018
20019 return SkipBodyInfo();
20020}
20021
20022Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20024 const ParsedAttributesView &Attrs,
20025 SourceLocation EqualLoc, Expr *Val) {
20026 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20027 EnumConstantDecl *LastEnumConst =
20028 cast_or_null<EnumConstantDecl>(lastEnumConst);
20029
20030 // The scope passed in may not be a decl scope. Zip up the scope tree until
20031 // we find one that is.
20032 S = getNonFieldDeclScope(S);
20033
20034 // Verify that there isn't already something declared with this name in this
20035 // scope.
20037 LookupName(R, S);
20038 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20039
20040 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20041 // Maybe we will complain about the shadowed template parameter.
20042 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20043 // Just pretend that we didn't see the previous declaration.
20044 PrevDecl = nullptr;
20045 }
20046
20047 // C++ [class.mem]p15:
20048 // If T is the name of a class, then each of the following shall have a name
20049 // different from T:
20050 // - every enumerator of every member of class T that is an unscoped
20051 // enumerated type
20052 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20054 DeclarationNameInfo(Id, IdLoc));
20055
20056 EnumConstantDecl *New =
20057 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20058 if (!New)
20059 return nullptr;
20060
20061 if (PrevDecl) {
20062 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20063 // Check for other kinds of shadowing not already handled.
20064 CheckShadow(New, PrevDecl, R);
20065 }
20066
20067 // When in C++, we may get a TagDecl with the same name; in this case the
20068 // enum constant will 'hide' the tag.
20069 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20070 "Received TagDecl when not in C++!");
20071 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20072 if (isa<EnumConstantDecl>(PrevDecl))
20073 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20074 else
20075 Diag(IdLoc, diag::err_redefinition) << Id;
20076 notePreviousDefinition(PrevDecl, IdLoc);
20077 return nullptr;
20078 }
20079 }
20080
20081 // Process attributes.
20082 ProcessDeclAttributeList(S, New, Attrs);
20083 AddPragmaAttributes(S, New);
20084 ProcessAPINotes(New);
20085
20086 // Register this decl in the current scope stack.
20087 New->setAccess(TheEnumDecl->getAccess());
20088 PushOnScopeChains(New, S);
20089
20091
20092 return New;
20093}
20094
20095// Returns true when the enum initial expression does not trigger the
20096// duplicate enum warning. A few common cases are exempted as follows:
20097// Element2 = Element1
20098// Element2 = Element1 + 1
20099// Element2 = Element1 - 1
20100// Where Element2 and Element1 are from the same enum.
20102 Expr *InitExpr = ECD->getInitExpr();
20103 if (!InitExpr)
20104 return true;
20105 InitExpr = InitExpr->IgnoreImpCasts();
20106
20107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20108 if (!BO->isAdditiveOp())
20109 return true;
20110 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20111 if (!IL)
20112 return true;
20113 if (IL->getValue() != 1)
20114 return true;
20115
20116 InitExpr = BO->getLHS();
20117 }
20118
20119 // This checks if the elements are from the same enum.
20120 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20121 if (!DRE)
20122 return true;
20123
20124 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20125 if (!EnumConstant)
20126 return true;
20127
20128 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
20129 Enum)
20130 return true;
20131
20132 return false;
20133}
20134
20135// Emits a warning when an element is implicitly set a value that
20136// a previous element has already been set to.
20139 // Avoid anonymous enums
20140 if (!Enum->getIdentifier())
20141 return;
20142
20143 // Only check for small enums.
20144 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20145 return;
20146
20147 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20148 return;
20149
20150 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20151 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20152
20153 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20154
20155 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20156 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20157
20158 // Use int64_t as a key to avoid needing special handling for map keys.
20159 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20160 llvm::APSInt Val = D->getInitVal();
20161 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20162 };
20163
20164 DuplicatesVector DupVector;
20165 ValueToVectorMap EnumMap;
20166
20167 // Populate the EnumMap with all values represented by enum constants without
20168 // an initializer.
20169 for (auto *Element : Elements) {
20170 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20171
20172 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20173 // this constant. Skip this enum since it may be ill-formed.
20174 if (!ECD) {
20175 return;
20176 }
20177
20178 // Constants with initializers are handled in the next loop.
20179 if (ECD->getInitExpr())
20180 continue;
20181
20182 // Duplicate values are handled in the next loop.
20183 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20184 }
20185
20186 if (EnumMap.size() == 0)
20187 return;
20188
20189 // Create vectors for any values that has duplicates.
20190 for (auto *Element : Elements) {
20191 // The last loop returned if any constant was null.
20192 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
20193 if (!ValidDuplicateEnum(ECD, Enum))
20194 continue;
20195
20196 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20197 if (Iter == EnumMap.end())
20198 continue;
20199
20200 DeclOrVector& Entry = Iter->second;
20201 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
20202 // Ensure constants are different.
20203 if (D == ECD)
20204 continue;
20205
20206 // Create new vector and push values onto it.
20207 auto Vec = std::make_unique<ECDVector>();
20208 Vec->push_back(D);
20209 Vec->push_back(ECD);
20210
20211 // Update entry to point to the duplicates vector.
20212 Entry = Vec.get();
20213
20214 // Store the vector somewhere we can consult later for quick emission of
20215 // diagnostics.
20216 DupVector.emplace_back(std::move(Vec));
20217 continue;
20218 }
20219
20220 ECDVector *Vec = Entry.get<ECDVector*>();
20221 // Make sure constants are not added more than once.
20222 if (*Vec->begin() == ECD)
20223 continue;
20224
20225 Vec->push_back(ECD);
20226 }
20227
20228 // Emit diagnostics.
20229 for (const auto &Vec : DupVector) {
20230 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20231
20232 // Emit warning for one enum constant.
20233 auto *FirstECD = Vec->front();
20234 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20235 << FirstECD << toString(FirstECD->getInitVal(), 10)
20236 << FirstECD->getSourceRange();
20237
20238 // Emit one note for each of the remaining enum constants with
20239 // the same value.
20240 for (auto *ECD : llvm::drop_begin(*Vec))
20241 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20242 << ECD << toString(ECD->getInitVal(), 10)
20243 << ECD->getSourceRange();
20244 }
20245}
20246
20247bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20248 bool AllowMask) const {
20249 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20250 assert(ED->isCompleteDefinition() && "expected enum definition");
20251
20252 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20253 llvm::APInt &FlagBits = R.first->second;
20254
20255 if (R.second) {
20256 for (auto *E : ED->enumerators()) {
20257 const auto &EVal = E->getInitVal();
20258 // Only single-bit enumerators introduce new flag values.
20259 if (EVal.isPowerOf2())
20260 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20261 }
20262 }
20263
20264 // A value is in a flag enum if either its bits are a subset of the enum's
20265 // flag bits (the first condition) or we are allowing masks and the same is
20266 // true of its complement (the second condition). When masks are allowed, we
20267 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20268 //
20269 // While it's true that any value could be used as a mask, the assumption is
20270 // that a mask will have all of the insignificant bits set. Anything else is
20271 // likely a logic error.
20272 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20273 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20274}
20275
20277 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20278 const ParsedAttributesView &Attrs) {
20279 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20281
20282 ProcessDeclAttributeList(S, Enum, Attrs);
20284
20285 if (Enum->isDependentType()) {
20286 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20287 EnumConstantDecl *ECD =
20288 cast_or_null<EnumConstantDecl>(Elements[i]);
20289 if (!ECD) continue;
20290
20291 ECD->setType(EnumType);
20292 }
20293
20294 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20295 return;
20296 }
20297
20298 // TODO: If the result value doesn't fit in an int, it must be a long or long
20299 // long value. ISO C does not support this, but GCC does as an extension,
20300 // emit a warning.
20301 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20302 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20303 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20304
20305 // Verify that all the values are okay, compute the size of the values, and
20306 // reverse the list.
20307 unsigned NumNegativeBits = 0;
20308 unsigned NumPositiveBits = 0;
20309
20310 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20311 EnumConstantDecl *ECD =
20312 cast_or_null<EnumConstantDecl>(Elements[i]);
20313 if (!ECD) continue; // Already issued a diagnostic.
20314
20315 const llvm::APSInt &InitVal = ECD->getInitVal();
20316
20317 // Keep track of the size of positive and negative values.
20318 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20319 // If the enumerator is zero that should still be counted as a positive
20320 // bit since we need a bit to store the value zero.
20321 unsigned ActiveBits = InitVal.getActiveBits();
20322 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20323 } else {
20324 NumNegativeBits =
20325 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20326 }
20327 }
20328
20329 // If we have an empty set of enumerators we still need one bit.
20330 // From [dcl.enum]p8
20331 // If the enumerator-list is empty, the values of the enumeration are as if
20332 // the enumeration had a single enumerator with value 0
20333 if (!NumPositiveBits && !NumNegativeBits)
20334 NumPositiveBits = 1;
20335
20336 // Figure out the type that should be used for this enum.
20337 QualType BestType;
20338 unsigned BestWidth;
20339
20340 // C++0x N3000 [conv.prom]p3:
20341 // An rvalue of an unscoped enumeration type whose underlying
20342 // type is not fixed can be converted to an rvalue of the first
20343 // of the following types that can represent all the values of
20344 // the enumeration: int, unsigned int, long int, unsigned long
20345 // int, long long int, or unsigned long long int.
20346 // C99 6.4.4.3p2:
20347 // An identifier declared as an enumeration constant has type int.
20348 // The C99 rule is modified by a gcc extension
20349 QualType BestPromotionType;
20350
20351 bool Packed = Enum->hasAttr<PackedAttr>();
20352 // -fshort-enums is the equivalent to specifying the packed attribute on all
20353 // enum definitions.
20354 if (LangOpts.ShortEnums)
20355 Packed = true;
20356
20357 // If the enum already has a type because it is fixed or dictated by the
20358 // target, promote that type instead of analyzing the enumerators.
20359 if (Enum->isComplete()) {
20360 BestType = Enum->getIntegerType();
20361 if (Context.isPromotableIntegerType(BestType))
20362 BestPromotionType = Context.getPromotedIntegerType(BestType);
20363 else
20364 BestPromotionType = BestType;
20365
20366 BestWidth = Context.getIntWidth(BestType);
20367 }
20368 else if (NumNegativeBits) {
20369 // If there is a negative value, figure out the smallest integer type (of
20370 // int/long/longlong) that fits.
20371 // If it's packed, check also if it fits a char or a short.
20372 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20373 BestType = Context.SignedCharTy;
20374 BestWidth = CharWidth;
20375 } else if (Packed && NumNegativeBits <= ShortWidth &&
20376 NumPositiveBits < ShortWidth) {
20377 BestType = Context.ShortTy;
20378 BestWidth = ShortWidth;
20379 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20380 BestType = Context.IntTy;
20381 BestWidth = IntWidth;
20382 } else {
20383 BestWidth = Context.getTargetInfo().getLongWidth();
20384
20385 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20386 BestType = Context.LongTy;
20387 } else {
20388 BestWidth = Context.getTargetInfo().getLongLongWidth();
20389
20390 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20391 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20392 BestType = Context.LongLongTy;
20393 }
20394 }
20395 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20396 } else {
20397 // If there is no negative value, figure out the smallest type that fits
20398 // all of the enumerator values.
20399 // If it's packed, check also if it fits a char or a short.
20400 if (Packed && NumPositiveBits <= CharWidth) {
20401 BestType = Context.UnsignedCharTy;
20402 BestPromotionType = Context.IntTy;
20403 BestWidth = CharWidth;
20404 } else if (Packed && NumPositiveBits <= ShortWidth) {
20405 BestType = Context.UnsignedShortTy;
20406 BestPromotionType = Context.IntTy;
20407 BestWidth = ShortWidth;
20408 } else if (NumPositiveBits <= IntWidth) {
20409 BestType = Context.UnsignedIntTy;
20410 BestWidth = IntWidth;
20411 BestPromotionType
20412 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20414 } else if (NumPositiveBits <=
20415 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20416 BestType = Context.UnsignedLongTy;
20417 BestPromotionType
20418 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20420 } else {
20421 BestWidth = Context.getTargetInfo().getLongLongWidth();
20422 if (NumPositiveBits > BestWidth) {
20423 // This can happen with bit-precise integer types, but those are not
20424 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20425 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20426 // a 128-bit integer, we should consider doing the same.
20427 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20428 }
20429 BestType = Context.UnsignedLongLongTy;
20430 BestPromotionType
20431 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20433 }
20434 }
20435
20436 // Loop over all of the enumerator constants, changing their types to match
20437 // the type of the enum if needed.
20438 for (auto *D : Elements) {
20439 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20440 if (!ECD) continue; // Already issued a diagnostic.
20441
20442 // Standard C says the enumerators have int type, but we allow, as an
20443 // extension, the enumerators to be larger than int size. If each
20444 // enumerator value fits in an int, type it as an int, otherwise type it the
20445 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20446 // that X has type 'int', not 'unsigned'.
20447
20448 // Determine whether the value fits into an int.
20449 llvm::APSInt InitVal = ECD->getInitVal();
20450
20451 // If it fits into an integer type, force it. Otherwise force it to match
20452 // the enum decl type.
20453 QualType NewTy;
20454 unsigned NewWidth;
20455 bool NewSign;
20456 if (!getLangOpts().CPlusPlus &&
20457 !Enum->isFixed() &&
20459 NewTy = Context.IntTy;
20460 NewWidth = IntWidth;
20461 NewSign = true;
20462 } else if (ECD->getType() == BestType) {
20463 // Already the right type!
20464 if (getLangOpts().CPlusPlus)
20465 // C++ [dcl.enum]p4: Following the closing brace of an
20466 // enum-specifier, each enumerator has the type of its
20467 // enumeration.
20468 ECD->setType(EnumType);
20469 continue;
20470 } else {
20471 NewTy = BestType;
20472 NewWidth = BestWidth;
20473 NewSign = BestType->isSignedIntegerOrEnumerationType();
20474 }
20475
20476 // Adjust the APSInt value.
20477 InitVal = InitVal.extOrTrunc(NewWidth);
20478 InitVal.setIsSigned(NewSign);
20479 ECD->setInitVal(Context, InitVal);
20480
20481 // Adjust the Expr initializer and type.
20482 if (ECD->getInitExpr() &&
20483 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20484 ECD->setInitExpr(ImplicitCastExpr::Create(
20485 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20486 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20487 if (getLangOpts().CPlusPlus)
20488 // C++ [dcl.enum]p4: Following the closing brace of an
20489 // enum-specifier, each enumerator has the type of its
20490 // enumeration.
20491 ECD->setType(EnumType);
20492 else
20493 ECD->setType(NewTy);
20494 }
20495
20496 Enum->completeDefinition(BestType, BestPromotionType,
20497 NumPositiveBits, NumNegativeBits);
20498
20499 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20500
20501 if (Enum->isClosedFlag()) {
20502 for (Decl *D : Elements) {
20503 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20504 if (!ECD) continue; // Already issued a diagnostic.
20505
20506 llvm::APSInt InitVal = ECD->getInitVal();
20507 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20508 !IsValueInFlagEnum(Enum, InitVal, true))
20509 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20510 << ECD << Enum;
20511 }
20512 }
20513
20514 // Now that the enum type is defined, ensure it's not been underaligned.
20515 if (Enum->hasAttrs())
20517}
20518
20520 SourceLocation StartLoc,
20521 SourceLocation EndLoc) {
20522 StringLiteral *AsmString = cast<StringLiteral>(expr);
20523
20525 AsmString, StartLoc,
20526 EndLoc);
20527 CurContext->addDecl(New);
20528 return New;
20529}
20530
20532 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20533 CurContext->addDecl(New);
20534 PushDeclContext(S, New);
20536 PushCompoundScope(false);
20537 return New;
20538}
20539
20541 D->setStmt(Statement);
20545}
20546
20548 IdentifierInfo* AliasName,
20549 SourceLocation PragmaLoc,
20550 SourceLocation NameLoc,
20551 SourceLocation AliasNameLoc) {
20552 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20554 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20556 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20557 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20558
20559 // If a declaration that:
20560 // 1) declares a function or a variable
20561 // 2) has external linkage
20562 // already exists, add a label attribute to it.
20563 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20564 if (isDeclExternC(PrevDecl))
20565 PrevDecl->addAttr(Attr);
20566 else
20567 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20568 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20569 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20570 } else
20571 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20572}
20573
20575 SourceLocation PragmaLoc,
20576 SourceLocation NameLoc) {
20577 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20578
20579 if (PrevDecl) {
20580 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20581 } else {
20582 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20583 }
20584}
20585
20587 IdentifierInfo* AliasName,
20588 SourceLocation PragmaLoc,
20589 SourceLocation NameLoc,
20590 SourceLocation AliasNameLoc) {
20591 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20593 WeakInfo W = WeakInfo(Name, NameLoc);
20594
20595 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20596 if (!PrevDecl->hasAttr<AliasAttr>())
20597 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20599 } else {
20600 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20601 }
20602}
20603
20605 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20606}
20607
20609 bool Final) {
20610 assert(FD && "Expected non-null FunctionDecl");
20611
20612 // SYCL functions can be template, so we check if they have appropriate
20613 // attribute prior to checking if it is a template.
20614 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20616
20617 // Templates are emitted when they're instantiated.
20618 if (FD->isDependentContext())
20620
20621 // Check whether this function is an externally visible definition.
20622 auto IsEmittedForExternalSymbol = [this, FD]() {
20623 // We have to check the GVA linkage of the function's *definition* -- if we
20624 // only have a declaration, we don't know whether or not the function will
20625 // be emitted, because (say) the definition could include "inline".
20626 const FunctionDecl *Def = FD->getDefinition();
20627
20628 return Def && !isDiscardableGVALinkage(
20629 getASTContext().GetGVALinkageForFunction(Def));
20630 };
20631
20632 if (LangOpts.OpenMPIsTargetDevice) {
20633 // In OpenMP device mode we will not emit host only functions, or functions
20634 // we don't need due to their linkage.
20635 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20636 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20637 // DevTy may be changed later by
20638 // #pragma omp declare target to(*) device_type(*).
20639 // Therefore DevTy having no value does not imply host. The emission status
20640 // will be checked again at the end of compilation unit with Final = true.
20641 if (DevTy)
20642 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20644 // If we have an explicit value for the device type, or we are in a target
20645 // declare context, we need to emit all extern and used symbols.
20646 if (isInOpenMPDeclareTargetContext() || DevTy)
20647 if (IsEmittedForExternalSymbol())
20649 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20650 // we'll omit it.
20651 if (Final)
20653 } else if (LangOpts.OpenMP > 45) {
20654 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20655 // function. In 5.0, no_host was introduced which might cause a function to
20656 // be ommitted.
20657 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20658 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20659 if (DevTy)
20660 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20662 }
20663
20664 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20666
20667 if (LangOpts.CUDA) {
20668 // When compiling for device, host functions are never emitted. Similarly,
20669 // when compiling for host, device and global functions are never emitted.
20670 // (Technically, we do emit a host-side stub for global functions, but this
20671 // doesn't count for our purposes here.)
20673 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20675 if (!LangOpts.CUDAIsDevice &&
20676 (T == Sema::CFT_Device || T == Sema::CFT_Global))
20678
20679 if (IsEmittedForExternalSymbol())
20681 }
20682
20683 // Otherwise, the function is known-emitted if it's in our set of
20684 // known-emitted functions.
20686}
20687
20689 // Host-side references to a __global__ function refer to the stub, so the
20690 // function itself is never emitted and therefore should not be marked.
20691 // If we have host fn calls kernel fn calls host+device, the HD function
20692 // does not get instantiated on the host. We model this by omitting at the
20693 // call to the kernel from the callgraph. This ensures that, when compiling
20694 // for host, only HD functions actually called from the host get marked as
20695 // known-emitted.
20696 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20697 IdentifyCUDATarget(Callee) == CFT_Global;
20698}
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:82
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.
const Environment & Env
Definition: HTMLLogger.cpp:148
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::Record Record
Definition: MachO.h:28
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.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:16016
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6958
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:143
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15541
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11469
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:198
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3430
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:3597
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:811
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6645
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:1490
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:6683
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2367
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9278
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:3544
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2883
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, Sema::CXXSpecialMember CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
Definition: SemaDecl.cpp:19165
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8270
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9627
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3328
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7522
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8655
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11827
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:2772
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4515
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11927
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15525
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2082
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15139
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:558
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:7289
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:19774
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:20137
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:5069
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:3011
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:17057
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3579
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7049
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:6024
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:4939
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9314
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:9810
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:16045
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3486
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8624
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2741
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9499
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3126
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8295
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:17221
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:5354
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, Sema::CXXSpecialMember CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
Definition: SemaDecl.cpp:19138
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:8541
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1958
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9821
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:5434
OpenCLParamType
Definition: SemaDecl.cpp:9490
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9494
@ ValidKernelParam
Definition: SemaDecl.cpp:9491
@ InvalidKernelParam
Definition: SemaDecl.cpp:9495
@ RecordKernelParam
Definition: SemaDecl.cpp:9496
@ PtrKernelParam
Definition: SemaDecl.cpp:9493
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9492
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:6133
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:578
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:19072
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7334
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5518
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11398
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:9801
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3391
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3523
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:17041
static bool MultiVersionTypesCompatible(MultiVersionKind Old, MultiVersionKind New)
Definition: SemaDecl.cpp:11592
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2198
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4405
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:9127
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:6059
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:826
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7361
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8259
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8266
@ SDK_Field
Definition: SemaDecl.cpp:8263
@ SDK_Global
Definition: SemaDecl.cpp:8261
@ SDK_Local
Definition: SemaDecl.cpp:8260
@ SDK_Typedef
Definition: SemaDecl.cpp:8264
@ SDK_StaticMember
Definition: SemaDecl.cpp:8262
@ SDK_Using
Definition: SemaDecl.cpp:8265
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4885
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3507
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
Definition: SemaDecl.cpp:18904
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9521
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5532
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12507
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7414
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1815
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:19230
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11229
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1804
static void filterNonConflictingPreviousTypedefDecls(Sema &S, 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:2490
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2985
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:6567
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14943
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7510
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:6006
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11478
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1869
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11179
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6919
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5497
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:240
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:8286
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:11444
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7140
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11244
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:20101
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19791
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, MultiVersionKind NewMVKind, 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:11606
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7320
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2760
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:11060
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1831
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:17258
static bool isRecordType(QualType T)
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:104
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:16003
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:16005
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:700
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1068
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2742
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1095
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:643
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2070
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:1856
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
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:1960
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:1882
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1938
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:2748
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:1114
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:1575
IdentifierTable & Idents
Definition: ASTContext.h:639
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:641
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:770
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:2058
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:1972
CanQualType UnsignedLongTy
Definition: ASTContext.h:1096
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:1088
CanQualType IntTy
Definition: ASTContext.h:1095
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:2141
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1095
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:692
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:2048
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
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:2315
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:1086
CanQualType UnsignedCharTy
Definition: ASTContext.h:1096
CanQualType UnsignedIntTy
Definition: ASTContext.h:1096
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1114
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1097
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1096
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:1553
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1405
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:2745
CanQualType ShortTy
Definition: ASTContext.h:1095
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1869
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:752
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:2164
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:1948
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:1095
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:2217
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2223
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2220
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2229
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2226
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:2346
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:2927
Wrapper for source info for arrays.
Definition: TypeLoc.h:1535
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1537
Expr * getSizeExpr() const
Definition: TypeLoc.h:1557
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1565
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1545
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
QualType getElementType() const
Definition: Type.h:3159
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
SourceLocation getLoc() const
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:629
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:725
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:5147
QualType getModifiedType() const
Definition: Type.h:5169
bool isCallingConv() const
Definition: Type.cpp:3973
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5202
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5524
AutoTypeKeyword getKeyword() const
Definition: Type.h:5555
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4235
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4289
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition: Expr.h:4277
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3834
Expr * getLHS() const
Definition: Expr.h:3883
Expr * getRHS() const
Definition: Expr.h:3885
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3974
A binding in a decomposition declaration.
Definition: DeclCXX.h:4100
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4459
bool doesNotEscape() const
Definition: Decl.h:4610
This class is used for builtin types like 'int'.
Definition: Type.h:2740
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:1530
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1673
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1593
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
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:2760
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:2721
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
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:2888
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:2156
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2792
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:2855
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:2053
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:2453
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2507
bool isVirtual() const
Definition: DeclCXX.h:2108
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2574
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2179
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2486
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:2273
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2214
bool isConst() const
Definition: DeclCXX.h:2105
bool isStatic() const
Definition: DeclCXX.cpp:2185
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2464
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2149
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:1334
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1240
base_class_iterator bases_end()
Definition: DeclCXX.h:627
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1547
base_class_range bases()
Definition: DeclCXX.h:618
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1376
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
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:131
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1929
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:625
capture_const_range captures() const
Definition: DeclCXX.h:1100
bool hasDefinition() const
Definition: DeclCXX.h:571
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1896
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1062
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1900
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1288
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:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:235
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
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:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
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:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
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:2819
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3010
bool isCallToStdMove() const
Definition: Expr.cpp:3496
Expr * getCallee()
Definition: Expr.h:2969
arg_range arguments()
Definition: Expr.h:3058
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:3533
Expr * getSubExpr()
Definition: Expr.h:3539
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:4173
const llvm::APInt & getSize() const
Definition: Type.h:3207
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:162
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:202
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:1379
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2352
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2201
bool isFileContext() const
Definition: DeclBase.h:2147
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1976
bool isObjCContainer() const
Definition: DeclBase.h:2115
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1265
bool isClosure() const
Definition: DeclBase.h:2109
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2092
bool isNamespace() const
Definition: DeclBase.h:2161
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1232
bool isTranslationUnit() const
Definition: DeclBase.h:2152
bool isRecord() const
Definition: DeclBase.h:2156
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1618
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1699
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1568
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1939
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1355
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2332
bool isFunctionOrMethod() const
Definition: DeclBase.h:2128
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1216
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1335
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2069
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1346
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:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:825
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:308
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:591
static const TST TST_typename
Definition: DeclSpec.h:305
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:511
bool isNoreturnSpecified() const
Definition: DeclSpec.h:657
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
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:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:705
static const TST TST_interface
Definition: DeclSpec.h:303
static const TST TST_typeofExpr
Definition: DeclSpec.h:307
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:612
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:704
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:658
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:501
static const TST TST_union
Definition: DeclSpec.h:301
SCS
storage-class-specifier
Definition: DeclSpec.h:250
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
static const TST TST_int
Definition: DeclSpec.h:284
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:826
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1494
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:784
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:622
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:613
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:651
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
static const TST TST_enum
Definition: DeclSpec.h:300
static const TST TST_decltype
Definition: DeclSpec.h:310
static bool isDeclRep(TST T)
Definition: DeclSpec.h:465
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:614
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:309
static const TST TST_class
Definition: DeclSpec.h:304
void ClearConstexprSpec()
Definition: DeclSpec.h:837
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:320
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
Decl * getRepAsDecl() const
Definition: DeclSpec.h:547
static const TST TST_unspecified
Definition: DeclSpec.h:277
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:616
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:788
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:266
static const TST TST_error
Definition: DeclSpec.h:324
ExplicitSpecifier getExplicitSpecifier() const
Definition: DeclSpec.h:640
bool isTypeSpecOwned() const
Definition: DeclSpec.h:537
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:615
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:817
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
static const TST TST_typeofType
Definition: DeclSpec.h:306
static const TST TST_auto
Definition: DeclSpec.h:317
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:828
static const TST TST_struct
Definition: DeclSpec.h:302
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1076
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:440
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
T * getAttr() const
Definition: DeclBase.h:578
bool hasAttrs() const
Definition: DeclBase.h:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:525
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:764
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1151
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:637
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1218
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:1074
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:843
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:968
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:209
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:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2749
bool isInvalidDecl() const
Definition: DeclBase.h:593
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:564
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:507
SourceLocation getLocation() const
Definition: DeclBase.h:444
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:143
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:830
void setImplicit(bool I=true)
Definition: DeclBase.h:599
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:613
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:453
attr_range attrs() const
Definition: DeclBase.h:540
AccessSpecifier getAccess() const
Definition: DeclBase.h:512
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:436
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:838
void dropAttr()
Definition: DeclBase.h:561
AttrVec & getAttrs()
Definition: DeclBase.h:529
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:918
bool hasAttr() const
Definition: DeclBase.h:582
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
Kind getKind() const
Definition: DeclBase.h:447
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h: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:1899
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2455
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2338
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2397
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2046
Expr * getAsmLabel() const
Definition: DeclSpec.h:2701
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2740
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2682
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2763
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2335
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2632
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2712
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition: DeclSpec.h:2662
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2393
bool isRedeclaration() const
Definition: DeclSpec.h:2764
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2685
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:2067
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2082
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:436
bool isFunctionDefinition() const
Definition: DeclSpec.h:2736
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2065
bool hasInitializer() const
Definition: DeclSpec.h:2745
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2732
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2061
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2675
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2329
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2352
bool isInvalidType() const
Definition: DeclSpec.h:2713
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:424
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2081
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2325
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2748
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:2053
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2486
A decomposition declaration.
Definition: DeclCXX.h:4159
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3354
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1789
SourceRange getSourceRange() const
Definition: DeclSpec.h:1835
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1833
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5490
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5511
bool isDeduced() const
Definition: Type.h:5512
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2392
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2372
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2381
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:2292
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2306
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3265
llvm::APSInt getInitVal() const
Definition: Decl.h:3285
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5412
const Expr * getInitExpr() const
Definition: Decl.h:3283
Represents an enum.
Definition: Decl.h:3832
enumerator_range enumerators() const
Definition: Decl.h:3965
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4037
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4001
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4004
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4051
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4819
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4864
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4046
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4839
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3987
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3992
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5118
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1892
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:3045
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:3041
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3025
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:3273
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:870
bool isFPConstrained() const
Definition: LangOptions.h:800
Represents a member of a struct/union/class.
Definition: Decl.h:3025
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3116
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4527
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:4564
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3238
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4512
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5542
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:1959
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2574
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2674
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2413
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4019
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3568
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4012
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4007
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3220
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2258
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2586
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2565
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3838
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3597
param_iterator param_end()
Definition: Decl.h:2664
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2798
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2580
QualType getReturnType() const
Definition: Decl.h:2722
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3541
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2326
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2314
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3453
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4127
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2385
void setWillHaveBody(bool V=true)
Definition: Decl.h:2571
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2380
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4137
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3582
param_iterator param_begin()
Definition: Decl.h:2663
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2700
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:2270
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2477
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3279
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4071
@ TK_MemberSpecialization
Definition: Decl.h:1971
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2765
bool isStatic() const
Definition: Decl.h:2806
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4339
void setTrivial(bool IT)
Definition: Decl.h:2315
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3958
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2407
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2402
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2297
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3457
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2301
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2365
bool isImmediateEscalating() const
Definition: Decl.cpp:3233
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2293
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2564
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2226
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3271
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2793
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:3331
bool param_empty() const
Definition: Decl.h:2662
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:2135
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3145
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2164
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3537
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2322
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2358
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4362
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2810
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3952
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3944
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2410
void setDefaulted(bool D=true)
Definition: Decl.h:2323
bool isConsteval() const
Definition: Decl.h:2419
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:2739
void setBody(Stmt *B)
Definition: Decl.cpp:3213
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3471
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2396
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3979
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3657
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2157
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2485
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3121
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2372
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:3168
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2776
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3523
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2570
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
unsigned getNumParams() const
Definition: Type.h:4432
QualType getParamType(unsigned i) const
Definition: Type.h:4434
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4464
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4555
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4443
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4439
Declaration of a template function.
Definition: DeclTemplate.h:958
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:523
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:537
Wrapper for source info for functions.
Definition: TypeLoc.h:1402
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3910
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4025
CallingConv getCC() const
Definition: Type.h:3972
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:3991
unsigned getRegParm() const
Definition: Type.h:3965
bool getNoCallerSavedRegs() const
Definition: Type.h:3961
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3984
bool getHasRegParm() const
Definition: Type.h:3963
bool getNoReturn() const
Definition: Type.h:3958
bool getProducesResult() const
Definition: Type.h:3959
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4005
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4019
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3799
ExtInfo getExtInfo() const
Definition: Type.h:4128
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3419
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4086
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4082
unsigned getRegParmType() const
Definition: Type.h:4119
CallingConv getCallConv() const
Definition: Type.h:4127
QualType getReturnType() const
Definition: Type.h:4116
bool getCmseNSCallAttr() const
Definition: Type.h:4126
@ SME_PStateSMEnabledMask
Definition: Type.h:4060
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:3649
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2060
Represents a C array with an unspecified size.
Definition: Type.h:3246
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3309
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5440
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2499
Describes an C or C++ initializer list.
Definition: Expr.h:4841
child_range children()
Definition: Expr.h:5033
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:8578
@ 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:957
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:266
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:418
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:582
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:710
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:615
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:453
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:510
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:621
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:492
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:2927
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2918
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:670
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:716
bool hasNext() const
Definition: Lookup.h:701
NamedDecl * next()
Definition: Lookup.h:705
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:553
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:359
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:659
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:744
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:563
bool isAmbiguous() const
Definition: Lookup.h:321
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:328
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:273
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:665
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:570
LookupResultKind getResultKind() const
Definition: Lookup.h:341
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:629
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:263
iterator end() const
Definition: Lookup.h:356
@ 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:355
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:253
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:3182
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3261
Expr * getBase() const
Definition: Expr.h:3255
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3089
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:591
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:607
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:630
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:596
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition: Module.h:200
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:665
@ 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:696
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 * 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.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2323
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:944
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:80
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2595
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1538
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1757
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1947
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1839
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 isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
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:977
@ CSK_Normal
Normal lookup.
Definition: Overload.h:981
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1150
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:5658
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5647
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1177
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1190
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1173
Sugar for parentheses used when specifying types.
Definition: Type.h:2872
Represents a parameter to a function.
Definition: Decl.h:1749
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1809
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1813
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1782
QualType getOriginalType() const
Definition: Decl.cpp:2924
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:831
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:911
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:951
AttributePool & getPool() const
Definition: ParsedAttr.h:957
PipeType - OpenCL20.
Definition: Type.h:6751
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1256
Wrapper for source info for pointers.
Definition: TypeLoc.h:1275
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1281
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
QualType getPointeeType() const
Definition: Type.h:2908
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:737
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6985
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:6979
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
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:7048
@ DK_nontrivial_c_struct
Definition: Type.h:1316
PrimitiveDefaultInitializeKind
Definition: Type.h:1244
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2759
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1006
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1088
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
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:2807
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
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:7042
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
QualType getCanonicalType() const
Definition: Type.h:6954
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2777
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:2791
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1224
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6974
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7022
bool isObjCGCWeak() const
true when Type is objc's weak.
Definition: Type.h:1219
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1323
bool isCanonical() const
Definition: Type.h:6959
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1101
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1124
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1233
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2510
NonConstantStorageReason
Definition: Type.h:821
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1274
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1279
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:7036
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6842
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6849
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4180
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:164
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
bool hasConst() const
Definition: Type.h:264
void removeConst()
Definition: Type.h:266
void addConst()
Definition: Type.h:267
ObjCLifetime getObjCLifetime() const
Definition: Type.h:352
bool empty() const
Definition: Type.h:440
Represents a struct/union/class.
Definition: Decl.h:4133
bool hasObjectMember() const
Definition: Decl.h:4193
field_range fields() const
Definition: Decl.h:4339
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4982
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5001
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5047
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
field_iterator field_begin() const
Definition: Decl.cpp:5035
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6634
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:866
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:4959
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:3009
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3017
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3065
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:375
void RemoveDecl(Decl *D)
Definition: Scope.h:347
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:378
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:575
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:264
@ 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
bool IsAlignAttr() const
Definition: Sema.h:1398
Mode getAlignMode() const
Definition: Sema.h:1400
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2671
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1109
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:1121
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:2894
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:2904
static NameClassification Unknown()
Definition: Sema.h:2874
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:2878
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:2922
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:2910
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:2884
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:2916
static NameClassification UndeclaredNonType()
Definition: Sema.h:2890
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:2898
static NameClassification Error()
Definition: Sema.h:2872
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9755
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9785
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:598
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
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)
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14396
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:11095
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6768
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6810
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:4810
void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl)
Definition: SemaDecl.cpp:18305
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:10034
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:869
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:2568
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9263
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:6728
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2529
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9848
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
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:1575
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:15286
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:6596
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7603
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7607
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:7626
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7642
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:7639
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7615
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7610
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6746
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2214
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5387
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15987
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13045
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:39
NonTrivialCUnionContext
Definition: Sema.h:3140
@ NTCUC_CopyInit
Definition: Sema.h:3150
@ NTCUC_AutoVar
Definition: Sema.h:3148
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3146
@ NTCUC_FunctionReturn
Definition: Sema.h:3144
@ NTCUC_FunctionParam
Definition: Sema.h:3142
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:3648
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:6215
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:991
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:3101
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18428
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
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.
Definition: SemaExpr.cpp:3028
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:6182
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:997
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18353
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:3648
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:2745
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1324
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:16518
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:4954
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15163
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12421
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:1097
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:18205
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)
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1474
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:2260
Preprocessor & getPreprocessor() const
Definition: Sema.h:500
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7008
void CheckHLSLEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12595
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1549
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:1165
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.
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12680
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6344
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:17996
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:4891
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:12347
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16734
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:2146
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:18546
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:14771
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1450
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15648
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:1489
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3515
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:642
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1681
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:20519
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15273
ASTContext & Context
Definition: Sema.h:1030
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14793
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5883
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20540
void * SkippedDefinitionContext
Definition: Sema.h:3383
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:917
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5396
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:5001
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:62
@ AllowFold
Definition: Sema.h:6010
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1517
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1552
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:2753
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:2425
ASTContext & getASTContext() const
Definition: Sema.h:501
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:16059
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
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:1746
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:18631
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1548
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:680
SmallVector< VarDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:2763
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3335
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:4846
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9635
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20688
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:947
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:5553
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1494
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:17092
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9114
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:9516
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6707
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:681
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:4428
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2141
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:1263
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
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:3529
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16985
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:496
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2159
void PopCompoundScope()
Definition: Sema.cpp:2298
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:11047
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:11050
@ UPPC_Initializer
An initializer.
Definition: Sema.h:11062
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:11056
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:11035
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:11074
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:11059
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:11038
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:11041
void checkAllowedCUDAInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:643
const LangOptions & getLangOpts() const
Definition: Sema.h:494
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:1588
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:2770
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1407
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:6700
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:6738
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1618
Preprocessor & PP
Definition: Sema.h:1029
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
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...
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:8323
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:1934
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:636
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:1028
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2375
void ActOnHLSLTopLevelFunction(FunctionDecl *FD)
Definition: SemaDecl.cpp:12561
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:11974
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15492
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15359
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1875
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11970
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:18651
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:1325
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
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:3863
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:201
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:20815
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 MaybeAddCUDAConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:787
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:1209
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1537
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:15945
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5371
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1547
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:873
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:9733
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:8323
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:875
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:17063
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1394
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: Sema.h:13706
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8475
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
Definition: SemaAttr.cpp:851
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12526
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:20022
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1064
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2293
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:15025
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2384
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2359
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20574
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18841
HLSLNumThreadsAttr * mergeHLSLNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5368
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1219
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
bool CheckCountedByAttr(Scope *Scope, const FieldDecl *FD)
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:18311
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:10712
ExprResult VerifyBitField(SourceLocation FieldLoc, 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:18447
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8987
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:645
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:3423
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11968
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1587
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20608
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7993
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:9009
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:15594
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:18296
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15521
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Sema.h:7688
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
Definition: Sema.h:7691
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:7694
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
Definition: Sema.h:7698
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15065
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5889
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition: SemaCUDA.cpp:723
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:8516
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19996
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1305
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4789
ObjCContainerDecl * getObjCDeclContext() const
Definition: SemaDecl.cpp:20604
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
bool isInOpenMPDeclareVariantScope() const
Can we exit an OpenMP declare variant scope at the moment.
Definition: Sema.h:13446
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:2767
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9371
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:15969
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:11115
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10722
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3298
@ NTK_Typedef
Definition: Sema.h:3303
@ NTK_NonUnion
Definition: Sema.h:3301
@ NTK_TypeAlias
Definition: Sema.h:3304
@ NTK_NonClass
Definition: Sema.h:3300
@ NTK_NonEnum
Definition: Sema.h:3302
@ NTK_NonStruct
Definition: Sema.h:3299
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3307
@ NTK_TypeAliasTemplate
Definition: Sema.h:3306
@ NTK_Template
Definition: Sema.h:3305
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:18412
SourceManager & getSourceManager() const
Definition: Sema.h:499
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:2720
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:4346
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20276
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:1359
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:11285
RedeclarationKind forRedeclarationInCurContext() const
Definition: Sema.h:7701
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18282
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition: Sema.h:1326
@ NTCUK_Destruct
Definition: Sema.h:3170
@ NTCUK_Init
Definition: Sema.h:3169
@ NTCUK_Copy
Definition: Sema.h:3171
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1323
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:21009
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15997
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 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 CheckHLSLSemanticAnnotation(FunctionDecl *EntryPoint, const Decl *Param, const HLSLAnnotationAttr *AnnotationAttr)
Definition: SemaDecl.cpp:12646
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:14015
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:1244
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:20547
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:5182
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:224
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:20531
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8357
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".
void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx)
Definition: SemaDecl.cpp:18423
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:2310
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:7858
@ CTK_ErrorRecovery
Definition: Sema.h:7859
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14425
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14948
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2316
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:4552
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:4976
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:588
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:8277
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:19030
CUDAFunctionTarget
Definition: Sema.h:3833
@ CFT_Device
Definition: Sema.h:3834
@ CFT_Global
Definition: Sema.h:3835
@ CFT_Host
Definition: Sema.h:3836
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3179
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:1938
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:2741
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:286
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19815
ASTConsumer & Consumer
Definition: Sema.h:1031
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3561
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:8188
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:8180
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:8184
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:5375
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2095
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:1069
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1617
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ FirstDecl
Parsing the first decl in a TU.
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16656
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6964
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
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:3483
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:3485
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:3491
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:3494
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:3497
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:3488
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:15069
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6102
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14734
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:17286
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:4871
void DiagnoseHLSLAttrStageMismatch(const Attr *A, HLSLShaderAttr::ShaderType Stage, std::initializer_list< HLSLShaderAttr::ShaderType > AllowedStages)
Definition: SemaDecl.cpp:12666
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:75
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9249
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15444
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1002
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1352
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:21659
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19273
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:1188
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:11148
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:2760
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18709
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6669
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1324
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:1033
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5839
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16054
DiagnosticsEngine & Diags
Definition: Sema.h:1032
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:495
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:16050
NamespaceDecl * getStdNamespace() const
QualType AdjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo)
Definition: SemaDecl.cpp:15328
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6763
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1546
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:648
@ TUK_Definition
Definition: Sema.h:3321
@ TUK_Declaration
Definition: Sema.h:3320
@ TUK_Friend
Definition: Sema.h:3322
@ TUK_Reference
Definition: Sema.h:3319
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7381
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:15102
@ TPC_FriendFunctionTemplate
Definition: Sema.h:9258
@ TPC_ClassTemplateMember
Definition: Sema.h:9256
@ TPC_FunctionTemplate
Definition: Sema.h:9255
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:9259
@ TPC_VarTemplate
Definition: Sema.h:9254
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:6850
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16503
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2113
void PopDeclContext()
Definition: SemaDecl.cpp:1331
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4988
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:1597
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:9813
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:14057
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:13227
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:1580
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16928
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2358
OffsetOfKind
Definition: Sema.h:3325
@ OOK_Outside
Definition: Sema.h:3327
@ OOK_Macro
Definition: Sema.h:3332
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13503
HLSLShaderAttr * mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
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:18536
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4382
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:14342
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:278
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:2735
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1894
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:21957
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1322
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6151
@ AbstractVariableType
Definition: Sema.h:4759
@ AbstractReturnType
Definition: Sema.h:4757
@ AbstractFieldType
Definition: Sema.h:4760
@ AbstractIvarType
Definition: Sema.h:4761
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:1720
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6711
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:1253
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:8337
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20586
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8687
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
Definition: SemaDecl.cpp:18916
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:4270
@ CXXCopyConstructor
Definition: Sema.h:4272
@ CXXMoveConstructor
Definition: Sema.h:4273
@ CXXDestructor
Definition: Sema.h:4276
@ CXXDefaultConstructor
Definition: Sema.h:4271
@ CXXInvalid
Definition: Sema.h:4277
@ CXXMoveAssignment
Definition: Sema.h:4275
@ CXXCopyAssignment
Definition: Sema.h:4274
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1338
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13193
std::string getCudaConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1036
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.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3213
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:2716
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1172
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:15934
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:13479
IdentifierResolver IdResolver
Definition: Sema.h:2664
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE=nullptr)
Builds an expression which might be an implicit member expression.
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:20247
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2307
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:696
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:15302
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:6677
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:3015
void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:982
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6138
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:17004
void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:18417
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7549
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:6967
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:1280
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:3549
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3824
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3672
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3647
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3633
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3652
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3777
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4704
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4695
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4687
bool isUnion() const
Definition: Decl.h:3755
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4750
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4787
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3773
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3690
TagKind getTagKind() const
Definition: Decl.h:3744
void setBraceRange(SourceRange R)
Definition: Decl.h:3629
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:213
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:304
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1482
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:493
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:501
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1761
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:511
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1525
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1533
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1468
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1291
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1357
unsigned getCharWidth() const
Definition: TargetInfo.h:488
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:537
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:506
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1447
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1258
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1436
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:628
std::string HLSLEntry
The entry point name for HLSL shader being compiled as specified by -E.
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:5632
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4102
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:4422
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5557
void setStmt(Stmt *S)
Definition: Decl.cpp:5577
Represents a declaration of a type.
Definition: Decl.h:3357
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3382
const Type * getTypeForDecl() const
Definition: Decl.h:3381
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:1199
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
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:742
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:2653
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:6873
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:6884
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:5895
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3070
The base class of the type hierarchy.
Definition: Type.h:1606
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:2403
bool isStructureType() const
Definition: Type.cpp:589
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isDependentSizedArrayType() const
Definition: Type.h:7236
bool isBlockPointerType() const
Definition: Type.h:7162
bool isVoidType() const
Definition: Type.h:7443
bool isBooleanType() const
Definition: Type.h:7567
bool isFunctionReferenceType() const
Definition: Type.h:7195
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2104
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7614
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:686
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2829
bool isIncompleteArrayType() const
Definition: Type.h:7228
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:7733
bool isDependentAddressSpaceType() const
Definition: Type.h:7278
bool isConstantArrayType() const
Definition: Type.h:7224
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7594
bool isVoidPointerType() const
Definition: Type.cpp:615
bool isArrayType() const
Definition: Type.h:7220
bool isFunctionPointerType() const
Definition: Type.h:7188
bool isPointerType() const
Definition: Type.h:7154
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2409
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isReferenceType() const
Definition: Type.h:7166
bool isEnumeralType() const
Definition: Type.h:7248
bool isScalarType() const
Definition: Type.h:7538
bool isVariableArrayType() const
Definition: Type.h:7232
bool isClkEventT() const
Definition: Type.h:7355
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1995
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7554
bool isImageType() const
Definition: Type.h:7367
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2525
bool isPipeType() const
Definition: Type.h:7374
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2428
bool isBitIntType() const
Definition: Type.h:7378
bool isOpenCLSpecificType() const
Definition: Type.h:7403
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2275
bool isHalfType() const
Definition: Type.h:7447
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1948
const RecordType * getAsStructureType() const
Definition: Type.cpp:667
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2393
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2414
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7607
bool isAtomicType() const
Definition: Type.h:7295
bool isFunctionProtoType() const
Definition: Type.h:2263
bool isObjCIdType() const
Definition: Type.h:7315
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2438
bool isObjCObjectType() const
Definition: Type.h:7286
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4778
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7573
bool isEventT() const
Definition: Type.h:7351
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4721
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2299
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:7674
bool isFunctionType() const
Definition: Type.h:7150
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isMemberFunctionPointerType() const
Definition: Type.h:7206
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2423
bool isFloatingType() const
Definition: Type.cpp:2186
bool isAnyPointerType() const
Definition: Type.h:7158
TypeClass getTypeClass() const
Definition: Type.h:2074
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:1953
bool isSamplerT() const
Definition: Type.h:7347
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:565
bool isNullPtrType() const
Definition: Type.h:7472
bool isRecordType() const
Definition: Type.h:7244
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4516
bool isUnionType() const
Definition: Type.cpp:621
bool isFunctionNoProtoType() const
Definition: Type.h:2262
bool isReserveIDT() const
Definition: Type.h:7363
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:1827
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1823
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3501
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5462
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3399
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3449
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3465
QualType getUnderlyingType() const
Definition: Decl.h:3454
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3461
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5470
TypedefNameDecl * getDecl() const
Definition: Type.h:4760
QualType desugar() const
Definition: Type.cpp:3722
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:2182
Expr * getSubExpr() const
Definition: Expr.h:2227
Opcode getOpcode() const
Definition: Expr.h:2222
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2282
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1233
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1082
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:373
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:3313
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3377
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3110
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:5330
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:1502
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1546
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool hasInit() const
Definition: Decl.cpp:2395
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1429
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:1555
@ 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:1574
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1267
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1210
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:1535
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1192
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1326
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1157
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:1528
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1161
const Expr * getInit() const
Definition: Decl.h:1352
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1201
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1168
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2423
void setConstexpr(bool IC)
Definition: Decl.h:1549
@ 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:1282
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1279
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1285
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:1237
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1152
void setImplicitlyInline()
Definition: Decl.h:1540
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1453
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1569
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:1246
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:1463
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:3290
Expr * getSizeExpr() const
Definition: Type.h:3309
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::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:175
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
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:1882
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:62
@ OpenCL
Definition: LangStandard.h:64
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus11
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:57
@ 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
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:303
TagTypeKind
The kind of a tag type.
Definition: Type.h:5842
@ 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:984
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
@ 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
MultiVersionKind
Definition: Decl.h:1938
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
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.
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
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:20
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
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1660
enum clang::DeclaratorChunk::@216 Kind
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
MemberPointerTypeInfo Mem
Definition: DeclSpec.h: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:4278
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:4297
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:56
std::vector< std::string > Features
Definition: TargetInfo.h:57
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1319
ValueType CurrentValue
Definition: Sema.h:1522
NamedDecl * Previous
Definition: Sema.h:2784
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.