clang 24.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
43#include "clang/Sema/DeclSpec.h"
46#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Scope.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
55#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaPPC.h"
60#include "clang/Sema/SemaSYCL.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
85 }
86
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(*this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
156 Diag(NameLoc,
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(TD, NameLoc);
165 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(*SS, false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(*SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
318 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
319 SS->getScopeRep(), &II);
321 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
328 (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
333 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
335 SourceLocation(), QualifierLoc, II, NameLoc);
336 return ParsedType::make(T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(*SS, LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
396 bool MemberOfUnknownSpecialization;
398 TemplateName.setIdentifier(NewII, NameLoc);
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 PDiag(diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
433 SS->getScopeRep(), &II);
434 TypeLocBuilder TLB;
438 TL.setNameLoc(NameLoc);
440 }
441 [[fallthrough]];
444 Result.suppressDiagnostics();
445 return nullptr;
446
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
463 RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 IsImplicitTypename ? DiagCtorKind::Implicit
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
508 SS ? SS->getScopeRep() : std::nullopt,
509 FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
518 SS ? SS->getScopeRep() : std::nullopt, Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(T);
522 auto TL = TLB.push<TagTypeLoc>(T);
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
528 TN && !isa<ObjCTypeParamDecl>(TN)) {
529 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
530 SS ? SS->getScopeRep() : std::nullopt, TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
538 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
539 SS ? SS->getScopeRep() : std::nullopt,
540 UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(T);
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
583 (void)DiagnoseUseOfDecl(UD, NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
595 Template);
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
656 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
687}
688
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
702 return DeclSpec::TST_union;
704 return DeclSpec::TST_class;
706 return DeclSpec::TST_enum;
707 }
708 }
709
711}
712
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
719 return true;
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T, Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Corrected,
757 PDiag(IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Corrected,
765 PDiag(IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
769 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Corrected,
773 PDiag(IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
788 SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
792 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(II, IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, nullptr, true, TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(IILoc, IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(*SS, false))
822 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
828 } else if (isDependentScopeSpecifier(*SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
835
836 Diag(SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(*I))
857 return true;
858 }
859
860 return false;
861}
862
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
873 FixItTagName = "class ";
874 break;
875
877 FixItTagName = "enum ";
878 break;
879
881 FixItTagName = "struct ";
882 break;
883
885 FixItTagName = "__interface ";
886 break;
887
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
905 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(*Name, S, &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
952 if (Ivar.isInvalid())
954 if (Ivar.isUsable())
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1002 Context.getAssumedTemplateName(NameInfo.getName());
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1020 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1045 << Name << computeDeclContext(SS, false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1070 if (R.isInvalid())
1072 if (R.isUsable())
1073 return NameClassification::NonType(Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1083
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1100 }
1101
1105 break;
1106
1108 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1109 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1134 (IsFilteredTemplateName ||
1136 Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Result.begin(),
1159 Result.end());
1160 } else if (!Result.empty()) {
1162 *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(*Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1199 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1200 USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1205 Type);
1206 if (isa<TagType>(T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1228 DiagnoseUseOfDecl(Type, NameLoc);
1229 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(Class, NameLoc);
1243
1244 if (NextToken.is(tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Class);
1252 return ParsedType::make(T);
1253 }
1254
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1277 if ((NextToken.is(tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(Type, NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1293 return NameClassification::NonType(Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1298 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1299 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1310}
1311
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(*I, I.getAccess());
1354 Result.resolveKind();
1356 nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1383
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1416
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1449 }
1450}
1451
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1509 // We assume that the caller has already called
1510 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1511 FunctionDecl *FD = D->getAsFunction();
1512 if (!FD)
1513 return;
1514
1515 // Same implementation as PushDeclContext, but enters the context
1516 // from the lexical parent, rather than the top-level class.
1517 assert(CurContext == FD->getLexicalParent() &&
1518 "The next DeclContext should be lexically contained in the current one.");
1519 CurContext = FD;
1521
1522 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1523 ParmVarDecl *Param = FD->getParamDecl(P);
1524 // If the parameter has an identifier, then add it to the scope
1525 if (Param->getIdentifier()) {
1526 S->AddDecl(Param);
1527 IdResolver.AddDecl(Param);
1528 }
1529 }
1530}
1531
1533 // Same implementation as PopDeclContext, but returns to the lexical parent,
1534 // rather than the top-level class.
1535 assert(CurContext && "DeclContext imbalance!");
1536 CurContext = CurContext->getLexicalParent();
1537 assert(CurContext && "Popped translation unit!");
1538}
1539
1540/// Determine whether overloading is allowed for a new function
1541/// declaration considering prior declarations of the same name.
1542///
1543/// This routine determines whether overloading is possible, not
1544/// whether a new declaration actually overloads a previous one.
1545/// It will return true in C++ (where overloads are always permitted)
1546/// or, as a C extension, when either the new declaration or a
1547/// previous one is declared with the 'overloadable' attribute.
1549 ASTContext &Context,
1550 const FunctionDecl *New) {
1551 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1552 return true;
1553
1554 // Multiversion function declarations are not overloads in the
1555 // usual sense of that term, but lookup will report that an
1556 // overload set was found if more than one multiversion function
1557 // declaration is present for the same name. It is therefore
1558 // inadequate to assume that some prior declaration(s) had
1559 // the overloadable attribute; checking is required. Since one
1560 // declaration is permitted to omit the attribute, it is necessary
1561 // to check at least two; hence the 'any_of' check below. Note that
1562 // the overloadable attribute is implicitly added to declarations
1563 // that were required to have it but did not.
1564 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1565 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1566 return ND->hasAttr<OverloadableAttr>();
1567 });
1568 } else if (Previous.getResultKind() == LookupResultKind::Found)
1569 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1570
1571 return false;
1572}
1573
1574void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1575 // Move up the scope chain until we find the nearest enclosing
1576 // non-transparent context. The declaration will be introduced into this
1577 // scope.
1578 while (S->getEntity() && S->getEntity()->isTransparentContext())
1579 S = S->getParent();
1580
1581 // Add scoped declarations into their context, so that they can be
1582 // found later. Declarations without a context won't be inserted
1583 // into any context.
1584 if (AddToContext)
1585 CurContext->addDecl(D);
1586
1587 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1588 // are function-local declarations.
1589 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1590 if (!S->getFnParent())
1591 return;
1592
1593 // Even inside a function, an out-of-line definition of a type that is
1594 // nested inside a local class must not be pushed into the enclosing
1595 // function scope. For example:
1596 //
1597 // class A { public: class B; };
1598 // class A::B {}; // out-of-line definition inside the function
1599 // B b; // must fail - only A::B is valid
1600 // Wrapper{B{}} // must also fail
1601 //
1602 // Per C++ scoping rules only the qualified form A::B is accessible.
1603 // Without this guard, PushOnScopeChains would add B to the function's
1604 // local scope, making it findable via unqualified lookup, which is
1605 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1606 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1607 // of a local class being defined out-of-line.
1609 return;
1610 }
1611
1612 // Template instantiations should also not be pushed into scope.
1613 if (isa<FunctionDecl>(D) &&
1614 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1615 return;
1616
1617 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1618 S->AddDecl(D);
1619 return;
1620 }
1621 // If this replaces anything in the current scope,
1623 IEnd = IdResolver.end();
1624 for (; I != IEnd; ++I) {
1625 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1626 S->RemoveDecl(*I);
1627 IdResolver.RemoveDecl(*I);
1628
1629 // Should only need to replace one decl.
1630 break;
1631 }
1632 }
1633
1634 S->AddDecl(D);
1635
1636 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1637 // Implicitly-generated labels may end up getting generated in an order that
1638 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1639 // the label at the appropriate place in the identifier chain.
1640 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1641 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1642 if (IDC == CurContext) {
1643 if (!S->isDeclScope(*I))
1644 continue;
1645 } else if (IDC->Encloses(CurContext))
1646 break;
1647 }
1648
1649 IdResolver.InsertDeclAfter(I, D);
1650 } else {
1651 IdResolver.AddDecl(D);
1652 }
1654}
1655
1657 bool AllowInlineNamespace) const {
1658 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1659}
1660
1662 DeclContext *TargetDC = DC->getPrimaryContext();
1663 do {
1664 if (DeclContext *ScopeDC = S->getEntity())
1665 if (ScopeDC->getPrimaryContext() == TargetDC)
1666 return S;
1667 } while ((S = S->getParent()));
1668
1669 return nullptr;
1670}
1671
1673 DeclContext*,
1674 ASTContext&);
1675
1677 bool ConsiderLinkage,
1678 bool AllowInlineNamespace) {
1679 LookupResult::Filter F = R.makeFilter();
1680 while (F.hasNext()) {
1681 NamedDecl *D = F.next();
1682
1683 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1684 continue;
1685
1686 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1687 continue;
1688
1689 F.erase();
1690 }
1691
1692 F.done();
1693}
1694
1696 if (auto *VD = dyn_cast<VarDecl>(D))
1697 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1698 if (auto *FD = dyn_cast<FunctionDecl>(D))
1699 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1700 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1701 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1702
1703 return false;
1704}
1705
1707 // [module.interface]p7:
1708 // A declaration is attached to a module as follows:
1709 // - If the declaration is a non-dependent friend declaration that nominates a
1710 // function with a declarator-id that is a qualified-id or template-id or that
1711 // nominates a class other than with an elaborated-type-specifier with neither
1712 // a nested-name-specifier nor a simple-template-id, it is attached to the
1713 // module to which the friend is attached ([basic.link]).
1714 if (New->getFriendObjectKind() &&
1715 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1716 New->setLocalOwningModule(Old->getOwningModule());
1718 return false;
1719 }
1720
1721 // Although we have questions for the module ownership of implicit
1722 // instantiations, it should be sure that we shouldn't diagnose the
1723 // redeclaration of incorrect module ownership for different implicit
1724 // instantiations in different modules. We will diagnose the redeclaration of
1725 // incorrect module ownership for the template itself.
1727 return false;
1728
1729 Module *NewM = New->getOwningModule();
1730 Module *OldM = Old->getOwningModule();
1731
1732 if (NewM && NewM->isPrivateModule())
1733 NewM = NewM->Parent;
1734 if (OldM && OldM->isPrivateModule())
1735 OldM = OldM->Parent;
1736
1737 if (NewM == OldM)
1738 return false;
1739
1740 if (NewM && OldM) {
1741 // A module implementation unit has visibility of the decls in its
1742 // implicitly imported interface.
1743 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1744 return false;
1745
1746 // Partitions are part of the module, but a partition could import another
1747 // module, so verify that the PMIs agree.
1748 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1749 getASTContext().isInSameModule(NewM, OldM))
1750 return false;
1751 }
1752
1753 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1754 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1755 if (NewIsModuleInterface || OldIsModuleInterface) {
1756 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1757 // if a declaration of D [...] appears in the purview of a module, all
1758 // other such declarations shall appear in the purview of the same module
1759 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1760 << New
1761 << NewIsModuleInterface
1762 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1763 << OldIsModuleInterface
1764 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1765 Diag(Old->getLocation(), diag::note_previous_declaration);
1766 New->setInvalidDecl();
1767 return true;
1768 }
1769
1770 return false;
1771}
1772
1774 // [module.interface]p1:
1775 // An export-declaration shall inhabit a namespace scope.
1776 //
1777 // So it is meaningless to talk about redeclaration which is not at namespace
1778 // scope.
1779 if (!New->getLexicalDeclContext()
1780 ->getNonTransparentContext()
1781 ->isFileContext() ||
1782 !Old->getLexicalDeclContext()
1784 ->isFileContext())
1785 return false;
1786
1787 bool IsNewExported = New->isInExportDeclContext();
1788 bool IsOldExported = Old->isInExportDeclContext();
1789
1790 // It should be irrevelant if both of them are not exported.
1791 if (!IsNewExported && !IsOldExported)
1792 return false;
1793
1794 if (IsOldExported)
1795 return false;
1796
1797 // If the Old declaration are not attached to named modules
1798 // and the New declaration are attached to global module.
1799 // It should be fine to allow the export since it doesn't change
1800 // the linkage of declarations. See
1801 // https://github.com/llvm/llvm-project/issues/98583 for details.
1802 if (!Old->isInNamedModule() && New->getOwningModule() &&
1803 New->getOwningModule()->isImplicitGlobalModule())
1804 return false;
1805
1806 assert(IsNewExported);
1807
1808 auto Lk = Old->getFormalLinkage();
1809 int S = 0;
1810 if (Lk == Linkage::Internal)
1811 S = 1;
1812 else if (Lk == Linkage::Module)
1813 S = 2;
1814 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1815 Diag(Old->getLocation(), diag::note_previous_declaration);
1816 return true;
1817}
1818
1821 return true;
1822
1824 return true;
1825
1826 return false;
1827}
1828
1830 const NamedDecl *Old) const {
1831 assert(getASTContext().isSameEntity(New, Old) &&
1832 "New and Old are not the same definition, we should diagnostic it "
1833 "immediately instead of checking it.");
1834 assert(const_cast<Sema *>(this)->isReachable(New) &&
1835 const_cast<Sema *>(this)->isReachable(Old) &&
1836 "We shouldn't see unreachable definitions here.");
1837
1838 Module *NewM = New->getOwningModule();
1839 Module *OldM = Old->getOwningModule();
1840
1841 // We only checks for named modules here. The header like modules is skipped.
1842 // FIXME: This is not right if we import the header like modules in the module
1843 // purview.
1844 //
1845 // For example, assuming "header.h" provides definition for `D`.
1846 // ```C++
1847 // //--- M.cppm
1848 // export module M;
1849 // import "header.h"; // or #include "header.h" but import it by clang modules
1850 // actually.
1851 //
1852 // //--- Use.cpp
1853 // import M;
1854 // import "header.h"; // or uses clang modules.
1855 // ```
1856 //
1857 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1858 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1859 // reject it. But the current implementation couldn't detect the case since we
1860 // don't record the information about the importee modules.
1861 //
1862 // But this might not be painful in practice. Since the design of C++20 Named
1863 // Modules suggests us to use headers in global module fragment instead of
1864 // module purview.
1865 if (NewM && NewM->isHeaderLikeModule())
1866 NewM = nullptr;
1867 if (OldM && OldM->isHeaderLikeModule())
1868 OldM = nullptr;
1869
1870 if (!NewM && !OldM)
1871 return true;
1872
1873 // [basic.def.odr]p14.3
1874 // Each such definition shall not be attached to a named module
1875 // ([module.unit]).
1876 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1877 return true;
1878
1879 // Then New and Old lives in the same TU if their share one same module unit.
1880 if (NewM)
1881 NewM = NewM->getTopLevelModule();
1882 if (OldM)
1883 OldM = OldM->getTopLevelModule();
1884 return OldM == NewM;
1885}
1886
1888 if (D->getDeclContext()->isFileContext())
1889 return false;
1890
1891 return isa<UsingShadowDecl>(D) ||
1894}
1895
1896/// Removes using shadow declarations not at class scope from the lookup
1897/// results.
1899 LookupResult::Filter F = R.makeFilter();
1900 while (F.hasNext())
1902 F.erase();
1903
1904 F.done();
1905}
1906
1907/// Check for this common pattern:
1908/// @code
1909/// class S {
1910/// S(const S&); // DO NOT IMPLEMENT
1911/// void operator=(const S&); // DO NOT IMPLEMENT
1912/// };
1913/// @endcode
1915 // FIXME: Should check for private access too but access is set after we get
1916 // the decl here.
1918 return false;
1919
1920 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1921 return CD->isCopyConstructor();
1922 return D->isCopyAssignmentOperator();
1923}
1924
1925bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1926 const DeclContext *DC = D->getDeclContext();
1927 while (!DC->isTranslationUnit()) {
1928 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1929 if (!RD->hasNameForLinkage())
1930 return true;
1931 }
1932 DC = DC->getParent();
1933 }
1934
1935 return !D->isExternallyVisible();
1936}
1937
1939 assert(D);
1940
1941 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1942 return false;
1943
1944 // Ignore all entities declared within templates, and out-of-line definitions
1945 // of members of class templates.
1946 if (D->getDeclContext()->isDependentContext() ||
1948 return false;
1949
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1951 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1952 return false;
1953 // A non-out-of-line declaration of a member specialization was implicitly
1954 // instantiated; it's the out-of-line declaration that we're interested in.
1955 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1956 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1957 return false;
1958
1959 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1960 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1961 return false;
1962 } else {
1963 // 'static inline' functions are defined in headers; don't warn.
1964 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1965 return false;
1966 }
1967
1968 if (FD->doesThisDeclarationHaveABody() &&
1969 Context.DeclMustBeEmitted(FD))
1970 return false;
1971 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1972 // Constants and utility variables are defined in headers with internal
1973 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1974 // like "inline".)
1975 if (!isMainFileLoc(VD->getLocation()))
1976 return false;
1977
1978 if (Context.DeclMustBeEmitted(VD))
1979 return false;
1980
1981 if (VD->isStaticDataMember() &&
1982 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1983 return false;
1984 if (VD->isStaticDataMember() &&
1985 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1986 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1987 return false;
1988
1989 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
1990 return false;
1991 } else {
1992 return false;
1993 }
1994
1995 // Only warn for unused decls internal to the translation unit.
1996 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1997 // for inline functions defined in the main source file, for instance.
1998 return mightHaveNonExternalLinkage(D);
1999}
2000
2002 if (!D)
2003 return;
2004
2005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2006 const FunctionDecl *First = FD->getFirstDecl();
2008 return; // First should already be in the vector.
2009 }
2010
2011 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2012 const VarDecl *First = VD->getFirstDecl();
2014 return; // First should already be in the vector.
2015 }
2016
2018 UnusedFileScopedDecls.push_back(D);
2019}
2020
2021static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2022 const NamedDecl *D) {
2023 if (D->isInvalidDecl())
2024 return false;
2025
2026 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2027 // For a decomposition declaration, warn if none of the bindings are
2028 // referenced, instead of if the variable itself is referenced (which
2029 // it is, by the bindings' expressions).
2030 bool IsAllIgnored = true;
2031 for (const auto *BD : DD->bindings()) {
2032 if (BD->isReferenced())
2033 return false;
2034 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2035 BD->hasAttr<UnusedAttr>());
2036 }
2037 if (IsAllIgnored)
2038 return false;
2039 } else if (!D->getDeclName()) {
2040 return false;
2041 } else if (D->isReferenced() || D->isUsed()) {
2042 return false;
2043 }
2044
2045 if (D->isPlaceholderVar(LangOpts))
2046 return false;
2047
2048 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2049 D->hasAttr<CleanupAttr>())
2050 return false;
2051
2052 if (isa<LabelDecl>(D))
2053 return true;
2054
2055 // Except for labels, we only care about unused decls that are local to
2056 // functions.
2057 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2058 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2059 // For dependent types, the diagnostic is deferred.
2060 WithinFunction =
2061 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2062 if (!WithinFunction)
2063 return false;
2064
2065 if (isa<TypedefNameDecl>(D))
2066 return true;
2067
2068 // White-list anything that isn't a local variable.
2070 return false;
2071
2072 // Types of valid local variables should be complete, so this should succeed.
2073 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2074
2075 const Expr *Init = VD->getInit();
2076 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2077 Init = Cleanups->getSubExpr();
2078
2079 const auto *Ty = VD->getType().getTypePtr();
2080
2081 // Only look at the outermost level of typedef.
2082 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2083 // Allow anything marked with __attribute__((unused)).
2084 if (TT->getDecl()->hasAttr<UnusedAttr>())
2085 return false;
2086 }
2087
2088 // Warn for reference variables whose initializtion performs lifetime
2089 // extension.
2090 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2091 MTE && MTE->getExtendingDecl()) {
2092 Ty = VD->getType().getNonReferenceType().getTypePtr();
2093 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2094 }
2095
2096 // If we failed to complete the type for some reason, or if the type is
2097 // dependent, don't diagnose the variable.
2098 if (Ty->isIncompleteType() || Ty->isDependentType())
2099 return false;
2100
2101 // Look at the element type to ensure that the warning behaviour is
2102 // consistent for both scalars and arrays.
2103 Ty = Ty->getBaseElementTypeUnsafe();
2104
2105 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2106 if (Tag->hasAttr<UnusedAttr>())
2107 return false;
2108
2109 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2110 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2111 return false;
2112
2113 if (Init) {
2114 const auto *Construct =
2115 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2116 if (Construct && !Construct->isElidable()) {
2117 const CXXConstructorDecl *CD = Construct->getConstructor();
2118 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2119 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2120 return false;
2121 }
2122
2123 // Suppress the warning if we don't know how this is constructed, and
2124 // it could possibly be non-trivial constructor.
2125 if (Init->isTypeDependent()) {
2126 for (const CXXConstructorDecl *Ctor : RD->ctors())
2127 if (!Ctor->isTrivial())
2128 return false;
2129 }
2130
2131 // Suppress the warning if the constructor is unresolved because
2132 // its arguments are dependent.
2134 return false;
2135 }
2136 }
2137 }
2138
2139 // TODO: __attribute__((unused)) templates?
2140 }
2141
2142 return true;
2143}
2144
2146 FixItHint &Hint) {
2147 if (isa<LabelDecl>(D)) {
2149 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2150 /*SkipTrailingWhitespaceAndNewline=*/false);
2151 if (AfterColon.isInvalid())
2152 return;
2154 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2155 }
2156}
2157
2160 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2161}
2162
2164 DiagReceiverTy DiagReceiver) {
2165 if (D->isDependentType())
2166 return;
2167
2168 for (auto *TmpD : D->decls()) {
2169 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2170 DiagnoseUnusedDecl(T, DiagReceiver);
2171 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2172 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2173 }
2174}
2175
2178 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2179}
2180
2183 return;
2184
2185 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2186 // typedefs can be referenced later on, so the diagnostics are emitted
2187 // at end-of-translation-unit.
2189 return;
2190 }
2191
2192 FixItHint Hint;
2194
2195 unsigned DiagID;
2196 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2197 DiagID = diag::warn_unused_exception_param;
2198 else if (isa<LabelDecl>(D))
2199 DiagID = diag::warn_unused_label;
2200 else
2201 DiagID = diag::warn_unused_variable;
2202
2203 SourceLocation DiagLoc = D->getLocation();
2204 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2205}
2206
2208 DiagReceiverTy DiagReceiver) {
2209 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2210 // it's not really unused.
2211 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2212 return;
2213
2214 // In C++, `_` variables behave as if they were maybe_unused
2215 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2216 return;
2217
2218 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2219
2220 if (Ty->isReferenceType() || Ty->isDependentType())
2221 return;
2222
2223 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2224 if (Tag->hasAttr<UnusedAttr>())
2225 return;
2226 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2227 // mimic gcc's behavior.
2228 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2229 RD && !RD->hasAttr<WarnUnusedAttr>())
2230 return;
2231 }
2232
2233 // Don't warn on volatile file-scope variables. They are visible beyond their
2234 // declaring function and writes to them could be observable side effects.
2235 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2236 return;
2237
2238 // Don't warn about __block Objective-C pointer variables, as they might
2239 // be assigned in the block but not used elsewhere for the purpose of lifetime
2240 // extension.
2241 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2242 return;
2243
2244 // Don't warn about Objective-C pointer variables with precise lifetime
2245 // semantics; they can be used to ensure ARC releases the object at a known
2246 // time, which may mean assignment but no other references.
2247 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2248 return;
2249
2250 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2251 if (iter == RefsMinusAssignments.end())
2252 return;
2253
2254 assert(iter->getSecond() >= 0 &&
2255 "Found a negative number of references to a VarDecl");
2256 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2257 // Assume the given VarDecl is "used" if its ref count stored in
2258 // `RefMinusAssignments` is positive, with one exception.
2259 //
2260 // For a C++ variable whose decl (with initializer) entirely consist the
2261 // condition expression of a if/while/for construct,
2262 // Clang creates a DeclRefExpr for the condition expression rather than a
2263 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2264 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2265 // used in the body of the if/while/for construct.
2266 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2267 if (!UnusedCXXCondDecl)
2268 return;
2269 }
2270
2271 unsigned DiagID;
2272 if (isa<ParmVarDecl>(VD))
2273 DiagID = diag::warn_unused_but_set_parameter;
2274 else if (VD->isFileVarDecl())
2275 DiagID = diag::warn_unused_but_set_global;
2276 else
2277 DiagID = diag::warn_unused_but_set_variable;
2278 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2279}
2280
2282 Sema::DiagReceiverTy DiagReceiver) {
2283 // Verify that we have no forward references left. If so, there was a goto
2284 // or address of a label taken, but no definition of it. Label fwd
2285 // definitions are indicated with a null substmt which is also not a resolved
2286 // MS inline assembly label name.
2287 bool Diagnose = false;
2288 if (L->isMSAsmLabel())
2289 Diagnose = !L->isResolvedMSAsmLabel();
2290 else
2291 Diagnose = L->getStmt() == nullptr;
2292 if (Diagnose)
2293 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2294 << L);
2295}
2296
2298 S->applyNRVO();
2299
2300 if (S->decl_empty()) return;
2302 "Scope shouldn't contain decls!");
2303
2304 /// We visit the decls in non-deterministic order, but we want diagnostics
2305 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2306 /// and sort the diagnostics before emitting them, after we visited all decls.
2307 struct LocAndDiag {
2308 SourceLocation Loc;
2309 std::optional<SourceLocation> PreviousDeclLoc;
2311 };
2313 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2314 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2315 };
2316 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2317 SourceLocation PreviousDeclLoc,
2318 PartialDiagnostic PD) {
2319 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2320 };
2321
2322 for (auto *TmpD : S->decls()) {
2323 assert(TmpD && "This decl didn't get pushed??");
2324
2325 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2326 NamedDecl *D = cast<NamedDecl>(TmpD);
2327
2328 // Diagnose unused variables in this scope.
2330 DiagnoseUnusedDecl(D, addDiag);
2331 if (const auto *RD = dyn_cast<RecordDecl>(D))
2332 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2333 // Wait until end of TU to diagnose internal linkage file vars.
2334 if (auto *VD = dyn_cast<VarDecl>(D);
2335 VD && !VD->isInternalLinkageFileVar()) {
2336 DiagnoseUnusedButSetDecl(VD, addDiag);
2337 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2338 }
2339 }
2340
2341 if (!D->getDeclName()) continue;
2342
2343 // If this was a forward reference to a label, verify it was defined.
2344 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2345 CheckPoppedLabel(LD, *this, addDiag);
2346
2347 // Partial translation units that are created in incremental processing must
2348 // not clean up the IdResolver because PTUs should take into account the
2349 // declarations that came from previous PTUs.
2350 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2352 IdResolver.RemoveDecl(D);
2353
2354 // Warn on it if we are shadowing a declaration.
2355 auto ShadowI = ShadowingDecls.find(D);
2356 if (ShadowI != ShadowingDecls.end()) {
2357 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2358 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2359 PDiag(diag::warn_ctor_parm_shadows_field)
2360 << D << FD << FD->getParent());
2361 }
2362 ShadowingDecls.erase(ShadowI);
2363 }
2364 }
2365
2366 llvm::sort(DeclDiags,
2367 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2368 // The particular order for diagnostics is not important, as long
2369 // as the order is deterministic. Using the raw location is going
2370 // to generally be in source order unless there are macro
2371 // expansions involved.
2372 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2373 });
2374 for (const LocAndDiag &D : DeclDiags) {
2375 Diag(D.Loc, D.PD);
2376 if (D.PreviousDeclLoc)
2377 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2378 }
2379}
2380
2382 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2383 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2384 (S->isClassScope() && !getLangOpts().CPlusPlus))
2385 S = S->getParent();
2386 return S;
2387}
2388
2389static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2391 switch (Error) {
2393 return "";
2395 return BuiltinInfo.getHeaderName(ID);
2397 return "stdio.h";
2399 return "setjmp.h";
2401 return "ucontext.h";
2402 }
2403 llvm_unreachable("unhandled error kind");
2404}
2405
2407 unsigned ID, SourceLocation Loc) {
2408 DeclContext *Parent = Context.getTranslationUnitDecl();
2409
2410 if (getLangOpts().CPlusPlus) {
2412 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2413 CLinkageDecl->setImplicit();
2414 Parent->addDecl(CLinkageDecl);
2415 Parent = CLinkageDecl;
2416 }
2417
2419 if (Context.BuiltinInfo.isImmediate(ID)) {
2420 assert(getLangOpts().CPlusPlus20 &&
2421 "consteval builtins should only be available in C++20 mode");
2422 ConstexprKind = ConstexprSpecKind::Consteval;
2423 }
2424
2426 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2427 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2428 Type->isFunctionProtoType(), ConstexprKind);
2429 New->setImplicit();
2430 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2431
2432 // Create Decl objects for each parameter, adding them to the
2433 // FunctionDecl.
2434 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2436 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2438 Context, New, SourceLocation(), SourceLocation(), nullptr,
2439 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2440 parm->setScopeInfo(0, i);
2441 Params.push_back(parm);
2442 }
2443 New->setParams(Params);
2444 }
2445
2447 return New;
2448}
2449
2451 Scope *S, bool ForRedeclaration,
2452 SourceLocation Loc) {
2454
2456 QualType R = Context.GetBuiltinType(ID, Error);
2457 if (Error) {
2458 if (!ForRedeclaration)
2459 return nullptr;
2460
2461 // If we have a builtin without an associated type we should not emit a
2462 // warning when we were not able to find a type for it.
2464 Context.BuiltinInfo.allowTypeMismatch(ID))
2465 return nullptr;
2466
2467 // If we could not find a type for setjmp it is because the jmp_buf type was
2468 // not defined prior to the setjmp declaration.
2470 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2471 << Context.BuiltinInfo.getName(ID);
2472 return nullptr;
2473 }
2474
2475 // Generally, we emit a warning that the declaration requires the
2476 // appropriate header.
2477 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2478 << getHeaderName(Context.BuiltinInfo, ID, Error)
2479 << Context.BuiltinInfo.getName(ID);
2480 return nullptr;
2481 }
2482
2483 if (!ForRedeclaration &&
2484 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2485 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2486 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2487 : diag::ext_implicit_lib_function_decl)
2488 << Context.BuiltinInfo.getName(ID) << R;
2489 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2490 Diag(Loc, diag::note_include_header_or_declare)
2491 << Header << Context.BuiltinInfo.getName(ID);
2492 }
2493
2494 if (R.isNull())
2495 return nullptr;
2496
2497 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2499
2500 // TUScope is the translation-unit scope to insert this function into.
2501 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2502 // relate Scopes to DeclContexts, and probably eliminate CurContext
2503 // entirely, but we're not there yet.
2504 DeclContext *SavedContext = CurContext;
2505 CurContext = New->getDeclContext();
2507 CurContext = SavedContext;
2508 return New;
2509}
2510
2511/// Typedef declarations don't have linkage, but they still denote the same
2512/// entity if their types are the same.
2513/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2514/// isSameEntity.
2515static void
2518 // This is only interesting when modules are enabled.
2519 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2520 return;
2521
2522 // Empty sets are uninteresting.
2523 if (Previous.empty())
2524 return;
2525
2526 LookupResult::Filter Filter = Previous.makeFilter();
2527 while (Filter.hasNext()) {
2528 NamedDecl *Old = Filter.next();
2529
2530 // Non-hidden declarations are never ignored.
2531 if (S.isVisible(Old))
2532 continue;
2533
2534 // Declarations of the same entity are not ignored, even if they have
2535 // different linkages.
2536 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2537 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2538 Decl->getUnderlyingType()))
2539 continue;
2540
2541 // If both declarations give a tag declaration a typedef name for linkage
2542 // purposes, then they declare the same entity.
2543 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2544 Decl->getAnonDeclWithTypedefName())
2545 continue;
2546 }
2547
2548 Filter.erase();
2549 }
2550
2551 Filter.done();
2552}
2553
2555 QualType OldType;
2556 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2557 OldType = OldTypedef->getUnderlyingType();
2558 else
2559 OldType = Context.getTypeDeclType(Old);
2560 QualType NewType = New->getUnderlyingType();
2561
2562 if (NewType->isVariablyModifiedType()) {
2563 // Must not redefine a typedef with a variably-modified type.
2564 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2565 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2566 << Kind << NewType;
2567 if (Old->getLocation().isValid())
2568 notePreviousDefinition(Old, New->getLocation());
2569 New->setInvalidDecl();
2570 return true;
2571 }
2572
2573 if (OldType != NewType &&
2574 !OldType->isDependentType() &&
2575 !NewType->isDependentType() &&
2576 !Context.hasSameType(OldType, NewType)) {
2577 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2578 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2579 << Kind << NewType << OldType;
2580 if (Old->getLocation().isValid())
2581 notePreviousDefinition(Old, New->getLocation());
2582 New->setInvalidDecl();
2583 return true;
2584 }
2585 return false;
2586}
2587
2589 LookupResult &OldDecls) {
2590 // If the new decl is known invalid already, don't bother doing any
2591 // merging checks.
2592 if (New->isInvalidDecl()) return;
2593
2594 // Allow multiple definitions for ObjC built-in typedefs.
2595 // FIXME: Verify the underlying types are equivalent!
2596 if (getLangOpts().ObjC) {
2597 const IdentifierInfo *TypeID = New->getIdentifier();
2598 switch (TypeID->getLength()) {
2599 default: break;
2600 case 2:
2601 {
2602 if (!TypeID->isStr("id"))
2603 break;
2604 QualType T = New->getUnderlyingType();
2605 if (!T->isPointerType())
2606 break;
2607 if (!T->isVoidPointerType()) {
2608 QualType PT = T->castAs<PointerType>()->getPointeeType();
2609 if (!PT->isStructureType())
2610 break;
2611 }
2612 Context.setObjCIdRedefinitionType(T);
2613 // Install the built-in type for 'id', ignoring the current definition.
2614 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2615 Context.getObjCIdType());
2616 return;
2617 }
2618 case 5:
2619 if (!TypeID->isStr("Class"))
2620 break;
2621 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2622 // Install the built-in type for 'Class', ignoring the current definition.
2623 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2624 Context.getObjCClassType());
2625 return;
2626 case 3:
2627 if (!TypeID->isStr("SEL"))
2628 break;
2629 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2630 // Install the built-in type for 'SEL', ignoring the current definition.
2631 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2632 Context.getObjCSelType());
2633 return;
2634 }
2635 // Fall through - the typedef name was not a builtin type.
2636 }
2637
2638 // Verify the old decl was also a type.
2639 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2640 if (!Old) {
2641 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2642 << New->getDeclName();
2643
2644 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2645 if (OldD->getLocation().isValid())
2646 notePreviousDefinition(OldD, New->getLocation());
2647
2648 return New->setInvalidDecl();
2649 }
2650
2651 // If the old declaration is invalid, just give up here.
2652 if (Old->isInvalidDecl())
2653 return New->setInvalidDecl();
2654
2655 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2656 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2657 auto *NewTag = New->getAnonDeclWithTypedefName();
2658 NamedDecl *Hidden = nullptr;
2659 if (OldTag && NewTag &&
2660 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2661 !hasVisibleDefinition(OldTag, &Hidden)) {
2662 // There is a definition of this tag, but it is not visible. Use it
2663 // instead of our tag.
2664 if (OldTD->isModed())
2665 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2666 OldTD->getUnderlyingType());
2667 else
2668 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2669
2670 // Make the old tag definition visible.
2672
2674 }
2675 }
2676
2677 // If the typedef types are not identical, reject them in all languages and
2678 // with any extensions enabled.
2679 if (isIncompatibleTypedef(Old, New))
2680 return;
2681
2682 // The types match. Link up the redeclaration chain and merge attributes if
2683 // the old declaration was a typedef.
2684 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2685 New->setPreviousDecl(Typedef);
2687 }
2688
2689 if (getLangOpts().MicrosoftExt)
2690 return;
2691
2692 if (getLangOpts().CPlusPlus) {
2693 // C++ [dcl.typedef]p2:
2694 // In a given non-class scope, a typedef specifier can be used to
2695 // redefine the name of any type declared in that scope to refer
2696 // to the type to which it already refers.
2698 return;
2699
2700 // C++0x [dcl.typedef]p4:
2701 // In a given class scope, a typedef specifier can be used to redefine
2702 // any class-name declared in that scope that is not also a typedef-name
2703 // to refer to the type to which it already refers.
2704 //
2705 // This wording came in via DR424, which was a correction to the
2706 // wording in DR56, which accidentally banned code like:
2707 //
2708 // struct S {
2709 // typedef struct A { } A;
2710 // };
2711 //
2712 // in the C++03 standard. We implement the C++0x semantics, which
2713 // allow the above but disallow
2714 //
2715 // struct S {
2716 // typedef int I;
2717 // typedef int I;
2718 // };
2719 //
2720 // since that was the intent of DR56.
2721 if (!isa<TypedefNameDecl>(Old))
2722 return;
2723
2724 Diag(New->getLocation(), diag::err_redefinition)
2725 << New->getDeclName();
2726 notePreviousDefinition(Old, New->getLocation());
2727 return New->setInvalidDecl();
2728 }
2729
2730 // Modules always permit redefinition of typedefs, as does C11.
2731 if (getLangOpts().Modules || getLangOpts().C11)
2732 return;
2733
2734 // If we have a redefinition of a typedef in C, emit a warning. This warning
2735 // is normally mapped to an error, but can be controlled with
2736 // -Wtypedef-redefinition. If either the original or the redefinition is
2737 // in a system header, don't emit this for compatibility with GCC.
2738 if (getDiagnostics().getSuppressSystemWarnings() &&
2739 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2740 (Old->isImplicit() ||
2741 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2742 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2743 return;
2744
2745 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2746 << New->getDeclName();
2747 notePreviousDefinition(Old, New->getLocation());
2748}
2749
2751 // If this was an unscoped enumeration, yank all of its enumerators
2752 // out of the scope.
2753 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2754 Scope *EnumScope = getNonFieldDeclScope(S);
2755 for (auto *ECD : ED->enumerators()) {
2756 assert(EnumScope->isDeclScope(ECD));
2757 EnumScope->RemoveDecl(ECD);
2758 IdResolver.RemoveDecl(ECD);
2759 }
2760 }
2761}
2762
2763/// DeclhasAttr - returns true if decl Declaration already has the target
2764/// attribute.
2765static bool DeclHasAttr(const Decl *D, const Attr *A) {
2766 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2767 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2768 for (const auto *i : D->attrs())
2769 if (i->getKind() == A->getKind()) {
2770 if (Ann) {
2771 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2772 return true;
2773 continue;
2774 }
2775 // FIXME: Don't hardcode this check
2776 if (OA && isa<OwnershipAttr>(i))
2777 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2778 return true;
2779 }
2780
2781 return false;
2782}
2783
2785 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2786 return VD->isThisDeclarationADefinition();
2787 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2788 return TD->isCompleteDefinition() || TD->isBeingDefined();
2789 return true;
2790}
2791
2792/// Merge alignment attributes from \p Old to \p New, taking into account the
2793/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2794///
2795/// \return \c true if any attributes were added to \p New.
2796static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2797 // Look for alignas attributes on Old, and pick out whichever attribute
2798 // specifies the strictest alignment requirement.
2799 AlignedAttr *OldAlignasAttr = nullptr;
2800 AlignedAttr *OldStrictestAlignAttr = nullptr;
2801 unsigned OldAlign = 0;
2802 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2803 // FIXME: We have no way of representing inherited dependent alignments
2804 // in a case like:
2805 // template<int A, int B> struct alignas(A) X;
2806 // template<int A, int B> struct alignas(B) X {};
2807 // For now, we just ignore any alignas attributes which are not on the
2808 // definition in such a case.
2809 if (I->isAlignmentDependent())
2810 return false;
2811
2812 if (I->isAlignas())
2813 OldAlignasAttr = I;
2814
2815 unsigned Align = I->getAlignment(S.Context);
2816 if (Align > OldAlign) {
2817 OldAlign = Align;
2818 OldStrictestAlignAttr = I;
2819 }
2820 }
2821
2822 // Look for alignas attributes on New.
2823 AlignedAttr *NewAlignasAttr = nullptr;
2824 unsigned NewAlign = 0;
2825 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2826 if (I->isAlignmentDependent())
2827 return false;
2828
2829 if (I->isAlignas())
2830 NewAlignasAttr = I;
2831
2832 unsigned Align = I->getAlignment(S.Context);
2833 if (Align > NewAlign)
2834 NewAlign = Align;
2835 }
2836
2837 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2838 // Both declarations have 'alignas' attributes. We require them to match.
2839 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2840 // fall short. (If two declarations both have alignas, they must both match
2841 // every definition, and so must match each other if there is a definition.)
2842
2843 // If either declaration only contains 'alignas(0)' specifiers, then it
2844 // specifies the natural alignment for the type.
2845 if (OldAlign == 0 || NewAlign == 0) {
2846 QualType Ty;
2847 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2848 Ty = VD->getType();
2849 else
2851
2852 if (OldAlign == 0)
2853 OldAlign = S.Context.getTypeAlign(Ty);
2854 if (NewAlign == 0)
2855 NewAlign = S.Context.getTypeAlign(Ty);
2856 }
2857
2858 if (OldAlign != NewAlign) {
2859 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2862 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2863 }
2864 }
2865
2866 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2867 // C++11 [dcl.align]p6:
2868 // if any declaration of an entity has an alignment-specifier,
2869 // every defining declaration of that entity shall specify an
2870 // equivalent alignment.
2871 // C11 6.7.5/7:
2872 // If the definition of an object does not have an alignment
2873 // specifier, any other declaration of that object shall also
2874 // have no alignment specifier.
2875 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2876 << OldAlignasAttr;
2877 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2878 << OldAlignasAttr;
2879 }
2880
2881 bool AnyAdded = false;
2882
2883 // Ensure we have an attribute representing the strictest alignment.
2884 if (OldAlign > NewAlign) {
2885 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2886 Clone->setInherited(true);
2887 New->addAttr(Clone);
2888 AnyAdded = true;
2889 }
2890
2891 // Ensure we have an alignas attribute if the old declaration had one.
2892 if (OldAlignasAttr && !NewAlignasAttr &&
2893 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2894 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2895 Clone->setInherited(true);
2896 New->addAttr(Clone);
2897 AnyAdded = true;
2898 }
2899
2900 return AnyAdded;
2901}
2902
2903#define WANT_DECL_MERGE_LOGIC
2904#include "clang/Sema/AttrParsedAttrImpl.inc"
2905#undef WANT_DECL_MERGE_LOGIC
2906
2908 const InheritableAttr *Attr,
2910 // Diagnose any mutual exclusions between the attribute that we want to add
2911 // and attributes that already exist on the declaration.
2912 if (!DiagnoseMutualExclusions(S, D, Attr))
2913 return false;
2914
2915 // This function copies an attribute Attr from a previous declaration to the
2916 // new declaration D if the new declaration doesn't itself have that attribute
2917 // yet or if that attribute allows duplicates.
2918 // If you're adding a new attribute that requires logic different from
2919 // "use explicit attribute on decl if present, else use attribute from
2920 // previous decl", for example if the attribute needs to be consistent
2921 // between redeclarations, you need to call a custom merge function here.
2922 InheritableAttr *NewAttr = nullptr;
2923 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2924 const IdentifierInfo *InferredPlatformII = nullptr;
2925 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2926 InferredPlatformII = Inf->getPlatform();
2928 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2929 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2930 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2931 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2932 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2933 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2934 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2935 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2936 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2937 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2938 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2939 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2940 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2941 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2942 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2943 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2944 FA->getFirstArg());
2945 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2946 NewAttr = S.mergeFormatMatchesAttr(
2947 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2948 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2949 NewAttr = S.mergeModularFormatAttr(
2950 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2951 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2952 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2953 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2954 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2955 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2956 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2957 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2958 IA->getInheritanceModel());
2959 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2960 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2961 &S.Context.Idents.get(AA->getSpelling()));
2962 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2965 // CUDA target attributes are part of function signature for
2966 // overloading purposes and must not be merged.
2967 return false;
2968 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2969 NewAttr = S.mergeMinSizeAttr(D, *MA);
2970 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2971 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2972 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2973 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2974 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2975 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2976 else if (isa<AlignedAttr>(Attr))
2977 // AlignedAttrs are handled separately, because we need to handle all
2978 // such attributes on a declaration at the same time.
2979 NewAttr = nullptr;
2984 NewAttr = nullptr;
2985 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2986 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2987 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2988 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2989 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2990 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2991 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2992 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2993 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2994 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2995 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2996 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2997 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2998 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2999 NT->getZ());
3000 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
3001 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
3002 WS->getPreferred(),
3003 WS->getSpelledArgsCount());
3004 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
3005 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
3006 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3007 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3008 else if (isa<SuppressAttr>(Attr))
3009 // Do nothing. Each redeclaration should be suppressed separately.
3010 NewAttr = nullptr;
3011 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
3012 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
3013 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3014 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3015 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
3016 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
3017
3018 if (NewAttr) {
3019 NewAttr->setInherited(true);
3020 D->addAttr(NewAttr);
3021 if (isa<MSInheritanceAttr>(NewAttr))
3023 return true;
3024 }
3025
3026 return false;
3027}
3028
3029static const NamedDecl *getDefinition(const Decl *D) {
3030 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3031 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3032 return Def;
3033 return nullptr;
3034 }
3035 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3036 const VarDecl *Def = VD->getDefinition();
3037 if (Def)
3038 return Def;
3039 return VD->getActingDefinition();
3040 }
3041 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3042 const FunctionDecl *Def = nullptr;
3043 if (FD->isDefined(Def, true))
3044 return Def;
3045 }
3046 return nullptr;
3047}
3048
3049static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3050 for (const auto *Attribute : D->attrs())
3051 if (Attribute->getKind() == Kind)
3052 return true;
3053 return false;
3054}
3055
3056/// checkNewAttributesAfterDef - If we already have a definition, check that
3057/// there are no new attributes in this declaration.
3058static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3059 if (!New->hasAttrs())
3060 return;
3061
3062 const NamedDecl *Def = getDefinition(Old);
3063 if (!Def || Def == New)
3064 return;
3065
3066 AttrVec &NewAttributes = New->getAttrs();
3067 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3068 Attr *NewAttribute = NewAttributes[I];
3069
3070 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3072 SkipBodyInfo SkipBody;
3073 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3074
3075 // If we're skipping this definition, drop the "alias" attribute.
3076 if (SkipBody.ShouldSkip) {
3077 NewAttributes.erase(NewAttributes.begin() + I);
3078 --E;
3079 continue;
3080 }
3081 } else {
3082 VarDecl *VD = cast<VarDecl>(New);
3083 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3085 ? diag::err_alias_after_tentative
3086 : diag::err_redefinition;
3087 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3088 if (Diag == diag::err_redefinition)
3089 S.notePreviousDefinition(Def, VD->getLocation());
3090 else
3091 S.Diag(Def->getLocation(), diag::note_previous_definition);
3092 VD->setInvalidDecl();
3093 }
3094 ++I;
3095 continue;
3096 }
3097
3098 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3099 // Tentative definitions are only interesting for the alias check above.
3100 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3101 ++I;
3102 continue;
3103 }
3104 }
3105
3106 if (hasAttribute(Def, NewAttribute->getKind())) {
3107 ++I;
3108 continue; // regular attr merging will take care of validating this.
3109 }
3110
3111 if (isa<C11NoReturnAttr>(NewAttribute)) {
3112 // C's _Noreturn is allowed to be added to a function after it is defined.
3113 ++I;
3114 continue;
3115 } else if (isa<UuidAttr>(NewAttribute)) {
3116 // msvc will allow a subsequent definition to add an uuid to a class
3117 ++I;
3118 continue;
3120 NewAttribute) &&
3121 NewAttribute->isStandardAttributeSyntax()) {
3122 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3123 // deprecated attribute can later be re-declared with the attribute and
3124 // vice-versa.
3125 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3126 // maybe_unused attribute can later be redeclared with the attribute and
3127 // vice versa.
3128 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3129 // nodiscard attribute can later be redeclared with the attribute and
3130 // vice-versa.
3131 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3132 ++I;
3133 continue;
3134 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3135 if (AA->isAlignas()) {
3136 // C++11 [dcl.align]p6:
3137 // if any declaration of an entity has an alignment-specifier,
3138 // every defining declaration of that entity shall specify an
3139 // equivalent alignment.
3140 // C11 6.7.5/7:
3141 // If the definition of an object does not have an alignment
3142 // specifier, any other declaration of that object shall also
3143 // have no alignment specifier.
3144 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3145 << AA;
3146 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3147 << AA;
3148 NewAttributes.erase(NewAttributes.begin() + I);
3149 --E;
3150 continue;
3151 }
3152 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3153 // If there is a C definition followed by a redeclaration with this
3154 // attribute then there are two different definitions. In C++, prefer the
3155 // standard diagnostics.
3156 if (!S.getLangOpts().CPlusPlus) {
3157 S.Diag(NewAttribute->getLocation(),
3158 diag::err_loader_uninitialized_redeclaration);
3159 S.Diag(Def->getLocation(), diag::note_previous_definition);
3160 NewAttributes.erase(NewAttributes.begin() + I);
3161 --E;
3162 continue;
3163 }
3164 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3165 cast<VarDecl>(New)->isInline() &&
3166 !cast<VarDecl>(New)->isInlineSpecified()) {
3167 // Don't warn about applying selectany to implicitly inline variables.
3168 // Older compilers and language modes would require the use of selectany
3169 // to make such variables inline, and it would have no effect if we
3170 // honored it.
3171 ++I;
3172 continue;
3173 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3174 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3175 // declarations after definitions.
3176 ++I;
3177 continue;
3178 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3179 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3180 // error since the definition will have already been created without
3181 // the semantic effects of the attribute having been applied.
3182 S.Diag(NewAttribute->getLocation(),
3183 diag::err_sycl_entry_point_after_definition)
3184 << NewAttribute;
3185 S.Diag(Def->getLocation(), diag::note_previous_definition);
3186 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3187 ++I;
3188 continue;
3189 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3190 // SYCLExternalAttr may be added after a definition.
3191 ++I;
3192 continue;
3193 }
3194
3195 S.Diag(NewAttribute->getLocation(),
3196 diag::warn_attribute_precede_definition);
3197 S.Diag(Def->getLocation(), diag::note_previous_definition);
3198 NewAttributes.erase(NewAttributes.begin() + I);
3199 --E;
3200 }
3201}
3202
3203static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3204 const ConstInitAttr *CIAttr,
3205 bool AttrBeforeInit) {
3206 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3207
3208 // Figure out a good way to write this specifier on the old declaration.
3209 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3210 // enough of the attribute list spelling information to extract that without
3211 // heroics.
3212 std::string SuitableSpelling;
3213 if (S.getLangOpts().CPlusPlus20)
3214 SuitableSpelling = std::string(
3215 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3216 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3217 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3218 InsertLoc, {tok::l_square, tok::l_square,
3219 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3220 S.PP.getIdentifierInfo("require_constant_initialization"),
3221 tok::r_square, tok::r_square}));
3222 if (SuitableSpelling.empty())
3223 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3224 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3225 S.PP.getIdentifierInfo("require_constant_initialization"),
3226 tok::r_paren, tok::r_paren}));
3227 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3228 SuitableSpelling = "constinit";
3229 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3230 SuitableSpelling = "[[clang::require_constant_initialization]]";
3231 if (SuitableSpelling.empty())
3232 SuitableSpelling = "__attribute__((require_constant_initialization))";
3233 SuitableSpelling += " ";
3234
3235 if (AttrBeforeInit) {
3236 // extern constinit int a;
3237 // int a = 0; // error (missing 'constinit'), accepted as extension
3238 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3239 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3240 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3241 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3242 } else {
3243 // int a = 0;
3244 // constinit extern int a; // error (missing 'constinit')
3245 S.Diag(CIAttr->getLocation(),
3246 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3247 : diag::warn_require_const_init_added_too_late)
3248 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3249 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3250 << CIAttr->isConstinit()
3251 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3252 }
3253}
3254
3257 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3258 UsedAttr *NewAttr = OldAttr->clone(Context);
3259 NewAttr->setInherited(true);
3260 New->addAttr(NewAttr);
3261 }
3262 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3263 RetainAttr *NewAttr = OldAttr->clone(Context);
3264 NewAttr->setInherited(true);
3265 New->addAttr(NewAttr);
3266 }
3267
3268 if (!Old->hasAttrs() && !New->hasAttrs())
3269 return;
3270
3271 // [dcl.constinit]p1:
3272 // If the [constinit] specifier is applied to any declaration of a
3273 // variable, it shall be applied to the initializing declaration.
3274 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3275 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3276 if (bool(OldConstInit) != bool(NewConstInit)) {
3277 const auto *OldVD = cast<VarDecl>(Old);
3278 auto *NewVD = cast<VarDecl>(New);
3279
3280 // Find the initializing declaration. Note that we might not have linked
3281 // the new declaration into the redeclaration chain yet.
3282 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3283 if (!InitDecl &&
3284 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3285 InitDecl = NewVD;
3286
3287 if (InitDecl == NewVD) {
3288 // This is the initializing declaration. If it would inherit 'constinit',
3289 // that's ill-formed. (Note that we do not apply this to the attribute
3290 // form).
3291 if (OldConstInit && OldConstInit->isConstinit())
3292 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3293 /*AttrBeforeInit=*/true);
3294 } else if (NewConstInit) {
3295 // This is the first time we've been told that this declaration should
3296 // have a constant initializer. If we already saw the initializing
3297 // declaration, this is too late.
3298 if (InitDecl && InitDecl != NewVD) {
3299 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3300 /*AttrBeforeInit=*/false);
3301 NewVD->dropAttr<ConstInitAttr>();
3302 }
3303 }
3304 }
3305
3306 // Attributes declared post-definition are currently ignored.
3307 checkNewAttributesAfterDef(*this, New, Old);
3308
3309 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3310 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3311 if (!OldA->isEquivalent(NewA)) {
3312 // This redeclaration changes __asm__ label.
3313 Diag(New->getLocation(), diag::err_different_asm_label);
3314 Diag(OldA->getLocation(), diag::note_previous_declaration);
3315 }
3316 } else if (Old->isUsed()) {
3317 // This redeclaration adds an __asm__ label to a declaration that has
3318 // already been ODR-used.
3319 Diag(New->getLocation(), diag::err_late_asm_label_name)
3320 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3321 }
3322 }
3323
3324 // Re-declaration cannot add abi_tag's.
3325 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3326 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3327 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3328 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3329 Diag(NewAbiTagAttr->getLocation(),
3330 diag::err_new_abi_tag_on_redeclaration)
3331 << NewTag;
3332 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3333 }
3334 }
3335 } else {
3336 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3337 Diag(Old->getLocation(), diag::note_previous_declaration);
3338 }
3339 }
3340
3341 // This redeclaration adds a section attribute.
3342 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3343 if (auto *VD = dyn_cast<VarDecl>(New)) {
3344 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3345 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3346 Diag(Old->getLocation(), diag::note_previous_declaration);
3347 }
3348 }
3349 }
3350
3351 // Redeclaration adds code-seg attribute.
3352 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3353 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3354 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3355 Diag(New->getLocation(), diag::warn_mismatched_section)
3356 << 0 /*codeseg*/;
3357 Diag(Old->getLocation(), diag::note_previous_declaration);
3358 }
3359
3360 if (!Old->hasAttrs())
3361 return;
3362
3363 bool foundAny = New->hasAttrs();
3364
3365 // Ensure that any moving of objects within the allocated map is done before
3366 // we process them.
3367 if (!foundAny) New->setAttrs(AttrVec());
3368
3369 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3370 // Ignore deprecated/unavailable/availability attributes if requested.
3372 if (isa<DeprecatedAttr>(I) ||
3375 switch (AMK) {
3377 continue;
3378
3383 LocalAMK = AMK;
3384 break;
3385 }
3386 }
3387
3388 // Already handled.
3389 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3390 continue;
3391
3393 if (auto *FD = dyn_cast<FunctionDecl>(New);
3394 FD &&
3395 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3396 continue; // Don't propagate inferred noreturn attributes to explicit
3397 }
3398
3399 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3400 foundAny = true;
3401 }
3402
3403 if (mergeAlignedAttrs(*this, New, Old))
3404 foundAny = true;
3405
3406 if (!foundAny) New->dropAttrs();
3407}
3408
3410 for (const Attr *A : D->attrs())
3411 checkAttrIsTypeDependent(D, A);
3412}
3413
3414// Returns the number of added attributes.
3415template <class T>
3416static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3417 Sema &S) {
3418 unsigned found = 0;
3419 for (const auto *I : From->specific_attrs<T>()) {
3420 if (!DeclHasAttr(To, I)) {
3421 T *newAttr = cast<T>(I->clone(S.Context));
3422 newAttr->setInherited(true);
3423 To->addAttr(newAttr);
3424 ++found;
3425 }
3426 }
3427 return found;
3428}
3429
3430template <class F>
3431static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3432 F &&propagator) {
3433 if (!From->hasAttrs()) {
3434 return;
3435 }
3436
3437 bool foundAny = To->hasAttrs();
3438
3439 // Ensure that any moving of objects within the allocated map is
3440 // done before we process them.
3441 if (!foundAny)
3442 To->setAttrs(AttrVec());
3443
3444 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3445
3446 if (!foundAny)
3447 To->dropAttrs();
3448}
3449
3450/// mergeParamDeclAttributes - Copy attributes from the old parameter
3451/// to the new one.
3453 const ParmVarDecl *oldDecl,
3454 Sema &S) {
3455 // C++11 [dcl.attr.depend]p2:
3456 // The first declaration of a function shall specify the
3457 // carries_dependency attribute for its declarator-id if any declaration
3458 // of the function specifies the carries_dependency attribute.
3459 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3460 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3461 S.Diag(CDA->getLocation(),
3462 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3463 // Find the first declaration of the parameter.
3464 // FIXME: Should we build redeclaration chains for function parameters?
3465 const FunctionDecl *FirstFD =
3466 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3467 const ParmVarDecl *FirstVD =
3468 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3469 S.Diag(FirstVD->getLocation(),
3470 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3471 }
3472
3474 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3475 unsigned found = 0;
3476 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3477 // Propagate the lifetimebound attribute from parameters to the
3478 // most recent declaration. Note that this doesn't include the implicit
3479 // 'this' parameter, as the attribute is applied to the function type in
3480 // that case.
3481 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3482 return found;
3483 });
3484}
3485
3487 const ASTContext &Ctx) {
3488
3489 auto NoSizeInfo = [&Ctx](QualType Ty) {
3490 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3491 return true;
3492 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3493 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3494 return false;
3495 };
3496
3497 // `type[]` is equivalent to `type *` and `type[*]`.
3498 if (NoSizeInfo(Old) && NoSizeInfo(New))
3499 return true;
3500
3501 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3502 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3503 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3504 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3505 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3506 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3507 return false;
3508 return true;
3509 }
3510
3511 // Only compare size, ignore Size modifiers and CVR.
3512 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3513 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3515 }
3516
3517 // Don't try to compare dependent sized array
3518 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3519 return true;
3520 }
3521
3522 return Old == New;
3523}
3524
3525static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3526 const ParmVarDecl *OldParam,
3527 Sema &S) {
3528 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3529 if (auto Newnullability = NewParam->getType()->getNullability()) {
3530 if (*Oldnullability != *Newnullability) {
3531 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3533 *Newnullability,
3535 != 0))
3537 *Oldnullability,
3539 != 0));
3540 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3541 }
3542 } else {
3543 QualType NewT = NewParam->getType();
3544 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3545 NewParam->setType(NewT);
3546 }
3547 }
3548 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3549 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3550 if (OldParamDT && NewParamDT &&
3551 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3552 QualType OldParamOT = OldParamDT->getOriginalType();
3553 QualType NewParamOT = NewParamDT->getOriginalType();
3554 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3555 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3556 << NewParam << NewParamOT;
3557 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3558 << OldParamOT;
3559 }
3560 }
3561}
3562
3563namespace {
3564
3565/// Used in MergeFunctionDecl to keep track of function parameters in
3566/// C.
3567struct GNUCompatibleParamWarning {
3568 ParmVarDecl *OldParm;
3569 ParmVarDecl *NewParm;
3570 QualType PromotedType;
3571};
3572
3573} // end anonymous namespace
3574
3575// Determine whether the previous declaration was a definition, implicit
3576// declaration, or a declaration.
3577template <typename T>
3578static std::pair<diag::kind, SourceLocation>
3580 diag::kind PrevDiag;
3581 SourceLocation OldLocation = Old->getLocation();
3582 if (Old->isThisDeclarationADefinition())
3583 PrevDiag = diag::note_previous_definition;
3584 else if (Old->isImplicit()) {
3585 PrevDiag = diag::note_previous_implicit_declaration;
3586 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3587 if (FD->getBuiltinID())
3588 PrevDiag = diag::note_previous_builtin_declaration;
3589 }
3590 if (OldLocation.isInvalid())
3591 OldLocation = New->getLocation();
3592 } else
3593 PrevDiag = diag::note_previous_declaration;
3594 return std::make_pair(PrevDiag, OldLocation);
3595}
3596
3597/// canRedefineFunction - checks if a function can be redefined. Currently,
3598/// only extern inline functions can be redefined, and even then only in
3599/// GNU89 mode.
3600static bool canRedefineFunction(const FunctionDecl *FD,
3601 const LangOptions& LangOpts) {
3602 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3603 !LangOpts.CPlusPlus &&
3604 FD->isInlineSpecified() &&
3605 FD->getStorageClass() == SC_Extern);
3606}
3607
3608const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3609 const AttributedType *AT = T->getAs<AttributedType>();
3610 while (AT && !AT->isCallingConv())
3611 AT = AT->getModifiedType()->getAs<AttributedType>();
3612 return AT;
3613}
3614
3615template <typename T>
3616static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3617 const DeclContext *DC = Old->getDeclContext();
3618 if (DC->isRecord())
3619 return false;
3620
3621 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3622 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3623 return true;
3624 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3625 return true;
3626 return false;
3627}
3628
3629template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3630static bool isExternC(VarTemplateDecl *) { return false; }
3631static bool isExternC(FunctionTemplateDecl *) { return false; }
3632
3633/// Check whether a redeclaration of an entity introduced by a
3634/// using-declaration is valid, given that we know it's not an overload
3635/// (nor a hidden tag declaration).
3636template<typename ExpectedDecl>
3638 ExpectedDecl *New) {
3639 // C++11 [basic.scope.declarative]p4:
3640 // Given a set of declarations in a single declarative region, each of
3641 // which specifies the same unqualified name,
3642 // -- they shall all refer to the same entity, or all refer to functions
3643 // and function templates; or
3644 // -- exactly one declaration shall declare a class name or enumeration
3645 // name that is not a typedef name and the other declarations shall all
3646 // refer to the same variable or enumerator, or all refer to functions
3647 // and function templates; in this case the class name or enumeration
3648 // name is hidden (3.3.10).
3649
3650 // C++11 [namespace.udecl]p14:
3651 // If a function declaration in namespace scope or block scope has the
3652 // same name and the same parameter-type-list as a function introduced
3653 // by a using-declaration, and the declarations do not declare the same
3654 // function, the program is ill-formed.
3655
3656 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3657 if (Old &&
3658 !Old->getDeclContext()->getRedeclContext()->Equals(
3659 New->getDeclContext()->getRedeclContext()) &&
3660 !(isExternC(Old) && isExternC(New)))
3661 Old = nullptr;
3662
3663 if (!Old) {
3664 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3665 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3666 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3667 return true;
3668 }
3669 return false;
3670}
3671
3673 const FunctionDecl *B) {
3674 assert(A->getNumParams() == B->getNumParams());
3675
3676 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3677 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3678 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3679 if (AttrA == AttrB)
3680 return true;
3681 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3682 AttrA->isDynamic() == AttrB->isDynamic();
3683 };
3684
3685 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3686}
3687
3688/// If necessary, adjust the semantic declaration context for a qualified
3689/// declaration to name the correct inline namespace within the qualifier.
3691 DeclaratorDecl *OldD) {
3692 // The only case where we need to update the DeclContext is when
3693 // redeclaration lookup for a qualified name finds a declaration
3694 // in an inline namespace within the context named by the qualifier:
3695 //
3696 // inline namespace N { int f(); }
3697 // int ::f(); // Sema DC needs adjusting from :: to N::.
3698 //
3699 // For unqualified declarations, the semantic context *can* change
3700 // along the redeclaration chain (for local extern declarations,
3701 // extern "C" declarations, and friend declarations in particular).
3702 if (!NewD->getQualifier())
3703 return;
3704
3705 // NewD is probably already in the right context.
3706 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3707 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3708 if (NamedDC->Equals(SemaDC))
3709 return;
3710
3711 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3712 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3713 "unexpected context for redeclaration");
3714
3715 auto *LexDC = NewD->getLexicalDeclContext();
3716 auto FixSemaDC = [=](NamedDecl *D) {
3717 if (!D)
3718 return;
3719 D->setDeclContext(SemaDC);
3720 D->setLexicalDeclContext(LexDC);
3721 };
3722
3723 FixSemaDC(NewD);
3724 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3725 FixSemaDC(FD->getDescribedFunctionTemplate());
3726 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3727 FixSemaDC(VD->getDescribedVarTemplate());
3728}
3729
3731 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3732 // Verify the old decl was also a function.
3733 FunctionDecl *Old = OldD->getAsFunction();
3734 if (!Old) {
3735 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3736 // We don't need to check the using friend pattern from other module unit
3737 // since we should have diagnosed such cases in its unit already.
3738 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3739 Diag(New->getLocation(), diag::err_using_decl_friend);
3740 Diag(Shadow->getTargetDecl()->getLocation(),
3741 diag::note_using_decl_target);
3742 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3743 << 0;
3744 return true;
3745 }
3746
3747 // Check whether the two declarations might declare the same function or
3748 // function template.
3749 if (FunctionTemplateDecl *NewTemplate =
3750 New->getDescribedFunctionTemplate()) {
3752 NewTemplate))
3753 return true;
3754 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3755 ->getAsFunction();
3756 } else {
3757 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3758 return true;
3759 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3760 }
3761 } else {
3762 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3763 << New->getDeclName();
3764 notePreviousDefinition(OldD, New->getLocation());
3765 return true;
3766 }
3767 }
3768
3769 // If the old declaration was found in an inline namespace and the new
3770 // declaration was qualified, update the DeclContext to match.
3772
3773 // If the old declaration is invalid, just give up here.
3774 if (Old->isInvalidDecl())
3775 return true;
3776
3777 // Disallow redeclaration of some builtins.
3778 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3779 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3780 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3781 << Old << Old->getType();
3782 return true;
3783 }
3784
3785 diag::kind PrevDiag;
3786 SourceLocation OldLocation;
3787 std::tie(PrevDiag, OldLocation) =
3789
3790 // Don't complain about this if we're in GNU89 mode and the old function
3791 // is an extern inline function.
3792 // Don't complain about specializations. They are not supposed to have
3793 // storage classes.
3794 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3795 New->getStorageClass() == SC_Static &&
3796 Old->hasExternalFormalLinkage() &&
3797 !New->getTemplateSpecializationInfo() &&
3799 if (getLangOpts().MicrosoftExt) {
3800 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3801 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3802 } else {
3803 Diag(New->getLocation(), diag::err_static_non_static) << New;
3804 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3805 return true;
3806 }
3807 }
3808
3809 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3810 if (!Old->hasAttr<InternalLinkageAttr>()) {
3811 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3812 << ILA;
3813 Diag(Old->getLocation(), diag::note_previous_declaration);
3814 New->dropAttr<InternalLinkageAttr>();
3815 }
3816
3817 if (auto *EA = New->getAttr<ErrorAttr>()) {
3818 if (!Old->hasAttr<ErrorAttr>()) {
3819 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3820 Diag(Old->getLocation(), diag::note_previous_declaration);
3821 New->dropAttr<ErrorAttr>();
3822 }
3823 }
3824
3826 return true;
3827
3828 if (!getLangOpts().CPlusPlus) {
3829 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3830 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3831 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3832 << New << OldOvl;
3833
3834 // Try our best to find a decl that actually has the overloadable
3835 // attribute for the note. In most cases (e.g. programs with only one
3836 // broken declaration/definition), this won't matter.
3837 //
3838 // FIXME: We could do this if we juggled some extra state in
3839 // OverloadableAttr, rather than just removing it.
3840 const Decl *DiagOld = Old;
3841 if (OldOvl) {
3842 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3843 const auto *A = D->getAttr<OverloadableAttr>();
3844 return A && !A->isImplicit();
3845 });
3846 // If we've implicitly added *all* of the overloadable attrs to this
3847 // chain, emitting a "previous redecl" note is pointless.
3848 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3849 }
3850
3851 if (DiagOld)
3852 Diag(DiagOld->getLocation(),
3853 diag::note_attribute_overloadable_prev_overload)
3854 << OldOvl;
3855
3856 if (OldOvl)
3857 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3858 else
3859 New->dropAttr<OverloadableAttr>();
3860 }
3861 }
3862
3863 // It is not permitted to redeclare an SME function with different SME
3864 // attributes.
3865 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3866 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3867 << New->getType() << Old->getType();
3868 Diag(OldLocation, diag::note_previous_declaration);
3869 return true;
3870 }
3871
3872 // If a function is first declared with a calling convention, but is later
3873 // declared or defined without one, all following decls assume the calling
3874 // convention of the first.
3875 //
3876 // It's OK if a function is first declared without a calling convention,
3877 // but is later declared or defined with the default calling convention.
3878 //
3879 // To test if either decl has an explicit calling convention, we look for
3880 // AttributedType sugar nodes on the type as written. If they are missing or
3881 // were canonicalized away, we assume the calling convention was implicit.
3882 //
3883 // Note also that we DO NOT return at this point, because we still have
3884 // other tests to run.
3885 QualType OldQType = Context.getCanonicalType(Old->getType());
3886 QualType NewQType = Context.getCanonicalType(New->getType());
3887 const FunctionType *OldType = cast<FunctionType>(OldQType);
3888 const FunctionType *NewType = cast<FunctionType>(NewQType);
3889 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3890 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3891 bool RequiresAdjustment = false;
3892
3893 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3895 const FunctionType *FT =
3896 First->getType().getCanonicalType()->castAs<FunctionType>();
3898 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3899 if (!NewCCExplicit) {
3900 // Inherit the CC from the previous declaration if it was specified
3901 // there but not here.
3902 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3903 RequiresAdjustment = true;
3904 } else if (Old->getBuiltinID()) {
3905 // Builtin attribute isn't propagated to the new one yet at this point,
3906 // so we check if the old one is a builtin.
3907
3908 // Calling Conventions on a Builtin aren't really useful and setting a
3909 // default calling convention and cdecl'ing some builtin redeclarations is
3910 // common, so warn and ignore the calling convention on the redeclaration.
3911 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3912 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3914 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3915 RequiresAdjustment = true;
3916 } else {
3917 // Calling conventions aren't compatible, so complain.
3918 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3919 Diag(New->getLocation(), diag::err_cconv_change)
3920 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3921 << !FirstCCExplicit
3922 << (!FirstCCExplicit ? "" :
3924
3925 // Put the note on the first decl, since it is the one that matters.
3926 Diag(First->getLocation(), diag::note_previous_declaration);
3927 return true;
3928 }
3929 }
3930
3931 // FIXME: diagnose the other way around?
3932 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3933 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3934 RequiresAdjustment = true;
3935 }
3936
3937 // If the declaration is marked with cfi_unchecked_callee but the definition
3938 // isn't, the definition is also cfi_unchecked_callee.
3939 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3940 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3941 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3942 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3943
3944 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3945 EPI2.CFIUncheckedCallee = true;
3946 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3947 FPT2->getParamTypes(), EPI2);
3948 NewType = cast<FunctionType>(NewQType);
3949 New->setType(NewQType);
3950 }
3951 }
3952 }
3953
3954 // Merge regparm attribute.
3955 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3956 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3957 if (NewTypeInfo.getHasRegParm()) {
3958 Diag(New->getLocation(), diag::err_regparm_mismatch)
3959 << NewType->getRegParmType()
3960 << OldType->getRegParmType();
3961 Diag(OldLocation, diag::note_previous_declaration);
3962 return true;
3963 }
3964
3965 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3966 RequiresAdjustment = true;
3967 }
3968
3969 // Merge ns_returns_retained attribute.
3970 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3971 if (NewTypeInfo.getProducesResult()) {
3972 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3973 << "'ns_returns_retained'";
3974 Diag(OldLocation, diag::note_previous_declaration);
3975 return true;
3976 }
3977
3978 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3979 RequiresAdjustment = true;
3980 }
3981
3982 if (OldTypeInfo.getNoCallerSavedRegs() !=
3983 NewTypeInfo.getNoCallerSavedRegs()) {
3984 if (NewTypeInfo.getNoCallerSavedRegs()) {
3985 AnyX86NoCallerSavedRegistersAttr *Attr =
3986 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3987 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3988 Diag(OldLocation, diag::note_previous_declaration);
3989 return true;
3990 }
3991
3992 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3993 RequiresAdjustment = true;
3994 }
3995
3996 if (RequiresAdjustment) {
3997 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3998 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3999 New->setType(QualType(AdjustedType, 0));
4000 NewQType = Context.getCanonicalType(New->getType());
4001 }
4002
4003 // If this redeclaration makes the function inline, we may need to add it to
4004 // UndefinedButUsed.
4005 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4006 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
4007 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4008 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4009 SourceLocation()));
4010
4011 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4012 // about it.
4013 if (New->hasAttr<GNUInlineAttr>() &&
4014 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4015 UndefinedButUsed.erase(Old->getCanonicalDecl());
4016 }
4017
4018 // If pass_object_size params don't match up perfectly, this isn't a valid
4019 // redeclaration.
4020 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4022 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4023 << New->getDeclName();
4024 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4025 return true;
4026 }
4027
4028 QualType OldQTypeForComparison = OldQType;
4029 if (Context.hasAnyFunctionEffects()) {
4030 const auto OldFX = Old->getFunctionEffects();
4031 const auto NewFX = New->getFunctionEffects();
4032 if (OldFX != NewFX) {
4033 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4034 for (const auto &Diff : Diffs) {
4035 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4036 Diag(New->getLocation(),
4037 diag::warn_mismatched_func_effect_redeclaration)
4038 << Diff.effectName();
4039 Diag(Old->getLocation(), diag::note_previous_declaration);
4040 }
4041 }
4042 // Following a warning, we could skip merging effects from the previous
4043 // declaration, but that would trigger an additional "conflicting types"
4044 // error.
4045 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4047 FunctionEffectSet MergedFX =
4048 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4049 if (!MergeErrs.empty())
4050 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4051 Old->getLocation());
4052
4053 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4054 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4055 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4056 NewFPT->getParamTypes(), EPI);
4057
4058 New->setType(ModQT);
4059 NewQType = New->getType();
4060
4061 // Revise OldQTForComparison to include the merged effects,
4062 // so as not to fail due to differences later.
4063 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4064 EPI = OldFPT->getExtProtoInfo();
4065 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4066 OldQTypeForComparison = Context.getFunctionType(
4067 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4068 }
4069 if (OldFX.empty()) {
4070 // A redeclaration may add the attribute to a previously seen function
4071 // body which needs to be verified.
4072 maybeAddDeclWithEffects(Old, MergedFX);
4073 }
4074 }
4075 }
4076 }
4077
4078 if (getLangOpts().CPlusPlus) {
4079 OldQType = Context.getCanonicalType(Old->getType());
4080 NewQType = Context.getCanonicalType(New->getType());
4081
4082 // Go back to the type source info to compare the declared return types,
4083 // per C++1y [dcl.type.auto]p13:
4084 // Redeclarations or specializations of a function or function template
4085 // with a declared return type that uses a placeholder type shall also
4086 // use that placeholder, not a deduced type.
4087 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4088 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4089 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4090 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4091 OldDeclaredReturnType)) {
4092 QualType ResQT;
4093 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4094 OldDeclaredReturnType->isObjCObjectPointerType())
4095 // FIXME: This does the wrong thing for a deduced return type.
4096 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4097 if (ResQT.isNull()) {
4098 if (New->isCXXClassMember() && New->isOutOfLine())
4099 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4100 << New << New->getReturnTypeSourceRange();
4101 else if (Old->isExternC() && New->isExternC() &&
4102 !Old->hasAttr<OverloadableAttr>() &&
4103 !New->hasAttr<OverloadableAttr>())
4104 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4105 else
4106 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4107 << New->getReturnTypeSourceRange();
4108 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4109 << Old->getReturnTypeSourceRange();
4110 return true;
4111 }
4112 else
4113 NewQType = ResQT;
4114 }
4115
4116 QualType OldReturnType = OldType->getReturnType();
4117 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4118 if (OldReturnType != NewReturnType) {
4119 // If this function has a deduced return type and has already been
4120 // defined, copy the deduced value from the old declaration.
4121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4122 if (OldAT && OldAT->isDeduced()) {
4123 QualType DT = OldAT->getDeducedType();
4124 if (DT.isNull()) {
4125 New->setType(SubstAutoTypeDependent(New->getType()));
4126 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4127 } else {
4128 New->setType(SubstAutoType(New->getType(), DT));
4129 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4130 }
4131 }
4132 }
4133
4134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4136 if (OldMethod && NewMethod) {
4137 // Preserve triviality.
4138 NewMethod->setTrivial(OldMethod->isTrivial());
4139
4140 // MSVC allows explicit template specialization at class scope:
4141 // 2 CXXMethodDecls referring to the same function will be injected.
4142 // We don't want a redeclaration error.
4143 bool IsClassScopeExplicitSpecialization =
4144 OldMethod->isFunctionTemplateSpecialization() &&
4146 bool isFriend = NewMethod->getFriendObjectKind();
4147
4148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4149 !IsClassScopeExplicitSpecialization) {
4150 // -- Member function declarations with the same name and the
4151 // same parameter types cannot be overloaded if any of them
4152 // is a static member function declaration.
4153 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4154 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4155 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4156 return true;
4157 }
4158
4159 // C++ [class.mem]p1:
4160 // [...] A member shall not be declared twice in the
4161 // member-specification, except that a nested class or member
4162 // class template can be declared and then later defined.
4163 if (!inTemplateInstantiation()) {
4164 unsigned NewDiag;
4165 if (isa<CXXConstructorDecl>(OldMethod))
4166 NewDiag = diag::err_constructor_redeclared;
4167 else if (isa<CXXDestructorDecl>(NewMethod))
4168 NewDiag = diag::err_destructor_redeclared;
4169 else if (isa<CXXConversionDecl>(NewMethod))
4170 NewDiag = diag::err_conv_function_redeclared;
4171 else
4172 NewDiag = diag::err_member_redeclared;
4173
4174 Diag(New->getLocation(), NewDiag);
4175 } else {
4176 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4177 << New << New->getType();
4178 }
4179 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4180 return true;
4181
4182 // Complain if this is an explicit declaration of a special
4183 // member that was initially declared implicitly.
4184 //
4185 // As an exception, it's okay to befriend such methods in order
4186 // to permit the implicit constructor/destructor/operator calls.
4187 } else if (OldMethod->isImplicit()) {
4188 if (isFriend) {
4189 NewMethod->setImplicit();
4190 } else {
4191 Diag(NewMethod->getLocation(),
4192 diag::err_definition_of_implicitly_declared_member)
4193 << New << getSpecialMember(OldMethod);
4194 return true;
4195 }
4196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4197 Diag(NewMethod->getLocation(),
4198 diag::err_definition_of_explicitly_defaulted_member)
4199 << getSpecialMember(OldMethod);
4200 return true;
4201 }
4202 }
4203
4204 // C++1z [over.load]p2
4205 // Certain function declarations cannot be overloaded:
4206 // -- Function declarations that differ only in the return type,
4207 // the exception specification, or both cannot be overloaded.
4208
4209 // Check the exception specifications match. This may recompute the type of
4210 // both Old and New if it resolved exception specifications, so grab the
4211 // types again after this. Because this updates the type, we do this before
4212 // any of the other checks below, which may update the "de facto" NewQType
4213 // but do not necessarily update the type of New.
4215 return true;
4216
4217 // C++11 [dcl.attr.noreturn]p1:
4218 // The first declaration of a function shall specify the noreturn
4219 // attribute if any declaration of that function specifies the noreturn
4220 // attribute.
4221 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4222 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4223 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4224 << NRA;
4225 Diag(Old->getLocation(), diag::note_previous_declaration);
4226 }
4227
4228 // C++11 [dcl.attr.depend]p2:
4229 // The first declaration of a function shall specify the
4230 // carries_dependency attribute for its declarator-id if any declaration
4231 // of the function specifies the carries_dependency attribute.
4232 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4233 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4234 Diag(CDA->getLocation(),
4235 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4236 Diag(Old->getFirstDecl()->getLocation(),
4237 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4238 }
4239
4240 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4241 // When a function is declared with SYCL_EXTERNAL, that macro must be
4242 // used on the first declaration of that function in the translation unit.
4243 // Redeclarations of the function in the same translation unit may
4244 // optionally use SYCL_EXTERNAL, but this is not required.
4245 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4246 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4247 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4248 << SEA;
4249 Diag(Old->getLocation(), diag::note_previous_declaration);
4250 }
4251
4252 // (C++98 8.3.5p3):
4253 // All declarations for a function shall agree exactly in both the
4254 // return type and the parameter-type-list.
4255 // We also want to respect all the extended bits except noreturn.
4256
4257 // noreturn should now match unless the old type info didn't have it.
4258 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4259 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4260 const FunctionType *OldTypeForComparison
4261 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4262 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4263 assert(OldQTypeForComparison.isCanonical());
4264 }
4265
4267 // As a special case, retain the language linkage from previous
4268 // declarations of a friend function as an extension.
4269 //
4270 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4271 // and is useful because there's otherwise no way to specify language
4272 // linkage within class scope.
4273 //
4274 // Check cautiously as the friend object kind isn't yet complete.
4275 if (New->getFriendObjectKind() != Decl::FOK_None) {
4276 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4277 Diag(OldLocation, PrevDiag);
4278 } else {
4279 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4280 Diag(OldLocation, PrevDiag);
4281 return true;
4282 }
4283 }
4284
4285 // HLSL check parameters for matching ABI specifications.
4286 if (getLangOpts().HLSL) {
4287 if (HLSL().CheckCompatibleParameterABI(New, Old))
4288 return true;
4289
4290 // If no errors are generated when checking parameter ABIs we can check if
4291 // the two declarations have the same type ignoring the ABIs and if so,
4292 // the declarations can be merged. This case for merging is only valid in
4293 // HLSL because there are no valid cases of merging mismatched parameter
4294 // ABIs except the HLSL implicit in and explicit in.
4295 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4296 NewQType))
4297 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4298 // Fall through for conflicting redeclarations and redefinitions.
4299 }
4300
4301 // If the function types are compatible, merge the declarations. Ignore the
4302 // exception specifier because it was already checked above in
4303 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4304 // about incompatible types under -fms-compatibility.
4305 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4306 NewQType))
4307 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4308
4309 // If the types are imprecise (due to dependent constructs in friends or
4310 // local extern declarations), it's OK if they differ. We'll check again
4311 // during instantiation.
4312 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4313 return false;
4314
4315 // Fall through for conflicting redeclarations and redefinitions.
4316 }
4317
4318 // C: Function types need to be compatible, not identical. This handles
4319 // duplicate function decls like "void f(int); void f(enum X);" properly.
4320 if (!getLangOpts().CPlusPlus) {
4321 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4322 // type is specified by a function definition that contains a (possibly
4323 // empty) identifier list, both shall agree in the number of parameters
4324 // and the type of each parameter shall be compatible with the type that
4325 // results from the application of default argument promotions to the
4326 // type of the corresponding identifier. ...
4327 // This cannot be handled by ASTContext::typesAreCompatible() because that
4328 // doesn't know whether the function type is for a definition or not when
4329 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4330 // we need to cover here is that the number of arguments agree as the
4331 // default argument promotion rules were already checked by
4332 // ASTContext::typesAreCompatible().
4333 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4334 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4335 if (Old->hasInheritedPrototype())
4336 Old = Old->getCanonicalDecl();
4337 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4338 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4339 return true;
4340 }
4341
4342 // If we are merging two functions where only one of them has a prototype,
4343 // we may have enough information to decide to issue a diagnostic that the
4344 // function without a prototype will change behavior in C23. This handles
4345 // cases like:
4346 // void i(); void i(int j);
4347 // void i(int j); void i();
4348 // void i(); void i(int j) {}
4349 // See ActOnFinishFunctionBody() for other cases of the behavior change
4350 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4351 // type without a prototype.
4352 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4353 !New->isImplicit() && !Old->isImplicit()) {
4354 const FunctionDecl *WithProto, *WithoutProto;
4355 if (New->hasWrittenPrototype()) {
4356 WithProto = New;
4357 WithoutProto = Old;
4358 } else {
4359 WithProto = Old;
4360 WithoutProto = New;
4361 }
4362
4363 if (WithProto->getNumParams() != 0) {
4364 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4365 // The one without the prototype will be changing behavior in C23, so
4366 // warn about that one so long as it's a user-visible declaration.
4367 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4368 if (WithoutProto == New)
4369 IsWithoutProtoADef = NewDeclIsDefn;
4370 else
4371 IsWithProtoADef = NewDeclIsDefn;
4372 Diag(WithoutProto->getLocation(),
4373 diag::warn_non_prototype_changes_behavior)
4374 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4375 << (WithoutProto == Old) << IsWithProtoADef;
4376
4377 // The reason the one without the prototype will be changing behavior
4378 // is because of the one with the prototype, so note that so long as
4379 // it's a user-visible declaration. There is one exception to this:
4380 // when the new declaration is a definition without a prototype, the
4381 // old declaration with a prototype is not the cause of the issue,
4382 // and that does not need to be noted because the one with a
4383 // prototype will not change behavior in C23.
4384 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4385 !IsWithoutProtoADef)
4386 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4387 }
4388 }
4389 }
4390
4391 if (Context.typesAreCompatible(OldQType, NewQType)) {
4392 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4393 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4394 const FunctionProtoType *OldProto = nullptr;
4395 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4396 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4397 // The old declaration provided a function prototype, but the
4398 // new declaration does not. Merge in the prototype.
4399 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4400 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4401 OldProto->getParamTypes(),
4402 OldProto->getExtProtoInfo());
4403 New->setType(NewQType);
4404 New->setHasInheritedPrototype();
4405
4406 // Synthesize parameters with the same types.
4408 for (const auto &ParamType : OldProto->param_types()) {
4410 Context, New, SourceLocation(), SourceLocation(), nullptr,
4411 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4412 Param->setScopeInfo(0, Params.size());
4413 Param->setImplicit();
4414 Params.push_back(Param);
4415 }
4416
4417 New->setParams(Params);
4418 }
4419
4420 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4421 }
4422 }
4423
4424 // Check if the function types are compatible when pointer size address
4425 // spaces are ignored.
4426 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4427 return false;
4428
4429 // GNU C permits a K&R definition to follow a prototype declaration
4430 // if the declared types of the parameters in the K&R definition
4431 // match the types in the prototype declaration, even when the
4432 // promoted types of the parameters from the K&R definition differ
4433 // from the types in the prototype. GCC then keeps the types from
4434 // the prototype.
4435 //
4436 // If a variadic prototype is followed by a non-variadic K&R definition,
4437 // the K&R definition becomes variadic. This is sort of an edge case, but
4438 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4439 // C99 6.9.1p8.
4440 if (!getLangOpts().CPlusPlus &&
4441 Old->hasPrototype() && !New->hasPrototype() &&
4442 New->getType()->getAs<FunctionProtoType>() &&
4443 Old->getNumParams() == New->getNumParams()) {
4446 const FunctionProtoType *OldProto
4447 = Old->getType()->getAs<FunctionProtoType>();
4448 const FunctionProtoType *NewProto
4449 = New->getType()->getAs<FunctionProtoType>();
4450
4451 // Determine whether this is the GNU C extension.
4452 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4453 NewProto->getReturnType());
4454 bool LooseCompatible = !MergedReturn.isNull();
4455 for (unsigned Idx = 0, End = Old->getNumParams();
4456 LooseCompatible && Idx != End; ++Idx) {
4457 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4458 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4459 if (Context.typesAreCompatible(OldParm->getType(),
4460 NewProto->getParamType(Idx))) {
4461 ArgTypes.push_back(NewParm->getType());
4462 } else if (Context.typesAreCompatible(OldParm->getType(),
4463 NewParm->getType(),
4464 /*CompareUnqualified=*/true)) {
4465 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4466 NewProto->getParamType(Idx) };
4467 Warnings.push_back(Warn);
4468 ArgTypes.push_back(NewParm->getType());
4469 } else
4470 LooseCompatible = false;
4471 }
4472
4473 if (LooseCompatible) {
4474 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4475 Diag(Warnings[Warn].NewParm->getLocation(),
4476 diag::ext_param_promoted_not_compatible_with_prototype)
4477 << Warnings[Warn].PromotedType
4478 << Warnings[Warn].OldParm->getType();
4479 if (Warnings[Warn].OldParm->getLocation().isValid())
4480 Diag(Warnings[Warn].OldParm->getLocation(),
4481 diag::note_previous_declaration);
4482 }
4483
4484 if (MergeTypeWithOld)
4485 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4486 OldProto->getExtProtoInfo()));
4487 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4488 }
4489
4490 // Fall through to diagnose conflicting types.
4491 }
4492
4493 // A function that has already been declared has been redeclared or
4494 // defined with a different type; show an appropriate diagnostic.
4495
4496 // If the previous declaration was an implicitly-generated builtin
4497 // declaration, then at the very least we should use a specialized note.
4498 unsigned BuiltinID;
4499 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4500 // If it's actually a library-defined builtin function like 'malloc'
4501 // or 'printf', just warn about the incompatible redeclaration.
4502 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4503 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4504 Diag(OldLocation, diag::note_previous_builtin_declaration)
4505 << Old << Old->getType();
4506 return false;
4507 }
4508
4509 PrevDiag = diag::note_previous_builtin_declaration;
4510 }
4511
4512 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4513 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4514 return true;
4515}
4516
4518 Scope *S, bool MergeTypeWithOld) {
4519 // Merge the attributes
4521
4522 // Merge "pure" flag.
4523 if (Old->isPureVirtual())
4524 New->setIsPureVirtual();
4525
4526 // Merge "used" flag.
4527 if (Old->getMostRecentDecl()->isUsed(false))
4528 New->setIsUsed();
4529
4530 // Merge attributes from the parameters. These can mismatch with K&R
4531 // declarations.
4532 if (New->getNumParams() == Old->getNumParams())
4533 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4534 ParmVarDecl *NewParam = New->getParamDecl(i);
4535 ParmVarDecl *OldParam = Old->getParamDecl(i);
4536 mergeParamDeclAttributes(NewParam, OldParam, *this);
4537 mergeParamDeclTypes(NewParam, OldParam, *this);
4538 }
4539
4540 if (getLangOpts().CPlusPlus)
4541 return MergeCXXFunctionDecl(New, Old, S);
4542
4543 // Merge the function types so the we get the composite types for the return
4544 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4545 // was visible.
4546 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4547 if (!Merged.isNull() && MergeTypeWithOld)
4548 New->setType(Merged);
4549
4550 return false;
4551}
4552
4554 ObjCMethodDecl *oldMethod) {
4555 // Merge the attributes, including deprecated/unavailable
4556 AvailabilityMergeKind MergeKind =
4558 ? (oldMethod->isOptional()
4561 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4564
4565 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4566
4567 // Merge attributes from the parameters.
4569 oe = oldMethod->param_end();
4571 ni = newMethod->param_begin(), ne = newMethod->param_end();
4572 ni != ne && oi != oe; ++ni, ++oi)
4573 mergeParamDeclAttributes(*ni, *oi, *this);
4574
4575 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4576}
4577
4579 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4580
4581 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4582 ? diag::err_redefinition_different_type
4583 : diag::err_redeclaration_different_type)
4584 << New->getDeclName() << New->getType() << Old->getType();
4585
4586 diag::kind PrevDiag;
4587 SourceLocation OldLocation;
4588 std::tie(PrevDiag, OldLocation)
4590 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4591 New->setInvalidDecl();
4592}
4593
4595 bool MergeTypeWithOld) {
4596 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4597 return;
4598
4599 QualType MergedT;
4600 if (getLangOpts().CPlusPlus) {
4601 if (New->getType()->isUndeducedType()) {
4602 // We don't know what the new type is until the initializer is attached.
4603 return;
4604 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4605 // These could still be something that needs exception specs checked.
4606 return MergeVarDeclExceptionSpecs(New, Old);
4607 }
4608 // C++ [basic.link]p10:
4609 // [...] the types specified by all declarations referring to a given
4610 // object or function shall be identical, except that declarations for an
4611 // array object can specify array types that differ by the presence or
4612 // absence of a major array bound (8.3.4).
4613 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4614 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4615 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4616
4617 // We are merging a variable declaration New into Old. If it has an array
4618 // bound, and that bound differs from Old's bound, we should diagnose the
4619 // mismatch.
4620 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4621 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4622 PrevVD = PrevVD->getPreviousDecl()) {
4623 QualType PrevVDTy = PrevVD->getType();
4624 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4625 continue;
4626
4627 if (!Context.hasSameType(New->getType(), PrevVDTy))
4628 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4629 }
4630 }
4631
4632 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4633 if (Context.hasSameType(OldArray->getElementType(),
4634 NewArray->getElementType()))
4635 MergedT = New->getType();
4636 }
4637 // FIXME: Check visibility. New is hidden but has a complete type. If New
4638 // has no array bound, it should not inherit one from Old, if Old is not
4639 // visible.
4640 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4641 if (Context.hasSameType(OldArray->getElementType(),
4642 NewArray->getElementType()))
4643 MergedT = Old->getType();
4644 }
4645 }
4646 else if (New->getType()->isObjCObjectPointerType() &&
4647 Old->getType()->isObjCObjectPointerType()) {
4648 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4649 Old->getType());
4650 }
4651 } else {
4652 // C 6.2.7p2:
4653 // All declarations that refer to the same object or function shall have
4654 // compatible type.
4655 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4656 }
4657 if (MergedT.isNull()) {
4658 // It's OK if we couldn't merge types if either type is dependent, for a
4659 // block-scope variable. In other cases (static data members of class
4660 // templates, variable templates, ...), we require the types to be
4661 // equivalent.
4662 // FIXME: The C++ standard doesn't say anything about this.
4663 if ((New->getType()->isDependentType() ||
4664 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4665 // If the old type was dependent, we can't merge with it, so the new type
4666 // becomes dependent for now. We'll reproduce the original type when we
4667 // instantiate the TypeSourceInfo for the variable.
4668 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4669 New->setType(Context.DependentTy);
4670 return;
4671 }
4672 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4673 }
4674
4675 // Don't actually update the type on the new declaration if the old
4676 // declaration was an extern declaration in a different scope.
4677 if (MergeTypeWithOld)
4678 New->setType(MergedT);
4679}
4680
4681static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4683 // C11 6.2.7p4:
4684 // For an identifier with internal or external linkage declared
4685 // in a scope in which a prior declaration of that identifier is
4686 // visible, if the prior declaration specifies internal or
4687 // external linkage, the type of the identifier at the later
4688 // declaration becomes the composite type.
4689 //
4690 // If the variable isn't visible, we do not merge with its type.
4691 if (Previous.isShadowed())
4692 return false;
4693
4694 if (S.getLangOpts().CPlusPlus) {
4695 // C++11 [dcl.array]p3:
4696 // If there is a preceding declaration of the entity in the same
4697 // scope in which the bound was specified, an omitted array bound
4698 // is taken to be the same as in that earlier declaration.
4699 return NewVD->isPreviousDeclInSameBlockScope() ||
4700 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4702 } else {
4703 // If the old declaration was function-local, don't merge with its
4704 // type unless we're in the same function.
4705 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4706 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4707 }
4708}
4709
4711 // If the new decl is already invalid, don't do any other checking.
4712 if (New->isInvalidDecl())
4713 return;
4714
4715 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4716 return;
4717
4718 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4719
4720 // Verify the old decl was also a variable or variable template.
4721 VarDecl *Old = nullptr;
4722 VarTemplateDecl *OldTemplate = nullptr;
4723 if (Previous.isSingleResult()) {
4724 if (NewTemplate) {
4725 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4726 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4727
4728 if (auto *Shadow =
4729 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4730 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4731 return New->setInvalidDecl();
4732 } else {
4733 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4734
4735 if (auto *Shadow =
4736 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4737 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4738 return New->setInvalidDecl();
4739 }
4740 }
4741 if (!Old) {
4742 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4743 << New->getDeclName();
4744 notePreviousDefinition(Previous.getRepresentativeDecl(),
4745 New->getLocation());
4746 return New->setInvalidDecl();
4747 }
4748
4749 // If the old declaration was found in an inline namespace and the new
4750 // declaration was qualified, update the DeclContext to match.
4752
4753 // Ensure the template parameters are compatible.
4754 if (NewTemplate &&
4756 OldTemplate->getTemplateParameters(),
4757 /*Complain=*/true, TPL_TemplateMatch))
4758 return New->setInvalidDecl();
4759
4760 // C++ [class.mem]p1:
4761 // A member shall not be declared twice in the member-specification [...]
4762 //
4763 // Here, we need only consider static data members.
4764 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4765 Diag(New->getLocation(), diag::err_duplicate_member)
4766 << New->getIdentifier();
4767 Diag(Old->getLocation(), diag::note_previous_declaration);
4768 New->setInvalidDecl();
4769 }
4770
4771 if (NewTemplate && OldTemplate)
4772 mergeDeclAttributes(NewTemplate, OldTemplate);
4773
4775
4776 // Warn if an already-defined variable is made a weak_import in a subsequent
4777 // declaration
4778 if (New->hasAttr<WeakImportAttr>())
4779 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4780 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4781 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4782 Diag(D->getLocation(), diag::note_previous_definition);
4783 // Remove weak_import attribute on new declaration.
4784 New->dropAttr<WeakImportAttr>();
4785 break;
4786 }
4787 }
4788
4789 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4790 if (!Old->hasAttr<InternalLinkageAttr>()) {
4791 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4792 << ILA;
4793 Diag(Old->getLocation(), diag::note_previous_declaration);
4794 New->dropAttr<InternalLinkageAttr>();
4795 }
4796
4797 // Merge the types.
4798 VarDecl *MostRecent = Old->getMostRecentDecl();
4799 if (MostRecent != Old) {
4800 MergeVarDeclTypes(New, MostRecent,
4801 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4802 if (New->isInvalidDecl())
4803 return;
4804 }
4805
4807 if (New->isInvalidDecl())
4808 return;
4809
4810 diag::kind PrevDiag;
4811 SourceLocation OldLocation;
4812 std::tie(PrevDiag, OldLocation) =
4814
4815 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4816 if (New->getStorageClass() == SC_Static &&
4817 !New->isStaticDataMember() &&
4818 Old->hasExternalFormalLinkage()) {
4819 if (getLangOpts().MicrosoftExt) {
4820 Diag(New->getLocation(), diag::ext_static_non_static)
4821 << New->getDeclName();
4822 Diag(OldLocation, PrevDiag);
4823 } else {
4824 Diag(New->getLocation(), diag::err_static_non_static)
4825 << New->getDeclName();
4826 Diag(OldLocation, PrevDiag);
4827 return New->setInvalidDecl();
4828 }
4829 }
4830 // C99 6.2.2p4:
4831 // For an identifier declared with the storage-class specifier
4832 // extern in a scope in which a prior declaration of that
4833 // identifier is visible,23) if the prior declaration specifies
4834 // internal or external linkage, the linkage of the identifier at
4835 // the later declaration is the same as the linkage specified at
4836 // the prior declaration. If no prior declaration is visible, or
4837 // if the prior declaration specifies no linkage, then the
4838 // identifier has external linkage.
4839 if (New->hasExternalStorage() && Old->hasLinkage())
4840 /* Okay */;
4841 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4842 !New->isStaticDataMember() &&
4844 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4845 Diag(OldLocation, PrevDiag);
4846 return New->setInvalidDecl();
4847 }
4848
4849 // Check if extern is followed by non-extern and vice-versa.
4850 if (New->hasExternalStorage() &&
4851 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4852 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4853 Diag(OldLocation, PrevDiag);
4854 return New->setInvalidDecl();
4855 }
4856 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4857 !New->hasExternalStorage()) {
4858 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4859 Diag(OldLocation, PrevDiag);
4860 return New->setInvalidDecl();
4861 }
4862
4864 return;
4865
4866 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4867
4868 // FIXME: The test for external storage here seems wrong? We still
4869 // need to check for mismatches.
4870 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4871 // Don't complain about out-of-line definitions of static members.
4872 !(Old->getLexicalDeclContext()->isRecord() &&
4873 !New->getLexicalDeclContext()->isRecord())) {
4874 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4875 Diag(OldLocation, PrevDiag);
4876 return New->setInvalidDecl();
4877 }
4878
4879 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4880 if (VarDecl *Def = Old->getDefinition()) {
4881 // C++1z [dcl.fcn.spec]p4:
4882 // If the definition of a variable appears in a translation unit before
4883 // its first declaration as inline, the program is ill-formed.
4884 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4885 Diag(Def->getLocation(), diag::note_previous_definition);
4886 }
4887 }
4888
4889 // If this redeclaration makes the variable inline, we may need to add it to
4890 // UndefinedButUsed.
4891 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4892 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4893 !Old->isInAnotherModuleUnit())
4894 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4895 SourceLocation()));
4896
4897 if (New->getTLSKind() != Old->getTLSKind()) {
4898 if (!Old->getTLSKind()) {
4899 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4900 Diag(OldLocation, PrevDiag);
4901 } else if (!New->getTLSKind()) {
4902 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4903 Diag(OldLocation, PrevDiag);
4904 } else {
4905 // Do not allow redeclaration to change the variable between requiring
4906 // static and dynamic initialization.
4907 // FIXME: GCC allows this, but uses the TLS keyword on the first
4908 // declaration to determine the kind. Do we need to be compatible here?
4909 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4910 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4911 Diag(OldLocation, PrevDiag);
4912 }
4913 }
4914
4915 // C++ doesn't have tentative definitions, so go right ahead and check here.
4916 if (getLangOpts().CPlusPlus) {
4917 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4918 Old->getCanonicalDecl()->isConstexpr()) {
4919 // This definition won't be a definition any more once it's been merged.
4920 Diag(New->getLocation(),
4921 diag::warn_deprecated_redundant_constexpr_static_def);
4922 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4923 VarDecl *Def = Old->getDefinition();
4924 if (Def && checkVarDeclRedefinition(Def, New))
4925 return;
4926 if (Old->isInvalidDecl())
4927 New->setInvalidDecl();
4928 }
4929 } else {
4930 // C++ may not have a tentative definition rule, but it has a different
4931 // rule about what constitutes a definition in the first place. See
4932 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4933 // contains the extern specifier and doesn't have an initializer, it's fine
4934 // in C++.
4935 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4936 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4937 << New;
4938 Diag(Old->getLocation(), diag::note_previous_declaration);
4939 }
4940 }
4941
4943 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4944 Diag(OldLocation, PrevDiag);
4945 New->setInvalidDecl();
4946 return;
4947 }
4948
4949 // Merge "used" flag.
4950 if (Old->getMostRecentDecl()->isUsed(false))
4951 New->setIsUsed();
4952
4953 // Keep a chain of previous declarations.
4954 New->setPreviousDecl(Old);
4955 if (NewTemplate)
4956 NewTemplate->setPreviousDecl(OldTemplate);
4957
4958 // Inherit access appropriately.
4959 New->setAccess(Old->getAccess());
4960 if (NewTemplate)
4961 NewTemplate->setAccess(New->getAccess());
4962
4963 if (Old->isInline())
4964 New->setImplicitlyInline();
4965}
4966
4969 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4970 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4971 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4972 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4973 auto &HSI = PP.getHeaderSearchInfo();
4974 StringRef HdrFilename =
4975 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4976
4977 auto noteFromModuleOrInclude = [&](Module *Mod,
4978 SourceLocation IncLoc) -> bool {
4979 // Redefinition errors with modules are common with non modular mapped
4980 // headers, example: a non-modular header H in module A that also gets
4981 // included directly in a TU. Pointing twice to the same header/definition
4982 // is confusing, try to get better diagnostics when modules is on.
4983 if (IncLoc.isValid()) {
4984 if (Mod) {
4985 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4986 << HdrFilename.str() << Mod->getFullModuleName();
4987 if (!Mod->DefinitionLoc.isInvalid())
4988 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4989 << Mod->getFullModuleName();
4990 } else {
4991 Diag(IncLoc, diag::note_redefinition_include_same_file)
4992 << HdrFilename.str();
4993 }
4994 return true;
4995 }
4996
4997 return false;
4998 };
4999
5000 // Is it the same file and same offset? Provide more information on why
5001 // this leads to a redefinition error.
5002 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5003 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
5004 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
5005 bool EmittedDiag =
5006 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5007 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5008
5009 // If the header has no guards, emit a note suggesting one.
5010 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
5011 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
5012
5013 if (EmittedDiag)
5014 return;
5015 }
5016
5017 // Redefinition coming from different files or couldn't do better above.
5018 if (Old->getLocation().isValid())
5019 Diag(Old->getLocation(), diag::note_previous_definition);
5020}
5021
5023 if (!hasVisibleDefinition(Old) &&
5024 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5026 New->getDescribedVarTemplate() ||
5027 !New->getTemplateParameterLists().empty() ||
5028 New->getDeclContext()->isDependentContext() ||
5029 New->hasAttr<SelectAnyAttr>())) {
5030 // The previous definition is hidden, and multiple definitions are
5031 // permitted (in separate TUs). Demote this to a declaration.
5032 New->demoteThisDefinitionToDeclaration();
5033
5034 // Make the canonical definition visible.
5035 if (auto *OldTD = Old->getDescribedVarTemplate())
5038 return false;
5039 } else {
5040 Diag(New->getLocation(), diag::err_redefinition) << New;
5041 notePreviousDefinition(Old, New->getLocation());
5042 New->setInvalidDecl();
5043 return true;
5044 }
5045}
5046
5048 DeclSpec &DS,
5049 const ParsedAttributesView &DeclAttrs,
5050 RecordDecl *&AnonRecord) {
5052 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5053}
5054
5055// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5056// disambiguate entities defined in different scopes.
5057// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5058// compatibility.
5059// We will pick our mangling number depending on which version of MSVC is being
5060// targeted.
5061static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5065}
5066
5067void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5068 if (!Context.getLangOpts().CPlusPlus)
5069 return;
5070
5071 if (isa<CXXRecordDecl>(Tag->getParent())) {
5072 // If this tag is the direct child of a class, number it if
5073 // it is anonymous.
5074 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5075 return;
5077 Context.getManglingNumberContext(Tag->getParent());
5078 Context.setManglingNumber(
5079 Tag, MCtx.getManglingNumber(
5080 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5081 return;
5082 }
5083
5084 // If this tag isn't a direct child of a class, number it if it is local.
5086 Decl *ManglingContextDecl;
5087 std::tie(MCtx, ManglingContextDecl) =
5088 getCurrentMangleNumberContext(Tag->getDeclContext());
5089 if (MCtx) {
5090 Context.setManglingNumber(
5091 Tag, MCtx->getManglingNumber(
5092 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5093 }
5094}
5095
5096namespace {
5097struct NonCLikeKind {
5098 enum {
5099 None,
5100 BaseClass,
5101 DefaultMemberInit,
5102 Lambda,
5103 Friend,
5104 OtherMember,
5105 Invalid,
5106 } Kind = None;
5107 SourceRange Range;
5108
5109 explicit operator bool() { return Kind != None; }
5110};
5111}
5112
5113/// Determine whether a class is C-like, according to the rules of C++
5114/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5115static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5116 if (RD->isInvalidDecl())
5117 return {NonCLikeKind::Invalid, {}};
5118
5119 // C++ [dcl.typedef]p9: [P1766R1]
5120 // An unnamed class with a typedef name for linkage purposes shall not
5121 //
5122 // -- have any base classes
5123 if (RD->getNumBases())
5124 return {NonCLikeKind::BaseClass,
5126 RD->bases_end()[-1].getEndLoc())};
5127 bool Invalid = false;
5128 for (Decl *D : RD->decls()) {
5129 // Don't complain about things we already diagnosed.
5130 if (D->isInvalidDecl()) {
5131 Invalid = true;
5132 continue;
5133 }
5134
5135 // -- have any [...] default member initializers
5136 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5137 if (FD->hasInClassInitializer()) {
5138 auto *Init = FD->getInClassInitializer();
5139 return {NonCLikeKind::DefaultMemberInit,
5140 Init ? Init->getSourceRange() : D->getSourceRange()};
5141 }
5142 continue;
5143 }
5144
5145 // FIXME: We don't allow friend declarations. This violates the wording of
5146 // P1766, but not the intent.
5147 if (isa<FriendDecl>(D))
5148 return {NonCLikeKind::Friend, D->getSourceRange()};
5149
5150 // -- declare any members other than non-static data members, member
5151 // enumerations, or member classes,
5153 isa<EnumDecl>(D))
5154 continue;
5155 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5156 if (!MemberRD) {
5157 if (D->isImplicit())
5158 continue;
5159 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5160 }
5161
5162 // -- contain a lambda-expression,
5163 if (MemberRD->isLambda())
5164 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5165
5166 // and all member classes shall also satisfy these requirements
5167 // (recursively).
5168 if (MemberRD->isThisDeclarationADefinition()) {
5169 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5170 return Kind;
5171 }
5172 }
5173
5174 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5175}
5176
5178 TypedefNameDecl *NewTD) {
5179 if (TagFromDeclSpec->isInvalidDecl())
5180 return;
5181
5182 // Do nothing if the tag already has a name for linkage purposes.
5183 if (TagFromDeclSpec->hasNameForLinkage())
5184 return;
5185
5186 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5187 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5188
5189 // The type must match the tag exactly; no qualifiers allowed.
5190 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5191 Context.getCanonicalTagType(TagFromDeclSpec))) {
5192 if (getLangOpts().CPlusPlus)
5193 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5194 return;
5195 }
5196
5197 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5198 // An unnamed class with a typedef name for linkage purposes shall [be
5199 // C-like].
5200 //
5201 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5202 // shouldn't happen, but there are constructs that the language rule doesn't
5203 // disallow for which we can't reasonably avoid computing linkage early.
5204 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5205 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5206 : NonCLikeKind();
5207 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5208 if (NonCLike || ChangesLinkage) {
5209 if (NonCLike.Kind == NonCLikeKind::Invalid)
5210 return;
5211
5212 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5213 if (ChangesLinkage) {
5214 // If the linkage changes, we can't accept this as an extension.
5215 if (NonCLike.Kind == NonCLikeKind::None)
5216 DiagID = diag::err_typedef_changes_linkage;
5217 else
5218 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5219 }
5220
5221 SourceLocation FixitLoc =
5222 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5223 llvm::SmallString<40> TextToInsert;
5224 TextToInsert += ' ';
5225 TextToInsert += NewTD->getIdentifier()->getName();
5226
5227 Diag(FixitLoc, DiagID)
5228 << isa<TypeAliasDecl>(NewTD)
5229 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5230 if (NonCLike.Kind != NonCLikeKind::None) {
5231 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5232 << NonCLike.Kind - 1 << NonCLike.Range;
5233 }
5234 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5235 << NewTD << isa<TypeAliasDecl>(NewTD);
5236
5237 if (ChangesLinkage)
5238 return;
5239 }
5240
5241 // Otherwise, set this as the anon-decl typedef for the tag.
5242 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5243
5244 // Now that we have a name for the tag, process API notes again.
5245 ProcessAPINotes(TagFromDeclSpec);
5246}
5247
5248static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5250 switch (T) {
5252 return 0;
5254 return 1;
5256 return 2;
5258 return 3;
5259 case DeclSpec::TST_enum:
5260 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5261 if (ED->isScopedUsingClassTag())
5262 return 5;
5263 if (ED->isScoped())
5264 return 6;
5265 }
5266 return 4;
5267 default:
5268 llvm_unreachable("unexpected type specifier");
5269 }
5270}
5271
5273 DeclSpec &DS,
5274 const ParsedAttributesView &DeclAttrs,
5275 MultiTemplateParamsArg TemplateParams,
5276 bool IsExplicitInstantiation,
5277 RecordDecl *&AnonRecord,
5278 SourceLocation EllipsisLoc) {
5279 Decl *TagD = nullptr;
5280 TagDecl *Tag = nullptr;
5286 TagD = DS.getRepAsDecl();
5287
5288 if (!TagD) // We probably had an error
5289 return nullptr;
5290
5291 // Note that the above type specs guarantee that the
5292 // type rep is a Decl, whereas in many of the others
5293 // it's a Type.
5294 if (isa<TagDecl>(TagD))
5295 Tag = cast<TagDecl>(TagD);
5296 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5297 Tag = CTD->getTemplatedDecl();
5298 }
5299
5300 if (Tag) {
5301 handleTagNumbering(Tag, S);
5302 Tag->setFreeStanding();
5303 if (Tag->isInvalidDecl())
5304 return Tag;
5305 }
5306
5307 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5308 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5309 // or incomplete types shall not be restrict-qualified."
5310 if (TypeQuals & DeclSpec::TQ_restrict)
5312 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5313 << DS.getSourceRange();
5314 }
5315
5316 if (DS.isInlineSpecified())
5317 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5318 << getLangOpts().CPlusPlus17;
5319
5320 if (DS.hasConstexprSpecifier()) {
5321 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5322 // and definitions of functions and variables.
5323 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5324 // the declaration of a function or function template
5325 if (Tag)
5326 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5328 << static_cast<int>(DS.getConstexprSpecifier());
5329 else if (getLangOpts().C23)
5330 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5331 else
5332 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5333 << static_cast<int>(DS.getConstexprSpecifier());
5334 // Don't emit warnings after this error.
5335 return TagD;
5336 }
5337
5339
5340 if (DS.isFriendSpecified()) {
5341 // If we're dealing with a decl but not a TagDecl, assume that
5342 // whatever routines created it handled the friendship aspect.
5343 if (TagD && !Tag)
5344 return nullptr;
5345 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5346 }
5347
5348 assert(EllipsisLoc.isInvalid() &&
5349 "Friend ellipsis but not friend-specified?");
5350
5351 // Track whether this decl-specifier declares anything.
5352 bool DeclaresAnything = true;
5353
5354 // Handle anonymous struct definitions.
5355 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5356 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5358 if (getLangOpts().CPlusPlus ||
5359 Record->getDeclContext()->isRecord()) {
5360 // If CurContext is a DeclContext that can contain statements,
5361 // RecursiveASTVisitor won't visit the decls that
5362 // BuildAnonymousStructOrUnion() will put into CurContext.
5363 // Also store them here so that they can be part of the
5364 // DeclStmt that gets created in this case.
5365 // FIXME: Also return the IndirectFieldDecls created by
5366 // BuildAnonymousStructOr union, for the same reason?
5367 if (CurContext->isFunctionOrMethod())
5368 AnonRecord = Record;
5369 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5370 Context.getPrintingPolicy());
5371 }
5372
5373 DeclaresAnything = false;
5374 }
5375 }
5376
5377 // C11 6.7.2.1p2:
5378 // A struct-declaration that does not declare an anonymous structure or
5379 // anonymous union shall contain a struct-declarator-list.
5380 //
5381 // This rule also existed in C89 and C99; the grammar for struct-declaration
5382 // did not permit a struct-declaration without a struct-declarator-list.
5383 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5385 // Check for Microsoft C extension: anonymous struct/union member.
5386 // Handle 2 kinds of anonymous struct/union:
5387 // struct STRUCT;
5388 // union UNION;
5389 // and
5390 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5391 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5392 if ((Tag && Tag->getDeclName()) ||
5394 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5395 : DS.getRepAsType().get()->getAsRecordDecl();
5396 if (Record && getLangOpts().MSAnonymousStructs) {
5397 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5398 << Record->isUnion() << DS.getSourceRange();
5400 }
5401
5402 DeclaresAnything = false;
5403 }
5404 }
5405
5406 // Skip all the checks below if we have a type error.
5408 (TagD && TagD->isInvalidDecl()))
5409 return TagD;
5410
5411 if (getLangOpts().CPlusPlus &&
5413 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5414 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5415 !Enum->isInvalidDecl())
5416 DeclaresAnything = false;
5417
5418 if (!DS.isMissingDeclaratorOk()) {
5419 // Customize diagnostic for a typedef missing a name.
5421 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5422 << DS.getSourceRange();
5423 else
5424 DeclaresAnything = false;
5425 }
5426
5427 if (DS.isModulePrivateSpecified() &&
5428 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5429 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5430 << Tag->getTagKind()
5432
5434
5435 // C 6.7/2:
5436 // A declaration [...] shall declare at least a declarator [...], a tag,
5437 // or the members of an enumeration.
5438 // C++ [dcl.dcl]p3:
5439 // [If there are no declarators], and except for the declaration of an
5440 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5441 // names into the program, or shall redeclare a name introduced by a
5442 // previous declaration.
5443 if (!DeclaresAnything) {
5444 // In C, we allow this as a (popular) extension / bug. Don't bother
5445 // producing further diagnostics for redundant qualifiers after this.
5446 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5447 ? diag::err_no_declarators
5448 : diag::ext_no_declarators)
5449 << DS.getSourceRange();
5450 return TagD;
5451 }
5452
5453 // C++ [dcl.stc]p1:
5454 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5455 // init-declarator-list of the declaration shall not be empty.
5456 // C++ [dcl.fct.spec]p1:
5457 // If a cv-qualifier appears in a decl-specifier-seq, the
5458 // init-declarator-list of the declaration shall not be empty.
5459 //
5460 // Spurious qualifiers here appear to be valid in C.
5461 unsigned DiagID = diag::warn_standalone_specifier;
5462 if (getLangOpts().CPlusPlus)
5463 DiagID = diag::ext_standalone_specifier;
5464
5465 // Note that a linkage-specification sets a storage class, but
5466 // 'extern "C" struct foo;' is actually valid and not theoretically
5467 // useless.
5468 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5469 if (SCS == DeclSpec::SCS_mutable)
5470 // Since mutable is not a viable storage class specifier in C, there is
5471 // no reason to treat it as an extension. Instead, diagnose as an error.
5472 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5473 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5474 Diag(DS.getStorageClassSpecLoc(), DiagID)
5476 }
5477
5481 if (DS.getTypeQualifiers()) {
5483 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5485 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5486 // Restrict is covered above.
5488 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5490 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5491 }
5492
5493 // Warn about ignored type attributes, for example:
5494 // __attribute__((aligned)) struct A;
5495 // Attributes should be placed after tag to apply to type declaration.
5496 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5497 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5498 if (TypeSpecType == DeclSpec::TST_class ||
5499 TypeSpecType == DeclSpec::TST_struct ||
5500 TypeSpecType == DeclSpec::TST_interface ||
5501 TypeSpecType == DeclSpec::TST_union ||
5502 TypeSpecType == DeclSpec::TST_enum) {
5503
5504 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5505 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5506 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5507 DiagnosticId = diag::warn_attribute_ignored;
5508 else if (AL.isRegularKeywordAttribute())
5509 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5510 else
5511 DiagnosticId = diag::warn_declspec_attribute_ignored;
5512 Diag(AL.getLoc(), DiagnosticId)
5513 << AL << GetDiagnosticTypeSpecifierID(DS);
5514 };
5515
5516 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5517 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5518 }
5519 }
5520
5521 return TagD;
5522}
5523
5524/// We are trying to inject an anonymous member into the given scope;
5525/// check if there's an existing declaration that can't be overloaded.
5526///
5527/// \return true if this is a forbidden redeclaration
5528static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5529 DeclContext *Owner,
5530 DeclarationName Name,
5531 SourceLocation NameLoc, bool IsUnion,
5532 StorageClass SC) {
5533 LookupResult R(SemaRef, Name, NameLoc,
5537 if (!SemaRef.LookupName(R, S)) return false;
5538
5539 // Pick a representative declaration.
5540 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5541 assert(PrevDecl && "Expected a non-null Decl");
5542
5543 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5544 return false;
5545
5546 if (SC == StorageClass::SC_None &&
5547 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5548 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5549 if (!Owner->isRecord())
5550 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5551 return false;
5552 }
5553
5554 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5555 << IsUnion << Name;
5556 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5557
5558 return true;
5559}
5560
5562 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5564}
5565
5567 if (!getLangOpts().CPlusPlus)
5568 return;
5569
5570 // This function can be parsed before we have validated the
5571 // structure as an anonymous struct
5572 if (Record->isAnonymousStructOrUnion())
5573 return;
5574
5575 const NamedDecl *First = 0;
5576 for (const Decl *D : Record->decls()) {
5577 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5578 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5579 continue;
5580 if (!First)
5581 First = ND;
5582 else
5584 }
5585}
5586
5587/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5588/// anonymous struct or union AnonRecord into the owning context Owner
5589/// and scope S. This routine will be invoked just after we realize
5590/// that an unnamed union or struct is actually an anonymous union or
5591/// struct, e.g.,
5592///
5593/// @code
5594/// union {
5595/// int i;
5596/// float f;
5597/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5598/// // f into the surrounding scope.x
5599/// @endcode
5600///
5601/// This routine is recursive, injecting the names of nested anonymous
5602/// structs/unions into the owning context and scope as well.
5603static bool
5605 RecordDecl *AnonRecord, AccessSpecifier AS,
5606 StorageClass SC,
5607 SmallVectorImpl<NamedDecl *> &Chaining) {
5608 bool Invalid = false;
5609
5610 // Look every FieldDecl and IndirectFieldDecl with a name.
5611 for (auto *D : AnonRecord->decls()) {
5612 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5613 cast<NamedDecl>(D)->getDeclName()) {
5614 ValueDecl *VD = cast<ValueDecl>(D);
5615 // C++ [class.union]p2:
5616 // The names of the members of an anonymous union shall be
5617 // distinct from the names of any other entity in the
5618 // scope in which the anonymous union is declared.
5619
5620 bool FieldInvalid = CheckAnonMemberRedeclaration(
5621 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5622 AnonRecord->isUnion(), SC);
5623 if (FieldInvalid)
5624 Invalid = true;
5625
5626 // Inject the IndirectFieldDecl even if invalid, because later
5627 // diagnostics may depend on it being present, see findDefaultInitializer.
5628
5629 // C++ [class.union]p2:
5630 // For the purpose of name lookup, after the anonymous union
5631 // definition, the members of the anonymous union are
5632 // considered to have been defined in the scope in which the
5633 // anonymous union is declared.
5634 unsigned OldChainingSize = Chaining.size();
5635 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5636 Chaining.append(IF->chain_begin(), IF->chain_end());
5637 else
5638 Chaining.push_back(VD);
5639
5640 assert(Chaining.size() >= 2);
5641 NamedDecl **NamedChain =
5642 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5643 for (unsigned i = 0; i < Chaining.size(); i++)
5644 NamedChain[i] = Chaining[i];
5645
5647 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5648 VD->getType(), {NamedChain, Chaining.size()});
5649
5650 for (const auto *Attr : VD->attrs())
5651 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5652
5653 IndirectField->setAccess(AS);
5654 IndirectField->setImplicit();
5655 IndirectField->setInvalidDecl(FieldInvalid);
5656 SemaRef.PushOnScopeChains(IndirectField, S);
5657
5658 // That includes picking up the appropriate access specifier.
5659 if (AS != AS_none)
5660 IndirectField->setAccess(AS);
5661
5662 Chaining.resize(OldChainingSize);
5663 }
5664 }
5665
5666 return Invalid;
5667}
5668
5669/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5670/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5671/// illegal input values are mapped to SC_None.
5672static StorageClass
5674 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5675 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5676 "Parser allowed 'typedef' as storage class VarDecl.");
5677 switch (StorageClassSpec) {
5680 if (DS.isExternInLinkageSpec())
5681 return SC_None;
5682 return SC_Extern;
5683 case DeclSpec::SCS_static: return SC_Static;
5684 case DeclSpec::SCS_auto: return SC_Auto;
5687 // Illegal SCSs map to None: error reporting is up to the caller.
5688 case DeclSpec::SCS_mutable: // Fall through.
5689 case DeclSpec::SCS_typedef: return SC_None;
5690 }
5691 llvm_unreachable("unknown storage class specifier");
5692}
5693
5695 assert(Record->hasInClassInitializer());
5696
5697 for (const auto *I : Record->decls()) {
5698 const auto *FD = dyn_cast<FieldDecl>(I);
5699 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5700 FD = IFD->getAnonField();
5701 if (FD && FD->hasInClassInitializer())
5702 return FD->getLocation();
5703 }
5704
5705 llvm_unreachable("couldn't find in-class initializer");
5706}
5707
5709 SourceLocation DefaultInitLoc) {
5710 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5711 return;
5712
5713 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5714 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5715}
5716
5718 CXXRecordDecl *AnonUnion) {
5719 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5720 return;
5721
5723}
5724
5726 AccessSpecifier AS,
5728 const PrintingPolicy &Policy) {
5729 DeclContext *Owner = Record->getDeclContext();
5730
5731 // Diagnose whether this anonymous struct/union is an extension.
5732 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5733 Diag(Record->getLocation(), diag::ext_anonymous_union);
5734 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5735 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5736 else if (!Record->isUnion() && !getLangOpts().C11)
5737 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5738
5739 // C and C++ require different kinds of checks for anonymous
5740 // structs/unions.
5741 bool Invalid = false;
5742 if (getLangOpts().CPlusPlus) {
5743 const char *PrevSpec = nullptr;
5744 if (Record->isUnion()) {
5745 // C++ [class.union]p6:
5746 // C++17 [class.union.anon]p2:
5747 // Anonymous unions declared in a named namespace or in the
5748 // global namespace shall be declared static.
5749 unsigned DiagID;
5750 DeclContext *OwnerScope = Owner->getRedeclContext();
5752 (OwnerScope->isTranslationUnit() ||
5753 (OwnerScope->isNamespace() &&
5754 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5755 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5756 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5757
5758 // Recover by adding 'static'.
5760 PrevSpec, DiagID, Policy);
5761 }
5762 // C++ [class.union]p6:
5763 // A storage class is not allowed in a declaration of an
5764 // anonymous union in a class scope.
5766 isa<RecordDecl>(Owner)) {
5768 diag::err_anonymous_union_with_storage_spec)
5770
5771 // Recover by removing the storage specifier.
5774 PrevSpec, DiagID, Context.getPrintingPolicy());
5775 }
5776 }
5777
5778 // Ignore const/volatile/restrict qualifiers.
5779 if (DS.getTypeQualifiers()) {
5781 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5782 << Record->isUnion() << "const"
5786 diag::ext_anonymous_struct_union_qualified)
5787 << Record->isUnion() << "volatile"
5791 diag::ext_anonymous_struct_union_qualified)
5792 << Record->isUnion() << "restrict"
5796 diag::ext_anonymous_struct_union_qualified)
5797 << Record->isUnion() << "_Atomic"
5801 diag::ext_anonymous_struct_union_qualified)
5802 << Record->isUnion() << "__unaligned"
5804
5806 }
5807
5808 // C++ [class.union]p2:
5809 // The member-specification of an anonymous union shall only
5810 // define non-static data members. [Note: nested types and
5811 // functions cannot be declared within an anonymous union. ]
5812 for (auto *Mem : Record->decls()) {
5813 // Ignore invalid declarations; we already diagnosed them.
5814 if (Mem->isInvalidDecl())
5815 continue;
5816
5817 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5818 // C++ [class.union]p3:
5819 // An anonymous union shall not have private or protected
5820 // members (clause 11).
5821 assert(FD->getAccess() != AS_none);
5822 if (FD->getAccess() != AS_public) {
5823 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5824 << Record->isUnion() << (FD->getAccess() == AS_protected);
5825 Invalid = true;
5826 }
5827
5828 // C++ [class.union]p1
5829 // An object of a class with a non-trivial constructor, a non-trivial
5830 // copy constructor, a non-trivial destructor, or a non-trivial copy
5831 // assignment operator cannot be a member of a union, nor can an
5832 // array of such objects.
5833 if (CheckNontrivialField(FD))
5834 Invalid = true;
5835 } else if (Mem->isImplicit()) {
5836 // Any implicit members are fine.
5837 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5838 // This is a type that showed up in an
5839 // elaborated-type-specifier inside the anonymous struct or
5840 // union, but which actually declares a type outside of the
5841 // anonymous struct or union. It's okay.
5842 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5843 if (!MemRecord->isAnonymousStructOrUnion() &&
5844 MemRecord->getDeclName()) {
5845 // Visual C++ allows type definition in anonymous struct or union.
5846 if (getLangOpts().MicrosoftExt)
5847 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5848 << Record->isUnion();
5849 else {
5850 // This is a nested type declaration.
5851 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5852 << Record->isUnion();
5853 Invalid = true;
5854 }
5855 } else {
5856 // This is an anonymous type definition within another anonymous type.
5857 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5858 // not part of standard C++.
5859 Diag(MemRecord->getLocation(),
5860 diag::ext_anonymous_record_with_anonymous_type)
5861 << Record->isUnion();
5862 }
5863 } else if (isa<AccessSpecDecl>(Mem)) {
5864 // Any access specifier is fine.
5865 } else if (isa<StaticAssertDecl>(Mem)) {
5866 // In C++1z, static_assert declarations are also fine.
5867 } else {
5868 // We have something that isn't a non-static data
5869 // member. Complain about it.
5870 unsigned DK = diag::err_anonymous_record_bad_member;
5871 if (isa<TypeDecl>(Mem))
5872 DK = diag::err_anonymous_record_with_type;
5873 else if (isa<FunctionDecl>(Mem))
5874 DK = diag::err_anonymous_record_with_function;
5875 else if (isa<VarDecl>(Mem))
5876 DK = diag::err_anonymous_record_with_static;
5877
5878 // Visual C++ allows type definition in anonymous struct or union.
5879 if (getLangOpts().MicrosoftExt &&
5880 DK == diag::err_anonymous_record_with_type)
5881 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5882 << Record->isUnion();
5883 else {
5884 Diag(Mem->getLocation(), DK) << Record->isUnion();
5885 Invalid = true;
5886 }
5887 }
5888 }
5889
5890 // C++11 [class.union]p8 (DR1460):
5891 // At most one variant member of a union may have a
5892 // brace-or-equal-initializer.
5893 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5894 Owner->isRecord())
5897 }
5898
5899 if (!Record->isUnion() && !Owner->isRecord()) {
5900 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5901 << getLangOpts().CPlusPlus;
5902 Invalid = true;
5903 }
5904
5905 // C++ [dcl.dcl]p3:
5906 // [If there are no declarators], and except for the declaration of an
5907 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5908 // names into the program
5909 // C++ [class.mem]p2:
5910 // each such member-declaration shall either declare at least one member
5911 // name of the class or declare at least one unnamed bit-field
5912 //
5913 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5914 if (getLangOpts().CPlusPlus && Record->field_empty())
5915 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5916
5917 // Mock up a declarator.
5921 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5922
5923 // Create a declaration for this anonymous struct/union.
5924 NamedDecl *Anon = nullptr;
5925 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5926 Anon = FieldDecl::Create(
5927 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5928 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5929 /*BitWidth=*/nullptr, /*Mutable=*/false,
5930 /*InitStyle=*/ICIS_NoInit);
5931 Anon->setAccess(AS);
5932 ProcessDeclAttributes(S, Anon, Dc);
5933
5934 if (getLangOpts().CPlusPlus)
5935 FieldCollector->Add(cast<FieldDecl>(Anon));
5936 } else {
5937 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5938 if (SCSpec == DeclSpec::SCS_mutable) {
5939 // mutable can only appear on non-static class members, so it's always
5940 // an error here
5941 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5942 Invalid = true;
5943 SC = SC_None;
5944 }
5945
5946 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5947 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5948 Context.getCanonicalTagType(Record), TInfo, SC);
5949 if (Invalid)
5950 Anon->setInvalidDecl();
5951
5952 ProcessDeclAttributes(S, Anon, Dc);
5953
5954 // Default-initialize the implicit variable. This initialization will be
5955 // trivial in almost all cases, except if a union member has an in-class
5956 // initializer:
5957 // union { int n = 0; };
5959 }
5960 Anon->setImplicit();
5961
5962 // Mark this as an anonymous struct/union type.
5963 Record->setAnonymousStructOrUnion(true);
5964
5965 // Add the anonymous struct/union object to the current
5966 // context. We'll be referencing this object when we refer to one of
5967 // its members.
5968 Owner->addDecl(Anon);
5969
5970 // Inject the members of the anonymous struct/union into the owning
5971 // context and into the identifier resolver chain for name lookup
5972 // purposes.
5974 Chain.push_back(Anon);
5975
5976 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5977 Chain))
5978 Invalid = true;
5979
5980 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5981 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5983 Decl *ManglingContextDecl;
5984 std::tie(MCtx, ManglingContextDecl) =
5985 getCurrentMangleNumberContext(NewVD->getDeclContext());
5986 if (MCtx) {
5987 Context.setManglingNumber(
5988 NewVD, MCtx->getManglingNumber(
5989 NewVD, getMSManglingNumber(getLangOpts(), S)));
5990 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5991 }
5992 }
5993 }
5994
5995 if (Invalid)
5996 Anon->setInvalidDecl();
5997
5998 return Anon;
5999}
6000
6002 RecordDecl *Record) {
6003 assert(Record && "expected a record!");
6004
6005 // Mock up a declarator.
6008 assert(TInfo && "couldn't build declarator info for anonymous struct");
6009
6010 auto *ParentDecl = cast<RecordDecl>(CurContext);
6011 CanQualType RecTy = Context.getCanonicalTagType(Record);
6012
6013 // Create a declaration for this anonymous struct.
6014 NamedDecl *Anon =
6015 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
6016 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6017 /*BitWidth=*/nullptr, /*Mutable=*/false,
6018 /*InitStyle=*/ICIS_NoInit);
6019 Anon->setImplicit();
6020
6021 // Add the anonymous struct object to the current context.
6022 CurContext->addDecl(Anon);
6023
6024 // Inject the members of the anonymous struct into the current
6025 // context and into the identifier resolver chain for name lookup
6026 // purposes.
6028 Chain.push_back(Anon);
6029
6030 RecordDecl *RecordDef = Record->getDefinition();
6031 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6032 diag::err_field_incomplete_or_sizeless) ||
6034 *this, S, CurContext, RecordDef, AS_none,
6036 Anon->setInvalidDecl();
6037 ParentDecl->setInvalidDecl();
6038 }
6039
6040 return Anon;
6041}
6042
6046
6049 DeclarationNameInfo NameInfo;
6050 NameInfo.setLoc(Name.StartLocation);
6051
6052 switch (Name.getKind()) {
6053
6056 NameInfo.setName(Name.Identifier);
6057 return NameInfo;
6058
6060 // C++ [temp.deduct.guide]p3:
6061 // The simple-template-id shall name a class template specialization.
6062 // The template-name shall be the same identifier as the template-name
6063 // of the simple-template-id.
6064 // These together intend to imply that the template-name shall name a
6065 // class template.
6066 // FIXME: template<typename T> struct X {};
6067 // template<typename T> using Y = X<T>;
6068 // Y(int) -> Y<int>;
6069 // satisfies these rules but does not name a class template.
6070 TemplateName TN = Name.TemplateName.get().get();
6071 auto *Template = TN.getAsTemplateDecl();
6073 Diag(Name.StartLocation,
6074 diag::err_deduction_guide_name_not_class_template)
6075 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6076 if (Template)
6078 return DeclarationNameInfo();
6079 }
6080
6081 NameInfo.setName(
6082 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6083 return NameInfo;
6084 }
6085
6087 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6091 return NameInfo;
6092
6094 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6095 Name.Identifier));
6097 return NameInfo;
6098
6100 TypeSourceInfo *TInfo;
6102 if (Ty.isNull())
6103 return DeclarationNameInfo();
6104 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6105 Context.getCanonicalType(Ty)));
6106 NameInfo.setNamedTypeInfo(TInfo);
6107 return NameInfo;
6108 }
6109
6111 TypeSourceInfo *TInfo;
6112 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6113 if (Ty.isNull())
6114 return DeclarationNameInfo();
6115 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6116 Context.getCanonicalType(Ty)));
6117 NameInfo.setNamedTypeInfo(TInfo);
6118 return NameInfo;
6119 }
6120
6122 // In well-formed code, we can only have a constructor
6123 // template-id that refers to the current context, so go there
6124 // to find the actual type being constructed.
6125 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6126 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6127 return DeclarationNameInfo();
6128
6129 // Determine the type of the class being constructed.
6130 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6131
6132 // FIXME: Check two things: that the template-id names the same type as
6133 // CurClassType, and that the template-id does not occur when the name
6134 // was qualified.
6135
6136 NameInfo.setName(
6137 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6138 // FIXME: should we retrieve TypeSourceInfo?
6139 NameInfo.setNamedTypeInfo(nullptr);
6140 return NameInfo;
6141 }
6142
6144 TypeSourceInfo *TInfo;
6145 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6146 if (Ty.isNull())
6147 return DeclarationNameInfo();
6148 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6149 Context.getCanonicalType(Ty)));
6150 NameInfo.setNamedTypeInfo(TInfo);
6151 return NameInfo;
6152 }
6153
6155 TemplateName TName = Name.TemplateId->Template.get();
6156 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6157 return Context.getNameForTemplate(TName, TNameLoc);
6158 }
6159
6160 } // switch (Name.getKind())
6161
6162 llvm_unreachable("Unknown name kind");
6163}
6164
6166 do {
6167 if (Ty->isPointerOrReferenceType())
6168 Ty = Ty->getPointeeType();
6169 else if (Ty->isArrayType())
6171 else
6172 return Ty.withoutLocalFastQualifiers();
6173 } while (true);
6174}
6175
6176/// hasSimilarParameters - Determine whether the C++ functions Declaration
6177/// and Definition have "nearly" matching parameters. This heuristic is
6178/// used to improve diagnostics in the case where an out-of-line function
6179/// definition doesn't match any declaration within the class or namespace.
6180/// Also sets Params to the list of indices to the parameters that differ
6181/// between the declaration and the definition. If hasSimilarParameters
6182/// returns true and Params is empty, then all of the parameters match.
6186 SmallVectorImpl<unsigned> &Params) {
6187 Params.clear();
6188 if (Declaration->param_size() != Definition->param_size())
6189 return false;
6190 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6191 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6192 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6193
6194 // The parameter types are identical
6195 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6196 continue;
6197
6198 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6199 QualType DefParamBaseTy = getCoreType(DefParamTy);
6200 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6201 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6202
6203 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6204 (DeclTyName && DeclTyName == DefTyName))
6205 Params.push_back(Idx);
6206 else // The two parameters aren't even close
6207 return false;
6208 }
6209
6210 return true;
6211}
6212
6213/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6214/// declarator needs to be rebuilt in the current instantiation.
6215/// Any bits of declarator which appear before the name are valid for
6216/// consideration here. That's specifically the type in the decl spec
6217/// and the base type in any member-pointer chunks.
6219 DeclarationName Name) {
6220 // The types we specifically need to rebuild are:
6221 // - typenames, typeofs, and decltypes
6222 // - types which will become injected class names
6223 // Of course, we also need to rebuild any type referencing such a
6224 // type. It's safest to just say "dependent", but we call out a
6225 // few cases here.
6226
6227 DeclSpec &DS = D.getMutableDeclSpec();
6228 switch (DS.getTypeSpecType()) {
6232#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6233#include "clang/Basic/Traits.inc"
6234 case DeclSpec::TST_atomic: {
6235 // Grab the type from the parser.
6236 TypeSourceInfo *TSI = nullptr;
6237 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6238 if (T.isNull() || !T->isInstantiationDependentType()) break;
6239
6240 // Make sure there's a type source info. This isn't really much
6241 // of a waste; most dependent types should have type source info
6242 // attached already.
6243 if (!TSI)
6245
6246 // Rebuild the type in the current instantiation.
6248 if (!TSI) return true;
6249
6250 // Store the new type back in the decl spec.
6251 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6252 DS.UpdateTypeRep(LocType);
6253 break;
6254 }
6255
6259 Expr *E = DS.getRepAsExpr();
6261 if (Result.isInvalid()) return true;
6262 DS.UpdateExprRep(Result.get());
6263 break;
6264 }
6265
6266 default:
6267 // Nothing to do for these decl specs.
6268 break;
6269 }
6270
6271 // It doesn't matter what order we do this in.
6272 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6273 DeclaratorChunk &Chunk = D.getTypeObject(I);
6274
6275 // The only type information in the declarator which can come
6276 // before the declaration name is the base type of a member
6277 // pointer.
6279 continue;
6280
6281 // Rebuild the scope specifier in-place.
6282 CXXScopeSpec &SS = Chunk.Mem.Scope();
6284 return true;
6285 }
6286
6287 return false;
6288}
6289
6290/// Returns true if the declaration is declared in a system header or from a
6291/// system macro.
6292static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6293 return SM.isInSystemHeader(D->getLocation()) ||
6294 SM.isInSystemMacro(D->getLocation());
6295}
6296
6298 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6299 // of system decl.
6300 if (D->getPreviousDecl() || D->isImplicit())
6301 return;
6304 !isFromSystemHeader(Context.getSourceManager(), D)) {
6305 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6306 << D << static_cast<int>(Status);
6307 }
6308}
6309
6312
6313 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6314 // declaration only if the `bind_to_declaration` extension is set.
6316 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6317 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6318 llvm::omp::TraitProperty::
6319 implementation_extension_bind_to_declaration))
6321 S, D, MultiTemplateParamsArg(), Bases);
6322
6324
6325 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6326 Dcl && Dcl->getDeclContext()->isFileContext())
6328
6329 if (!Bases.empty())
6331 Bases);
6332
6333 return Dcl;
6334}
6335
6337 DeclarationNameInfo NameInfo) {
6338 DeclarationName Name = NameInfo.getName();
6339
6340 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6341 while (Record && Record->isAnonymousStructOrUnion())
6342 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6343 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6344 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6345 return true;
6346 }
6347
6348 return false;
6349}
6350
6352 DeclarationName Name,
6353 SourceLocation Loc,
6354 TemplateIdAnnotation *TemplateId,
6355 bool IsMemberSpecialization) {
6356 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6357 "without nested-name-specifier");
6358 DeclContext *Cur = CurContext;
6359 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6360 Cur = Cur->getParent();
6361
6362 // If the user provided a superfluous scope specifier that refers back to the
6363 // class in which the entity is already declared, diagnose and ignore it.
6364 //
6365 // class X {
6366 // void X::f();
6367 // };
6368 //
6369 // Note, it was once ill-formed to give redundant qualification in all
6370 // contexts, but that rule was removed by DR482.
6371 if (Cur->Equals(DC)) {
6372 if (Cur->isRecord()) {
6373 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6374 : diag::err_member_extra_qualification)
6375 << Name << FixItHint::CreateRemoval(SS.getRange());
6376 SS.clear();
6377 } else {
6378 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6379 }
6380 return false;
6381 }
6382
6383 // Check whether the qualifying scope encloses the scope of the original
6384 // declaration. For a template-id, we perform the checks in
6385 // CheckTemplateSpecializationScope.
6386 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6387 if (Cur->isRecord())
6388 Diag(Loc, diag::err_member_qualification)
6389 << Name << SS.getRange();
6390 else if (isa<TranslationUnitDecl>(DC))
6391 Diag(Loc, diag::err_invalid_declarator_global_scope)
6392 << Name << SS.getRange();
6393 else if (isa<FunctionDecl>(Cur))
6394 Diag(Loc, diag::err_invalid_declarator_in_function)
6395 << Name << SS.getRange();
6396 else if (isa<BlockDecl>(Cur))
6397 Diag(Loc, diag::err_invalid_declarator_in_block)
6398 << Name << SS.getRange();
6399 else if (isa<ExportDecl>(Cur)) {
6400 if (!isa<NamespaceDecl>(DC))
6401 Diag(Loc, diag::err_export_non_namespace_scope_name)
6402 << Name << SS.getRange();
6403 else
6404 // The cases that DC is not NamespaceDecl should be handled in
6405 // CheckRedeclarationExported.
6406 return false;
6407 } else
6408 Diag(Loc, diag::err_invalid_declarator_scope)
6409 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6410
6411 return true;
6412 }
6413
6414 if (Cur->isRecord()) {
6415 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6416 // An explicit specialization may be declared in any scope in which the
6417 // corresponding primary template may be defined.
6418 if (IsMemberSpecialization)
6419 return false;
6420
6421 // Cannot qualify members within a class.
6422 Diag(Loc, diag::err_member_qualification)
6423 << Name << SS.getRange();
6424 SS.clear();
6425
6426 // C++ constructors and destructors with incorrect scopes can break
6427 // our AST invariants by having the wrong underlying types. If
6428 // that's the case, then drop this declaration entirely.
6431 !Context.hasSameType(
6432 Name.getCXXNameType(),
6433 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6434 return true;
6435
6436 return false;
6437 }
6438
6439 // C++23 [temp.names]p5:
6440 // The keyword template shall not appear immediately after a declarative
6441 // nested-name-specifier.
6442 //
6443 // First check the template-id (if any), and then check each component of the
6444 // nested-name-specifier in reverse order.
6445 //
6446 // FIXME: nested-name-specifiers in friend declarations are declarative,
6447 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6448 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6449 Diag(Loc, diag::ext_template_after_declarative_nns)
6451
6453 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6454 TL = std::exchange(NextTL, TypeLoc())) {
6455 SourceLocation TemplateKeywordLoc;
6456 switch (TL.getTypeLocClass()) {
6457 case TypeLoc::TemplateSpecialization: {
6458 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6459 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6460 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6461 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6462 << TST.getLocalSourceRange();
6463 break;
6464 }
6465 case TypeLoc::Decltype:
6466 case TypeLoc::PackIndexing: {
6467 const Type *T = TL.getTypePtr();
6468 // C++23 [expr.prim.id.qual]p2:
6469 // [...] A declarative nested-name-specifier shall not have a
6470 // computed-type-specifier.
6471 //
6472 // CWG2858 changed this from 'decltype-specifier' to
6473 // 'computed-type-specifier'.
6474 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6475 << T->isDecltypeType() << TL.getSourceRange();
6476 break;
6477 }
6478 case TypeLoc::DependentName:
6479 NextTL =
6480 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6481 break;
6482 default:
6483 break;
6484 }
6485 if (TemplateKeywordLoc.isValid())
6486 Diag(Loc, diag::ext_template_after_declarative_nns)
6487 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6488 }
6489
6490 return false;
6491}
6492
6494 MultiTemplateParamsArg TemplateParamLists) {
6495 // TODO: consider using NameInfo for diagnostic.
6497 DeclarationName Name = NameInfo.getName();
6498
6499 // All of these full declarators require an identifier. If it doesn't have
6500 // one, the ParsedFreeStandingDeclSpec action should be used.
6501 if (D.isDecompositionDeclarator()) {
6502 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6503 } else if (!Name) {
6504 if (!D.isInvalidType()) // Reject this if we think it is valid.
6505 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6507 return nullptr;
6509 return nullptr;
6510
6511 DeclContext *DC = CurContext;
6512 if (D.getCXXScopeSpec().isInvalid())
6513 D.setInvalidType();
6514 else if (D.getCXXScopeSpec().isSet()) {
6517 return nullptr;
6518
6519 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6520 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6521 if (!DC || isa<EnumDecl>(DC)) {
6522 // If we could not compute the declaration context, it's because the
6523 // declaration context is dependent but does not refer to a class,
6524 // class template, or class template partial specialization. Complain
6525 // and return early, to avoid the coming semantic disaster.
6527 diag::err_template_qualified_declarator_no_match)
6529 << D.getCXXScopeSpec().getRange();
6530 return nullptr;
6531 }
6532 bool IsDependentContext = DC->isDependentContext();
6533
6534 if (!IsDependentContext &&
6536 return nullptr;
6537
6538 // If a class is incomplete, do not parse entities inside it.
6541 diag::err_member_def_undefined_record)
6542 << Name << DC << D.getCXXScopeSpec().getRange();
6543 return nullptr;
6544 }
6545 if (!D.getDeclSpec().isFriendSpecified()) {
6546 TemplateIdAnnotation *TemplateId =
6548 ? D.getName().TemplateId
6549 : nullptr;
6551 D.getIdentifierLoc(), TemplateId,
6552 /*IsMemberSpecialization=*/false)) {
6553 if (DC->isRecord())
6554 return nullptr;
6555
6556 D.setInvalidType();
6557 }
6558 }
6559
6560 // Check whether we need to rebuild the type of the given
6561 // declaration in the current instantiation.
6562 if (EnteringContext && IsDependentContext &&
6563 TemplateParamLists.size() != 0) {
6564 ContextRAII SavedContext(*this, DC);
6565 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6566 D.setInvalidType();
6567 }
6568 }
6569
6571 QualType R = TInfo->getType();
6572
6575 D.setInvalidType();
6576
6577 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6579
6580 // See if this is a redefinition of a variable in the same scope.
6581 if (!D.getCXXScopeSpec().isSet()) {
6582 bool IsLinkageLookup = false;
6583 bool CreateBuiltins = false;
6584
6585 // If the declaration we're planning to build will be a function
6586 // or object with linkage, then look for another declaration with
6587 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6588 //
6589 // If the declaration we're planning to build will be declared with
6590 // external linkage in the translation unit, create any builtin with
6591 // the same name.
6593 /* Do nothing*/;
6594 else if (CurContext->isFunctionOrMethod() &&
6596 R->isFunctionType())) {
6597 IsLinkageLookup = true;
6598 CreateBuiltins =
6599 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6600 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6602 CreateBuiltins = true;
6603
6604 if (IsLinkageLookup) {
6606 Previous.setRedeclarationKind(
6608 }
6609
6610 LookupName(Previous, S, CreateBuiltins);
6611 } else { // Something like "int foo::x;"
6613
6614 // C++ [dcl.meaning]p1:
6615 // When the declarator-id is qualified, the declaration shall refer to a
6616 // previously declared member of the class or namespace to which the
6617 // qualifier refers (or, in the case of a namespace, of an element of the
6618 // inline namespace set of that namespace (7.3.1)) or to a specialization
6619 // thereof; [...]
6620 //
6621 // Note that we already checked the context above, and that we do not have
6622 // enough information to make sure that Previous contains the declaration
6623 // we want to match. For example, given:
6624 //
6625 // class X {
6626 // void f();
6627 // void f(float);
6628 // };
6629 //
6630 // void X::f(int) { } // ill-formed
6631 //
6632 // In this case, Previous will point to the overload set
6633 // containing the two f's declared in X, but neither of them
6634 // matches.
6635
6637 }
6638
6639 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6640 TPD && TPD->isTemplateParameter()) {
6641 // Older versions of clang allowed the names of function/variable templates
6642 // to shadow the names of their template parameters. For the compatibility
6643 // purposes we detect such cases and issue a default-to-error warning that
6644 // can be disabled with -Wno-strict-primary-template-shadow.
6645 if (!D.isInvalidType()) {
6646 bool AllowForCompatibility = false;
6647 if (Scope *DeclParent = S->getDeclParent();
6648 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6649 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6650 TemplateParamParent->isDeclScope(TPD);
6651 }
6653 AllowForCompatibility);
6654 }
6655
6656 // Just pretend that we didn't see the previous declaration.
6657 Previous.clear();
6658 }
6659
6660 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6661 // Forget that the previous declaration is the injected-class-name.
6662 Previous.clear();
6663
6664 // In C++, the previous declaration we find might be a tag type
6665 // (class or enum). In this case, the new declaration will hide the
6666 // tag type. Note that this applies to functions, function templates, and
6667 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6668 if (Previous.isSingleTagDecl() &&
6670 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6671 Previous.clear();
6672
6673 // Check that there are no default arguments other than in the parameters
6674 // of a function declaration (C++ only).
6675 if (getLangOpts().CPlusPlus)
6677
6678 /// Get the innermost enclosing declaration scope.
6679 S = S->getDeclParent();
6680
6681 NamedDecl *New;
6682
6683 bool AddToScope = true;
6685 if (TemplateParamLists.size()) {
6686 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6687 return nullptr;
6688 }
6689
6690 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6691 } else if (R->isFunctionType()) {
6692 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6693 TemplateParamLists,
6694 AddToScope);
6695 } else {
6696 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6697 AddToScope);
6698 }
6699
6700 if (!New)
6701 return nullptr;
6702
6704
6705 // If this has an identifier and is not a function template specialization,
6706 // add it to the scope stack.
6707 if (New->getDeclName() && AddToScope)
6709
6710 if (OpenMP().isInOpenMPDeclareTargetContext())
6712
6713 return New;
6714}
6715
6716/// Helper method to turn variable array types into constant array
6717/// types in certain situations which would otherwise be errors (for
6718/// GCC compatibility).
6720 ASTContext &Context,
6721 bool &SizeIsNegative,
6722 llvm::APSInt &Oversized) {
6723 // This method tries to turn a variable array into a constant
6724 // array even when the size isn't an ICE. This is necessary
6725 // for compatibility with code that depends on gcc's buggy
6726 // constant expression folding, like struct {char x[(int)(char*)2];}
6727 SizeIsNegative = false;
6728 Oversized = 0;
6729
6730 if (T->isDependentType())
6731 return QualType();
6732
6734 const Type *Ty = Qs.strip(T);
6735
6736 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6737 QualType Pointee = PTy->getPointeeType();
6738 QualType FixedType =
6739 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6740 Oversized);
6741 if (FixedType.isNull()) return FixedType;
6742 FixedType = Context.getPointerType(FixedType);
6743 return Qs.apply(Context, FixedType);
6744 }
6745 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6746 QualType Inner = PTy->getInnerType();
6747 QualType FixedType =
6748 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6749 Oversized);
6750 if (FixedType.isNull()) return FixedType;
6751 FixedType = Context.getParenType(FixedType);
6752 return Qs.apply(Context, FixedType);
6753 }
6754
6755 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6756 if (!VLATy)
6757 return QualType();
6758
6759 QualType ElemTy = VLATy->getElementType();
6760 if (ElemTy->isVariablyModifiedType()) {
6761 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6762 SizeIsNegative, Oversized);
6763 if (ElemTy.isNull())
6764 return QualType();
6765 }
6766
6768 if (!VLATy->getSizeExpr() ||
6769 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6770 return QualType();
6771
6772 llvm::APSInt Res = Result.Val.getInt();
6773
6774 // Check whether the array size is negative.
6775 if (Res.isSigned() && Res.isNegative()) {
6776 SizeIsNegative = true;
6777 return QualType();
6778 }
6779
6780 // Check whether the array is too large to be addressed.
6781 unsigned ActiveSizeBits =
6782 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6783 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6784 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6785 : Res.getActiveBits();
6786 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6787 Oversized = std::move(Res);
6788 return QualType();
6789 }
6790
6791 QualType FoldedArrayType = Context.getConstantArrayType(
6792 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6793 return Qs.apply(Context, FoldedArrayType);
6794}
6795
6796static void
6798 SrcTL = SrcTL.getUnqualifiedLoc();
6799 DstTL = DstTL.getUnqualifiedLoc();
6800 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6801 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6802 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6803 DstPTL.getPointeeLoc());
6804 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6805 return;
6806 }
6807 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6808 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6809 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6810 DstPTL.getInnerLoc());
6811 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6812 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6813 return;
6814 }
6815 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6816 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6817 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6818 TypeLoc DstElemTL = DstATL.getElementLoc();
6819 if (VariableArrayTypeLoc SrcElemATL =
6820 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6821 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6822 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6823 } else {
6824 DstElemTL.initializeFullCopy(SrcElemTL);
6825 }
6826 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6827 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6828 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6829}
6830
6831/// Helper method to turn variable array types into constant array
6832/// types in certain situations which would otherwise be errors (for
6833/// GCC compatibility).
6834static TypeSourceInfo*
6836 ASTContext &Context,
6837 bool &SizeIsNegative,
6838 llvm::APSInt &Oversized) {
6839 QualType FixedTy
6840 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6841 SizeIsNegative, Oversized);
6842 if (FixedTy.isNull())
6843 return nullptr;
6844 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6846 FixedTInfo->getTypeLoc());
6847 return FixedTInfo;
6848}
6849
6852 unsigned FailedFoldDiagID) {
6853 bool SizeIsNegative;
6854 llvm::APSInt Oversized;
6856 TInfo, Context, SizeIsNegative, Oversized);
6857 if (FixedTInfo) {
6858 Diag(Loc, diag::ext_vla_folded_to_constant);
6859 TInfo = FixedTInfo;
6860 T = FixedTInfo->getType();
6861 return true;
6862 }
6863
6864 if (SizeIsNegative)
6865 Diag(Loc, diag::err_typecheck_negative_array_size);
6866 else if (Oversized.getBoolValue())
6867 Diag(Loc, diag::err_array_too_large) << toString(
6868 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6869 /*UpperCase=*/false, /*InsertSeparators=*/true);
6870 else if (FailedFoldDiagID)
6871 Diag(Loc, FailedFoldDiagID);
6872 return false;
6873}
6874
6875void
6877 if (!getLangOpts().CPlusPlus &&
6879 // Don't need to track declarations in the TU in C.
6880 return;
6881
6882 // Note that we have a locally-scoped external with this name.
6883 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6884}
6885
6887 // FIXME: We can have multiple results via __attribute__((overloadable)).
6888 auto Result = Context.getExternCContextDecl()->lookup(Name);
6889 return Result.empty() ? nullptr : *Result.begin();
6890}
6891
6893 // FIXME: We should probably indicate the identifier in question to avoid
6894 // confusion for constructs like "virtual int a(), b;"
6895 if (DS.isVirtualSpecified())
6897 diag::err_virtual_non_function);
6898
6899 if (DS.hasExplicitSpecifier())
6901 diag::err_explicit_non_function);
6902
6903 if (DS.isNoreturnSpecified())
6905 diag::err_noreturn_non_function);
6906}
6907
6908NamedDecl*
6911 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6912 if (D.getCXXScopeSpec().isSet()) {
6913 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6914 << D.getCXXScopeSpec().getRange();
6915 D.setInvalidType();
6916 // Pretend we didn't see the scope specifier.
6917 DC = CurContext;
6918 Previous.clear();
6919 }
6920
6922
6925 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6926 ? diag::warn_ms_inline_non_function
6927 : diag::err_inline_non_function)
6928 << getLangOpts().CPlusPlus17;
6930 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6931 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6932
6936 diag::err_deduction_guide_invalid_specifier)
6937 << "typedef";
6938 else
6939 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6940 << D.getName().getSourceRange();
6941 return nullptr;
6942 }
6943
6944 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6945 if (!NewTD) return nullptr;
6946
6947 // Handle attributes prior to checking for duplicates in MergeVarDecl
6948 ProcessDeclAttributes(S, NewTD, D);
6949
6951
6952 bool Redeclaration = D.isRedeclaration();
6955 return ND;
6956}
6957
6958void
6960 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6961 // then it shall have block scope.
6962 // Note that variably modified types must be fixed before merging the decl so
6963 // that redeclarations will match.
6964 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6965 QualType T = TInfo->getType();
6966 if (T->isVariablyModifiedType()) {
6968
6969 if (S->getFnParent() == nullptr) {
6970 bool SizeIsNegative;
6971 llvm::APSInt Oversized;
6972 TypeSourceInfo *FixedTInfo =
6974 SizeIsNegative,
6975 Oversized);
6976 if (FixedTInfo) {
6977 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6978 NewTD->setTypeSourceInfo(FixedTInfo);
6979 } else {
6980 if (SizeIsNegative)
6981 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6982 else if (T->isVariableArrayType())
6983 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6984 else if (Oversized.getBoolValue())
6985 Diag(NewTD->getLocation(), diag::err_array_too_large)
6986 << toString(Oversized, 10);
6987 else
6988 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6989 NewTD->setInvalidDecl();
6990 }
6991 }
6992 }
6993}
6994
6995NamedDecl*
6998
6999 // Find the shadowed declaration before filtering for scope.
7000 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
7001
7002 // Merge the decl with the existing one if appropriate. If the decl is
7003 // in an outer scope, it isn't the same thing.
7004 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
7005 /*AllowInlineNamespace*/false);
7007 if (!Previous.empty()) {
7008 Redeclaration = true;
7009 MergeTypedefNameDecl(S, NewTD, Previous);
7010 } else {
7012 }
7013
7014 if (ShadowedDecl && !Redeclaration)
7015 CheckShadow(NewTD, ShadowedDecl, Previous);
7016
7017 // If this is the C FILE type, notify the AST context.
7018 if (IdentifierInfo *II = NewTD->getIdentifier())
7019 if (!NewTD->isInvalidDecl() &&
7021 switch (II->getNotableIdentifierID()) {
7022 case tok::NotableIdentifierKind::FILE:
7023 Context.setFILEDecl(NewTD);
7024 break;
7025 case tok::NotableIdentifierKind::jmp_buf:
7026 Context.setjmp_bufDecl(NewTD);
7027 break;
7028 case tok::NotableIdentifierKind::sigjmp_buf:
7029 Context.setsigjmp_bufDecl(NewTD);
7030 break;
7031 case tok::NotableIdentifierKind::ucontext_t:
7032 Context.setucontext_tDecl(NewTD);
7033 break;
7034 case tok::NotableIdentifierKind::float_t:
7035 case tok::NotableIdentifierKind::double_t:
7036 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7037 break;
7038 default:
7039 break;
7040 }
7041 }
7042
7043 return NewTD;
7044}
7045
7046/// Determines whether the given declaration is an out-of-scope
7047/// previous declaration.
7048///
7049/// This routine should be invoked when name lookup has found a
7050/// previous declaration (PrevDecl) that is not in the scope where a
7051/// new declaration by the same name is being introduced. If the new
7052/// declaration occurs in a local scope, previous declarations with
7053/// linkage may still be considered previous declarations (C99
7054/// 6.2.2p4-5, C++ [basic.link]p6).
7055///
7056/// \param PrevDecl the previous declaration found by name
7057/// lookup
7058///
7059/// \param DC the context in which the new declaration is being
7060/// declared.
7061///
7062/// \returns true if PrevDecl is an out-of-scope previous declaration
7063/// for a new delcaration with the same name.
7064static bool
7066 ASTContext &Context) {
7067 if (!PrevDecl)
7068 return false;
7069
7070 if (!PrevDecl->hasLinkage())
7071 return false;
7072
7073 if (Context.getLangOpts().CPlusPlus) {
7074 // C++ [basic.link]p6:
7075 // If there is a visible declaration of an entity with linkage
7076 // having the same name and type, ignoring entities declared
7077 // outside the innermost enclosing namespace scope, the block
7078 // scope declaration declares that same entity and receives the
7079 // linkage of the previous declaration.
7080 DeclContext *OuterContext = DC->getRedeclContext();
7081 if (!OuterContext->isFunctionOrMethod())
7082 // This rule only applies to block-scope declarations.
7083 return false;
7084
7085 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7086 if (PrevOuterContext->isRecord())
7087 // We found a member function: ignore it.
7088 return false;
7089
7090 // Find the innermost enclosing namespace for the new and
7091 // previous declarations.
7092 OuterContext = OuterContext->getEnclosingNamespaceContext();
7093 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7094
7095 // The previous declaration is in a different namespace, so it
7096 // isn't the same function.
7097 if (!OuterContext->Equals(PrevOuterContext))
7098 return false;
7099 }
7100
7101 return true;
7102}
7103
7105 CXXScopeSpec &SS = D.getCXXScopeSpec();
7106 if (!SS.isSet()) return;
7108}
7109
7112 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7113 // __opencl_c_program_scope_global_variables feature, the address space
7114 // for a variable at program scope or a static or extern variable inside
7115 // a function are inferred to be __global.
7116 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7117 Var->hasGlobalStorage())
7118 ImplAS = LangAS::opencl_global;
7119 Var->assignAddressSpace(Context, ImplAS);
7120}
7121
7122static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7123 // 'weak' only applies to declarations with external linkage.
7124 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7125 if (!ND.isExternallyVisible()) {
7126 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7127 ND.dropAttr<WeakAttr>();
7128 }
7129 }
7130}
7131
7132static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7133 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7134 if (ND.isExternallyVisible()) {
7135 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7136 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7137 }
7138 }
7139}
7140
7141static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7142 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7143 if (VD->hasInit()) {
7144 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7145 assert(VD->isThisDeclarationADefinition() &&
7146 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7147 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7148 VD->dropAttr<AliasAttr>();
7149 }
7150 }
7151 }
7152}
7153
7154static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7155 // 'selectany' only applies to externally visible variable declarations.
7156 // It does not apply to functions.
7157 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7158 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7159 S.Diag(Attr->getLocation(),
7160 diag::err_attribute_selectany_non_extern_data);
7161 ND.dropAttr<SelectAnyAttr>();
7162 }
7163 }
7164}
7165
7167 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7168 if (!ND.isExternallyVisible())
7169 S.Diag(Attr->getLocation(),
7170 diag::warn_attribute_hybrid_patchable_non_extern);
7171 }
7172}
7173
7175 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7176 auto *VD = dyn_cast<VarDecl>(&ND);
7177 bool IsAnonymousNS = false;
7178 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7179 if (VD) {
7180 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7181 while (NS && !IsAnonymousNS) {
7182 IsAnonymousNS = NS->isAnonymousNamespace();
7183 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7184 }
7185 }
7186 // dll attributes require external linkage. Static locals may have external
7187 // linkage but still cannot be explicitly imported or exported.
7188 // In Microsoft mode, a variable defined in anonymous namespace must have
7189 // external linkage in order to be exported.
7190 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7191 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7192 (!AnonNSInMicrosoftMode &&
7193 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7194 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7195 << &ND << Attr;
7196 ND.setInvalidDecl();
7197 }
7198 }
7199}
7200
7202 // Check the attributes on the function type and function params, if any.
7203 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7204 FD = FD->getMostRecentDecl();
7205 // Don't declare this variable in the second operand of the for-statement;
7206 // GCC miscompiles that by ending its lifetime before evaluating the
7207 // third operand. See gcc.gnu.org/PR86769.
7209 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7210 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7211 TL = ATL.getModifiedLoc()) {
7212 // The [[lifetimebound]] attribute can be applied to the implicit object
7213 // parameter of a non-static member function (other than a ctor or dtor)
7214 // by applying it to the function type.
7215 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7216 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7217 int NoImplicitObjectError = -1;
7218 if (!MD)
7219 NoImplicitObjectError = 0;
7220 else if (MD->isStatic())
7221 NoImplicitObjectError = 1;
7222 else if (MD->isExplicitObjectMemberFunction())
7223 NoImplicitObjectError = 2;
7224 if (NoImplicitObjectError != -1) {
7225 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7226 << NoImplicitObjectError << A->getRange();
7227 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7228 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7229 << isa<CXXDestructorDecl>(MD) << A->getRange();
7230 } else if (MD->getReturnType()->isVoidType()) {
7231 S.Diag(
7232 MD->getLocation(),
7233 diag::
7234 err_lifetimebound_implicit_object_parameter_void_return_type);
7235 }
7236 }
7237 }
7238
7239 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7240 const ParmVarDecl *P = FD->getParamDecl(I);
7241
7242 // The [[lifetimebound]] attribute can be applied to a function parameter
7243 // only if the function returns a value.
7244 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7245 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7246 S.Diag(A->getLocation(),
7247 diag::err_lifetimebound_parameter_void_return_type);
7248 }
7249 }
7250 }
7251 }
7252}
7253
7255 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7256 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7257}
7258
7260 // Ensure that an auto decl is deduced otherwise the checks below might cache
7261 // the wrong linkage.
7262 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7263
7264 checkWeakAttr(S, ND);
7265 checkWeakRefAttr(S, ND);
7266 checkAliasAttr(S, ND);
7267 checkSelectAnyAttr(S, ND);
7269 checkInheritableAttr(S, ND);
7271}
7272
7274 NamedDecl *NewDecl,
7275 bool IsSpecialization,
7276 bool IsDefinition) {
7277 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7278 return;
7279
7280 bool IsTemplate = false;
7281 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7282 OldDecl = OldTD->getTemplatedDecl();
7283 IsTemplate = true;
7284 if (!IsSpecialization)
7285 IsDefinition = false;
7286 }
7287 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7288 NewDecl = NewTD->getTemplatedDecl();
7289 IsTemplate = true;
7290 }
7291
7292 if (!OldDecl || !NewDecl)
7293 return;
7294
7295 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7296 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7297 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7298 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7299
7300 // dllimport and dllexport are inheritable attributes so we have to exclude
7301 // inherited attribute instances.
7302 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7303 (NewExportAttr && !NewExportAttr->isInherited());
7304
7305 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7306 // the only exception being explicit specializations.
7307 // Implicitly generated declarations are also excluded for now because there
7308 // is no other way to switch these to use dllimport or dllexport.
7309 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7310
7311 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7312 // Allow with a warning for free functions and global variables.
7313 bool JustWarn = false;
7314 if (!OldDecl->isCXXClassMember()) {
7315 auto *VD = dyn_cast<VarDecl>(OldDecl);
7316 if (VD && !VD->getDescribedVarTemplate())
7317 JustWarn = true;
7318 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7319 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7320 JustWarn = true;
7321 }
7322
7323 // We cannot change a declaration that's been used because IR has already
7324 // been emitted. Dllimported functions will still work though (modulo
7325 // address equality) as they can use the thunk.
7326 if (OldDecl->isUsed())
7327 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7328 JustWarn = false;
7329
7330 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7331 : diag::err_attribute_dll_redeclaration;
7332 S.Diag(NewDecl->getLocation(), DiagID)
7333 << NewDecl
7334 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7335 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7336 if (!JustWarn) {
7337 NewDecl->setInvalidDecl();
7338 return;
7339 }
7340 }
7341
7342 // A redeclaration is not allowed to drop a dllimport attribute, the only
7343 // exceptions being inline function definitions (except for function
7344 // templates), local extern declarations, qualified friend declarations or
7345 // special MSVC extension: in the last case, the declaration is treated as if
7346 // it were marked dllexport.
7347 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7348 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7349 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7350 // Ignore static data because out-of-line definitions are diagnosed
7351 // separately.
7352 IsStaticDataMember = VD->isStaticDataMember();
7353 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7355 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7356 IsInline = FD->isInlined();
7357 IsQualifiedFriend = FD->getQualifier() &&
7358 FD->getFriendObjectKind() == Decl::FOK_Declared;
7359 }
7360
7361 if (OldImportAttr && !HasNewAttr &&
7362 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7363 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7364 if (IsMicrosoftABI && IsDefinition) {
7365 if (IsSpecialization) {
7366 S.Diag(
7367 NewDecl->getLocation(),
7368 diag::err_attribute_dllimport_function_specialization_definition);
7369 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7370 NewDecl->dropAttr<DLLImportAttr>();
7371 } else {
7372 S.Diag(NewDecl->getLocation(),
7373 diag::warn_redeclaration_without_import_attribute)
7374 << NewDecl;
7375 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7376 NewDecl->dropAttr<DLLImportAttr>();
7377 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7378 S.Context, NewImportAttr->getRange()));
7379 }
7380 } else if (IsMicrosoftABI && IsSpecialization) {
7381 assert(!IsDefinition);
7382 // MSVC allows this. Keep the inherited attribute.
7383 } else {
7384 S.Diag(NewDecl->getLocation(),
7385 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7386 << NewDecl << OldImportAttr;
7387 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7388 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7389 OldDecl->dropAttr<DLLImportAttr>();
7390 NewDecl->dropAttr<DLLImportAttr>();
7391 }
7392 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7393 // In MinGW, seeing a function declared inline drops the dllimport
7394 // attribute.
7395 OldDecl->dropAttr<DLLImportAttr>();
7396 NewDecl->dropAttr<DLLImportAttr>();
7397 S.Diag(NewDecl->getLocation(),
7398 diag::warn_dllimport_dropped_from_inline_function)
7399 << NewDecl << OldImportAttr;
7400 }
7401
7402 // A specialization of a class template member function is processed here
7403 // since it's a redeclaration. If the parent class is dllexport, the
7404 // specialization inherits that attribute. This doesn't happen automatically
7405 // since the parent class isn't instantiated until later.
7406 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7407 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7408 !NewImportAttr && !NewExportAttr) {
7409 if (const DLLExportAttr *ParentExportAttr =
7410 MD->getParent()->getAttr<DLLExportAttr>()) {
7411 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7412 NewAttr->setInherited(true);
7413 NewDecl->addAttr(NewAttr);
7414 }
7415 }
7416 }
7417}
7418
7419/// Given that we are within the definition of the given function,
7420/// will that definition behave like C99's 'inline', where the
7421/// definition is discarded except for optimization purposes?
7423 // Try to avoid calling GetGVALinkageForFunction.
7424
7425 // All cases of this require the 'inline' keyword.
7426 if (!FD->isInlined()) return false;
7427
7428 // This is only possible in C++ with the gnu_inline attribute.
7429 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7430 return false;
7431
7432 // Okay, go ahead and call the relatively-more-expensive function.
7434}
7435
7436/// Determine whether a variable is extern "C" prior to attaching
7437/// an initializer. We can't just call isExternC() here, because that
7438/// will also compute and cache whether the declaration is externally
7439/// visible, which might change when we attach the initializer.
7440///
7441/// This can only be used if the declaration is known to not be a
7442/// redeclaration of an internal linkage declaration.
7443///
7444/// For instance:
7445///
7446/// auto x = []{};
7447///
7448/// Attaching the initializer here makes this declaration not externally
7449/// visible, because its type has internal linkage.
7450///
7451/// FIXME: This is a hack.
7452template<typename T>
7453static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7454 if (S.getLangOpts().CPlusPlus) {
7455 // In C++, the overloadable attribute negates the effects of extern "C".
7456 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7457 return false;
7458
7459 // So do CUDA's host/device attributes.
7460 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7461 D->template hasAttr<CUDAHostAttr>()))
7462 return false;
7463 }
7464 return D->isExternC();
7465}
7466
7467static bool shouldConsiderLinkage(const VarDecl *VD) {
7468 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7471 return VD->hasExternalStorage();
7472 if (DC->isFileContext())
7473 return true;
7474 if (DC->isRecord())
7475 return false;
7476 if (DC->getDeclKind() == Decl::HLSLBuffer)
7477 return false;
7478
7480 return false;
7481 llvm_unreachable("Unexpected context");
7482}
7483
7484static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7485 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7486 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7488 return true;
7489 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(DC))
7490 return false;
7491 llvm_unreachable("Unexpected context");
7492}
7493
7494static bool hasParsedAttr(Scope *S, const Declarator &PD,
7495 ParsedAttr::Kind Kind) {
7496 // Check decl attributes on the DeclSpec.
7497 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7498 return true;
7499
7500 // Walk the declarator structure, checking decl attributes that were in a type
7501 // position to the decl itself.
7502 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7503 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7504 return true;
7505 }
7506
7507 // Finally, check attributes on the decl itself.
7508 return PD.getAttributes().hasAttribute(Kind) ||
7510}
7511
7514 return false;
7515
7516 // If this is a local extern function or variable declared within a function
7517 // template, don't add it into the enclosing namespace scope until it is
7518 // instantiated; it might have a dependent type right now.
7519 if (DC->isDependentContext())
7520 return true;
7521
7522 // C++11 [basic.link]p7:
7523 // When a block scope declaration of an entity with linkage is not found to
7524 // refer to some other declaration, then that entity is a member of the
7525 // innermost enclosing namespace.
7526 //
7527 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7528 // semantically-enclosing namespace, not a lexically-enclosing one.
7529 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7530 DC = DC->getParent();
7531 return true;
7532}
7533
7534/// Returns true if given declaration has external C language linkage.
7535static bool isDeclExternC(const Decl *D) {
7536 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7537 return FD->isExternC();
7538 if (const auto *VD = dyn_cast<VarDecl>(D))
7539 return VD->isExternC();
7540
7541 llvm_unreachable("Unknown type of decl!");
7542}
7543
7544/// Returns true if there hasn't been any invalid type diagnosed.
7545static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7546 DeclContext *DC = NewVD->getDeclContext();
7547 QualType R = NewVD->getType();
7548
7549 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7550 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7551 // argument.
7552 if (R->isImageType() || R->isPipeType()) {
7553 Se.Diag(NewVD->getLocation(),
7554 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7555 << R;
7556 NewVD->setInvalidDecl();
7557 return false;
7558 }
7559
7560 // OpenCL v1.2 s6.9.r:
7561 // The event type cannot be used to declare a program scope variable.
7562 // OpenCL v2.0 s6.9.q:
7563 // The clk_event_t and reserve_id_t types cannot be declared in program
7564 // scope.
7565 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7566 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7567 Se.Diag(NewVD->getLocation(),
7568 diag::err_invalid_type_for_program_scope_var)
7569 << R;
7570 NewVD->setInvalidDecl();
7571 return false;
7572 }
7573 }
7574
7575 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7576 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7577 Se.getLangOpts())) {
7578 QualType NR = R.getCanonicalType();
7579 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7580 NR->isReferenceType()) {
7583 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7584 << NR->isReferenceType();
7585 NewVD->setInvalidDecl();
7586 return false;
7587 }
7588 NR = NR->getPointeeType();
7589 }
7590 }
7591
7592 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7593 Se.getLangOpts())) {
7594 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7595 // half array type (unless the cl_khr_fp16 extension is enabled).
7596 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7597 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7598 NewVD->setInvalidDecl();
7599 return false;
7600 }
7601 }
7602
7603 // OpenCL v1.2 s6.9.r:
7604 // The event type cannot be used with the __local, __constant and __global
7605 // address space qualifiers.
7606 if (R->isEventT()) {
7607 if (R.getAddressSpace() != LangAS::opencl_private) {
7608 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7609 NewVD->setInvalidDecl();
7610 return false;
7611 }
7612 }
7613
7614 if (R->isSamplerT()) {
7615 // OpenCL v1.2 s6.9.b p4:
7616 // The sampler type cannot be used with the __local and __global address
7617 // space qualifiers.
7618 if (R.getAddressSpace() == LangAS::opencl_local ||
7619 R.getAddressSpace() == LangAS::opencl_global) {
7620 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7621 NewVD->setInvalidDecl();
7622 }
7623
7624 // OpenCL v1.2 s6.12.14.1:
7625 // A global sampler must be declared with either the constant address
7626 // space qualifier or with the const qualifier.
7627 if (DC->isTranslationUnit() &&
7628 !(R.getAddressSpace() == LangAS::opencl_constant ||
7629 R.isConstQualified())) {
7630 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7631 NewVD->setInvalidDecl();
7632 }
7633 if (NewVD->isInvalidDecl())
7634 return false;
7635 }
7636
7637 return true;
7638}
7639
7640template <typename AttrTy>
7641static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7642 const TypedefNameDecl *TND = TT->getDecl();
7643 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7644 AttrTy *Clone = Attribute->clone(S.Context);
7645 Clone->setInherited(true);
7646 D->addAttr(Clone);
7647 }
7648}
7649
7650// This function emits warning and a corresponding note based on the
7651// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7652// declarations of an annotated type must be const qualified.
7654 QualType VarType = VD->getType().getCanonicalType();
7655
7656 // Ignore local declarations (for now) and those with const qualification.
7657 // TODO: Local variables should not be allowed if their type declaration has
7658 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7659 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7660 return;
7661
7662 if (VarType->isArrayType()) {
7663 // Retrieve element type for array declarations.
7664 VarType = S.getASTContext().getBaseElementType(VarType);
7665 }
7666
7667 const RecordDecl *RD = VarType->getAsRecordDecl();
7668
7669 // Check if the record declaration is present and if it has any attributes.
7670 if (RD == nullptr)
7671 return;
7672
7673 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7674 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7675 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7676 return;
7677 }
7678}
7679
7681 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7682 "NewD is not a function or variable");
7683
7684 if (PendingExportedNames.empty())
7685 return;
7686 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7687 if (getLangOpts().CPlusPlus && !FD->isExternC())
7688 return;
7689 }
7690 IdentifierInfo *IdentName = NewD->getIdentifier();
7691 if (IdentName == nullptr)
7692 return;
7693 auto PendingName = PendingExportedNames.find(IdentName);
7694 if (PendingName != PendingExportedNames.end()) {
7695 auto &Label = PendingName->second;
7696 if (!Label.Used) {
7697 Label.Used = true;
7698 if (NewD->hasExternalFormalLinkage())
7699 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7700 else
7701 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7702 }
7703 }
7704}
7705
7706// Checks if VD is declared at global scope or with C language linkage.
7707static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7708 return Name.getAsIdentifierInfo() &&
7709 Name.getAsIdentifierInfo()->isStr("main") &&
7710 !VD->getDescribedVarTemplate() &&
7711 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7712 VD->isExternC());
7713}
7714
7715void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7716 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7717
7718 // Quickly return if the function does not have an `asm` attribute.
7719 if (E == nullptr)
7720 return;
7721
7722 // The parser guarantees this is a string.
7723 StringLiteral *SE = cast<StringLiteral>(E);
7724 StringRef Label = SE->getString();
7725 QualType R = TInfo->getType();
7726 if (S->getFnParent() != nullptr) {
7727 switch (SC) {
7728 case SC_None:
7729 case SC_Auto:
7730 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7731 break;
7732 case SC_Register:
7733 // Local Named register
7734 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7736 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7737 break;
7738 case SC_Static:
7739 case SC_Extern:
7740 case SC_PrivateExtern:
7741 break;
7742 }
7743 } else if (SC == SC_Register) {
7744 // Global Named register
7745 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7746 const auto &TI = Context.getTargetInfo();
7747 bool HasSizeMismatch;
7748
7749 if (!TI.isValidGCCRegisterName(Label))
7750 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7751 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7752 HasSizeMismatch))
7753 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7754 else if (HasSizeMismatch)
7755 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7756 }
7757
7758 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7759 Diag(TInfo->getTypeLoc().getBeginLoc(),
7760 diag::err_asm_unsupported_register_type)
7761 << TInfo->getTypeLoc().getSourceRange();
7762 NewVD->setInvalidDecl(true);
7763 }
7764 }
7765}
7766
7768 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7769 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7770 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7771 QualType R = TInfo->getType();
7773
7775 bool IsPlaceholderVariable = false;
7776
7777 if (D.isDecompositionDeclarator()) {
7778 // Take the name of the first declarator as our name for diagnostic
7779 // purposes.
7780 auto &Decomp = D.getDecompositionDeclarator();
7781 if (!Decomp.bindings().empty()) {
7782 II = Decomp.bindings()[0].Name;
7783 Name = II;
7784 }
7785 } else if (!II) {
7786 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7787 return nullptr;
7788 }
7789
7790
7793 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7794 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7795
7796 IsPlaceholderVariable = true;
7797
7798 if (!Previous.empty()) {
7799 NamedDecl *PrevDecl = *Previous.begin();
7800 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7801 DC->getRedeclContext());
7802 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7803 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7804 if (IsPlaceholderVariable)
7806 }
7807 }
7808 }
7809
7810 // dllimport globals without explicit storage class are treated as extern. We
7811 // have to change the storage class this early to get the right DeclContext.
7812 if (SC == SC_None && !DC->isRecord() &&
7813 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7814 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7815 SC = SC_Extern;
7816
7817 DeclContext *OriginalDC = DC;
7818 bool IsLocalExternDecl = SC == SC_Extern &&
7820
7821 if (SCSpec == DeclSpec::SCS_mutable) {
7822 // mutable can only appear on non-static class members, so it's always
7823 // an error here
7824 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7825 D.setInvalidType();
7826 SC = SC_None;
7827 }
7828
7829 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7830 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7832 // In C++11, the 'register' storage class specifier is deprecated.
7833 // Suppress the warning in system macros, it's used in macros in some
7834 // popular C system headers, such as in glibc's htonl() macro.
7836 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7837 : diag::warn_deprecated_register)
7839 }
7840
7842
7843 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7844 // C99 6.9p2: The storage-class specifiers auto and register shall not
7845 // appear in the declaration specifiers in an external declaration.
7846 // Global Register+Asm is a GNU extension we support.
7847 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7848 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7849 D.setInvalidType();
7850 }
7851 }
7852
7853 // If this variable has a VLA type and an initializer, try to
7854 // fold to a constant-sized type. This is otherwise invalid.
7855 if (D.hasInitializer() && R->isVariableArrayType())
7857 /*DiagID=*/0);
7858
7859 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7860 const AutoType *AT = TL.getTypePtr();
7861 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7862 }
7863
7864 bool IsMemberSpecialization = false;
7865 bool IsVariableTemplateSpecialization = false;
7866 bool IsPartialSpecialization = false;
7867 bool IsVariableTemplate = false;
7868 VarDecl *NewVD = nullptr;
7869 VarTemplateDecl *NewTemplate = nullptr;
7870 TemplateParameterList *TemplateParams = nullptr;
7871 if (!getLangOpts().CPlusPlus) {
7873 II, R, TInfo, SC);
7874
7875 if (R->getContainedDeducedType())
7876 ParsingInitForAutoVars.insert(NewVD);
7877
7878 if (D.isInvalidType())
7879 NewVD->setInvalidDecl();
7880
7882 NewVD->hasLocalStorage())
7883 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7885 } else {
7886 bool Invalid = false;
7887 // Match up the template parameter lists with the scope specifier, then
7888 // determine whether we have a template or a template specialization.
7891 D.getCXXScopeSpec(),
7893 ? D.getName().TemplateId
7894 : nullptr,
7895 TemplateParamLists,
7896 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7897
7898 if (TemplateParams) {
7899 if (DC->isDependentContext()) {
7900 ContextRAII SavedContext(*this, DC);
7902 Invalid = true;
7903 }
7904
7905 if (!TemplateParams->size() &&
7907 // There is an extraneous 'template<>' for this variable. Complain
7908 // about it, but allow the declaration of the variable.
7909 Diag(TemplateParams->getTemplateLoc(),
7910 diag::err_template_variable_noparams)
7911 << II
7912 << SourceRange(TemplateParams->getTemplateLoc(),
7913 TemplateParams->getRAngleLoc());
7914 TemplateParams = nullptr;
7915 } else {
7916 // Check that we can declare a template here.
7917 if (CheckTemplateDeclScope(S, TemplateParams))
7918 return nullptr;
7919
7921 // This is an explicit specialization or a partial specialization.
7922 IsVariableTemplateSpecialization = true;
7923 IsPartialSpecialization = TemplateParams->size() > 0;
7924 } else { // if (TemplateParams->size() > 0)
7925 // This is a template declaration.
7926 IsVariableTemplate = true;
7927
7928 // Only C++1y supports variable templates (N3651).
7929 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7930 }
7931 }
7932 } else {
7933 // Check that we can declare a member specialization here.
7934 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7935 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7936 return nullptr;
7937 assert((Invalid ||
7939 "should have a 'template<>' for this decl");
7940 }
7941
7942 bool IsExplicitSpecialization =
7943 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7944
7945 // C++ [temp.expl.spec]p2:
7946 // The declaration in an explicit-specialization shall not be an
7947 // export-declaration. An explicit specialization shall not use a
7948 // storage-class-specifier other than thread_local.
7949 //
7950 // We use the storage-class-specifier from DeclSpec because we may have
7951 // added implicit 'extern' for declarations with __declspec(dllimport)!
7952 if (SCSpec != DeclSpec::SCS_unspecified &&
7953 (IsExplicitSpecialization || IsMemberSpecialization)) {
7955 diag::ext_explicit_specialization_storage_class)
7957 }
7958
7959 if (CurContext->isRecord()) {
7960 if (SC == SC_Static) {
7961 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7962 // Walk up the enclosing DeclContexts to check for any that are
7963 // incompatible with static data members.
7964 const DeclContext *FunctionOrMethod = nullptr;
7965 const CXXRecordDecl *AnonStruct = nullptr;
7966 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7967 if (Ctxt->isFunctionOrMethod()) {
7968 FunctionOrMethod = Ctxt;
7969 break;
7970 }
7971 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7972 if (ParentDecl && !ParentDecl->getDeclName()) {
7973 AnonStruct = ParentDecl;
7974 break;
7975 }
7976 }
7977 if (FunctionOrMethod) {
7978 // C++ [class.static.data]p5: A local class shall not have static
7979 // data members.
7981 diag::err_static_data_member_not_allowed_in_local_class)
7982 << Name << RD->getDeclName() << RD->getTagKind();
7983 Invalid = true;
7984 } else if (AnonStruct) {
7985 // C++ [class.static.data]p4: Unnamed classes and classes contained
7986 // directly or indirectly within unnamed classes shall not contain
7987 // static data members.
7989 diag::err_static_data_member_not_allowed_in_anon_struct)
7990 << Name << AnonStruct->getTagKind();
7991 Invalid = true;
7992 } else if (RD->isUnion()) {
7993 // C++98 [class.union]p1: If a union contains a static data member,
7994 // the program is ill-formed. C++11 drops this restriction.
7996 diag_compat::static_data_member_in_union)
7997 << Name;
7998 }
7999 }
8000 } else if (IsVariableTemplate || IsPartialSpecialization) {
8001 // There is no such thing as a member field template.
8002 Diag(D.getIdentifierLoc(), diag::err_template_member)
8003 << II << TemplateParams->getSourceRange();
8004 // Recover by pretending this is a static data member template.
8005 SC = SC_Static;
8006 }
8007 } else if (DC->isRecord()) {
8008 // This is an out-of-line definition of a static data member.
8009 switch (SC) {
8010 case SC_None:
8011 break;
8012 case SC_Static:
8014 diag::err_static_out_of_line)
8017 break;
8018 case SC_Auto:
8019 case SC_Register:
8020 case SC_Extern:
8021 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8022 // to names of variables declared in a block or to function parameters.
8023 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8024 // of class members
8025
8027 diag::err_storage_class_for_static_member)
8030 break;
8031 case SC_PrivateExtern:
8032 llvm_unreachable("C storage class in c++!");
8033 }
8034 }
8035
8036 if (IsVariableTemplateSpecialization) {
8037 SourceLocation TemplateKWLoc =
8038 TemplateParamLists.size() > 0
8039 ? TemplateParamLists[0]->getTemplateLoc()
8040 : SourceLocation();
8042 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8044 if (Res.isInvalid())
8045 return nullptr;
8046 NewVD = cast<VarDecl>(Res.get());
8047 AddToScope = false;
8048 } else if (D.isDecompositionDeclarator()) {
8050 D.getIdentifierLoc(), D.getEndLoc(), R,
8051 TInfo, SC, Bindings);
8052 } else
8053 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8054 D.getIdentifierLoc(), II, R, TInfo, SC);
8055
8056 // If this is supposed to be a variable template, create it as such.
8057 if (IsVariableTemplate) {
8058 NewTemplate =
8060 TemplateParams, NewVD);
8061 NewVD->setDescribedVarTemplate(NewTemplate);
8062 }
8063
8064 // If this decl has an auto type in need of deduction, make a note of the
8065 // Decl so we can diagnose uses of it in its own initializer.
8066 if (R->getContainedDeducedType())
8067 ParsingInitForAutoVars.insert(NewVD);
8068
8069 if (D.isInvalidType() || Invalid) {
8070 NewVD->setInvalidDecl();
8071 if (NewTemplate)
8072 NewTemplate->setInvalidDecl();
8073 }
8074
8075 SetNestedNameSpecifier(*this, NewVD, D);
8076
8077 // If we have any template parameter lists that don't directly belong to
8078 // the variable (matching the scope specifier), store them.
8079 // An explicit variable template specialization does not own any template
8080 // parameter lists.
8081 unsigned VDTemplateParamLists =
8082 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8083 if (TemplateParamLists.size() > VDTemplateParamLists)
8085 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8086 }
8087
8088 if (D.getDeclSpec().isInlineSpecified()) {
8089 if (!getLangOpts().CPlusPlus) {
8090 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8091 << 0;
8092 } else if (CurContext->isFunctionOrMethod()) {
8093 // 'inline' is not allowed on block scope variable declaration.
8095 diag::err_inline_declaration_block_scope) << Name
8097 } else {
8099 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8100 : diag::compat_pre_cxx17_inline_variable);
8101 NewVD->setInlineSpecified();
8102 }
8103 }
8104
8105 // Set the lexical context. If the declarator has a C++ scope specifier, the
8106 // lexical context will be different from the semantic context.
8108 if (NewTemplate)
8109 NewTemplate->setLexicalDeclContext(CurContext);
8110
8111 if (IsLocalExternDecl) {
8113 for (auto *B : Bindings)
8114 B->setLocalExternDecl();
8115 else
8116 NewVD->setLocalExternDecl();
8117 }
8118
8119 bool EmitTLSUnsupportedError = false;
8121 // C++11 [dcl.stc]p4:
8122 // When thread_local is applied to a variable of block scope the
8123 // storage-class-specifier static is implied if it does not appear
8124 // explicitly.
8125 // Core issue: 'static' is not implied if the variable is declared
8126 // 'extern'.
8127 if (NewVD->hasLocalStorage() &&
8128 (SCSpec != DeclSpec::SCS_unspecified ||
8130 !DC->isFunctionOrMethod()))
8132 diag::err_thread_non_global)
8134 else if (!Context.getTargetInfo().isTLSSupported()) {
8135 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8136 // Postpone error emission until we've collected attributes required to
8137 // figure out whether it's a host or device variable and whether the
8138 // error should be ignored.
8139 EmitTLSUnsupportedError = true;
8140 // We still need to mark the variable as TLS so it shows up in AST with
8141 // proper storage class for other tools to use even if we're not going
8142 // to emit any code for it.
8143 NewVD->setTSCSpec(TSCS);
8144 } else
8146 diag::err_thread_unsupported);
8147 } else
8148 NewVD->setTSCSpec(TSCS);
8149 }
8150
8151 switch (D.getDeclSpec().getConstexprSpecifier()) {
8153 break;
8154
8157 diag::err_constexpr_wrong_decl_kind)
8158 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8159 [[fallthrough]];
8160
8162 NewVD->setConstexpr(true);
8163 // C++1z [dcl.spec.constexpr]p1:
8164 // A static data member declared with the constexpr specifier is
8165 // implicitly an inline variable.
8166 if (NewVD->isStaticDataMember() &&
8168 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8169 NewVD->setImplicitlyInline();
8170 break;
8171
8173 if (!NewVD->hasGlobalStorage())
8175 diag::err_constinit_local_variable);
8176 else
8177 NewVD->addAttr(
8178 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8179 ConstInitAttr::Keyword_constinit));
8180 break;
8181 }
8182
8183 // C99 6.7.4p3
8184 // An inline definition of a function with external linkage shall
8185 // not contain a definition of a modifiable object with static or
8186 // thread storage duration...
8187 // We only apply this when the function is required to be defined
8188 // elsewhere, i.e. when the function is not 'extern inline'. Note
8189 // that a local variable with thread storage duration still has to
8190 // be marked 'static'. Also note that it's possible to get these
8191 // semantics in C++ using __attribute__((gnu_inline)).
8192 if (SC == SC_Static && S->getFnParent() != nullptr &&
8193 !NewVD->getType().isConstQualified()) {
8195 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8197 diag::warn_static_local_in_extern_inline);
8199 }
8200 }
8201
8203 if (IsVariableTemplateSpecialization)
8204 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8205 << (IsPartialSpecialization ? 1 : 0)
8208 else if (IsMemberSpecialization)
8209 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8210 << 2
8212 else if (NewVD->hasLocalStorage())
8213 Diag(NewVD->getLocation(), diag::err_module_private_local)
8214 << 0 << NewVD
8218 else {
8219 NewVD->setModulePrivate();
8220 if (NewTemplate)
8221 NewTemplate->setModulePrivate();
8222 for (auto *B : Bindings)
8223 B->setModulePrivate();
8224 }
8225 }
8226
8227 if (getLangOpts().OpenCL) {
8229
8231 if (TSC != TSCS_unspecified) {
8233 diag::err_opencl_unknown_type_specifier)
8235 << DeclSpec::getSpecifierName(TSC) << 1;
8236 NewVD->setInvalidDecl();
8237 }
8238 }
8239
8240 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8241 // address space if the table has local storage (semantic checks elsewhere
8242 // will produce an error anyway).
8243 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8244 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8245 !NewVD->hasLocalStorage()) {
8246 QualType Type = Context.getAddrSpaceQualType(
8247 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8248 NewVD->setType(Type);
8249 }
8250 }
8251
8253
8254 if (Expr *E = D.getAsmLabel()) {
8255 // The parser guarantees this is a string.
8257 StringRef Label = SE->getString();
8258
8259 // Insert the asm attribute.
8260 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8261 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8262 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8264 if (I != ExtnameUndeclaredIdentifiers.end()) {
8265 if (isDeclExternC(NewVD)) {
8266 NewVD->addAttr(I->second);
8268 } else if (NewVD->getDeclContext()
8271 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8272 << /*Variable*/ 1 << NewVD;
8273 }
8274 }
8275
8276 // Handle attributes prior to checking for duplicates in MergeVarDecl
8277 ProcessDeclAttributes(S, NewVD, D);
8278
8279 if (getLangOpts().HLSL)
8281
8282 if (getLangOpts().OpenACC)
8284
8285 // FIXME: This is probably the wrong location to be doing this and we should
8286 // probably be doing this for more attributes (especially for function
8287 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8288 // the code to copy attributes would be generated by TableGen.
8289 if (R->isFunctionPointerType())
8290 if (const auto *TT = R->getAs<TypedefType>())
8292
8293 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8294 if (EmitTLSUnsupportedError &&
8296 (getLangOpts().OpenMPIsTargetDevice &&
8297 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8299 diag::err_thread_unsupported);
8300
8301 if (EmitTLSUnsupportedError &&
8302 (LangOpts.SYCLIsDevice ||
8303 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8304 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8305 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8306 // storage [duration]."
8307 if (SC == SC_None && S->getFnParent() != nullptr &&
8308 (NewVD->hasAttr<CUDASharedAttr>() ||
8309 NewVD->hasAttr<CUDAConstantAttr>())) {
8310 NewVD->setStorageClass(SC_Static);
8311 }
8312 }
8313
8314 // Ensure that dllimport globals without explicit storage class are treated as
8315 // extern. The storage class is set above using parsed attributes. Now we can
8316 // check the VarDecl itself.
8317 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8318 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8319 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8320
8321 // In auto-retain/release, infer strong retension for variables of
8322 // retainable type.
8323 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8324 NewVD->setInvalidDecl();
8325
8326 // Check the ASM label here, as we need to know all other attributes of the
8327 // Decl first. Otherwise, we can't know if the asm label refers to the
8328 // host or device in a CUDA context. The device has other registers than
8329 // host and we must know where the function will be placed.
8330 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8331
8332 // Find the shadowed declaration before filtering for scope.
8333 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8335 : nullptr;
8336
8337 // Don't consider existing declarations that are in a different
8338 // scope and are out-of-semantic-context declarations (if the new
8339 // declaration has linkage).
8342 IsMemberSpecialization ||
8343 IsVariableTemplateSpecialization);
8344
8345 // Check whether the previous declaration is in the same block scope. This
8346 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8347 if (getLangOpts().CPlusPlus &&
8348 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8350 Previous.isSingleResult() && !Previous.isShadowed() &&
8351 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8352
8353 if (!getLangOpts().CPlusPlus) {
8355 } else {
8356 // If this is an explicit specialization of a static data member, check it.
8357 if (IsMemberSpecialization && !IsVariableTemplate &&
8358 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8360 NewVD->setInvalidDecl();
8361
8362 // Merge the decl with the existing one if appropriate.
8363 if (!Previous.empty()) {
8364 if (Previous.isSingleResult() &&
8365 isa<FieldDecl>(Previous.getFoundDecl()) &&
8366 D.getCXXScopeSpec().isSet()) {
8367 // The user tried to define a non-static data member
8368 // out-of-line (C++ [dcl.meaning]p1).
8369 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8370 << D.getCXXScopeSpec().getRange();
8371 Previous.clear();
8372 NewVD->setInvalidDecl();
8373 }
8374 } else if (D.getCXXScopeSpec().isSet() &&
8375 !IsVariableTemplateSpecialization) {
8376 // No previous declaration in the qualifying scope.
8377 Diag(D.getIdentifierLoc(), diag::err_no_member)
8378 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8379 << D.getCXXScopeSpec().getRange();
8380 NewVD->setInvalidDecl();
8381
8382 // if this is a member specialization, we don't have any primary template
8383 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8384 // that anything that attempts to refer to this invalid declaration can
8385 // act as if there IS a primary instantiation.
8386 if (NewTemplate && IsMemberSpecialization) {
8387 VarDecl *FakeVD =
8389 II, R, TInfo, SC);
8390 FakeVD->setInvalidDecl();
8391 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8392 Context, DC, D.getIdentifierLoc(), Name, TemplateParams, FakeVD);
8393 FakeInstantiatedFrom->setInvalidDecl();
8394 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8395 }
8396 }
8397
8398 if (!IsPlaceholderVariable)
8400
8401 // CheckVariableDeclaration will set NewVD as invalid if something is in
8402 // error like WebAssembly tables being declared as arrays with a non-zero
8403 // size, but then parsing continues and emits further errors on that line.
8404 // To avoid that we check here if it happened and return nullptr.
8405 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8406 return nullptr;
8407
8408 if (NewTemplate) {
8409 VarTemplateDecl *PrevVarTemplate =
8410 NewVD->getPreviousDecl()
8412 : nullptr;
8413
8414 // Check the template parameter list of this declaration, possibly
8415 // merging in the template parameter list from the previous variable
8416 // template declaration.
8418 TemplateParams,
8419 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8420 : nullptr,
8421 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8422 DC->isDependentContext())
8424 : TPC_Other))
8425 NewVD->setInvalidDecl();
8426 }
8427 }
8428
8429 if (IsMemberSpecialization) {
8430 if (NewTemplate && NewVD->getPreviousDecl()) {
8431 NewTemplate->setMemberSpecialization();
8432 } else if (IsPartialSpecialization) {
8434 ->setMemberSpecialization();
8435 }
8436 }
8437
8438 // Diagnose shadowed variables iff this isn't a redeclaration.
8439 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8440 CheckShadow(NewVD, ShadowedDecl, Previous);
8441
8442 ProcessPragmaWeak(S, NewVD);
8443 ProcessPragmaExport(NewVD);
8444
8445 // If this is the first declaration of an extern C variable, update
8446 // the map of such variables.
8447 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8448 isIncompleteDeclExternC(*this, NewVD))
8450
8451 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8453 Decl *ManglingContextDecl;
8454 std::tie(MCtx, ManglingContextDecl) =
8456 if (MCtx) {
8457 Context.setManglingNumber(
8458 NewVD, MCtx->getManglingNumber(
8459 NewVD, getMSManglingNumber(getLangOpts(), S)));
8460 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8461 }
8462 }
8463
8464 // Special handling of variable named 'main'.
8465 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8466 // C++ [basic.start.main]p3:
8467 // A program that declares
8468 // - a variable main at global scope, or
8469 // - an entity named main with C language linkage (in any namespace)
8470 // is ill-formed
8471 if (getLangOpts().CPlusPlus)
8472 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8473 << NewVD->isExternC();
8474
8475 // In C, and external-linkage variable named main results in undefined
8476 // behavior.
8477 else if (NewVD->hasExternalFormalLinkage())
8478 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8479 }
8480
8481 if (D.isRedeclaration() && !Previous.empty()) {
8482 NamedDecl *Prev = Previous.getRepresentativeDecl();
8483 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8485 }
8486
8487 if (NewTemplate) {
8488 if (NewVD->isInvalidDecl())
8489 NewTemplate->setInvalidDecl();
8490 ActOnDocumentableDecl(NewTemplate);
8491 return NewTemplate;
8492 }
8493
8494 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8496
8498
8499 return NewVD;
8500}
8501
8502/// Enum describing the %select options in diag::warn_decl_shadow.
8512
8513/// Determine what kind of declaration we're shadowing.
8515 const DeclContext *OldDC) {
8516 if (isa<TypeAliasDecl>(ShadowedDecl))
8517 return SDK_Using;
8518 else if (isa<TypedefDecl>(ShadowedDecl))
8519 return SDK_Typedef;
8520 else if (isa<BindingDecl>(ShadowedDecl))
8521 return SDK_StructuredBinding;
8522 else if (isa<RecordDecl>(OldDC))
8523 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8524
8525 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8526}
8527
8528/// Return the location of the capture if the given lambda captures the given
8529/// variable \p VD, or an invalid source location otherwise.
8531 const ValueDecl *VD) {
8532 for (const Capture &Capture : LSI->Captures) {
8534 return Capture.getLocation();
8535 }
8536 return SourceLocation();
8537}
8538
8540 const LookupResult &R) {
8541 // Only diagnose if we're shadowing an unambiguous field or variable.
8542 if (R.getResultKind() != LookupResultKind::Found)
8543 return false;
8544
8545 // Return false if warning is ignored.
8546 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8547}
8548
8550 const LookupResult &R) {
8552 return nullptr;
8553
8554 // Don't diagnose declarations at file scope.
8555 if (D->hasGlobalStorage() && !D->isStaticLocal())
8556 return nullptr;
8557
8558 NamedDecl *ShadowedDecl = R.getFoundDecl();
8559 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8560 : nullptr;
8561}
8562
8564 const LookupResult &R) {
8565 // Don't warn if typedef declaration is part of a class
8566 if (D->getDeclContext()->isRecord())
8567 return nullptr;
8568
8570 return nullptr;
8571
8572 NamedDecl *ShadowedDecl = R.getFoundDecl();
8573 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8574}
8575
8577 const LookupResult &R) {
8579 return nullptr;
8580
8581 NamedDecl *ShadowedDecl = R.getFoundDecl();
8582 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8583 : nullptr;
8584}
8585
8587 const LookupResult &R) {
8588 DeclContext *NewDC = D->getDeclContext();
8589
8590 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8591 if (const auto *MD =
8592 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8593 // Fields aren't shadowed in C++ static members or in member functions
8594 // with an explicit object parameter.
8595 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8596 return;
8597 }
8598 // Fields shadowed by constructor parameters are a special case. Usually
8599 // the constructor initializes the field with the parameter.
8600 if (isa<CXXConstructorDecl>(NewDC))
8601 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8602 // Remember that this was shadowed so we can either warn about its
8603 // modification or its existence depending on warning settings.
8604 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8605 return;
8606 }
8607 }
8608
8609 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8610 if (shadowedVar->isExternC()) {
8611 // For shadowing external vars, make sure that we point to the global
8612 // declaration, not a locally scoped extern declaration.
8613 for (auto *I : shadowedVar->redecls())
8614 if (I->isFileVarDecl()) {
8615 ShadowedDecl = I;
8616 break;
8617 }
8618 }
8619
8620 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8621
8622 unsigned WarningDiag = diag::warn_decl_shadow;
8623 SourceLocation CaptureLoc;
8624 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8625 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8626 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8627 // Handle both VarDecl and BindingDecl in lambda contexts
8628 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8629 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8630 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8631 if (RD->getLambdaCaptureDefault() == LCD_None) {
8632 // Try to avoid warnings for lambdas with an explicit capture
8633 // list. Warn only when the lambda captures the shadowed decl
8634 // explicitly.
8635 CaptureLoc = getCaptureLocation(LSI, VD);
8636 if (CaptureLoc.isInvalid())
8637 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8638 } else {
8639 // Remember that this was shadowed so we can avoid the warning if
8640 // the shadowed decl isn't captured and the warning settings allow
8641 // it.
8643 ->ShadowingDecls.push_back({D, VD});
8644 return;
8645 }
8646 }
8647 if (isa<FieldDecl>(ShadowedDecl)) {
8648 // If lambda can capture this, then emit default shadowing warning,
8649 // Otherwise it is not really a shadowing case since field is not
8650 // available in lambda's body.
8651 // At this point we don't know that lambda can capture this, so
8652 // remember that this was shadowed and delay until we know.
8654 ->ShadowingDecls.push_back({D, ShadowedDecl});
8655 return;
8656 }
8657 }
8658 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8659 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8660 bool HasLocalStorage = false;
8661 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8662 HasLocalStorage = VD->hasLocalStorage();
8663 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8664 HasLocalStorage =
8665 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8666
8667 if (HasLocalStorage) {
8668 // A variable can't shadow a local variable or binding in an enclosing
8669 // scope, if they are separated by a non-capturing declaration
8670 // context.
8671 for (DeclContext *ParentDC = NewDC;
8672 ParentDC && !ParentDC->Equals(OldDC);
8673 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8674 // Only block literals, captured statements, and lambda expressions
8675 // can capture; other scopes don't.
8676 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8677 !isLambdaCallOperator(ParentDC))
8678 return;
8679 }
8680 }
8681 }
8682 }
8683 }
8684
8685 // Never warn about shadowing a placeholder variable.
8686 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8687 return;
8688
8689 // Only warn about certain kinds of shadowing for class members.
8690 if (NewDC) {
8691 // In particular, don't warn about shadowing non-class members.
8692 if (NewDC->isRecord() && !OldDC->isRecord())
8693 return;
8694
8695 // Skip shadowing check if we're in a class scope, dealing with an enum
8696 // constant in a different context.
8697 DeclContext *ReDC = NewDC->getRedeclContext();
8698 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8699 return;
8700
8701 // TODO: should we warn about static data members shadowing
8702 // static data members from base classes?
8703
8704 // TODO: don't diagnose for inaccessible shadowed members.
8705 // This is hard to do perfectly because we might friend the
8706 // shadowing context, but that's just a false negative.
8707 }
8708
8709 DeclarationName Name = R.getLookupName();
8710
8711 // Emit warning and note.
8712 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8713 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8714 if (!CaptureLoc.isInvalid())
8715 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8716 << Name << /*explicitly*/ 1;
8717 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8718}
8719
8721 for (const auto &Shadow : LSI->ShadowingDecls) {
8722 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8723 // Try to avoid the warning when the shadowed decl isn't captured.
8724 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8725 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8726 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8727 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8728 Diag(Shadow.VD->getLocation(),
8729 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8730 : diag::warn_decl_shadow)
8731 << Shadow.VD->getDeclName()
8732 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8733 if (CaptureLoc.isValid())
8734 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8735 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8736 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8737 } else if (isa<FieldDecl>(ShadowedDecl)) {
8738 Diag(Shadow.VD->getLocation(),
8739 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8740 : diag::warn_decl_shadow_uncaptured_local)
8741 << Shadow.VD->getDeclName()
8742 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8743 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8744 }
8745 }
8746}
8747
8749 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8750 return;
8751
8752 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8755 LookupName(R, S);
8756 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8757 CheckShadow(D, ShadowedDecl, R);
8758}
8759
8760/// Check if 'E', which is an expression that is about to be modified, refers
8761/// to a constructor parameter that shadows a field.
8763 // Quickly ignore expressions that can't be shadowing ctor parameters.
8764 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8765 return;
8766 E = E->IgnoreParenImpCasts();
8767 auto *DRE = dyn_cast<DeclRefExpr>(E);
8768 if (!DRE)
8769 return;
8770 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8771 auto I = ShadowingDecls.find(D);
8772 if (I == ShadowingDecls.end())
8773 return;
8774 const NamedDecl *ShadowedDecl = I->second;
8775 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8776 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8777 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8778 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8779
8780 // Avoid issuing multiple warnings about the same decl.
8781 ShadowingDecls.erase(I);
8782}
8783
8784/// Check for conflict between this global or extern "C" declaration and
8785/// previous global or extern "C" declarations. This is only used in C++.
8786template<typename T>
8788 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8789 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8790 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8791
8792 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8793 // The common case: this global doesn't conflict with any extern "C"
8794 // declaration.
8795 return false;
8796 }
8797
8798 if (Prev) {
8799 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8800 // Both the old and new declarations have C language linkage. This is a
8801 // redeclaration.
8802 Previous.clear();
8803 Previous.addDecl(Prev);
8804 return true;
8805 }
8806
8807 // This is a global, non-extern "C" declaration, and there is a previous
8808 // non-global extern "C" declaration. Diagnose if this is a variable
8809 // declaration.
8810 if (!isa<VarDecl>(ND))
8811 return false;
8812 } else {
8813 // The declaration is extern "C". Check for any declaration in the
8814 // translation unit which might conflict.
8815 if (IsGlobal) {
8816 // We have already performed the lookup into the translation unit.
8817 IsGlobal = false;
8818 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8819 I != E; ++I) {
8820 if (isa<VarDecl>(*I)) {
8821 Prev = *I;
8822 break;
8823 }
8824 }
8825 } else {
8827 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8828 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8829 I != E; ++I) {
8830 if (isa<VarDecl>(*I)) {
8831 Prev = *I;
8832 break;
8833 }
8834 // FIXME: If we have any other entity with this name in global scope,
8835 // the declaration is ill-formed, but that is a defect: it breaks the
8836 // 'stat' hack, for instance. Only variables can have mangled name
8837 // clashes with extern "C" declarations, so only they deserve a
8838 // diagnostic.
8839 }
8840 }
8841
8842 if (!Prev)
8843 return false;
8844 }
8845
8846 // Use the first declaration's location to ensure we point at something which
8847 // is lexically inside an extern "C" linkage-spec.
8848 assert(Prev && "should have found a previous declaration to diagnose");
8849 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8850 Prev = FD->getFirstDecl();
8851 else
8852 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8853
8854 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8855 << IsGlobal << ND;
8856 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8857 << IsGlobal;
8858 return false;
8859}
8860
8861/// Apply special rules for handling extern "C" declarations. Returns \c true
8862/// if we have found that this is a redeclaration of some prior entity.
8863///
8864/// Per C++ [dcl.link]p6:
8865/// Two declarations [for a function or variable] with C language linkage
8866/// with the same name that appear in different scopes refer to the same
8867/// [entity]. An entity with C language linkage shall not be declared with
8868/// the same name as an entity in global scope.
8869template<typename T>
8872 if (!S.getLangOpts().CPlusPlus) {
8873 // In C, when declaring a global variable, look for a corresponding 'extern'
8874 // variable declared in function scope. We don't need this in C++, because
8875 // we find local extern decls in the surrounding file-scope DeclContext.
8876 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8877 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8878 Previous.clear();
8879 Previous.addDecl(Prev);
8880 return true;
8881 }
8882 }
8883 return false;
8884 }
8885
8886 // A declaration in the translation unit can conflict with an extern "C"
8887 // declaration.
8888 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8889 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8890
8891 // An extern "C" declaration can conflict with a declaration in the
8892 // translation unit or can be a redeclaration of an extern "C" declaration
8893 // in another scope.
8894 if (isIncompleteDeclExternC(S,ND))
8895 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8896
8897 // Neither global nor extern "C": nothing to do.
8898 return false;
8899}
8900
8901static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8902 QualType T) {
8903 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8904 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8905 // any of its members, even recursively, shall not have an atomic type, or a
8906 // variably modified type, or a type that is volatile or restrict qualified.
8907 if (CanonT->isVariablyModifiedType()) {
8908 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8909 return true;
8910 }
8911
8912 // Arrays are qualified by their element type, so get the base type (this
8913 // works on non-arrays as well).
8914 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8915
8916 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8917 CanonT.isRestrictQualified()) {
8918 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8919 return true;
8920 }
8921
8922 if (CanonT->isRecordType()) {
8923 const RecordDecl *RD = CanonT->getAsRecordDecl();
8924 if (!RD->isInvalidDecl() &&
8925 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8926 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8927 }))
8928 return true;
8929 }
8930
8931 return false;
8932}
8933
8935 // If the decl is already known invalid, don't check it.
8936 if (NewVD->isInvalidDecl())
8937 return;
8938
8939 QualType T = NewVD->getType();
8940
8941 // Defer checking an 'auto' type until its initializer is attached.
8942 if (T->isUndeducedType())
8943 return;
8944
8945 if (NewVD->hasAttrs())
8947
8948 if (T->isObjCObjectType()) {
8949 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8950 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8951 T = Context.getObjCObjectPointerType(T);
8952 NewVD->setType(T);
8953 }
8954
8955 // Emit an error if an address space was applied to decl with local storage.
8956 // This includes arrays of objects with address space qualifiers, but not
8957 // automatic variables that point to other address spaces.
8958 // ISO/IEC TR 18037 S5.1.2
8959 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8960 T.getAddressSpace() != LangAS::Default) {
8961 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8962 NewVD->setInvalidDecl();
8963 return;
8964 }
8965
8966 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8967 // scope.
8968 if (getLangOpts().OpenCLVersion == 120 &&
8969 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8970 getLangOpts()) &&
8971 NewVD->isStaticLocal()) {
8972 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8973 NewVD->setInvalidDecl();
8974 return;
8975 }
8976
8977 if (getLangOpts().OpenCL) {
8978 if (!diagnoseOpenCLTypes(*this, NewVD))
8979 return;
8980
8981 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8982 if (NewVD->hasAttr<BlocksAttr>()) {
8983 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8984 return;
8985 }
8986
8987 if (T->isBlockPointerType()) {
8988 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8989 // can't use 'extern' storage class.
8990 if (!T.isConstQualified()) {
8991 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8992 << 0 /*const*/;
8993 NewVD->setInvalidDecl();
8994 return;
8995 }
8996 if (NewVD->hasExternalStorage()) {
8997 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8998 NewVD->setInvalidDecl();
8999 return;
9000 }
9001 }
9002
9003 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9004 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9005 NewVD->hasExternalStorage()) {
9006 if (!T->isSamplerT() && !T->isDependentType() &&
9007 !(T.getAddressSpace() == LangAS::opencl_constant ||
9008 (T.getAddressSpace() == LangAS::opencl_global &&
9009 getOpenCLOptions().areProgramScopeVariablesSupported(
9010 getLangOpts())))) {
9011 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9012 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
9013 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9014 << Scope << "global or constant";
9015 else
9016 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9017 << Scope << "constant";
9018 NewVD->setInvalidDecl();
9019 return;
9020 }
9021 } else {
9022 if (T.getAddressSpace() == LangAS::opencl_global) {
9023 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9024 << 1 /*is any function*/ << "global";
9025 NewVD->setInvalidDecl();
9026 return;
9027 }
9028 // When this extension is enabled, 'local' variables are permitted in
9029 // non-kernel functions and within nested scopes of kernel functions,
9030 // bypassing standard OpenCL address space restrictions.
9031 bool AllowFunctionScopeLocalVariables =
9032 T.getAddressSpace() == LangAS::opencl_local &&
9034 "__cl_clang_function_scope_local_variables", getLangOpts());
9035 if (AllowFunctionScopeLocalVariables) {
9036 // Direct pass: No further diagnostics needed for this specific case.
9037 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9038 T.getAddressSpace() == LangAS::opencl_local) {
9040 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9041 // in functions.
9042 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9043 if (T.getAddressSpace() == LangAS::opencl_constant)
9044 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9045 << 0 /*non-kernel only*/ << "constant";
9046 else
9047 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9048 << 0 /*non-kernel only*/ << "local";
9049 NewVD->setInvalidDecl();
9050 return;
9051 }
9052 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9053 // in the outermost scope of a kernel function.
9054 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9055 if (!getCurScope()->isFunctionScope()) {
9056 if (T.getAddressSpace() == LangAS::opencl_constant)
9057 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9058 << "constant";
9059 else
9060 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9061 << "local";
9062 NewVD->setInvalidDecl();
9063 return;
9064 }
9065 }
9066 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9067 // If we are parsing a template we didn't deduce an addr
9068 // space yet.
9069 T.getAddressSpace() != LangAS::Default) {
9070 // Do not allow other address spaces on automatic variable.
9071 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9072 NewVD->setInvalidDecl();
9073 return;
9074 }
9075 }
9076 }
9077
9078 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9079 && !NewVD->hasAttr<BlocksAttr>()) {
9080 if (getLangOpts().getGC() != LangOptions::NonGC)
9081 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9082 else {
9083 assert(!getLangOpts().ObjCAutoRefCount);
9084 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9085 }
9086 }
9087
9088 // WebAssembly tables must be static with a zero length and can't be
9089 // declared within functions.
9090 if (T->isWebAssemblyTableType()) {
9091 if (getCurScope()->getParent()) { // Parent is null at top-level
9092 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9093 NewVD->setInvalidDecl();
9094 return;
9095 }
9096 if (NewVD->getStorageClass() != SC_Static) {
9097 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9098 NewVD->setInvalidDecl();
9099 return;
9100 }
9101 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9102 if (!ATy || ATy->getZExtSize() != 0) {
9103 Diag(NewVD->getLocation(),
9104 diag::err_typecheck_wasm_table_must_have_zero_length);
9105 NewVD->setInvalidDecl();
9106 return;
9107 }
9108 }
9109
9110 // zero sized static arrays are not allowed in HIP device functions
9111 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9112 if (FunctionDecl *FD = getCurFunctionDecl();
9113 FD &&
9114 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9115 if (const ConstantArrayType *ArrayT =
9116 getASTContext().getAsConstantArrayType(T);
9117 ArrayT && ArrayT->isZeroSize()) {
9118 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9119 }
9120 }
9121 }
9122
9123 bool isVM = T->isVariablyModifiedType();
9124 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9125 NewVD->hasAttr<BlocksAttr>())
9127
9128 if ((isVM && NewVD->hasLinkage()) ||
9129 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9130 bool SizeIsNegative;
9131 llvm::APSInt Oversized;
9133 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9134 QualType FixedT;
9135 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9136 FixedT = FixedTInfo->getType();
9137 else if (FixedTInfo) {
9138 // Type and type-as-written are canonically different. We need to fix up
9139 // both types separately.
9140 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9141 Oversized);
9142 }
9143 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9144 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9145 // FIXME: This won't give the correct result for
9146 // int a[10][n];
9147 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9148
9149 if (NewVD->isFileVarDecl())
9150 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9151 << SizeRange;
9152 else if (NewVD->isStaticLocal())
9153 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9154 << SizeRange;
9155 else
9156 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9157 << SizeRange;
9158 NewVD->setInvalidDecl();
9159 return;
9160 }
9161
9162 if (!FixedTInfo) {
9163 if (NewVD->isFileVarDecl())
9164 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9165 else
9166 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9167 NewVD->setInvalidDecl();
9168 return;
9169 }
9170
9171 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9172 NewVD->setType(FixedT);
9173 NewVD->setTypeSourceInfo(FixedTInfo);
9174 }
9175
9176 if (T->isVoidType()) {
9177 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9178 // of objects and functions.
9180 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9181 << T;
9182 NewVD->setInvalidDecl();
9183 return;
9184 }
9185 }
9186
9187 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9188 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9189 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9190 NewVD->setInvalidDecl();
9191 return;
9192 }
9193
9194 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9195 Diag(NewVD->getLocation(), diag::err_block_not_allowed_on)
9196 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9197 NewVD->setInvalidDecl();
9198 return;
9199 }
9200
9201 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9202 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9203 NewVD->setInvalidDecl();
9204 return;
9205 }
9206
9207 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9208 !T->isDependentType() &&
9210 diag::err_constexpr_var_non_literal)) {
9211 NewVD->setInvalidDecl();
9212 return;
9213 }
9214
9215 // PPC MMA non-pointer types are not allowed as non-local variable types.
9216 if (Context.getTargetInfo().getTriple().isPPC64() &&
9217 !NewVD->isLocalVarDecl() &&
9218 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9219 NewVD->setInvalidDecl();
9220 return;
9221 }
9222
9223 // Check that SVE types are only used in functions with SVE available.
9224 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9226 llvm::StringMap<bool> CallerFeatureMap;
9227 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9228 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9229 CallerFeatureMap)) {
9230 NewVD->setInvalidDecl();
9231 return;
9232 }
9233 }
9234
9235 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9237 llvm::StringMap<bool> CallerFeatureMap;
9238 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9240 CallerFeatureMap);
9241 }
9242
9243 if (T.hasAddressSpace() &&
9244 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9245 NewVD->setInvalidDecl();
9246 return;
9247 }
9248}
9249
9252
9253 // If the decl is already known invalid, don't check it.
9254 if (NewVD->isInvalidDecl())
9255 return false;
9256
9257 // If we did not find anything by this name, look for a non-visible
9258 // extern "C" declaration with the same name.
9259 if (Previous.empty() &&
9261 Previous.setShadowed();
9262
9263 if (!Previous.empty()) {
9264 MergeVarDecl(NewVD, Previous);
9265 return true;
9266 }
9267 return false;
9268}
9269
9272
9273 // Look for methods in base classes that this method might override.
9274 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9275 /*DetectVirtual=*/false);
9276 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9277 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9278 DeclarationName Name = MD->getDeclName();
9279
9281 // We really want to find the base class destructor here.
9282 Name = Context.DeclarationNames.getCXXDestructorName(
9283 Context.getCanonicalTagType(BaseRecord));
9284 }
9285
9286 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9287 CXXMethodDecl *BaseMD =
9288 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9289 if (!BaseMD || !BaseMD->isVirtual() ||
9290 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9291 /*ConsiderCudaAttrs=*/true))
9292 continue;
9293 if (!CheckExplicitObjectOverride(MD, BaseMD))
9294 continue;
9295 if (Overridden.insert(BaseMD).second) {
9296 MD->addOverriddenMethod(BaseMD);
9301 }
9302
9303 // A method can only override one function from each base class. We
9304 // don't track indirectly overridden methods from bases of bases.
9305 return true;
9306 }
9307
9308 return false;
9309 };
9310
9311 DC->lookupInBases(VisitBase, Paths);
9312 return !Overridden.empty();
9313}
9314
9315namespace {
9316 // Struct for holding all of the extra arguments needed by
9317 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9318 struct ActOnFDArgs {
9319 Scope *S;
9320 Declarator &D;
9321 MultiTemplateParamsArg TemplateParamLists;
9322 bool AddToScope;
9323 };
9324} // end anonymous namespace
9325
9326namespace {
9327
9328// Callback to only accept typo corrections that have a non-zero edit distance.
9329// Also only accept corrections that have the same parent decl.
9330class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9331 public:
9332 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9333 CXXRecordDecl *Parent)
9334 : Context(Context), OriginalFD(TypoFD),
9335 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9336
9337 bool ValidateCandidate(const TypoCorrection &candidate) override {
9338 if (candidate.getEditDistance() == 0)
9339 return false;
9340
9341 SmallVector<unsigned, 1> MismatchedParams;
9342 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9343 CDeclEnd = candidate.end();
9344 CDecl != CDeclEnd; ++CDecl) {
9345 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9346
9347 if (FD && !FD->hasBody() &&
9348 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9349 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9350 CXXRecordDecl *Parent = MD->getParent();
9351 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9352 return true;
9353 } else if (!ExpectedParent) {
9354 return true;
9355 }
9356 }
9357 }
9358
9359 return false;
9360 }
9361
9362 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9363 return std::make_unique<DifferentNameValidatorCCC>(*this);
9364 }
9365
9366 private:
9367 ASTContext &Context;
9368 FunctionDecl *OriginalFD;
9369 CXXRecordDecl *ExpectedParent;
9370};
9371
9372} // end anonymous namespace
9373
9377
9378/// Generate diagnostics for an invalid function redeclaration.
9379///
9380/// This routine handles generating the diagnostic messages for an invalid
9381/// function redeclaration, including finding possible similar declarations
9382/// or performing typo correction if there are no previous declarations with
9383/// the same name.
9384///
9385/// Returns a NamedDecl iff typo correction was performed and substituting in
9386/// the new declaration name does not cause new errors.
9388 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9389 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9390 DeclarationName Name = NewFD->getDeclName();
9391 DeclContext *NewDC = NewFD->getDeclContext();
9392 SmallVector<unsigned, 1> MismatchedParams;
9394 TypoCorrection Correction;
9395 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9396 unsigned DiagMsg =
9397 IsLocalFriend ? diag::err_no_matching_local_friend :
9398 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9399 diag::err_member_decl_does_not_match;
9400 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9401 IsLocalFriend ? Sema::LookupLocalFriendName
9404
9405 NewFD->setInvalidDecl();
9406 if (IsLocalFriend)
9407 SemaRef.LookupName(Prev, S);
9408 else
9409 SemaRef.LookupQualifiedName(Prev, NewDC);
9410 assert(!Prev.isAmbiguous() &&
9411 "Cannot have an ambiguity in previous-declaration lookup");
9412 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9413 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9414 MD ? MD->getParent() : nullptr);
9415 if (!Prev.empty()) {
9416 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9417 Func != FuncEnd; ++Func) {
9418 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9419 if (FD &&
9420 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9421 // Add 1 to the index so that 0 can mean the mismatch didn't
9422 // involve a parameter
9423 unsigned ParamNum =
9424 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9425 NearMatches.push_back(std::make_pair(FD, ParamNum));
9426 }
9427 }
9428 // If the qualified name lookup yielded nothing, try typo correction
9429 } else if ((Correction = SemaRef.CorrectTypo(
9430 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9431 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9433 IsLocalFriend ? nullptr : NewDC))) {
9434 // Set up everything for the call to ActOnFunctionDeclarator
9435 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9436 ExtraArgs.D.getIdentifierLoc());
9437 Previous.clear();
9438 Previous.setLookupName(Correction.getCorrection());
9439 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9440 CDeclEnd = Correction.end();
9441 CDecl != CDeclEnd; ++CDecl) {
9442 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9443 if (FD && !FD->hasBody() &&
9444 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9445 Previous.addDecl(FD);
9446 }
9447 }
9448 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9449
9451 // Retry building the function declaration with the new previous
9452 // declarations, and with errors suppressed.
9453 {
9454 // Trap errors.
9455 Sema::SFINAETrap Trap(SemaRef);
9456
9457 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9458 // pieces need to verify the typo-corrected C++ declaration and hopefully
9459 // eliminate the need for the parameter pack ExtraArgs.
9461 ExtraArgs.S, ExtraArgs.D,
9462 Correction.getCorrectionDecl()->getDeclContext(),
9463 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9464 ExtraArgs.AddToScope);
9465
9466 if (Trap.hasErrorOccurred())
9467 Result = nullptr;
9468 }
9469
9470 if (Result) {
9471 // Determine which correction we picked.
9472 Decl *Canonical = Result->getCanonicalDecl();
9473 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9474 I != E; ++I)
9475 if ((*I)->getCanonicalDecl() == Canonical)
9476 Correction.setCorrectionDecl(*I);
9477
9478 // Let Sema know about the correction.
9480 SemaRef.diagnoseTypo(
9481 Correction,
9482 SemaRef.PDiag(IsLocalFriend
9483 ? diag::err_no_matching_local_friend_suggest
9484 : diag::err_member_decl_does_not_match_suggest)
9485 << Name << NewDC << IsDefinition);
9486 return Result;
9487 }
9488
9489 // Pretend the typo correction never occurred
9490 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9491 ExtraArgs.D.getIdentifierLoc());
9492 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9493 Previous.clear();
9494 Previous.setLookupName(Name);
9495 }
9496
9497 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9498 << Name << NewDC << IsDefinition << NewFD->getLocation();
9499
9500 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9501 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9502 CXXRecordDecl *RD = NewMD->getParent();
9503 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9504 << RD->getName() << RD->getLocation();
9505 }
9506
9507 bool NewFDisConst = NewMD && NewMD->isConst();
9508
9509 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9510 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9511 NearMatch != NearMatchEnd; ++NearMatch) {
9512 FunctionDecl *FD = NearMatch->first;
9513 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9514 bool FDisConst = MD && MD->isConst();
9515 bool IsMember = MD || !IsLocalFriend;
9516
9517 // FIXME: These notes are poorly worded for the local friend case.
9518 if (unsigned Idx = NearMatch->second) {
9519 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9520 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9521 if (Loc.isInvalid()) Loc = FD->getLocation();
9522 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9523 : diag::note_local_decl_close_param_match)
9524 << Idx << FDParam->getType()
9525 << NewFD->getParamDecl(Idx - 1)->getType();
9526 } else if (FDisConst != NewFDisConst) {
9527 auto DB = SemaRef.Diag(FD->getLocation(),
9528 diag::note_member_def_close_const_match)
9529 << NewFDisConst << FD->getSourceRange().getEnd();
9530 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9531 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9532 " const");
9533 else if (FTI.hasMethodTypeQualifiers() &&
9534 FTI.getConstQualifierLoc().isValid())
9535 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9536 } else {
9537 SemaRef.Diag(FD->getLocation(),
9538 IsMember ? diag::note_member_def_close_match
9539 : diag::note_local_decl_close_match);
9540 }
9541 }
9542 return nullptr;
9543}
9544
9546 switch (D.getDeclSpec().getStorageClassSpec()) {
9547 default: llvm_unreachable("Unknown storage class!");
9548 case DeclSpec::SCS_auto:
9552 diag::err_typecheck_sclass_func);
9554 D.setInvalidType();
9555 break;
9556 case DeclSpec::SCS_unspecified: break;
9559 return SC_None;
9560 return SC_Extern;
9561 case DeclSpec::SCS_static: {
9563 // C99 6.7.1p5:
9564 // The declaration of an identifier for a function that has
9565 // block scope shall have no explicit storage-class specifier
9566 // other than extern
9567 // See also (C++ [dcl.stc]p4).
9569 diag::err_static_block_func);
9570 break;
9571 } else
9572 return SC_Static;
9573 }
9575 }
9576
9577 // No explicit storage class has already been returned
9578 return SC_None;
9579}
9580
9582 DeclContext *DC, QualType &R,
9583 TypeSourceInfo *TInfo,
9584 StorageClass SC,
9585 bool &IsVirtualOkay) {
9586 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9587 DeclarationName Name = NameInfo.getName();
9588
9589 FunctionDecl *NewFD = nullptr;
9590 bool isInline = D.getDeclSpec().isInlineSpecified();
9591
9593 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9594 (SemaRef.getLangOpts().C23 &&
9595 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9596
9597 if (SemaRef.getLangOpts().C23)
9598 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9599 diag::err_c23_constexpr_not_variable);
9600 else
9601 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9602 diag::err_constexpr_wrong_decl_kind)
9603 << static_cast<int>(ConstexprKind);
9604 ConstexprKind = ConstexprSpecKind::Unspecified;
9606 }
9607
9608 if (!SemaRef.getLangOpts().CPlusPlus) {
9609 // Determine whether the function was written with a prototype. This is
9610 // true when:
9611 // - there is a prototype in the declarator, or
9612 // - the type R of the function is some kind of typedef or other non-
9613 // attributed reference to a type name (which eventually refers to a
9614 // function type). Note, we can't always look at the adjusted type to
9615 // check this case because attributes may cause a non-function
9616 // declarator to still have a function type. e.g.,
9617 // typedef void func(int a);
9618 // __attribute__((noreturn)) func other_func; // This has a prototype
9619 bool HasPrototype =
9621 (D.getDeclSpec().isTypeRep() &&
9622 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9623 ->isFunctionProtoType()) ||
9624 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9625 assert(
9626 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9627 "Strict prototypes are required");
9628
9629 NewFD = FunctionDecl::Create(
9630 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9631 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9633 /*TrailingRequiresClause=*/{});
9634 if (D.isInvalidType())
9635 NewFD->setInvalidDecl();
9636
9637 return NewFD;
9638 }
9639
9641 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9642
9643 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9644
9646 // This is a C++ constructor declaration.
9647 assert(DC->isRecord() &&
9648 "Constructors can only be declared in a member context");
9649
9650 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9652 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9654 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9655 InheritedConstructor(), TrailingRequiresClause);
9656
9657 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9658 // This is a C++ destructor declaration.
9659 if (DC->isRecord()) {
9660 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9663 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9664 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9665 /*isImplicitlyDeclared=*/false, ConstexprKind,
9666 TrailingRequiresClause);
9667 // User defined destructors start as not selected if the class definition is still
9668 // not done.
9669 if (Record->isBeingDefined())
9670 NewDD->setIneligibleOrNotSelected(true);
9671
9672 // If the destructor needs an implicit exception specification, set it
9673 // now. FIXME: It'd be nice to be able to create the right type to start
9674 // with, but the type needs to reference the destructor declaration.
9675 if (SemaRef.getLangOpts().CPlusPlus11)
9676 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9677
9678 IsVirtualOkay = true;
9679 return NewDD;
9680
9681 } else {
9682 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9683 D.setInvalidType();
9684
9685 // Create a FunctionDecl to satisfy the function definition parsing
9686 // code path.
9687 return FunctionDecl::Create(
9688 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9689 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9690 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9691 }
9692
9694 if (!DC->isRecord()) {
9695 SemaRef.Diag(D.getIdentifierLoc(),
9696 diag::err_conv_function_not_member);
9697 return nullptr;
9698 }
9699
9700 SemaRef.CheckConversionDeclarator(D, R, SC);
9701 if (D.isInvalidType())
9702 return nullptr;
9703
9704 IsVirtualOkay = true;
9706 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9707 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9708 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9709 TrailingRequiresClause);
9710
9712 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9713 return nullptr;
9715 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9716 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9717 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9718 } else if (DC->isRecord()) {
9719 // If the name of the function is the same as the name of the record,
9720 // then this must be an invalid constructor that has a return type.
9721 // (The parser checks for a return type and makes the declarator a
9722 // constructor if it has no return type).
9723 if (Name.getAsIdentifierInfo() &&
9724 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9725 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9728 return nullptr;
9729 }
9730
9731 // This is a C++ method declaration.
9733 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9734 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9735 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9736 IsVirtualOkay = !Ret->isStatic();
9737 return Ret;
9738 } else {
9739 bool isFriend =
9740 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9741 if (!isFriend && SemaRef.CurContext->isRecord())
9742 return nullptr;
9743
9744 // Determine whether the function was written with a
9745 // prototype. This true when:
9746 // - we're in C++ (where every function has a prototype),
9747 return FunctionDecl::Create(
9748 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9749 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9750 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9751 }
9752}
9753
9762
9764 // Size dependent types are just typedefs to normal integer types
9765 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9766 // integers other than by their names.
9767 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9768
9769 // Remove typedefs one by one until we reach a typedef
9770 // for a size dependent type.
9771 QualType DesugaredTy = Ty;
9772 do {
9773 ArrayRef<StringRef> Names(SizeTypeNames);
9774 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9775 if (Names.end() != Match)
9776 return true;
9777
9778 Ty = DesugaredTy;
9779 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9780 } while (DesugaredTy != Ty);
9781
9782 return false;
9783}
9784
9786 if (PT->isDependentType())
9787 return InvalidKernelParam;
9788
9789 if (PT->isPointerOrReferenceType()) {
9790 QualType PointeeType = PT->getPointeeType();
9791 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9792 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9793 PointeeType.getAddressSpace() == LangAS::Default)
9795
9796 if (PointeeType->isPointerType()) {
9797 // This is a pointer to pointer parameter.
9798 // Recursively check inner type.
9799 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9800 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9801 ParamKind == InvalidKernelParam)
9802 return ParamKind;
9803
9804 // OpenCL v3.0 s6.11.a:
9805 // A restriction to pass pointers to pointers only applies to OpenCL C
9806 // v1.2 or below.
9808 return ValidKernelParam;
9809
9810 return PtrPtrKernelParam;
9811 }
9812
9813 // C++ for OpenCL v1.0 s2.4:
9814 // Moreover the types used in parameters of the kernel functions must be:
9815 // Standard layout types for pointer parameters. The same applies to
9816 // reference if an implementation supports them in kernel parameters.
9817 if (S.getLangOpts().OpenCLCPlusPlus &&
9819 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9820 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9821 bool IsStandardLayoutType = true;
9822 if (CXXRec) {
9823 // If template type is not ODR-used its definition is only available
9824 // in the template definition not its instantiation.
9825 // FIXME: This logic doesn't work for types that depend on template
9826 // parameter (PR58590).
9827 if (!CXXRec->hasDefinition())
9828 CXXRec = CXXRec->getTemplateInstantiationPattern();
9829 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9830 IsStandardLayoutType = false;
9831 }
9832 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9833 !IsStandardLayoutType)
9834 return InvalidKernelParam;
9835 }
9836
9837 // OpenCL v1.2 s6.9.p:
9838 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9840 return ValidKernelParam;
9841
9842 return PtrKernelParam;
9843 }
9844
9845 // OpenCL v1.2 s6.9.k:
9846 // Arguments to kernel functions in a program cannot be declared with the
9847 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9848 // uintptr_t or a struct and/or union that contain fields declared to be one
9849 // of these built-in scalar types.
9851 return InvalidKernelParam;
9852
9853 if (PT->isImageType())
9854 return PtrKernelParam;
9855
9856 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9857 return InvalidKernelParam;
9858
9859 // OpenCL extension spec v1.2 s9.5:
9860 // This extension adds support for half scalar and vector types as built-in
9861 // types that can be used for arithmetic operations, conversions etc.
9862 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9863 PT->isHalfType())
9864 return InvalidKernelParam;
9865
9866 // Look into an array argument to check if it has a forbidden type.
9867 if (PT->isArrayType()) {
9868 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9869 // Call ourself to check an underlying type of an array. Since the
9870 // getPointeeOrArrayElementType returns an innermost type which is not an
9871 // array, this recursive call only happens once.
9872 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9873 }
9874
9875 // C++ for OpenCL v1.0 s2.4:
9876 // Moreover the types used in parameters of the kernel functions must be:
9877 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9878 // types) for parameters passed by value;
9879 if (S.getLangOpts().OpenCLCPlusPlus &&
9881 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9882 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9883 return InvalidKernelParam;
9884
9885 if (PT->isRecordType())
9886 return RecordKernelParam;
9887
9888 return ValidKernelParam;
9889}
9890
9892 Sema &S,
9893 Declarator &D,
9894 ParmVarDecl *Param,
9895 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9896 QualType PT = Param->getType();
9897
9898 // Cache the valid types we encounter to avoid rechecking structs that are
9899 // used again
9900 if (ValidTypes.count(PT.getTypePtr()))
9901 return;
9902
9903 switch (getOpenCLKernelParameterType(S, PT)) {
9904 case PtrPtrKernelParam:
9905 // OpenCL v3.0 s6.11.a:
9906 // A kernel function argument cannot be declared as a pointer to a pointer
9907 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9908 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9909 D.setInvalidType();
9910 return;
9911
9913 // OpenCL v1.0 s6.5:
9914 // __kernel function arguments declared to be a pointer of a type can point
9915 // to one of the following address spaces only : __global, __local or
9916 // __constant.
9917 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9918 D.setInvalidType();
9919 return;
9920
9921 // OpenCL v1.2 s6.9.k:
9922 // Arguments to kernel functions in a program cannot be declared with the
9923 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9924 // uintptr_t or a struct and/or union that contain fields declared to be
9925 // one of these built-in scalar types.
9926
9927 case InvalidKernelParam:
9928 // OpenCL v1.2 s6.8 n:
9929 // A kernel function argument cannot be declared
9930 // of event_t type.
9931 // Do not diagnose half type since it is diagnosed as invalid argument
9932 // type for any function elsewhere.
9933 if (!PT->isHalfType()) {
9934 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9935
9936 // Explain what typedefs are involved.
9937 const TypedefType *Typedef = nullptr;
9938 while ((Typedef = PT->getAs<TypedefType>())) {
9939 SourceLocation Loc = Typedef->getDecl()->getLocation();
9940 // SourceLocation may be invalid for a built-in type.
9941 if (Loc.isValid())
9942 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9943 PT = Typedef->desugar();
9944 }
9945 }
9946
9947 D.setInvalidType();
9948 return;
9949
9950 case PtrKernelParam:
9951 case ValidKernelParam:
9952 ValidTypes.insert(PT.getTypePtr());
9953 return;
9954
9955 case RecordKernelParam:
9956 break;
9957 }
9958
9959 // Track nested structs we will inspect
9961
9962 // Track where we are in the nested structs. Items will migrate from
9963 // VisitStack to HistoryStack as we do the DFS for bad field.
9965 HistoryStack.push_back(nullptr);
9966
9967 // At this point we already handled everything except of a RecordType.
9968 assert(PT->isRecordType() && "Unexpected type.");
9969 const auto *PD = PT->castAsRecordDecl();
9970 VisitStack.push_back(PD);
9971 assert(VisitStack.back() && "First decl null?");
9972
9973 do {
9974 const Decl *Next = VisitStack.pop_back_val();
9975 if (!Next) {
9976 assert(!HistoryStack.empty());
9977 // Found a marker, we have gone up a level
9978 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9979 ValidTypes.insert(Hist->getType().getTypePtr());
9980
9981 continue;
9982 }
9983
9984 // Adds everything except the original parameter declaration (which is not a
9985 // field itself) to the history stack.
9986 const RecordDecl *RD;
9987 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9988 HistoryStack.push_back(Field);
9989
9990 QualType FieldTy = Field->getType();
9991 // Other field types (known to be valid or invalid) are handled while we
9992 // walk around RecordDecl::fields().
9993 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9994 "Unexpected type.");
9995 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9996
9997 RD = FieldRecTy->castAsRecordDecl();
9998 } else {
9999 RD = cast<RecordDecl>(Next);
10000 }
10001
10002 // Add a null marker so we know when we've gone back up a level
10003 VisitStack.push_back(nullptr);
10004
10005 for (const auto *FD : RD->fields()) {
10006 QualType QT = FD->getType();
10007
10008 if (ValidTypes.count(QT.getTypePtr()))
10009 continue;
10010
10012 if (ParamType == ValidKernelParam)
10013 continue;
10014
10015 if (ParamType == RecordKernelParam) {
10016 VisitStack.push_back(FD);
10017 continue;
10018 }
10019
10020 // OpenCL v1.2 s6.9.p:
10021 // Arguments to kernel functions that are declared to be a struct or union
10022 // do not allow OpenCL objects to be passed as elements of the struct or
10023 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10024 // of SVM.
10025 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10026 ParamType == InvalidAddrSpacePtrKernelParam) {
10027 S.Diag(Param->getLocation(),
10028 diag::err_record_with_pointers_kernel_param)
10029 << PT->isUnionType()
10030 << PT;
10031 } else {
10032 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10033 }
10034
10035 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10036 << PD->getDeclName();
10037
10038 // We have an error, now let's go back up through history and show where
10039 // the offending field came from
10041 I = HistoryStack.begin() + 1,
10042 E = HistoryStack.end();
10043 I != E; ++I) {
10044 const FieldDecl *OuterField = *I;
10045 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10046 << OuterField->getType();
10047 }
10048
10049 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10050 << QT->isPointerType()
10051 << QT;
10052 D.setInvalidType();
10053 return;
10054 }
10055 } while (!VisitStack.empty());
10056}
10057
10058/// Find the DeclContext in which a tag is implicitly declared if we see an
10059/// elaborated type specifier in the specified context, and lookup finds
10060/// nothing.
10062 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10063 DC = DC->getParent();
10064 return DC;
10065}
10066
10067/// Find the Scope in which a tag is implicitly declared if we see an
10068/// elaborated type specifier in the specified context, and lookup finds
10069/// nothing.
10070static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10071 while (S->isClassScope() ||
10072 (LangOpts.CPlusPlus &&
10074 ((S->getFlags() & Scope::DeclScope) == 0) ||
10075 (S->getEntity() && S->getEntity()->isTransparentContext()))
10076 S = S->getParent();
10077 return S;
10078}
10079
10080/// Determine whether a declaration matches a known function in namespace std.
10082 unsigned BuiltinID) {
10083 switch (BuiltinID) {
10084 case Builtin::BI__GetExceptionInfo:
10085 // No type checking whatsoever.
10086 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10087
10088 case Builtin::BIaddressof:
10089 case Builtin::BI__addressof:
10090 case Builtin::BIforward:
10091 case Builtin::BIforward_like:
10092 case Builtin::BImove:
10093 case Builtin::BImove_if_noexcept:
10094 case Builtin::BIas_const: {
10095 // Ensure that we don't treat the algorithm
10096 // OutputIt std::move(InputIt, InputIt, OutputIt)
10097 // as the builtin std::move.
10098 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10099 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10100 }
10101
10102 default:
10103 return false;
10104 }
10105}
10106
10107NamedDecl*
10110 MultiTemplateParamsArg TemplateParamListsRef,
10111 bool &AddToScope) {
10112 QualType R = TInfo->getType();
10113
10114 assert(R->isFunctionType());
10115 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10116 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10117
10118 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10119 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10121 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10122 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10123 TemplateParamLists.back() = Invented;
10124 else
10125 TemplateParamLists.push_back(Invented);
10126 }
10127
10128 // TODO: consider using NameInfo for diagnostic.
10130 DeclarationName Name = NameInfo.getName();
10132
10135 diag::err_invalid_thread)
10137
10142
10143 bool isFriend = false;
10145 bool isMemberSpecialization = false;
10146 bool isFunctionTemplateSpecialization = false;
10147
10148 bool HasExplicitTemplateArgs = false;
10149 TemplateArgumentListInfo TemplateArgs;
10150
10151 bool isVirtualOkay = false;
10152
10153 DeclContext *OriginalDC = DC;
10154 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10155
10156 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10157 isVirtualOkay);
10158 if (!NewFD) return nullptr;
10159
10160 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10162
10163 // Set the lexical context. If this is a function-scope declaration, or has a
10164 // C++ scope specifier, or is the object of a friend declaration, the lexical
10165 // context will be different from the semantic context.
10167
10168 if (IsLocalExternDecl)
10169 NewFD->setLocalExternDecl();
10170
10171 if (getLangOpts().CPlusPlus) {
10172 // The rules for implicit inlines changed in C++20 for methods and friends
10173 // with an in-class definition (when such a definition is not attached to
10174 // the global module). This does not affect declarations that are already
10175 // inline (whether explicitly or implicitly by being declared constexpr,
10176 // consteval, etc).
10177 // FIXME: We need a better way to separate C++ standard and clang modules.
10178 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10179 !NewFD->getOwningModule() ||
10180 NewFD->isFromGlobalModule() ||
10182 bool isInline = D.getDeclSpec().isInlineSpecified();
10183 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10184 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10185 isFriend = D.getDeclSpec().isFriendSpecified();
10186 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10187 // Pre-C++20 [class.friend]p5
10188 // A function can be defined in a friend declaration of a
10189 // class . . . . Such a function is implicitly inline.
10190 // Post C++20 [class.friend]p7
10191 // Such a function is implicitly an inline function if it is attached
10192 // to the global module.
10193 NewFD->setImplicitlyInline();
10194 }
10195
10196 // If this is a method defined in an __interface, and is not a constructor
10197 // or an overloaded operator, then set the pure flag (isVirtual will already
10198 // return true).
10199 if (const CXXRecordDecl *Parent =
10200 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10201 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10202 NewFD->setIsPureVirtual(true);
10203
10204 // C++ [class.union]p2
10205 // A union can have member functions, but not virtual functions.
10206 if (isVirtual && Parent->isUnion()) {
10207 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10208 NewFD->setInvalidDecl();
10209 }
10210 if ((Parent->isClass() || Parent->isStruct()) &&
10211 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10212 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10213 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10214 if (auto *Def = Parent->getDefinition())
10215 Def->setInitMethod(true);
10216 }
10217 }
10218
10219 SetNestedNameSpecifier(*this, NewFD, D);
10220 isMemberSpecialization = false;
10221 isFunctionTemplateSpecialization = false;
10222 if (D.isInvalidType())
10223 NewFD->setInvalidDecl();
10224
10225 // Match up the template parameter lists with the scope specifier, then
10226 // determine whether we have a template or a template specialization.
10227 bool Invalid = false;
10228 TemplateIdAnnotation *TemplateId =
10230 ? D.getName().TemplateId
10231 : nullptr;
10232 TemplateParameterList *TemplateParams =
10235 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10236 isMemberSpecialization, Invalid);
10237 if (TemplateParams) {
10238 // Check that we can declare a template here.
10239 if (CheckTemplateDeclScope(S, TemplateParams))
10240 NewFD->setInvalidDecl();
10241
10242 if (TemplateParams->size() > 0) {
10243 // This is a function template
10244
10245 // A destructor cannot be a template.
10247 Diag(NewFD->getLocation(), diag::err_destructor_template);
10248 NewFD->setInvalidDecl();
10249 // Function template with explicit template arguments.
10250 } else if (TemplateId) {
10251 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10252 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10253 NewFD->setInvalidDecl();
10254 }
10255
10256 // If we're adding a template to a dependent context, we may need to
10257 // rebuilding some of the types used within the template parameter list,
10258 // now that we know what the current instantiation is.
10259 if (DC->isDependentContext()) {
10260 ContextRAII SavedContext(*this, DC);
10262 Invalid = true;
10263 }
10264
10266 NewFD->getLocation(),
10267 Name, TemplateParams,
10268 NewFD);
10269 FunctionTemplate->setLexicalDeclContext(CurContext);
10271
10272 // For source fidelity, store the other template param lists.
10273 if (TemplateParamLists.size() > 1) {
10275 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10276 .drop_back(1));
10277 }
10278 } else {
10279 // This is a function template specialization.
10280 isFunctionTemplateSpecialization = true;
10281 // For source fidelity, store all the template param lists.
10282 if (TemplateParamLists.size() > 0)
10283 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10284
10285 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10286 if (isFriend) {
10287 // We want to remove the "template<>", found here.
10288 SourceRange RemoveRange = TemplateParams->getSourceRange();
10289
10290 // If we remove the template<> and the name is not a
10291 // template-id, we're actually silently creating a problem:
10292 // the friend declaration will refer to an untemplated decl,
10293 // and clearly the user wants a template specialization. So
10294 // we need to insert '<>' after the name.
10295 SourceLocation InsertLoc;
10297 InsertLoc = D.getName().getSourceRange().getEnd();
10298 InsertLoc = getLocForEndOfToken(InsertLoc);
10299 }
10300
10301 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10302 << Name << RemoveRange
10303 << FixItHint::CreateRemoval(RemoveRange)
10304 << FixItHint::CreateInsertion(InsertLoc, "<>");
10305 Invalid = true;
10306
10307 // Recover by faking up an empty template argument list.
10308 HasExplicitTemplateArgs = true;
10309 TemplateArgs.setLAngleLoc(InsertLoc);
10310 TemplateArgs.setRAngleLoc(InsertLoc);
10311 }
10312 }
10313 } else {
10314 // Check that we can declare a template here.
10315 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10316 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10317 NewFD->setInvalidDecl();
10318
10319 // All template param lists were matched against the scope specifier:
10320 // this is NOT (an explicit specialization of) a template.
10321 if (TemplateParamLists.size() > 0)
10322 // For source fidelity, store all the template param lists.
10323 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10324
10325 // "friend void foo<>(int);" is an implicit specialization decl.
10326 if (isFriend && TemplateId)
10327 isFunctionTemplateSpecialization = true;
10328 }
10329
10330 // If this is a function template specialization and the unqualified-id of
10331 // the declarator-id is a template-id, convert the template argument list
10332 // into our AST format and check for unexpanded packs.
10333 if (isFunctionTemplateSpecialization && TemplateId) {
10334 HasExplicitTemplateArgs = true;
10335
10336 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10337 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10338 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10339 TemplateId->NumArgs);
10340 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10341
10342 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10343 // declaration of a function template partial specialization? Should we
10344 // consider the unexpanded pack context to be a partial specialization?
10345 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10347 ArgLoc, isFriend ? UPPC_FriendDeclaration
10349 NewFD->setInvalidDecl();
10350 }
10351 }
10352
10353 if (Invalid) {
10354 NewFD->setInvalidDecl();
10355 if (FunctionTemplate)
10356 FunctionTemplate->setInvalidDecl();
10357 }
10358
10359 // C++ [dcl.fct.spec]p5:
10360 // The virtual specifier shall only be used in declarations of
10361 // nonstatic class member functions that appear within a
10362 // member-specification of a class declaration; see 10.3.
10363 //
10364 if (isVirtual && !NewFD->isInvalidDecl()) {
10365 if (!isVirtualOkay) {
10367 diag::err_virtual_non_function);
10368 } else if (!CurContext->isRecord()) {
10369 // 'virtual' was specified outside of the class.
10371 diag::err_virtual_out_of_class)
10373 } else if (NewFD->getDescribedFunctionTemplate()) {
10374 // C++ [temp.mem]p3:
10375 // A member function template shall not be virtual.
10377 diag::err_virtual_member_function_template)
10379 } else {
10380 // Okay: Add virtual to the method.
10381 NewFD->setVirtualAsWritten(true);
10382 }
10383
10384 if (getLangOpts().CPlusPlus14 &&
10385 NewFD->getReturnType()->isUndeducedType())
10386 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10387 }
10388
10389 // C++ [dcl.fct.spec]p3:
10390 // The inline specifier shall not appear on a block scope function
10391 // declaration.
10392 if (isInline && !NewFD->isInvalidDecl()) {
10393 if (CurContext->isFunctionOrMethod()) {
10394 // 'inline' is not allowed on block scope function declaration.
10396 diag::err_inline_declaration_block_scope) << Name
10398 }
10399 }
10400
10401 // C++ [dcl.fct.spec]p6:
10402 // The explicit specifier shall be used only in the declaration of a
10403 // constructor or conversion function within its class definition;
10404 // see 12.3.1 and 12.3.2.
10405 if (hasExplicit && !NewFD->isInvalidDecl() &&
10407 if (!CurContext->isRecord()) {
10408 // 'explicit' was specified outside of the class.
10410 diag::err_explicit_out_of_class)
10412 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10413 !isa<CXXConversionDecl>(NewFD)) {
10414 // 'explicit' was specified on a function that wasn't a constructor
10415 // or conversion function.
10417 diag::err_explicit_non_ctor_or_conv_function)
10419 }
10420 }
10421
10423 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10424 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10425 // are implicitly inline.
10426 NewFD->setImplicitlyInline();
10427
10428 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10429 // be either constructors or to return a literal type. Therefore,
10430 // destructors cannot be declared constexpr.
10431 if (isa<CXXDestructorDecl>(NewFD) &&
10433 ConstexprKind == ConstexprSpecKind::Consteval)) {
10434 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10435 << static_cast<int>(ConstexprKind);
10439 }
10440 // C++20 [dcl.constexpr]p2: An allocation function, or a
10441 // deallocation function shall not be declared with the consteval
10442 // specifier.
10443 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10446 diag::err_invalid_consteval_decl_kind)
10447 << NewFD;
10449 }
10450 }
10451
10452 // If __module_private__ was specified, mark the function accordingly.
10454 if (isFunctionTemplateSpecialization) {
10455 SourceLocation ModulePrivateLoc
10457 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10458 << 0
10459 << FixItHint::CreateRemoval(ModulePrivateLoc);
10460 } else {
10461 NewFD->setModulePrivate();
10462 if (FunctionTemplate)
10463 FunctionTemplate->setModulePrivate();
10464 }
10465 }
10466
10467 if (isFriend) {
10468 if (FunctionTemplate) {
10469 FunctionTemplate->setObjectOfFriendDecl();
10470 FunctionTemplate->setAccess(AS_public);
10471 }
10472 NewFD->setObjectOfFriendDecl();
10473 NewFD->setAccess(AS_public);
10474 }
10475
10476 // If a function is defined as defaulted or deleted, mark it as such now.
10477 // We'll do the relevant checks on defaulted / deleted functions later.
10478 switch (D.getFunctionDefinitionKind()) {
10481 break;
10482
10484 NewFD->setDefaulted();
10485 break;
10486
10488 NewFD->setDeletedAsWritten();
10489 break;
10490 }
10491
10492 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10494 // Pre C++20 [class.mfct]p2:
10495 // A member function may be defined (8.4) in its class definition, in
10496 // which case it is an inline member function (7.1.2)
10497 // Post C++20 [class.mfct]p1:
10498 // If a member function is attached to the global module and is defined
10499 // in its class definition, it is inline.
10500 NewFD->setImplicitlyInline();
10501 }
10502
10503 if (!isFriend && SC != SC_None) {
10504 // C++ [temp.expl.spec]p2:
10505 // The declaration in an explicit-specialization shall not be an
10506 // export-declaration. An explicit specialization shall not use a
10507 // storage-class-specifier other than thread_local.
10508 //
10509 // We diagnose friend declarations with storage-class-specifiers
10510 // elsewhere.
10511 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10513 diag::ext_explicit_specialization_storage_class)
10516 }
10517
10518 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10519 assert(isa<CXXMethodDecl>(NewFD) &&
10520 "Out-of-line member function should be a CXXMethodDecl");
10521 // C++ [class.static]p1:
10522 // A data or function member of a class may be declared static
10523 // in a class definition, in which case it is a static member of
10524 // the class.
10525
10526 // Complain about the 'static' specifier if it's on an out-of-line
10527 // member function definition.
10528
10529 // MSVC permits the use of a 'static' storage specifier on an
10530 // out-of-line member function template declaration and class member
10531 // template declaration (MSVC versions before 2015), warn about this.
10533 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10534 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10535 (getLangOpts().MSVCCompat &&
10537 ? diag::ext_static_out_of_line
10538 : diag::err_static_out_of_line)
10541 }
10542 }
10543
10544 // C++11 [except.spec]p15:
10545 // A deallocation function with no exception-specification is treated
10546 // as if it were specified with noexcept(true).
10547 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10548 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10549 !FPT->hasExceptionSpec())
10550 NewFD->setType(Context.getFunctionType(
10551 FPT->getReturnType(), FPT->getParamTypes(),
10553
10554 // C++20 [dcl.inline]/7
10555 // If an inline function or variable that is attached to a named module
10556 // is declared in a definition domain, it shall be defined in that
10557 // domain.
10558 // So, if the current declaration does not have a definition, we must
10559 // check at the end of the TU (or when the PMF starts) to see that we
10560 // have a definition at that point.
10561 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10562 NewFD->isInNamedModule()) {
10563 PendingInlineFuncDecls.insert(NewFD);
10564 }
10565 }
10566
10567 // Filter out previous declarations that don't match the scope.
10570 isMemberSpecialization ||
10571 isFunctionTemplateSpecialization);
10572
10574
10575 // Handle GNU asm-label extension (encoded as an attribute).
10576 if (Expr *E = D.getAsmLabel()) {
10577 // The parser guarantees this is a string.
10579 NewFD->addAttr(
10580 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10581 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10582 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10584 if (I != ExtnameUndeclaredIdentifiers.end()) {
10585 if (isDeclExternC(NewFD)) {
10586 NewFD->addAttr(I->second);
10588 } else if (NewFD->getDeclContext()
10591 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10592 << /*Variable*/0 << NewFD;
10593 }
10594 }
10595
10596 // Copy the parameter declarations from the declarator D to the function
10597 // declaration NewFD, if they are available. First scavenge them into Params.
10599 unsigned FTIIdx;
10600 if (D.isFunctionDeclarator(FTIIdx)) {
10602
10603 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10604 // function that takes no arguments, not a function that takes a
10605 // single void argument.
10606 // We let through "const void" here because Sema::GetTypeForDeclarator
10607 // already checks for that case.
10608 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10609 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10610 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10611 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10612 Param->setDeclContext(NewFD);
10613 Params.push_back(Param);
10614
10615 if (Param->isInvalidDecl())
10616 NewFD->setInvalidDecl();
10617 }
10618 }
10619
10620 if (!getLangOpts().CPlusPlus) {
10621 // In C, find all the tag declarations from the prototype and move them
10622 // into the function DeclContext. Remove them from the surrounding tag
10623 // injection context of the function, which is typically but not always
10624 // the TU.
10625 DeclContext *PrototypeTagContext =
10627 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10628 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10629
10630 // We don't want to reparent enumerators. Look at their parent enum
10631 // instead.
10632 if (!TD) {
10633 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10634 TD = cast<EnumDecl>(ECD->getDeclContext());
10635 }
10636 if (!TD)
10637 continue;
10638 DeclContext *TagDC = TD->getLexicalDeclContext();
10639 if (!TagDC->containsDecl(TD))
10640 continue;
10641 TagDC->removeDecl(TD);
10642 TD->setDeclContext(NewFD);
10643 NewFD->addDecl(TD);
10644
10645 // Preserve the lexical DeclContext if it is not the surrounding tag
10646 // injection context of the FD. In this example, the semantic context of
10647 // E will be f and the lexical context will be S, while both the
10648 // semantic and lexical contexts of S will be f:
10649 // void f(struct S { enum E { a } f; } s);
10650 if (TagDC != PrototypeTagContext)
10651 TD->setLexicalDeclContext(TagDC);
10652 }
10653 }
10654 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10655 // When we're declaring a function with a typedef, typeof, etc as in the
10656 // following example, we'll need to synthesize (unnamed)
10657 // parameters for use in the declaration.
10658 //
10659 // @code
10660 // typedef void fn(int);
10661 // fn f;
10662 // @endcode
10663
10664 // Synthesize a parameter for each argument type.
10665 for (const auto &AI : FT->param_types()) {
10666 ParmVarDecl *Param =
10668 Param->setScopeInfo(0, Params.size());
10669 Params.push_back(Param);
10670 }
10671 } else {
10672 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10673 "Should not need args for typedef of non-prototype fn");
10674 }
10675
10676 // Finally, we know we have the right number of parameters, install them.
10677 NewFD->setParams(Params);
10678
10679 // If this declarator is a declaration and not a definition, its parameters
10680 // will not be pushed onto a scope chain. That means we will not issue any
10681 // reserved identifier warnings for the declaration, but we will for the
10682 // definition. Handle those here.
10683 if (!D.isFunctionDefinition()) {
10684 for (const ParmVarDecl *PVD : Params)
10686 }
10687
10689 NewFD->addAttr(
10690 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10691
10692 // Functions returning a variably modified type violate C99 6.7.5.2p2
10693 // because all functions have linkage.
10694 if (!NewFD->isInvalidDecl() &&
10696 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10697 NewFD->setInvalidDecl();
10698 }
10699
10700 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10702 !NewFD->hasAttr<SectionAttr>())
10703 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10704 Context, PragmaClangTextSection.SectionName,
10705 PragmaClangTextSection.PragmaLocation));
10706
10707 // Apply an implicit SectionAttr if #pragma code_seg is active.
10708 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10709 !NewFD->hasAttr<SectionAttr>()) {
10710 NewFD->addAttr(SectionAttr::CreateImplicit(
10711 Context, CodeSegStack.CurrentValue->getString(),
10712 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10713 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10716 NewFD))
10717 NewFD->dropAttr<SectionAttr>();
10718 }
10719
10720 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10721 // active.
10722 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10723 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10724 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10725 Context, PragmaClangTextSection.PragmaLocation));
10726
10727 // Apply an implicit CodeSegAttr from class declspec or
10728 // apply an implicit SectionAttr from #pragma code_seg if active.
10729 if (!NewFD->hasAttr<CodeSegAttr>()) {
10731 D.isFunctionDefinition())) {
10732 NewFD->addAttr(SAttr);
10733 }
10734 }
10735
10736 // Handle attributes.
10737 ProcessDeclAttributes(S, NewFD, D);
10738 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10739 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10740 !NewTVA->isDefaultVersion() &&
10741 !Context.getTargetInfo().hasFeature("fmv")) {
10742 // Don't add to scope fmv functions declarations if fmv disabled
10743 AddToScope = false;
10744 return NewFD;
10745 }
10746
10747 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10748 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10749 // type.
10750 //
10751 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10752 // type declaration will generate a compilation error.
10753 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10754 if (AddressSpace != LangAS::Default) {
10755 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10756 NewFD->setInvalidDecl();
10757 }
10758 }
10759
10760 if (!getLangOpts().CPlusPlus) {
10761 // Perform semantic checking on the function declaration.
10762 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10763 CheckMain(NewFD, D.getDeclSpec());
10764
10765 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10766 CheckMSVCRTEntryPoint(NewFD);
10767
10768 if (!NewFD->isInvalidDecl())
10770 isMemberSpecialization,
10772 else if (!Previous.empty())
10773 // Recover gracefully from an invalid redeclaration.
10774 D.setRedeclaration(true);
10775 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10776 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10777 "previous declaration set still overloaded");
10778
10779 // Diagnose no-prototype function declarations with calling conventions that
10780 // don't support variadic calls. Only do this in C and do it after merging
10781 // possibly prototyped redeclarations.
10782 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10784 CallingConv CC = FT->getExtInfo().getCC();
10785 if (!supportsVariadicCall(CC)) {
10786 // Windows system headers sometimes accidentally use stdcall without
10787 // (void) parameters, so we relax this to a warning.
10788 int DiagID =
10789 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10790 Diag(NewFD->getLocation(), DiagID)
10792 }
10793 }
10794
10798 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10800 } else {
10801 // C++11 [replacement.functions]p3:
10802 // The program's definitions shall not be specified as inline.
10803 //
10804 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10805 //
10806 // Suppress the diagnostic if the function is __attribute__((used)), since
10807 // that forces an external definition to be emitted.
10808 if (D.getDeclSpec().isInlineSpecified() &&
10810 !NewFD->hasAttr<UsedAttr>())
10812 diag::ext_operator_new_delete_declared_inline)
10813 << NewFD->getDeclName();
10814
10815 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10816 // C++20 [dcl.decl.general]p4:
10817 // The optional requires-clause in an init-declarator or
10818 // member-declarator shall be present only if the declarator declares a
10819 // templated function.
10820 //
10821 // C++20 [temp.pre]p8:
10822 // An entity is templated if it is
10823 // - a template,
10824 // - an entity defined or created in a templated entity,
10825 // - a member of a templated entity,
10826 // - an enumerator for an enumeration that is a templated entity, or
10827 // - the closure type of a lambda-expression appearing in the
10828 // declaration of a templated entity.
10829 //
10830 // [Note 6: A local class, a local or block variable, or a friend
10831 // function defined in a templated entity is a templated entity.
10832 // — end note]
10833 //
10834 // A templated function is a function template or a function that is
10835 // templated. A templated class is a class template or a class that is
10836 // templated. A templated variable is a variable template or a variable
10837 // that is templated.
10838 if (!FunctionTemplate) {
10839 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10840 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10841 // An explicit specialization shall not have a trailing
10842 // requires-clause unless it declares a function template.
10843 //
10844 // Since a friend function template specialization cannot be
10845 // definition, and since a non-template friend declaration with a
10846 // trailing requires-clause must be a definition, we diagnose
10847 // friend function template specializations with trailing
10848 // requires-clauses on the same path as explicit specializations
10849 // even though they aren't necessarily prohibited by the same
10850 // language rule.
10851 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10852 << isFriend;
10853 } else if (isFriend && NewFD->isTemplated() &&
10854 !D.isFunctionDefinition()) {
10855 // C++ [temp.friend]p9:
10856 // A non-template friend declaration with a requires-clause shall be
10857 // a definition.
10858 Diag(NewFD->getBeginLoc(),
10859 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10860 NewFD->setInvalidDecl();
10861 } else if (!NewFD->isTemplated() ||
10862 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10863 Diag(TRC->getBeginLoc(),
10864 diag::err_constrained_non_templated_function);
10865 }
10866 }
10867 }
10868
10869 // We do not add HD attributes to specializations here because
10870 // they may have different constexpr-ness compared to their
10871 // templates and, after maybeAddHostDeviceAttrs() is applied,
10872 // may end up with different effective targets. Instead, a
10873 // specialization inherits its target attributes from its template
10874 // in the CheckFunctionTemplateSpecialization() call below.
10875 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10877
10878 // Handle explicit specializations of function templates
10879 // and friend function declarations with an explicit
10880 // template argument list.
10881 if (isFunctionTemplateSpecialization) {
10882 bool isDependentSpecialization = false;
10883 if (isFriend) {
10884 // For friend function specializations, this is a dependent
10885 // specialization if its semantic context is dependent, its
10886 // type is dependent, or if its template-id is dependent.
10887 isDependentSpecialization =
10888 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10889 (HasExplicitTemplateArgs &&
10890 TemplateSpecializationType::
10891 anyInstantiationDependentTemplateArguments(
10892 TemplateArgs.arguments()));
10893 assert((!isDependentSpecialization ||
10894 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10895 "dependent friend function specialization without template "
10896 "args");
10897 } else {
10898 // For class-scope explicit specializations of function templates,
10899 // if the lexical context is dependent, then the specialization
10900 // is dependent.
10901 isDependentSpecialization =
10902 CurContext->isRecord() && CurContext->isDependentContext();
10903 }
10904
10905 TemplateArgumentListInfo *ExplicitTemplateArgs =
10906 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10907 if (isDependentSpecialization) {
10908 // If it's a dependent specialization, it may not be possible
10909 // to determine the primary template (for explicit specializations)
10910 // or befriended declaration (for friends) until the enclosing
10911 // template is instantiated. In such cases, we store the declarations
10912 // found by name lookup and defer resolution until instantiation.
10914 NewFD, ExplicitTemplateArgs, Previous))
10915 NewFD->setInvalidDecl();
10916 } else if (!NewFD->isInvalidDecl()) {
10917 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10918 Previous))
10919 NewFD->setInvalidDecl();
10920 }
10921 } else if (isMemberSpecialization && !FunctionTemplate) {
10923 NewFD->setInvalidDecl();
10924 }
10925
10926 // Perform semantic checking on the function declaration.
10927 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10928 CheckMain(NewFD, D.getDeclSpec());
10929
10930 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10931 CheckMSVCRTEntryPoint(NewFD);
10932
10933 if (!NewFD->isInvalidDecl())
10935 isMemberSpecialization,
10937 else if (!Previous.empty())
10938 // Recover gracefully from an invalid redeclaration.
10939 D.setRedeclaration(true);
10940
10941 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10942 !D.isRedeclaration() ||
10943 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10944 "previous declaration set still overloaded");
10945
10946 NamedDecl *PrincipalDecl = (FunctionTemplate
10948 : NewFD);
10949
10950 if (isFriend && NewFD->getPreviousDecl()) {
10951 AccessSpecifier Access = AS_public;
10952 if (!NewFD->isInvalidDecl())
10953 Access = NewFD->getPreviousDecl()->getAccess();
10954
10955 NewFD->setAccess(Access);
10956 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10957 }
10958
10959 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10961 PrincipalDecl->setNonMemberOperator();
10962
10963 // If we have a function template, check the template parameter
10964 // list. This will check and merge default template arguments.
10965 if (FunctionTemplate) {
10966 FunctionTemplateDecl *PrevTemplate =
10967 FunctionTemplate->getPreviousDecl();
10968 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10969 PrevTemplate ? PrevTemplate->getTemplateParameters()
10970 : nullptr,
10975 : (D.getCXXScopeSpec().isSet() &&
10976 DC && DC->isRecord() &&
10977 DC->isDependentContext())
10980 }
10981
10982 if (NewFD->isInvalidDecl()) {
10983 // Ignore all the rest of this.
10984 } else if (!D.isRedeclaration()) {
10985 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10986 AddToScope };
10987 // Fake up an access specifier if it's supposed to be a class member.
10988 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10989 NewFD->setAccess(AS_public);
10990
10991 // Qualified decls generally require a previous declaration.
10992 if (D.getCXXScopeSpec().isSet()) {
10993 // ...with the major exception of templated-scope or
10994 // dependent-scope friend declarations.
10995
10996 // TODO: we currently also suppress this check in dependent
10997 // contexts because (1) the parameter depth will be off when
10998 // matching friend templates and (2) we might actually be
10999 // selecting a friend based on a dependent factor. But there
11000 // are situations where these conditions don't apply and we
11001 // can actually do this check immediately.
11002 //
11003 // Unless the scope is dependent, it's always an error if qualified
11004 // redeclaration lookup found nothing at all. Diagnose that now;
11005 // nothing will diagnose that error later.
11006 if (isFriend &&
11008 (!Previous.empty() && CurContext->isDependentContext()))) {
11009 // ignore these
11010 } else if (NewFD->isCPUDispatchMultiVersion() ||
11011 NewFD->isCPUSpecificMultiVersion()) {
11012 // ignore this, we allow the redeclaration behavior here to create new
11013 // versions of the function.
11014 } else {
11015 // The user tried to provide an out-of-line definition for a
11016 // function that is a member of a class or namespace, but there
11017 // was no such member function declared (C++ [class.mfct]p2,
11018 // C++ [namespace.memdef]p2). For example:
11019 //
11020 // class X {
11021 // void f() const;
11022 // };
11023 //
11024 // void X::f() { } // ill-formed
11025 //
11026 // Complain about this problem, and attempt to suggest close
11027 // matches (e.g., those that differ only in cv-qualifiers and
11028 // whether the parameter types are references).
11029
11031 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
11032 AddToScope = ExtraArgs.AddToScope;
11033 return Result;
11034 }
11035 }
11036
11037 // Unqualified local friend declarations are required to resolve
11038 // to something.
11039 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11041 *this, Previous, NewFD, ExtraArgs, true, S)) {
11042 AddToScope = ExtraArgs.AddToScope;
11043 return Result;
11044 }
11045 }
11046 } else if (!D.isFunctionDefinition() &&
11047 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11048 !isFriend && !isFunctionTemplateSpecialization &&
11049 !isMemberSpecialization) {
11050 // An out-of-line member function declaration must also be a
11051 // definition (C++ [class.mfct]p2).
11052 // Note that this is not the case for explicit specializations of
11053 // function templates or member functions of class templates, per
11054 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11055 // extension for compatibility with old SWIG code which likes to
11056 // generate them.
11057 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11058 << D.getCXXScopeSpec().getRange();
11059 }
11060 }
11061
11062 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11063 // Any top level function could potentially be specified as an entry.
11064 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11065 HLSL().ActOnTopLevelFunction(NewFD);
11066
11067 if (NewFD->hasAttr<HLSLShaderAttr>())
11068 HLSL().CheckEntryPoint(NewFD);
11069
11070 // Resources cannot be passed to functions that are not inlined.
11071 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11072 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11073 QualType ParamTy = PVD->getType().getNonReferenceType();
11074 QualType EltTy = Context.getBaseElementType(ParamTy);
11075 // `isCompleteType` forces completion of the element type without
11076 // reporting an error (diagnosed elsewhere) so the resource parameter
11077 // check is valid.
11078 if (!EltTy->isDependentType() &&
11079 isCompleteType(PVD->getLocation(), EltTy) &&
11080 ParamTy->isHLSLIntangibleType()) {
11081 Diag(PVD->getLocation(),
11082 diag::err_hlsl_resource_param_in_noinline_function)
11083 << ParamTy;
11084 Diag(NoInline->getLocation(), diag::note_attribute);
11085 }
11086 }
11087 }
11088 }
11089
11090 // If this is the first declaration of a library builtin function, add
11091 // attributes as appropriate.
11092 if (!D.isRedeclaration()) {
11093 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11094 if (unsigned BuiltinID = II->getBuiltinID()) {
11095 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11096 if (!InStdNamespace &&
11098 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11099 // Validate the type matches unless this builtin is specified as
11100 // matching regardless of its declared type.
11101 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11102 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11103 } else {
11105 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11106 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11107
11108 if (!Error && !BuiltinType.isNull() &&
11109 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11110 NewFD->getType(), BuiltinType))
11111 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11112 }
11113 }
11114 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11115 isStdBuiltin(Context, NewFD, BuiltinID)) {
11116 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11117 }
11118 }
11119 }
11120 }
11121
11122 ProcessPragmaWeak(S, NewFD);
11123 ProcessPragmaExport(NewFD);
11124 checkAttributesAfterMerging(*this, *NewFD);
11125
11127 // The above can add the format attribute for known builtin/library functions
11128 // which is required by the modular_format attribute, thus
11129 // validate modular_format now after those attributes have been added.
11130 checkModularFormatAttr(*this, *NewFD);
11131
11132 if (NewFD->hasAttr<OverloadableAttr>() &&
11133 !NewFD->getType()->getAs<FunctionProtoType>()) {
11134 Diag(NewFD->getLocation(),
11135 diag::err_attribute_overloadable_no_prototype)
11136 << NewFD;
11137 NewFD->dropAttr<OverloadableAttr>();
11138 }
11139
11140 // If there's a #pragma GCC visibility in scope, and this isn't a class
11141 // member, set the visibility of this function.
11142 if (!DC->isRecord() && NewFD->isExternallyVisible())
11144
11145 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11146 // marking the function.
11147 ObjC().AddCFAuditedAttribute(NewFD);
11148
11149 // If this is a function definition, check if we have to apply any
11150 // attributes (i.e. optnone and no_builtin) due to a pragma.
11151 if (D.isFunctionDefinition()) {
11152 AddRangeBasedOptnone(NewFD);
11154 AddSectionMSAllocText(NewFD);
11156 }
11157
11158 // If this is the first declaration of an extern C variable, update
11159 // the map of such variables.
11160 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11161 isIncompleteDeclExternC(*this, NewFD))
11163
11164 // Set this FunctionDecl's range up to the right paren.
11165 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11166
11167 if (D.isRedeclaration() && !Previous.empty()) {
11168 NamedDecl *Prev = Previous.getRepresentativeDecl();
11169 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11170 isMemberSpecialization ||
11171 isFunctionTemplateSpecialization,
11173 }
11174
11175 if (getLangOpts().CUDA) {
11176 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11177 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11179 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11180 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11182 Context.setcudaConfigureCallDecl(NewFD);
11183 }
11184 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11185 !NewFD->isInvalidDecl() &&
11187 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11188 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11190 Context.setcudaGetParameterBufferDecl(NewFD);
11191 }
11192 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11193 !NewFD->isInvalidDecl() &&
11195 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11196 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11198 Context.setcudaLaunchDeviceDecl(NewFD);
11199 }
11200 }
11201 }
11202
11204
11205 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11206 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11207 if (SC == SC_Static) {
11208 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11209 D.setInvalidType();
11210 }
11211
11212 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11213 if (!NewFD->getReturnType()->isVoidType()) {
11214 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11215 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11216 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11217 : FixItHint());
11218 D.setInvalidType();
11219 }
11220
11222 for (auto *Param : NewFD->parameters())
11223 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11224
11225 if (getLangOpts().OpenCLCPlusPlus) {
11226 if (DC->isRecord()) {
11227 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11228 D.setInvalidType();
11229 }
11230 if (FunctionTemplate) {
11231 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11232 D.setInvalidType();
11233 }
11234 }
11235 }
11236
11237 if (getLangOpts().CPlusPlus) {
11238 // Precalculate whether this is a friend function template with a constraint
11239 // that depends on an enclosing template, per [temp.friend]p9.
11240 if (isFriend && FunctionTemplate &&
11243
11244 // C++ [temp.friend]p9:
11245 // A friend function template with a constraint that depends on a
11246 // template parameter from an enclosing template shall be a definition.
11247 if (!D.isFunctionDefinition()) {
11248 Diag(NewFD->getBeginLoc(),
11249 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11250 NewFD->setInvalidDecl();
11251 }
11252 }
11253
11254 if (FunctionTemplate) {
11255 if (NewFD->isInvalidDecl())
11256 FunctionTemplate->setInvalidDecl();
11257 return FunctionTemplate;
11258 }
11259
11260 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11262 }
11263
11264 for (const ParmVarDecl *Param : NewFD->parameters()) {
11265 QualType PT = Param->getType();
11266
11267 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11268 // types.
11269 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11270 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11271 QualType ElemTy = PipeTy->getElementType();
11272 if (ElemTy->isPointerOrReferenceType()) {
11273 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11274 D.setInvalidType();
11275 }
11276 }
11277 }
11278 // WebAssembly tables can't be used as function parameters.
11279 if (Context.getTargetInfo().getTriple().isWasm()) {
11281 Diag(Param->getTypeSpecStartLoc(),
11282 diag::err_wasm_table_as_function_parameter);
11283 D.setInvalidType();
11284 }
11285 }
11286 }
11287
11288 // Diagnose availability attributes. Availability cannot be used on functions
11289 // that are run during load/unload.
11290 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11291 if (NewFD->hasAttr<ConstructorAttr>()) {
11292 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11293 << 1;
11294 NewFD->dropAttr<AvailabilityAttr>();
11295 }
11296 if (NewFD->hasAttr<DestructorAttr>()) {
11297 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11298 << 2;
11299 NewFD->dropAttr<AvailabilityAttr>();
11300 }
11301 }
11302
11303 // Diagnose no_builtin attribute on function declaration that are not a
11304 // definition.
11305 // FIXME: We should really be doing this in
11306 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11307 // the FunctionDecl and at this point of the code
11308 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11309 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11310 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11311 switch (D.getFunctionDefinitionKind()) {
11314 Diag(NBA->getLocation(),
11315 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11316 << NBA->getSpelling();
11317 break;
11319 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11320 << NBA->getSpelling();
11321 break;
11323 break;
11324 }
11325
11326 // Similar to no_builtin logic above, at this point of the code
11327 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11328 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11329 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11330 !NewFD->isInvalidDecl() &&
11332 ExternalDeclarations.push_back(NewFD);
11333
11334 // Used for a warning on the 'next' declaration when used with a
11335 // `routine(name)`.
11336 if (getLangOpts().OpenACC)
11338
11339 return NewFD;
11340}
11341
11342/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11343/// when __declspec(code_seg) "is applied to a class, all member functions of
11344/// the class and nested classes -- this includes compiler-generated special
11345/// member functions -- are put in the specified segment."
11346/// The actual behavior is a little more complicated. The Microsoft compiler
11347/// won't check outer classes if there is an active value from #pragma code_seg.
11348/// The CodeSeg is always applied from the direct parent but only from outer
11349/// classes when the #pragma code_seg stack is empty. See:
11350/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11351/// available since MS has removed the page.
11353 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11354 if (!Method)
11355 return nullptr;
11356 const CXXRecordDecl *Parent = Method->getParent();
11357 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11358 Attr *NewAttr = SAttr->clone(S.getASTContext());
11359 NewAttr->setImplicit(true);
11360 return NewAttr;
11361 }
11362
11363 // The Microsoft compiler won't check outer classes for the CodeSeg
11364 // when the #pragma code_seg stack is active.
11365 if (S.CodeSegStack.CurrentValue)
11366 return nullptr;
11367
11368 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11369 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11370 Attr *NewAttr = SAttr->clone(S.getASTContext());
11371 NewAttr->setImplicit(true);
11372 return NewAttr;
11373 }
11374 }
11375 return nullptr;
11376}
11377
11379 bool IsDefinition) {
11380 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11381 return A;
11382 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11383 CodeSegStack.CurrentValue)
11384 return SectionAttr::CreateImplicit(
11385 getASTContext(), CodeSegStack.CurrentValue->getString(),
11386 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11387 return nullptr;
11388}
11389
11391 QualType NewT, QualType OldT) {
11393 return true;
11394
11395 // For dependently-typed local extern declarations and friends, we can't
11396 // perform a correct type check in general until instantiation:
11397 //
11398 // int f();
11399 // template<typename T> void g() { T f(); }
11400 //
11401 // (valid if g() is only instantiated with T = int).
11402 if (NewT->isDependentType() &&
11403 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11404 return false;
11405
11406 // Similarly, if the previous declaration was a dependent local extern
11407 // declaration, we don't really know its type yet.
11408 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11409 return false;
11410
11411 return true;
11412}
11413
11416 return true;
11417
11418 // Don't chain dependent friend function definitions until instantiation, to
11419 // permit cases like
11420 //
11421 // void func();
11422 // template<typename T> class C1 { friend void func() {} };
11423 // template<typename T> class C2 { friend void func() {} };
11424 //
11425 // ... which is valid if only one of C1 and C2 is ever instantiated.
11426 //
11427 // FIXME: This need only apply to function definitions. For now, we proxy
11428 // this by checking for a file-scope function. We do not want this to apply
11429 // to friend declarations nominating member functions, because that gets in
11430 // the way of access checks.
11432 return false;
11433
11434 auto *VD = dyn_cast<ValueDecl>(D);
11435 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11436 return !VD || !PrevVD ||
11437 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11438 PrevVD->getType());
11439}
11440
11441/// Check the target or target_version attribute of the function for
11442/// MultiVersion validity.
11443///
11444/// Returns true if there was an error, false otherwise.
11445static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11446 const auto *TA = FD->getAttr<TargetAttr>();
11447 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11448
11449 assert((TA || TVA) && "Expecting target or target_version attribute");
11450
11452 enum ErrType { Feature = 0, Architecture = 1 };
11453
11454 if (TA) {
11455 ParsedTargetAttr ParseInfo =
11456 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11457 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11458 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11459 << Architecture << ParseInfo.CPU;
11460 return true;
11461 }
11462 for (const auto &Feat : ParseInfo.Features) {
11463 auto BareFeat = StringRef{Feat}.substr(1);
11464 if (Feat[0] == '-') {
11465 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11466 << Feature << ("no-" + BareFeat);
11467 return true;
11468 }
11469
11470 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11471 !TargetInfo.isValidFeatureName(BareFeat) ||
11472 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11473 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11474 << Feature << BareFeat;
11475 return true;
11476 }
11477 }
11478 }
11479
11480 if (TVA) {
11482 ParsedTargetAttr ParseInfo;
11483 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11484 ParseInfo =
11485 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11486 for (auto &Feat : ParseInfo.Features)
11487 Feats.push_back(StringRef{Feat}.substr(1));
11488 } else {
11489 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11490 TVA->getFeatures(Feats);
11491 }
11492 for (const auto &Feat : Feats) {
11493 if (!TargetInfo.validateCpuSupports(Feat)) {
11494 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11495 << Feature << Feat;
11496 return true;
11497 }
11498 }
11499 }
11500 return false;
11501}
11502
11503// Provide a white-list of attributes that are allowed to be combined with
11504// multiversion functions.
11506 MultiVersionKind MVKind) {
11507 // Note: this list/diagnosis must match the list in
11508 // checkMultiversionAttributesAllSame.
11509 switch (Kind) {
11510 default:
11511 return false;
11512 case attr::ArmLocallyStreaming:
11513 return MVKind == MultiVersionKind::TargetVersion ||
11515 case attr::Used:
11516 return MVKind == MultiVersionKind::Target;
11517 case attr::NonNull:
11518 case attr::NoThrow:
11519 return true;
11520 }
11521}
11522
11524 const FunctionDecl *FD,
11525 const FunctionDecl *CausedFD,
11526 MultiVersionKind MVKind) {
11527 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11528 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11529 << static_cast<unsigned>(MVKind) << A;
11530 if (CausedFD)
11531 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11532 return true;
11533 };
11534
11535 for (const Attr *A : FD->attrs()) {
11536 switch (A->getKind()) {
11537 case attr::CPUDispatch:
11538 case attr::CPUSpecific:
11539 if (MVKind != MultiVersionKind::CPUDispatch &&
11541 return Diagnose(S, A);
11542 break;
11543 case attr::Target:
11544 if (MVKind != MultiVersionKind::Target)
11545 return Diagnose(S, A);
11546 break;
11547 case attr::TargetVersion:
11548 if (MVKind != MultiVersionKind::TargetVersion &&
11550 return Diagnose(S, A);
11551 break;
11552 case attr::TargetClones:
11553 if (MVKind != MultiVersionKind::TargetClones &&
11555 return Diagnose(S, A);
11556 break;
11557 default:
11558 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11559 return Diagnose(S, A);
11560 break;
11561 }
11562 }
11563 return false;
11564}
11565
11567 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11568 const PartialDiagnostic &NoProtoDiagID,
11569 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11570 const PartialDiagnosticAt &NoSupportDiagIDAt,
11571 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11572 bool ConstexprSupported, bool CLinkageMayDiffer) {
11573 enum DoesntSupport {
11574 FuncTemplates = 0,
11575 VirtFuncs = 1,
11576 DeducedReturn = 2,
11577 Constructors = 3,
11578 Destructors = 4,
11579 DeletedFuncs = 5,
11580 DefaultedFuncs = 6,
11581 ConstexprFuncs = 7,
11582 ConstevalFuncs = 8,
11583 Lambda = 9,
11584 };
11585 enum Different {
11586 CallingConv = 0,
11587 ReturnType = 1,
11588 ConstexprSpec = 2,
11589 InlineSpec = 3,
11590 Linkage = 4,
11591 LanguageLinkage = 5,
11592 };
11593
11594 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11595 !OldFD->getType()->getAs<FunctionProtoType>()) {
11596 Diag(OldFD->getLocation(), NoProtoDiagID);
11597 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11598 return true;
11599 }
11600
11601 if (NoProtoDiagID.getDiagID() != 0 &&
11602 !NewFD->getType()->getAs<FunctionProtoType>())
11603 return Diag(NewFD->getLocation(), NoProtoDiagID);
11604
11605 if (!TemplatesSupported &&
11607 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11608 << FuncTemplates;
11609
11610 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11611 if (NewCXXFD->isVirtual())
11612 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11613 << VirtFuncs;
11614
11615 if (isa<CXXConstructorDecl>(NewCXXFD))
11616 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11617 << Constructors;
11618
11619 if (isa<CXXDestructorDecl>(NewCXXFD))
11620 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11621 << Destructors;
11622 }
11623
11624 if (NewFD->isDeleted())
11625 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11626 << DeletedFuncs;
11627
11628 if (NewFD->isDefaulted())
11629 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11630 << DefaultedFuncs;
11631
11632 if (!ConstexprSupported && NewFD->isConstexpr())
11633 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11634 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11635
11636 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11637 const auto *NewType = cast<FunctionType>(NewQType);
11638 QualType NewReturnType = NewType->getReturnType();
11639
11640 if (NewReturnType->isUndeducedType())
11641 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11642 << DeducedReturn;
11643
11644 // Ensure the return type is identical.
11645 if (OldFD) {
11646 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11647 const auto *OldType = cast<FunctionType>(OldQType);
11648 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11649 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11650
11651 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11652 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11653
11654 bool ArmStreamingCCMismatched = false;
11655 if (OldFPT && NewFPT) {
11656 unsigned Diff =
11657 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11658 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11659 // cannot be mixed.
11662 ArmStreamingCCMismatched = true;
11663 }
11664
11665 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11666 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11667
11668 QualType OldReturnType = OldType->getReturnType();
11669
11670 if (OldReturnType != NewReturnType)
11671 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11672
11673 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11674 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11675
11676 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11677 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11678
11679 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11680 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11681
11682 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11683 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11684
11685 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11686 NewFD->getLocation()))
11687 return true;
11688 }
11689 return false;
11690}
11691
11693 const FunctionDecl *NewFD,
11694 bool CausesMV,
11695 MultiVersionKind MVKind) {
11697 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11698 if (OldFD)
11699 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11700 return true;
11701 }
11702
11703 bool IsCPUSpecificCPUDispatchMVKind =
11706
11707 if (CausesMV && OldFD &&
11708 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11709 return true;
11710
11711 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11712 return true;
11713
11714 // Only allow transition to MultiVersion if it hasn't been used.
11715 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11716 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11717 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11718 return true;
11719 }
11720
11722 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11724 S.PDiag(diag::note_multiversioning_caused_here)),
11726 S.PDiag(diag::err_multiversion_doesnt_support)
11727 << static_cast<unsigned>(MVKind)),
11729 S.PDiag(diag::err_multiversion_diff)),
11730 /*TemplatesSupported=*/false,
11731 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11732 /*CLinkageMayDiffer=*/false);
11733}
11734
11735/// Check the validity of a multiversion function declaration that is the
11736/// first of its kind. Also sets the multiversion'ness' of the function itself.
11737///
11738/// This sets NewFD->isInvalidDecl() to true if there was an error.
11739///
11740/// Returns true if there was an error, false otherwise.
11743 assert(MVKind != MultiVersionKind::None &&
11744 "Function lacks multiversion attribute");
11745 const auto *TA = FD->getAttr<TargetAttr>();
11746 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11747 // The target attribute only causes MV if this declaration is the default,
11748 // otherwise it is treated as a normal function.
11749 if (TA && !TA->isDefaultVersion())
11750 return false;
11751
11752 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11753 FD->setInvalidDecl();
11754 return true;
11755 }
11756
11757 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11758 FD->setInvalidDecl();
11759 return true;
11760 }
11761
11762 FD->setIsMultiVersion();
11763 return false;
11764}
11765
11767 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11769 return true;
11770 }
11771
11772 return false;
11773}
11774
11776 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11777 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11778 return;
11779
11780 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11781 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11782
11783 if (MVKindTo == MultiVersionKind::None &&
11784 (MVKindFrom == MultiVersionKind::TargetVersion ||
11785 MVKindFrom == MultiVersionKind::TargetClones))
11786 To->addAttr(TargetVersionAttr::CreateImplicit(
11787 To->getASTContext(), "default", To->getSourceRange()));
11788}
11789
11791 FunctionDecl *NewFD,
11792 bool &Redeclaration,
11793 NamedDecl *&OldDecl,
11795 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11796
11797 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11798 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11799 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11800 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11801
11802 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11803
11804 // The definitions should be allowed in any order. If we have discovered
11805 // a new target version and the preceeding was the default, then add the
11806 // corresponding attribute to it.
11807 patchDefaultTargetVersion(NewFD, OldFD);
11808
11809 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11810 // to change, this is a simple redeclaration.
11811 if (NewTA && !NewTA->isDefaultVersion() &&
11812 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11813 return false;
11814
11815 // Otherwise, this decl causes MultiVersioning.
11816 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11819 NewFD->setInvalidDecl();
11820 return true;
11821 }
11822
11823 if (CheckMultiVersionValue(S, NewFD)) {
11824 NewFD->setInvalidDecl();
11825 return true;
11826 }
11827
11828 // If this is 'default', permit the forward declaration.
11829 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11830 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11831 Redeclaration = true;
11832 OldDecl = OldFD;
11833 OldFD->setIsMultiVersion();
11834 NewFD->setIsMultiVersion();
11835 return false;
11836 }
11837
11838 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11839 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11840 NewFD->setInvalidDecl();
11841 return true;
11842 }
11843
11844 if (NewTA) {
11845 ParsedTargetAttr OldParsed =
11847 OldTA->getFeaturesStr());
11848 llvm::sort(OldParsed.Features);
11849 ParsedTargetAttr NewParsed =
11851 NewTA->getFeaturesStr());
11852 // Sort order doesn't matter, it just needs to be consistent.
11853 llvm::sort(NewParsed.Features);
11854 if (OldParsed == NewParsed) {
11855 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11856 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11857 NewFD->setInvalidDecl();
11858 return true;
11859 }
11860 }
11861
11862 for (const auto *FD : OldFD->redecls()) {
11863 const auto *CurTA = FD->getAttr<TargetAttr>();
11864 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11865 // We allow forward declarations before ANY multiversioning attributes, but
11866 // nothing after the fact.
11868 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11869 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11870 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11871 << (NewTA ? 0 : 2);
11872 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11873 NewFD->setInvalidDecl();
11874 return true;
11875 }
11876 }
11877
11878 OldFD->setIsMultiVersion();
11879 NewFD->setIsMultiVersion();
11880 Redeclaration = false;
11881 OldDecl = nullptr;
11882 Previous.clear();
11883 return false;
11884}
11885
11887 MultiVersionKind OldKind = Old->getMultiVersionKind();
11888 MultiVersionKind NewKind = New->getMultiVersionKind();
11889
11890 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11891 NewKind == MultiVersionKind::None)
11892 return true;
11893
11894 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11895 switch (OldKind) {
11897 return NewKind == MultiVersionKind::TargetClones;
11899 return NewKind == MultiVersionKind::TargetVersion;
11900 default:
11901 return false;
11902 }
11903 } else {
11904 switch (OldKind) {
11906 return NewKind == MultiVersionKind::CPUSpecific;
11908 return NewKind == MultiVersionKind::CPUDispatch;
11909 default:
11910 return false;
11911 }
11912 }
11913}
11914
11915/// Check the validity of a new function declaration being added to an existing
11916/// multiversioned declaration collection.
11918 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11919 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11920 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11922
11923 // Disallow mixing of multiversioning types.
11924 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11925 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11926 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11927 NewFD->setInvalidDecl();
11928 return true;
11929 }
11930
11931 // Add the default target_version attribute if it's missing.
11932 patchDefaultTargetVersion(OldFD, NewFD);
11933 patchDefaultTargetVersion(NewFD, OldFD);
11934
11935 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11936 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11937 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11938 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11939
11940 ParsedTargetAttr NewParsed;
11941 if (NewTA) {
11943 NewTA->getFeaturesStr());
11944 llvm::sort(NewParsed.Features);
11945 }
11947 if (NewTVA) {
11948 NewTVA->getFeatures(NewFeats);
11949 llvm::sort(NewFeats);
11950 }
11951
11952 bool UseMemberUsingDeclRules =
11953 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11954
11955 bool MayNeedOverloadableChecks =
11957
11958 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11959 // of a previous member of the MultiVersion set.
11960 for (NamedDecl *ND : Previous) {
11961 FunctionDecl *CurFD = ND->getAsFunction();
11962 if (!CurFD || CurFD->isInvalidDecl())
11963 continue;
11964 if (MayNeedOverloadableChecks &&
11965 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11966 continue;
11967
11968 switch (NewMVKind) {
11970 assert(OldMVKind == MultiVersionKind::TargetClones &&
11971 "Only target_clones can be omitted in subsequent declarations");
11972 break;
11974 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11975 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11976 NewFD->setIsMultiVersion();
11977 Redeclaration = true;
11978 OldDecl = ND;
11979 return false;
11980 }
11981
11982 ParsedTargetAttr CurParsed =
11984 CurTA->getFeaturesStr());
11985 llvm::sort(CurParsed.Features);
11986 if (CurParsed == NewParsed) {
11987 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11988 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11989 NewFD->setInvalidDecl();
11990 return true;
11991 }
11992 break;
11993 }
11995 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11996 if (CurTVA->getName() == NewTVA->getName()) {
11997 NewFD->setIsMultiVersion();
11998 Redeclaration = true;
11999 OldDecl = ND;
12000 return false;
12001 }
12003 CurTVA->getFeatures(CurFeats);
12004 llvm::sort(CurFeats);
12005
12006 if (CurFeats == NewFeats) {
12007 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12008 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12009 NewFD->setInvalidDecl();
12010 return true;
12011 }
12012 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12013 // Default
12014 if (NewFeats.empty())
12015 break;
12016
12017 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12019 CurClones->getFeatures(CurFeats, I);
12020 llvm::sort(CurFeats);
12021
12022 if (CurFeats == NewFeats) {
12023 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12024 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12025 NewFD->setInvalidDecl();
12026 return true;
12027 }
12028 }
12029 }
12030 break;
12031 }
12033 assert(NewClones && "MultiVersionKind does not match attribute type");
12034 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12035 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12036 !std::equal(CurClones->featuresStrs_begin(),
12037 CurClones->featuresStrs_end(),
12038 NewClones->featuresStrs_begin())) {
12039 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
12040 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12041 NewFD->setInvalidDecl();
12042 return true;
12043 }
12044 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12046 CurTVA->getFeatures(CurFeats);
12047 llvm::sort(CurFeats);
12048
12049 // Default
12050 if (CurFeats.empty())
12051 break;
12052
12053 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12054 NewFeats.clear();
12055 NewClones->getFeatures(NewFeats, I);
12056 llvm::sort(NewFeats);
12057
12058 if (CurFeats == NewFeats) {
12059 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12060 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12061 NewFD->setInvalidDecl();
12062 return true;
12063 }
12064 }
12065 break;
12066 }
12067 Redeclaration = true;
12068 OldDecl = CurFD;
12069 NewFD->setIsMultiVersion();
12070 return false;
12071 }
12074 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12075 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12076 // Handle CPUDispatch/CPUSpecific versions.
12077 // Only 1 CPUDispatch function is allowed, this will make it go through
12078 // the redeclaration errors.
12079 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12080 CurFD->hasAttr<CPUDispatchAttr>()) {
12081 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12082 std::equal(
12083 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12084 NewCPUDisp->cpus_begin(),
12085 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12086 return Cur->getName() == New->getName();
12087 })) {
12088 NewFD->setIsMultiVersion();
12089 Redeclaration = true;
12090 OldDecl = ND;
12091 return false;
12092 }
12093
12094 // If the declarations don't match, this is an error condition.
12095 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12096 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12097 NewFD->setInvalidDecl();
12098 return true;
12099 }
12100 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12101 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12102 std::equal(
12103 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12104 NewCPUSpec->cpus_begin(),
12105 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12106 return Cur->getName() == New->getName();
12107 })) {
12108 NewFD->setIsMultiVersion();
12109 Redeclaration = true;
12110 OldDecl = ND;
12111 return false;
12112 }
12113
12114 // Only 1 version of CPUSpecific is allowed for each CPU.
12115 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12116 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12117 if (CurII == NewII) {
12118 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12119 << NewII;
12120 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12121 NewFD->setInvalidDecl();
12122 return true;
12123 }
12124 }
12125 }
12126 }
12127 break;
12128 }
12129 }
12130 }
12131
12132 // Redeclarations of a target_clones function may omit the attribute, in which
12133 // case it will be inherited during declaration merging.
12134 if (NewMVKind == MultiVersionKind::None &&
12135 OldMVKind == MultiVersionKind::TargetClones) {
12136 NewFD->setIsMultiVersion();
12137 Redeclaration = true;
12138 OldDecl = OldFD;
12139 return false;
12140 }
12141
12142 // Else, this is simply a non-redecl case. Checking the 'value' is only
12143 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12144 // handled in the attribute adding step.
12145 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12146 NewFD->setInvalidDecl();
12147 return true;
12148 }
12149
12150 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12151 !OldFD->isMultiVersion(), NewMVKind)) {
12152 NewFD->setInvalidDecl();
12153 return true;
12154 }
12155
12156 // Permit forward declarations in the case where these two are compatible.
12157 if (!OldFD->isMultiVersion()) {
12158 OldFD->setIsMultiVersion();
12159 NewFD->setIsMultiVersion();
12160 Redeclaration = true;
12161 OldDecl = OldFD;
12162 return false;
12163 }
12164
12165 NewFD->setIsMultiVersion();
12166 Redeclaration = false;
12167 OldDecl = nullptr;
12168 Previous.clear();
12169 return false;
12170}
12171
12172/// Check the validity of a mulitversion function declaration.
12173/// Also sets the multiversion'ness' of the function itself.
12174///
12175/// This sets NewFD->isInvalidDecl() to true if there was an error.
12176///
12177/// Returns true if there was an error, false otherwise.
12179 bool &Redeclaration, NamedDecl *&OldDecl,
12181 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12182
12183 // Check if FMV is disabled.
12184 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12185 return false;
12186
12187 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12188 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12189 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12190 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12191 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12192 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12193
12194 // Main isn't allowed to become a multiversion function, however it IS
12195 // permitted to have 'main' be marked with the 'target' optimization hint,
12196 // for 'target_version' only default is allowed.
12197 if (NewFD->isMain()) {
12198 if (MVKind != MultiVersionKind::None &&
12199 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12200 !(MVKind == MultiVersionKind::TargetVersion &&
12201 NewTVA->isDefaultVersion())) {
12202 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12203 NewFD->setInvalidDecl();
12204 return true;
12205 }
12206 return false;
12207 }
12208
12209 // Target attribute on AArch64 is not used for multiversioning
12210 if (NewTA && TI.getTriple().isAArch64())
12211 return false;
12212
12213 // Target attribute on RISCV is not used for multiversioning
12214 if (NewTA && TI.getTriple().isRISCV())
12215 return false;
12216
12217 if (!OldDecl || !OldDecl->getAsFunction() ||
12218 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12219 NewFD->getDeclContext()->getRedeclContext())) {
12220 // If there's no previous declaration, AND this isn't attempting to cause
12221 // multiversioning, this isn't an error condition.
12222 if (MVKind == MultiVersionKind::None)
12223 return false;
12224 return CheckMultiVersionFirstFunction(S, NewFD);
12225 }
12226
12227 FunctionDecl *OldFD = OldDecl->getAsFunction();
12228
12229 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12230 return false;
12231
12232 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12233 // for target_clones and target_version.
12234 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12237 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12239 NewFD->setInvalidDecl();
12240 return true;
12241 }
12242
12243 if (!OldFD->isMultiVersion()) {
12244 switch (MVKind) {
12248 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12250 if (OldFD->isUsed(false)) {
12251 NewFD->setInvalidDecl();
12252 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12253 }
12254 OldFD->setIsMultiVersion();
12255 break;
12256
12260 break;
12261 }
12262 }
12263
12264 // At this point, we have a multiversion function decl (in OldFD) AND an
12265 // appropriate attribute in the current function decl (unless it's allowed to
12266 // omit the attribute). Resolve that these are still compatible with previous
12267 // declarations.
12268 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12269 NewCPUSpec, NewClones, Redeclaration,
12270 OldDecl, Previous);
12271}
12272
12274 bool IsPure = NewFD->hasAttr<PureAttr>();
12275 bool IsConst = NewFD->hasAttr<ConstAttr>();
12276
12277 // If there are no pure or const attributes, there's nothing to check.
12278 if (!IsPure && !IsConst)
12279 return;
12280
12281 // If the function is marked both pure and const, we retain the const
12282 // attribute because it makes stronger guarantees than the pure attribute, and
12283 // we drop the pure attribute explicitly to prevent later confusion about
12284 // semantics.
12285 if (IsPure && IsConst) {
12286 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12287 NewFD->dropAttrs<PureAttr>();
12288 }
12289
12290 // Constructors and destructors are functions which return void, so are
12291 // handled here as well.
12292 if (NewFD->getReturnType()->isVoidType()) {
12293 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12294 << IsConst;
12295 NewFD->dropAttrs<PureAttr, ConstAttr>();
12296 }
12297}
12298
12301 bool IsMemberSpecialization,
12302 bool DeclIsDefn) {
12303 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12304 "Variably modified return types are not handled here");
12305
12306 // Determine whether the type of this function should be merged with
12307 // a previous visible declaration. This never happens for functions in C++,
12308 // and always happens in C if the previous declaration was visible.
12309 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12310 !Previous.isShadowed();
12311
12312 bool Redeclaration = false;
12313 NamedDecl *OldDecl = nullptr;
12314 bool MayNeedOverloadableChecks = false;
12315
12317 // Merge or overload the declaration with an existing declaration of
12318 // the same name, if appropriate.
12319 if (!Previous.empty()) {
12320 // Determine whether NewFD is an overload of PrevDecl or
12321 // a declaration that requires merging. If it's an overload,
12322 // there's no more work to do here; we'll just add the new
12323 // function to the scope.
12325 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12326 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12327 Redeclaration = true;
12328 OldDecl = Candidate;
12329 }
12330 } else {
12331 MayNeedOverloadableChecks = true;
12332 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12333 /*NewIsUsingDecl*/ false)) {
12335 Redeclaration = true;
12336 break;
12337
12339 Redeclaration = true;
12340 break;
12341
12343 Redeclaration = false;
12344 break;
12345 }
12346 }
12347 }
12348
12349 // Check for a previous extern "C" declaration with this name.
12350 if (!Redeclaration &&
12352 if (!Previous.empty()) {
12353 // This is an extern "C" declaration with the same name as a previous
12354 // declaration, and thus redeclares that entity...
12355 Redeclaration = true;
12356 OldDecl = Previous.getFoundDecl();
12357 MergeTypeWithPrevious = false;
12358
12359 // ... except in the presence of __attribute__((overloadable)).
12360 if (OldDecl->hasAttr<OverloadableAttr>() ||
12361 NewFD->hasAttr<OverloadableAttr>()) {
12362 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12363 MayNeedOverloadableChecks = true;
12364 Redeclaration = false;
12365 OldDecl = nullptr;
12366 }
12367 }
12368 }
12369 }
12370
12371 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12372 return Redeclaration;
12373
12374 // PPC MMA non-pointer types are not allowed as function return types.
12375 if (Context.getTargetInfo().getTriple().isPPC64() &&
12376 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12377 NewFD->setInvalidDecl();
12378 }
12379
12380 CheckConstPureAttributesUsage(*this, NewFD);
12381
12382 // C++ [dcl.spec.auto.general]p12:
12383 // Return type deduction for a templated function with a placeholder in its
12384 // declared type occurs when the definition is instantiated even if the
12385 // function body contains a return statement with a non-type-dependent
12386 // operand.
12387 //
12388 // C++ [temp.dep.expr]p3:
12389 // An id-expression is type-dependent if it is a template-id that is not a
12390 // concept-id and is dependent; or if its terminal name is:
12391 // - [...]
12392 // - associated by name lookup with one or more declarations of member
12393 // functions of a class that is the current instantiation declared with a
12394 // return type that contains a placeholder type,
12395 // - [...]
12396 //
12397 // If this is a templated function with a placeholder in its return type,
12398 // make the placeholder type dependent since it won't be deduced until the
12399 // definition is instantiated. We do this here because it needs to happen
12400 // for implicitly instantiated member functions/member function templates.
12401 if (getLangOpts().CPlusPlus14 &&
12402 (NewFD->isDependentContext() &&
12403 NewFD->getReturnType()->isUndeducedType())) {
12404 const FunctionProtoType *FPT =
12405 NewFD->getType()->castAs<FunctionProtoType>();
12406 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12407 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12408 FPT->getExtProtoInfo()));
12409 }
12410
12411 // C++11 [dcl.constexpr]p8:
12412 // A constexpr specifier for a non-static member function that is not
12413 // a constructor declares that member function to be const.
12414 //
12415 // This needs to be delayed until we know whether this is an out-of-line
12416 // definition of a static member function.
12417 //
12418 // This rule is not present in C++1y, so we produce a backwards
12419 // compatibility warning whenever it happens in C++11.
12420 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12421 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12422 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12424 CXXMethodDecl *OldMD = nullptr;
12425 if (OldDecl)
12426 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12427 if (!OldMD || !OldMD->isStatic()) {
12428 const FunctionProtoType *FPT =
12431 EPI.TypeQuals.addConst();
12432 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12433 FPT->getParamTypes(), EPI));
12434
12435 // Warn that we did this, if we're not performing template instantiation.
12436 // In that case, we'll have warned already when the template was defined.
12437 if (!inTemplateInstantiation()) {
12438 SourceLocation AddConstLoc;
12441 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12442
12443 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12444 << FixItHint::CreateInsertion(AddConstLoc, " const");
12445 }
12446 }
12447 }
12448
12449 if (Redeclaration) {
12450 // NewFD and OldDecl represent declarations that need to be
12451 // merged.
12452 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12453 DeclIsDefn)) {
12454 NewFD->setInvalidDecl();
12455 return Redeclaration;
12456 }
12457
12458 Previous.clear();
12459 Previous.addDecl(OldDecl);
12460
12461 if (FunctionTemplateDecl *OldTemplateDecl =
12462 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12463 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12464 FunctionTemplateDecl *NewTemplateDecl
12466 assert(NewTemplateDecl && "Template/non-template mismatch");
12467
12468 // The call to MergeFunctionDecl above may have created some state in
12469 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12470 // can add it as a redeclaration.
12471 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12472
12473 NewFD->setPreviousDeclaration(OldFD);
12474 if (NewFD->isCXXClassMember()) {
12475 NewFD->setAccess(OldTemplateDecl->getAccess());
12476 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12477 }
12478
12479 // If this is an explicit specialization of a member that is a function
12480 // template, mark it as a member specialization.
12481 if (IsMemberSpecialization &&
12482 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12483 NewTemplateDecl->setMemberSpecialization();
12484 assert(OldTemplateDecl->isMemberSpecialization());
12485 // Explicit specializations of a member template do not inherit deleted
12486 // status from the parent member template that they are specializing.
12487 if (OldFD->isDeleted()) {
12488 // FIXME: This assert will not hold in the presence of modules.
12489 assert(OldFD->getCanonicalDecl() == OldFD);
12490 // FIXME: We need an update record for this AST mutation.
12491 OldFD->setDeletedAsWritten(false);
12492 }
12493 }
12494
12495 } else {
12496 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12497 auto *OldFD = cast<FunctionDecl>(OldDecl);
12498 // This needs to happen first so that 'inline' propagates.
12499 NewFD->setPreviousDeclaration(OldFD);
12500 if (NewFD->isCXXClassMember())
12501 NewFD->setAccess(OldFD->getAccess());
12502 }
12503 }
12504 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12505 !NewFD->getAttr<OverloadableAttr>()) {
12506 assert((Previous.empty() ||
12507 llvm::any_of(Previous,
12508 [](const NamedDecl *ND) {
12509 return ND->hasAttr<OverloadableAttr>();
12510 })) &&
12511 "Non-redecls shouldn't happen without overloadable present");
12512
12513 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12514 const auto *FD = dyn_cast<FunctionDecl>(ND);
12515 return FD && !FD->hasAttr<OverloadableAttr>();
12516 });
12517
12518 if (OtherUnmarkedIter != Previous.end()) {
12519 Diag(NewFD->getLocation(),
12520 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12521 Diag((*OtherUnmarkedIter)->getLocation(),
12522 diag::note_attribute_overloadable_prev_overload)
12523 << false;
12524
12525 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12526 }
12527 }
12528
12529 if (LangOpts.OpenMP)
12531
12532 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12534
12535 if (NewFD->hasAttr<SYCLExternalAttr>())
12537
12538 // Semantic checking for this function declaration (in isolation).
12539
12540 if (getLangOpts().CPlusPlus) {
12541 // C++-specific checks.
12542 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12544 } else if (CXXDestructorDecl *Destructor =
12545 dyn_cast<CXXDestructorDecl>(NewFD)) {
12546 // We check here for invalid destructor names.
12547 // If we have a friend destructor declaration that is dependent, we can't
12548 // diagnose right away because cases like this are still valid:
12549 // template <class T> struct A { friend T::X::~Y(); };
12550 // struct B { struct Y { ~Y(); }; using X = Y; };
12551 // template struct A<B>;
12553 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12554 CanQualType ClassType =
12555 Context.getCanonicalTagType(Destructor->getParent());
12556
12557 DeclarationName Name =
12558 Context.DeclarationNames.getCXXDestructorName(ClassType);
12559 if (NewFD->getDeclName() != Name) {
12560 Diag(NewFD->getLocation(), diag::err_destructor_name);
12561 NewFD->setInvalidDecl();
12562 return Redeclaration;
12563 }
12564 }
12565 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12566 if (auto *TD = Guide->getDescribedFunctionTemplate())
12568
12569 // A deduction guide is not on the list of entities that can be
12570 // explicitly specialized.
12571 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12572 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12573 << /*explicit specialization*/ 1;
12574 }
12575
12576 // Find any virtual functions that this function overrides.
12577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12578 if (!Method->isFunctionTemplateSpecialization() &&
12579 !Method->getDescribedFunctionTemplate() &&
12580 Method->isCanonicalDecl()) {
12581 AddOverriddenMethods(Method->getParent(), Method);
12582 }
12583 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12584 // C++2a [class.virtual]p6
12585 // A virtual method shall not have a requires-clause.
12587 diag::err_constrained_virtual_method);
12588
12589 if (Method->isStatic())
12591 }
12592
12593 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12594 ActOnConversionDeclarator(Conversion);
12595
12596 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12597 if (NewFD->isOverloadedOperator() &&
12599 NewFD->setInvalidDecl();
12600 return Redeclaration;
12601 }
12602
12603 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12604 if (NewFD->getLiteralIdentifier() &&
12606 NewFD->setInvalidDecl();
12607 return Redeclaration;
12608 }
12609
12610 // In C++, check default arguments now that we have merged decls. Unless
12611 // the lexical context is the class, because in this case this is done
12612 // during delayed parsing anyway.
12613 if (!CurContext->isRecord())
12615
12616 // If this function is declared as being extern "C", then check to see if
12617 // the function returns a UDT (class, struct, or union type) that is not C
12618 // compatible, and if it does, warn the user.
12619 // But, issue any diagnostic on the first declaration only.
12620 if (Previous.empty() && NewFD->isExternC()) {
12621 QualType R = NewFD->getReturnType();
12622 if (R->isIncompleteType() && !R->isVoidType())
12623 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12624 << NewFD << R;
12625 else if (!R.isPODType(Context) && !R->isVoidType() &&
12626 !R->isObjCObjectPointerType())
12627 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12628 }
12629
12630 // C++1z [dcl.fct]p6:
12631 // [...] whether the function has a non-throwing exception-specification
12632 // [is] part of the function type
12633 //
12634 // This results in an ABI break between C++14 and C++17 for functions whose
12635 // declared type includes an exception-specification in a parameter or
12636 // return type. (Exception specifications on the function itself are OK in
12637 // most cases, and exception specifications are not permitted in most other
12638 // contexts where they could make it into a mangling.)
12639 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12640 auto HasNoexcept = [&](QualType T) -> bool {
12641 // Strip off declarator chunks that could be between us and a function
12642 // type. We don't need to look far, exception specifications are very
12643 // restricted prior to C++17.
12644 if (auto *RT = T->getAs<ReferenceType>())
12645 T = RT->getPointeeType();
12646 else if (T->isAnyPointerType())
12647 T = T->getPointeeType();
12648 else if (auto *MPT = T->getAs<MemberPointerType>())
12649 T = MPT->getPointeeType();
12650 if (auto *FPT = T->getAs<FunctionProtoType>())
12651 if (FPT->isNothrow())
12652 return true;
12653 return false;
12654 };
12655
12656 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12657 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12658 for (QualType T : FPT->param_types())
12659 AnyNoexcept |= HasNoexcept(T);
12660 if (AnyNoexcept)
12661 Diag(NewFD->getLocation(),
12662 diag::warn_cxx17_compat_exception_spec_in_signature)
12663 << NewFD;
12664 }
12665
12666 if (!Redeclaration && LangOpts.CUDA) {
12667 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12668 for (auto *Parm : NewFD->parameters()) {
12669 if (!Parm->getType()->isDependentType() &&
12670 Parm->hasAttr<CUDAGridConstantAttr>() &&
12671 !(IsKernel && Parm->getType().isConstQualified()))
12672 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12673 diag::err_cuda_grid_constant_not_allowed);
12674 }
12676 }
12677 }
12678
12679 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12681
12682 return Redeclaration;
12683}
12684
12686 // [basic.start.main]p3
12687 // The main function shall not be declared with C linkage-specification.
12688 if (FD->isExternCContext())
12689 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12690
12691 // C++11 [basic.start.main]p3:
12692 // A program that [...] declares main to be inline, static or
12693 // constexpr is ill-formed.
12694 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12695 // appear in a declaration of main.
12696 // static main is not an error under C99, but we should warn about it.
12697 // We accept _Noreturn main as an extension.
12698 if (FD->getStorageClass() == SC_Static)
12700 ? diag::err_static_main : diag::warn_static_main)
12702 if (FD->isInlineSpecified())
12703 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12705 if (DS.isNoreturnSpecified()) {
12706 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12707 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12708 Diag(NoreturnLoc, diag::ext_noreturn_main);
12709 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12710 << FixItHint::CreateRemoval(NoreturnRange);
12711 }
12712 if (FD->isConstexpr()) {
12713 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12714 << FD->isConsteval()
12717 }
12718
12719 if (getLangOpts().OpenCL) {
12720 Diag(FD->getLocation(), diag::err_opencl_no_main)
12721 << FD->hasAttr<DeviceKernelAttr>();
12722 FD->setInvalidDecl();
12723 return;
12724 }
12725
12726 if (FD->hasAttr<SYCLExternalAttr>()) {
12727 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12728 << FD->getAttr<SYCLExternalAttr>();
12729 FD->setInvalidDecl();
12730 return;
12731 }
12732
12733 // Functions named main in hlsl are default entries, but don't have specific
12734 // signatures they are required to conform to.
12735 if (getLangOpts().HLSL)
12736 return;
12737
12738 QualType T = FD->getType();
12739 assert(T->isFunctionType() && "function decl is not of function type");
12740 const FunctionType* FT = T->castAs<FunctionType>();
12741
12742 // Set default calling convention for main()
12743 if (FT->getCallConv() != CC_C) {
12744 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12745 FD->setType(QualType(FT, 0));
12746 T = Context.getCanonicalType(FD->getType());
12747 }
12748
12750 // In C with GNU extensions we allow main() to have non-integer return
12751 // type, but we should warn about the extension, and we disable the
12752 // implicit-return-zero rule.
12753
12754 // GCC in C mode accepts qualified 'int'.
12755 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12756 FD->setHasImplicitReturnZero(true);
12757 else {
12758 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12759 SourceRange RTRange = FD->getReturnTypeSourceRange();
12760 if (RTRange.isValid())
12761 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12762 << FixItHint::CreateReplacement(RTRange, "int");
12763 }
12764 } else {
12765 // In C and C++, main magically returns 0 if you fall off the end;
12766 // set the flag which tells us that.
12767 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12768
12769 // All the standards say that main() should return 'int'.
12770 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12771 FD->setHasImplicitReturnZero(true);
12772 else {
12773 // Otherwise, this is just a flat-out error.
12774 SourceRange RTRange = FD->getReturnTypeSourceRange();
12775 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12776 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12777 : FixItHint());
12778 FD->setInvalidDecl(true);
12779 }
12780
12781 // [basic.start.main]p3:
12782 // A program that declares a function main that belongs to the global scope
12783 // and is attached to a named module is ill-formed.
12784 if (FD->isInNamedModule()) {
12785 const SourceLocation start = FD->getTypeSpecStartLoc();
12786 Diag(start, diag::warn_main_in_named_module)
12787 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12788 }
12789 }
12790
12791 // Treat protoless main() as nullary.
12792 if (isa<FunctionNoProtoType>(FT)) return;
12793
12795 unsigned nparams = FTP->getNumParams();
12796 assert(FD->getNumParams() == nparams);
12797
12798 bool HasExtraParameters = (nparams > 3);
12799
12800 if (FTP->isVariadic()) {
12801 Diag(FD->getLocation(), diag::ext_variadic_main);
12802 // FIXME: if we had information about the location of the ellipsis, we
12803 // could add a FixIt hint to remove it as a parameter.
12804 }
12805
12806 // Darwin passes an undocumented fourth argument of type char**. If
12807 // other platforms start sprouting these, the logic below will start
12808 // getting shifty.
12809 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12810 HasExtraParameters = false;
12811
12812 if (HasExtraParameters) {
12813 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12814 FD->setInvalidDecl(true);
12815 nparams = 3;
12816 }
12817
12818 // FIXME: a lot of the following diagnostics would be improved
12819 // if we had some location information about types.
12820
12821 QualType CharPP =
12822 Context.getPointerType(Context.getPointerType(Context.CharTy));
12823 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12824
12825 for (unsigned i = 0; i < nparams; ++i) {
12826 QualType AT = FTP->getParamType(i);
12827
12828 bool mismatch = true;
12829
12830 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12831 mismatch = false;
12832 else if (Expected[i] == CharPP) {
12833 // As an extension, the following forms are okay:
12834 // char const **
12835 // char const * const *
12836 // char * const *
12837
12839 const PointerType* PT;
12840 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12841 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12842 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12843 Context.CharTy)) {
12844 qs.removeConst();
12845 mismatch = !qs.empty();
12846 }
12847 }
12848
12849 if (mismatch) {
12850 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12851 // TODO: suggest replacing given type with expected type
12852 FD->setInvalidDecl(true);
12853 }
12854 }
12855
12856 if (nparams == 1 && !FD->isInvalidDecl()) {
12857 Diag(FD->getLocation(), diag::warn_main_one_arg);
12858 }
12859
12860 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12861 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12862 FD->setInvalidDecl();
12863 }
12864}
12865
12866static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12867
12868 // Default calling convention for main and wmain is __cdecl
12869 if (FD->getName() == "main" || FD->getName() == "wmain")
12870 return false;
12871
12872 // Default calling convention for MinGW and Cygwin is __cdecl
12873 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12874 if (T.isOSCygMing())
12875 return false;
12876
12877 // Default calling convention for WinMain, wWinMain and DllMain
12878 // is __stdcall on 32 bit Windows
12879 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12880 return true;
12881
12882 return false;
12883}
12884
12886 QualType T = FD->getType();
12887 assert(T->isFunctionType() && "function decl is not of function type");
12888 const FunctionType *FT = T->castAs<FunctionType>();
12889
12890 // Set an implicit return of 'zero' if the function can return some integral,
12891 // enumeration, pointer or nullptr type.
12895 // DllMain is exempt because a return value of zero means it failed.
12896 if (FD->getName() != "DllMain")
12897 FD->setHasImplicitReturnZero(true);
12898
12899 // Explicitly specified calling conventions are applied to MSVC entry points
12900 if (!hasExplicitCallingConv(T)) {
12901 if (isDefaultStdCall(FD, *this)) {
12902 if (FT->getCallConv() != CC_X86StdCall) {
12903 FT = Context.adjustFunctionType(
12905 FD->setType(QualType(FT, 0));
12906 }
12907 } else if (FT->getCallConv() != CC_C) {
12908 FT = Context.adjustFunctionType(FT,
12910 FD->setType(QualType(FT, 0));
12911 }
12912 }
12913
12914 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12915 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12916 FD->setInvalidDecl();
12917 }
12918}
12919
12921 // FIXME: Need strict checking. In C89, we need to check for
12922 // any assignment, increment, decrement, function-calls, or
12923 // commas outside of a sizeof. In C99, it's the same list,
12924 // except that the aforementioned are allowed in unevaluated
12925 // expressions. Everything else falls under the
12926 // "may accept other forms of constant expressions" exception.
12927 //
12928 // Regular C++ code will not end up here (exceptions: language extensions,
12929 // OpenCL C++ etc), so the constant expression rules there don't matter.
12930 if (Init->isValueDependent()) {
12931 assert(Init->containsErrors() &&
12932 "Dependent code should only occur in error-recovery path.");
12933 return true;
12934 }
12935 const Expr *Culprit;
12936 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
12937 return false;
12938
12939 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12940 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Culprit)) {
12941
12942 // For collection literals iterate the elements to highlight which one is
12943 // the offender.
12944 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Init)) {
12945 for (auto *Elm : ALE->elements()) {
12946 if (!Elm->isConstantInitializer(Context)) {
12947 Diag(Elm->getExprLoc(),
12948 diag::err_objc_literal_nonconstant_at_file_scope)
12949 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
12950 return true;
12951 }
12952 }
12953 }
12954
12955 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Init)) {
12956 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12957 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
12958
12959 // Check that the key is a string literal and is constant.
12960 if (!isa<ObjCStringLiteral>(Elm.Key) ||
12962 Diag(Elm.Key->getExprLoc(),
12963 diag::err_objc_literal_nonconstant_at_file_scope)
12965 return true;
12966 }
12967
12968 if (!Elm.Value->isConstantInitializer(Context)) {
12969 Diag(Elm.Value->getExprLoc(),
12970 diag::err_objc_literal_nonconstant_at_file_scope)
12972 return true;
12973 }
12974 }
12975 }
12976
12977 Diag(Culprit->getExprLoc(),
12978 diag::err_objc_literal_nonconstant_at_file_scope)
12979 << ObjC().CheckLiteralKind(Init) << Culprit->getSourceRange();
12980 return true;
12981 }
12982
12983 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12984 return true;
12985}
12986
12987namespace {
12988 // Visits an initialization expression to see if OrigDecl is evaluated in
12989 // its own initialization and throws a warning if it does.
12990 class SelfReferenceChecker
12991 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12992 Sema &S;
12993 Decl *OrigDecl;
12994 bool isRecordType;
12995 bool isPODType;
12996 bool isReferenceType;
12997 bool isInCXXOperatorCall;
12998
12999 bool isInitList;
13000 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13001
13002 public:
13004
13005 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13006 S(S), OrigDecl(OrigDecl) {
13007 isPODType = false;
13008 isRecordType = false;
13009 isReferenceType = false;
13010 isInCXXOperatorCall = false;
13011 isInitList = false;
13012 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
13013 isPODType = VD->getType().isPODType(S.Context);
13014 isRecordType = VD->getType()->isRecordType();
13015 isReferenceType = VD->getType()->isReferenceType();
13016 }
13017 }
13018
13019 // For most expressions, just call the visitor. For initializer lists,
13020 // track the index of the field being initialized since fields are
13021 // initialized in order allowing use of previously initialized fields.
13022 void CheckExpr(Expr *E) {
13023 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
13024 if (!InitList) {
13025 Visit(E);
13026 return;
13027 }
13028
13029 // Track and increment the index here.
13030 isInitList = true;
13031 InitFieldIndex.push_back(0);
13032 for (auto *Child : InitList->children()) {
13033 CheckExpr(cast<Expr>(Child));
13034 ++InitFieldIndex.back();
13035 }
13036 InitFieldIndex.pop_back();
13037 }
13038
13039 // Returns true if MemberExpr is checked and no further checking is needed.
13040 // Returns false if additional checking is required.
13041 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13042 llvm::SmallVector<FieldDecl*, 4> Fields;
13043 Expr *Base = E;
13044 bool ReferenceField = false;
13045
13046 // Get the field members used.
13047 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13048 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13049 if (!FD)
13050 return false;
13051 Fields.push_back(FD);
13052 if (FD->getType()->isReferenceType())
13053 ReferenceField = true;
13054 Base = ME->getBase()->IgnoreParenImpCasts();
13055 }
13056
13057 // Keep checking only if the base Decl is the same.
13058 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
13059 if (!DRE || DRE->getDecl() != OrigDecl)
13060 return false;
13061
13062 // A reference field can be bound to an unininitialized field.
13063 if (CheckReference && !ReferenceField)
13064 return true;
13065
13066 // Convert FieldDecls to their index number.
13067 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13068 for (const FieldDecl *I : llvm::reverse(Fields))
13069 UsedFieldIndex.push_back(I->getFieldIndex());
13070
13071 // See if a warning is needed by checking the first difference in index
13072 // numbers. If field being used has index less than the field being
13073 // initialized, then the use is safe.
13074 for (auto UsedIter = UsedFieldIndex.begin(),
13075 UsedEnd = UsedFieldIndex.end(),
13076 OrigIter = InitFieldIndex.begin(),
13077 OrigEnd = InitFieldIndex.end();
13078 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13079 if (*UsedIter < *OrigIter)
13080 return true;
13081 if (*UsedIter > *OrigIter)
13082 break;
13083 }
13084
13085 // TODO: Add a different warning which will print the field names.
13086 HandleDeclRefExpr(DRE);
13087 return true;
13088 }
13089
13090 // For most expressions, the cast is directly above the DeclRefExpr.
13091 // For conditional operators, the cast can be outside the conditional
13092 // operator if both expressions are DeclRefExpr's.
13093 void HandleValue(Expr *E) {
13094 E = E->IgnoreParens();
13095 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13096 HandleDeclRefExpr(DRE);
13097 return;
13098 }
13099
13100 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13101 Visit(CO->getCond());
13102 HandleValue(CO->getTrueExpr());
13103 HandleValue(CO->getFalseExpr());
13104 return;
13105 }
13106
13107 if (BinaryConditionalOperator *BCO =
13108 dyn_cast<BinaryConditionalOperator>(E)) {
13109 Visit(BCO->getCond());
13110 HandleValue(BCO->getFalseExpr());
13111 return;
13112 }
13113
13114 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13115 if (Expr *SE = OVE->getSourceExpr())
13116 HandleValue(SE);
13117 return;
13118 }
13119
13120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13121 if (BO->getOpcode() == BO_Comma) {
13122 Visit(BO->getLHS());
13123 HandleValue(BO->getRHS());
13124 return;
13125 }
13126 }
13127
13128 if (isa<MemberExpr>(E)) {
13129 if (isInitList) {
13130 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13131 false /*CheckReference*/))
13132 return;
13133 }
13134
13135 Expr *Base = E->IgnoreParenImpCasts();
13136 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13137 // Check for static member variables and don't warn on them.
13138 if (!isa<FieldDecl>(ME->getMemberDecl()))
13139 return;
13140 Base = ME->getBase()->IgnoreParenImpCasts();
13141 }
13142 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13143 HandleDeclRefExpr(DRE);
13144 return;
13145 }
13146
13147 Visit(E);
13148 }
13149
13150 // Reference types not handled in HandleValue are handled here since all
13151 // uses of references are bad, not just r-value uses.
13152 void VisitDeclRefExpr(DeclRefExpr *E) {
13153 if (isReferenceType)
13154 HandleDeclRefExpr(E);
13155 }
13156
13157 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13158 if (E->getCastKind() == CK_LValueToRValue) {
13159 HandleValue(E->getSubExpr());
13160 return;
13161 }
13162
13163 Inherited::VisitImplicitCastExpr(E);
13164 }
13165
13166 void VisitMemberExpr(MemberExpr *E) {
13167 if (isInitList) {
13168 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13169 return;
13170 }
13171
13172 // Don't warn on arrays since they can be treated as pointers.
13173 if (E->getType()->canDecayToPointerType()) return;
13174
13175 // Warn when a non-static method call is followed by non-static member
13176 // field accesses, which is followed by a DeclRefExpr.
13177 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13178 bool Warn = (MD && !MD->isStatic());
13179 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13180 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13181 if (!isa<FieldDecl>(ME->getMemberDecl()))
13182 Warn = false;
13183 Base = ME->getBase()->IgnoreParenImpCasts();
13184 }
13185
13186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13187 if (Warn)
13188 HandleDeclRefExpr(DRE);
13189 return;
13190 }
13191
13192 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13193 // Visit that expression.
13194 Visit(Base);
13195 }
13196
13197 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13198 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13199 Expr *Callee = E->getCallee();
13200
13201 if (isa<UnresolvedLookupExpr>(Callee))
13202 return Inherited::VisitCXXOperatorCallExpr(E);
13203
13204 Visit(Callee);
13205 for (auto Arg: E->arguments())
13206 HandleValue(Arg->IgnoreParenImpCasts());
13207 }
13208
13209 void VisitLambdaExpr(LambdaExpr *E) {
13210 if (!isInCXXOperatorCall) {
13211 Inherited::VisitLambdaExpr(E);
13212 return;
13213 }
13214
13215 for (Expr *Init : E->capture_inits())
13216 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13217 HandleDeclRefExpr(DRE);
13218 else if (Init)
13219 Visit(Init);
13220 }
13221
13222 void VisitUnaryOperator(UnaryOperator *E) {
13223 // For POD record types, addresses of its own members are well-defined.
13224 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13226 if (!isPODType)
13227 HandleValue(E->getSubExpr());
13228 return;
13229 }
13230
13231 if (E->isIncrementDecrementOp()) {
13232 HandleValue(E->getSubExpr());
13233 return;
13234 }
13235
13236 Inherited::VisitUnaryOperator(E);
13237 }
13238
13239 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13240
13241 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13242 if (E->getConstructor()->isCopyConstructor()) {
13243 Expr *ArgExpr = E->getArg(0);
13244 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13245 if (ILE->getNumInits() == 1)
13246 ArgExpr = ILE->getInit(0);
13247 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13248 if (ICE->getCastKind() == CK_NoOp)
13249 ArgExpr = ICE->getSubExpr();
13250 HandleValue(ArgExpr);
13251 return;
13252 }
13253 Inherited::VisitCXXConstructExpr(E);
13254 }
13255
13256 void VisitCallExpr(CallExpr *E) {
13257 // Treat std::move as a use.
13258 if (E->isCallToStdMove()) {
13259 HandleValue(E->getArg(0));
13260 return;
13261 }
13262
13263 Inherited::VisitCallExpr(E);
13264 }
13265
13266 void VisitBinaryOperator(BinaryOperator *E) {
13267 if (E->isCompoundAssignmentOp()) {
13268 HandleValue(E->getLHS());
13269 Visit(E->getRHS());
13270 return;
13271 }
13272
13273 Inherited::VisitBinaryOperator(E);
13274 }
13275
13276 // A custom visitor for BinaryConditionalOperator is needed because the
13277 // regular visitor would check the condition and true expression separately
13278 // but both point to the same place giving duplicate diagnostics.
13279 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13280 Visit(E->getCond());
13281 Visit(E->getFalseExpr());
13282 }
13283
13284 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13285 Decl* ReferenceDecl = DRE->getDecl();
13286 if (OrigDecl != ReferenceDecl) return;
13287 unsigned diag;
13288 if (isReferenceType) {
13289 diag = diag::warn_uninit_self_reference_in_reference_init;
13290 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13291 diag = diag::warn_static_self_reference_in_init;
13292 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13293 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13294 DRE->getDecl()->getType()->isRecordType()) {
13295 diag = diag::warn_uninit_self_reference_in_init;
13296 } else {
13297 // Local variables will be handled by the CFG analysis.
13298 return;
13299 }
13300
13301 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13302 S.PDiag(diag)
13303 << DRE->getDecl() << OrigDecl->getLocation()
13304 << DRE->getSourceRange());
13305 }
13306 };
13307
13308 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13309 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13310 bool DirectInit) {
13311 // Parameters arguments are occassionially constructed with itself,
13312 // for instance, in recursive functions. Skip them.
13313 if (isa<ParmVarDecl>(OrigDecl))
13314 return;
13315
13316 // Skip checking for file-scope constexpr variables - constant evaluation
13317 // will produce appropriate errors without needing runtime diagnostics.
13318 // Local constexpr should still emit runtime warnings.
13319 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13320 VD && VD->isConstexpr() && VD->isFileVarDecl())
13321 return;
13322
13323 E = E->IgnoreParens();
13324
13325 // Skip checking T a = a where T is not a record or reference type.
13326 // Doing so is a way to silence uninitialized warnings.
13327 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13328 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13329 if (ICE->getCastKind() == CK_LValueToRValue)
13330 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13331 if (DRE->getDecl() == OrigDecl)
13332 return;
13333
13334 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13335 }
13336} // end anonymous namespace
13337
13338namespace {
13339 // Simple wrapper to add the name of a variable or (if no variable is
13340 // available) a DeclarationName into a diagnostic.
13341 struct VarDeclOrName {
13342 VarDecl *VDecl;
13343 DeclarationName Name;
13344
13345 friend const Sema::SemaDiagnosticBuilder &
13346 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13347 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13348 }
13349 };
13350} // end anonymous namespace
13351
13354 TypeSourceInfo *TSI,
13355 SourceRange Range, bool DirectInit,
13356 Expr *Init) {
13357 bool IsInitCapture = !VDecl;
13358 assert((!VDecl || !VDecl->isInitCapture()) &&
13359 "init captures are expected to be deduced prior to initialization");
13360
13361 VarDeclOrName VN{VDecl, Name};
13362
13363 DeducedType *Deduced = Type->getContainedDeducedType();
13364 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13365
13366 // Diagnose auto array declarations in C23, unless it's a supported extension.
13367 if (getLangOpts().C23 && Type->isArrayType() &&
13368 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13369 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13370 << (int)Deduced->getContainedAutoType()->getKeyword()
13371 << /*in array decl*/ 23 << Range;
13372 return QualType();
13373 }
13374
13375 // C++11 [dcl.spec.auto]p3
13376 if (!Init) {
13377 assert(VDecl && "no init for init capture deduction?");
13378
13379 // Except for class argument deduction, and then for an initializing
13380 // declaration only, i.e. no static at class scope or extern.
13382 VDecl->hasExternalStorage() ||
13383 VDecl->isStaticDataMember()) {
13384 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13385 << VDecl->getDeclName() << Type;
13386 return QualType();
13387 }
13388 }
13389
13390 ArrayRef<Expr*> DeduceInits;
13391 if (Init)
13392 DeduceInits = Init;
13393
13394 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13395 if (DirectInit && PL)
13396 DeduceInits = PL->exprs();
13397
13399 assert(VDecl && "non-auto type for init capture deduction?");
13402 VDecl->getLocation(), DirectInit, Init);
13403 // FIXME: Initialization should not be taking a mutable list of inits.
13404 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13405 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13406 InitsCopy);
13407 }
13408
13409 if (DirectInit) {
13410 if (auto *IL = dyn_cast<InitListExpr>(Init))
13411 DeduceInits = IL->inits();
13412 }
13413
13414 // Deduction only works if we have exactly one source expression.
13415 if (DeduceInits.empty()) {
13416 // It isn't possible to write this directly, but it is possible to
13417 // end up in this situation with "auto x(some_pack...);"
13418 Diag(Init->getBeginLoc(), IsInitCapture
13419 ? diag::err_init_capture_no_expression
13420 : diag::err_auto_var_init_no_expression)
13421 << VN << Type << Range;
13422 return QualType();
13423 }
13424
13425 if (DeduceInits.size() > 1) {
13426 Diag(DeduceInits[1]->getBeginLoc(),
13427 IsInitCapture ? diag::err_init_capture_multiple_expressions
13428 : diag::err_auto_var_init_multiple_expressions)
13429 << VN << Type << Range;
13430 return QualType();
13431 }
13432
13433 Expr *DeduceInit = DeduceInits[0];
13434 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13435 Diag(Init->getBeginLoc(), IsInitCapture
13436 ? diag::err_init_capture_paren_braces
13437 : diag::err_auto_var_init_paren_braces)
13438 << isa<InitListExpr>(Init) << VN << Type << Range;
13439 return QualType();
13440 }
13441
13442 // Expressions default to 'id' when we're in a debugger.
13443 bool DefaultedAnyToId = false;
13444 if (getLangOpts().DebuggerCastResultToId &&
13445 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13447 if (Result.isInvalid()) {
13448 return QualType();
13449 }
13450 Init = Result.get();
13451 DefaultedAnyToId = true;
13452 }
13453
13454 // C++ [dcl.decomp]p1:
13455 // If the assignment-expression [...] has array type A and no ref-qualifier
13456 // is present, e has type cv A
13457 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13458 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13459 DeduceInit->getType()->isConstantArrayType())
13460 return Context.getQualifiedType(DeduceInit->getType(),
13461 Type.getQualifiers());
13462
13463 QualType DeducedType;
13464 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13466 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13469 if (!IsInitCapture)
13470 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13471 else if (isa<InitListExpr>(Init))
13472 Diag(Range.getBegin(),
13473 diag::err_init_capture_deduction_failure_from_init_list)
13474 << VN
13475 << (DeduceInit->getType().isNull() ? TSI->getType()
13476 : DeduceInit->getType())
13477 << DeduceInit->getSourceRange();
13478 else
13479 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13480 << VN << TSI->getType()
13481 << (DeduceInit->getType().isNull() ? TSI->getType()
13482 : DeduceInit->getType())
13483 << DeduceInit->getSourceRange();
13484 }
13485
13486 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13487 // 'id' instead of a specific object type prevents most of our usual
13488 // checks.
13489 // We only want to warn outside of template instantiations, though:
13490 // inside a template, the 'id' could have come from a parameter.
13491 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13492 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13493 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13494 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13495 }
13496
13497 return DeducedType;
13498}
13499
13501 Expr *Init) {
13502 assert(!Init || !Init->containsErrors());
13504 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13505 VDecl->getSourceRange(), DirectInit, Init);
13506 if (DeducedType.isNull()) {
13507 VDecl->setInvalidDecl();
13508 return true;
13509 }
13510
13511 VDecl->setType(DeducedType);
13512 assert(VDecl->isLinkageValid());
13513
13514 // In ARC, infer lifetime.
13515 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13516 VDecl->setInvalidDecl();
13517
13518 if (getLangOpts().OpenCL)
13520
13521 if (getLangOpts().HLSL)
13522 HLSL().deduceAddressSpace(VDecl);
13523
13524 // If this is a redeclaration, check that the type we just deduced matches
13525 // the previously declared type.
13526 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13527 // We never need to merge the type, because we cannot form an incomplete
13528 // array of auto, nor deduce such a type.
13529 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13530 }
13531
13532 // Check the deduced type is valid for a variable declaration.
13534 return VDecl->isInvalidDecl();
13535}
13536
13538 SourceLocation Loc) {
13539 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13540 Init = EWC->getSubExpr();
13541
13542 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13543 Init = CE->getSubExpr();
13544
13545 QualType InitType = Init->getType();
13548 "shouldn't be called if type doesn't have a non-trivial C struct");
13549 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13550 for (auto *I : ILE->inits()) {
13551 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13552 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13553 continue;
13554 SourceLocation SL = I->getExprLoc();
13555 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13556 }
13557 return;
13558 }
13559
13562 checkNonTrivialCUnion(InitType, Loc,
13564 NTCUK_Init);
13565 } else {
13566 // Assume all other explicit initializers involving copying some existing
13567 // object.
13568 // TODO: ignore any explicit initializers where we can guarantee
13569 // copy-elision.
13572 NTCUK_Copy);
13573 }
13574}
13575
13576namespace {
13577
13578bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13579 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13580 // in the source code or implicitly by the compiler if it is in a union
13581 // defined in a system header and has non-trivial ObjC ownership
13582 // qualifications. We don't want those fields to participate in determining
13583 // whether the containing union is non-trivial.
13584 return FD->hasAttr<UnavailableAttr>();
13585}
13586
13587struct DiagNonTrivalCUnionDefaultInitializeVisitor
13588 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13589 void> {
13590 using Super =
13591 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13592 void>;
13593
13594 DiagNonTrivalCUnionDefaultInitializeVisitor(
13595 QualType OrigTy, SourceLocation OrigLoc,
13596 NonTrivialCUnionContext UseContext, Sema &S)
13597 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13598
13599 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13600 const FieldDecl *FD, bool InNonTrivialUnion) {
13601 if (const auto *AT = S.Context.getAsArrayType(QT))
13602 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13603 InNonTrivialUnion);
13604 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13605 }
13606
13607 void visitARCStrong(QualType QT, const FieldDecl *FD,
13608 bool InNonTrivialUnion) {
13609 if (InNonTrivialUnion)
13610 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13611 << 1 << 0 << QT << FD->getName();
13612 }
13613
13614 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13615 if (InNonTrivialUnion)
13616 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13617 << 1 << 0 << QT << FD->getName();
13618 }
13619
13620 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13621 const auto *RD = QT->castAsRecordDecl();
13622 if (RD->isUnion()) {
13623 if (OrigLoc.isValid()) {
13624 bool IsUnion = false;
13625 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13626 IsUnion = OrigRD->isUnion();
13627 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13628 << 0 << OrigTy << IsUnion << UseContext;
13629 // Reset OrigLoc so that this diagnostic is emitted only once.
13630 OrigLoc = SourceLocation();
13631 }
13632 InNonTrivialUnion = true;
13633 }
13634
13635 if (InNonTrivialUnion)
13636 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13637 << 0 << 0 << QT.getUnqualifiedType() << "";
13638
13639 for (const FieldDecl *FD : RD->fields())
13640 if (!shouldIgnoreForRecordTriviality(FD))
13641 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13642 }
13643
13644 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13645
13646 // The non-trivial C union type or the struct/union type that contains a
13647 // non-trivial C union.
13648 QualType OrigTy;
13649 SourceLocation OrigLoc;
13650 NonTrivialCUnionContext UseContext;
13651 Sema &S;
13652};
13653
13654struct DiagNonTrivalCUnionDestructedTypeVisitor
13655 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13656 using Super =
13657 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13658
13659 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13660 SourceLocation OrigLoc,
13661 NonTrivialCUnionContext UseContext,
13662 Sema &S)
13663 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13664
13665 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13666 const FieldDecl *FD, bool InNonTrivialUnion) {
13667 if (const auto *AT = S.Context.getAsArrayType(QT))
13668 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13669 InNonTrivialUnion);
13670 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13671 }
13672
13673 void visitARCStrong(QualType QT, const FieldDecl *FD,
13674 bool InNonTrivialUnion) {
13675 if (InNonTrivialUnion)
13676 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13677 << 1 << 1 << QT << FD->getName();
13678 }
13679
13680 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13681 if (InNonTrivialUnion)
13682 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13683 << 1 << 1 << QT << FD->getName();
13684 }
13685
13686 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13687 const auto *RD = QT->castAsRecordDecl();
13688 if (RD->isUnion()) {
13689 if (OrigLoc.isValid()) {
13690 bool IsUnion = false;
13691 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13692 IsUnion = OrigRD->isUnion();
13693 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13694 << 1 << OrigTy << IsUnion << UseContext;
13695 // Reset OrigLoc so that this diagnostic is emitted only once.
13696 OrigLoc = SourceLocation();
13697 }
13698 InNonTrivialUnion = true;
13699 }
13700
13701 if (InNonTrivialUnion)
13702 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13703 << 0 << 1 << QT.getUnqualifiedType() << "";
13704
13705 for (const FieldDecl *FD : RD->fields())
13706 if (!shouldIgnoreForRecordTriviality(FD))
13707 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13708 }
13709
13710 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13711 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13712 bool InNonTrivialUnion) {}
13713
13714 // The non-trivial C union type or the struct/union type that contains a
13715 // non-trivial C union.
13716 QualType OrigTy;
13717 SourceLocation OrigLoc;
13718 NonTrivialCUnionContext UseContext;
13719 Sema &S;
13720};
13721
13722struct DiagNonTrivalCUnionCopyVisitor
13723 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13724 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13725
13726 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13727 NonTrivialCUnionContext UseContext, Sema &S)
13728 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13729
13730 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13731 const FieldDecl *FD, bool InNonTrivialUnion) {
13732 if (const auto *AT = S.Context.getAsArrayType(QT))
13733 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13734 InNonTrivialUnion);
13735 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13736 }
13737
13738 void visitARCStrong(QualType QT, const FieldDecl *FD,
13739 bool InNonTrivialUnion) {
13740 if (InNonTrivialUnion)
13741 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13742 << 1 << 2 << QT << FD->getName();
13743 }
13744
13745 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13746 if (InNonTrivialUnion)
13747 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13748 << 1 << 2 << QT << FD->getName();
13749 }
13750
13751 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13752 const auto *RD = QT->castAsRecordDecl();
13753 if (RD->isUnion()) {
13754 if (OrigLoc.isValid()) {
13755 bool IsUnion = false;
13756 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13757 IsUnion = OrigRD->isUnion();
13758 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13759 << 2 << OrigTy << IsUnion << UseContext;
13760 // Reset OrigLoc so that this diagnostic is emitted only once.
13761 OrigLoc = SourceLocation();
13762 }
13763 InNonTrivialUnion = true;
13764 }
13765
13766 if (InNonTrivialUnion)
13767 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13768 << 0 << 2 << QT.getUnqualifiedType() << "";
13769
13770 for (const FieldDecl *FD : RD->fields())
13771 if (!shouldIgnoreForRecordTriviality(FD))
13772 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13773 }
13774
13775 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13776 if (InNonTrivialUnion)
13777 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13778 << 1 << 2 << QT << FD->getName();
13779 }
13780
13781 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13782 const FieldDecl *FD, bool InNonTrivialUnion) {}
13783 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13784 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13785 bool InNonTrivialUnion) {}
13786
13787 // The non-trivial C union type or the struct/union type that contains a
13788 // non-trivial C union.
13789 QualType OrigTy;
13790 SourceLocation OrigLoc;
13791 NonTrivialCUnionContext UseContext;
13792 Sema &S;
13793};
13794
13795} // namespace
13796
13798 NonTrivialCUnionContext UseContext,
13799 unsigned NonTrivialKind) {
13803 "shouldn't be called if type doesn't have a non-trivial C union");
13804
13805 if ((NonTrivialKind & NTCUK_Init) &&
13807 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13808 .visit(QT, nullptr, false);
13809 if ((NonTrivialKind & NTCUK_Destruct) &&
13811 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13812 .visit(QT, nullptr, false);
13813 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13814 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13815 .visit(QT, nullptr, false);
13816}
13817
13819 const VarDecl *Dcl) {
13820 if (!getLangOpts().CPlusPlus)
13821 return false;
13822
13823 // We only need to warn if the definition is in a header file, so wait to
13824 // diagnose until we've seen the definition.
13825 if (!Dcl->isThisDeclarationADefinition())
13826 return false;
13827
13828 // If an object is defined in a source file, its definition can't get
13829 // duplicated since it will never appear in more than one TU.
13831 return false;
13832
13833 // If the variable we're looking at is a static local, then we actually care
13834 // about the properties of the function containing it.
13835 const ValueDecl *Target = Dcl;
13836 // VarDecls and FunctionDecls have different functions for checking
13837 // inline-ness, and whether they were originally templated, so we have to
13838 // call the appropriate functions manually.
13839 bool TargetIsInline = Dcl->isInline();
13840 bool TargetWasTemplated =
13842
13843 // Update the Target and TargetIsInline property if necessary
13844 if (Dcl->isStaticLocal()) {
13845 const DeclContext *Ctx = Dcl->getDeclContext();
13846 if (!Ctx)
13847 return false;
13848
13849 const FunctionDecl *FunDcl =
13850 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13851 if (!FunDcl)
13852 return false;
13853
13854 Target = FunDcl;
13855 // IsInlined() checks for the C++ inline property
13856 TargetIsInline = FunDcl->isInlined();
13857 TargetWasTemplated =
13859 }
13860
13861 // Non-inline functions/variables can only legally appear in one TU
13862 // unless they were part of a template. Unfortunately, making complex
13863 // template instantiations visible is infeasible in practice, since
13864 // everything the template depends on also has to be visible. To avoid
13865 // giving impractical-to-fix warnings, don't warn if we're inside
13866 // something that was templated, even on inline stuff.
13867 if (!TargetIsInline || TargetWasTemplated)
13868 return false;
13869
13870 // If the object isn't hidden, the dynamic linker will prevent duplication.
13871 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13872
13873 // The target is "hidden" (from the dynamic linker) if:
13874 // 1. On posix, it has hidden visibility, or
13875 // 2. On windows, it has no import/export annotation, and neither does the
13876 // class which directly contains it.
13877 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13878 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13879 return false;
13880
13881 // If the variable isn't directly annotated, check to see if it's a member
13882 // of an annotated class.
13883 const CXXRecordDecl *Ctx =
13884 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13885 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13886 return false;
13887
13888 } else if (Lnk.getVisibility() != HiddenVisibility) {
13889 // Posix case
13890 return false;
13891 }
13892
13893 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13895 return false;
13896
13897 return true;
13898}
13899
13900// Determine whether the object seems mutable for the purpose of diagnosing
13901// possible unique object duplication, i.e. non-const-qualified, and
13902// not an always-constant type like a function.
13903// Not perfect: doesn't account for mutable members, for example, or
13904// elements of container types.
13905// For nested pointers, any individual level being non-const is sufficient.
13906static bool looksMutable(QualType T, const ASTContext &Ctx) {
13907 T = T.getNonReferenceType();
13908 if (T->isFunctionType())
13909 return false;
13910 if (!T.isConstant(Ctx))
13911 return true;
13912 if (T->isPointerType())
13913 return looksMutable(T->getPointeeType(), Ctx);
13914 return false;
13915}
13916
13918 // If this object has external linkage and hidden visibility, it might be
13919 // duplicated when built into a shared library, which causes problems if it's
13920 // mutable (since the copies won't be in sync) or its initialization has side
13921 // effects (since it will run once per copy instead of once globally).
13922
13923 // Don't diagnose if we're inside a template, because it's not practical to
13924 // fix the warning in most cases.
13925 if (!VD->isTemplated() &&
13927
13928 QualType Type = VD->getType();
13929 if (looksMutable(Type, VD->getASTContext())) {
13930 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13931 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13932 }
13933
13934 // To keep false positives low, only warn if we're certain that the
13935 // initializer has side effects. Don't warn on operator new, since a mutable
13936 // pointer will trigger the previous warning, and an immutable pointer
13937 // getting duplicated just results in a little extra memory usage.
13938 const Expr *Init = VD->getAnyInitializer();
13939 if (Init &&
13940 Init->HasSideEffects(VD->getASTContext(),
13941 /*IncludePossibleEffects=*/false) &&
13942 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13943 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13944 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13945 }
13946 }
13947}
13948
13950 llvm::scope_exit ResetDeclForInitializer([this]() {
13951 if (!this->ExprEvalContexts.empty())
13952 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13953 });
13954
13955 // If there is no declaration, there was an error parsing it. Just ignore
13956 // the initializer.
13957 if (!RealDecl) {
13958 return;
13959 }
13960
13961 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13962 if (!Method->isInvalidDecl()) {
13963 // Pure-specifiers are handled in ActOnPureSpecifier.
13964 Diag(Method->getLocation(), diag::err_member_function_initialization)
13965 << Method->getDeclName() << Init->getSourceRange();
13966 Method->setInvalidDecl();
13967 }
13968 return;
13969 }
13970
13971 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13972 if (!VDecl) {
13973 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13974 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13975 RealDecl->setInvalidDecl();
13976 return;
13977 }
13978
13979 if (VDecl->isInvalidDecl()) {
13980 ExprResult Recovery =
13981 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13982 if (Expr *E = Recovery.get())
13983 VDecl->setInit(E);
13984 return;
13985 }
13986
13987 // __amdgpu_feature_predicate_t cannot be initialised
13988 if (VDecl->getType().getDesugaredType(Context) ==
13989 Context.AMDGPUFeaturePredicateTy) {
13990 Diag(VDecl->getLocation(),
13991 diag::err_amdgcn_predicate_type_is_not_constructible)
13992 << VDecl;
13993 VDecl->setInvalidDecl();
13994 return;
13995 }
13996
13997 // WebAssembly tables can't be used to initialise a variable.
13998 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13999 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
14000 VDecl->setInvalidDecl();
14001 return;
14002 }
14003
14004 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14005 if (VDecl->getType()->isUndeducedType()) {
14006 if (Init->containsErrors()) {
14007 // Invalidate the decl as we don't know the type for recovery-expr yet.
14008 RealDecl->setInvalidDecl();
14009 VDecl->setInit(Init);
14010 return;
14011 }
14012
14014 assert(VDecl->isInvalidDecl() &&
14015 "decl should be invalidated when deduce fails");
14016 if (auto *RecoveryExpr =
14017 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
14018 .get())
14019 VDecl->setInit(RecoveryExpr);
14020 return;
14021 }
14022 }
14023
14024 this->CheckAttributesOnDeducedType(RealDecl);
14025
14026 // we don't initialize groupshared variables so warn and return
14027 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14028 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
14029 return;
14030 }
14031
14032 // dllimport cannot be used on variable definitions.
14033 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14034 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
14035 VDecl->setInvalidDecl();
14036 return;
14037 }
14038
14039 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14040 // the identifier has external or internal linkage, the declaration shall
14041 // have no initializer for the identifier.
14042 // C++14 [dcl.init]p5 is the same restriction for C++.
14043 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14044 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
14045 VDecl->setInvalidDecl();
14046 return;
14047 }
14048
14049 if (!VDecl->getType()->isDependentType()) {
14050 // A definition must end up with a complete type, which means it must be
14051 // complete with the restriction that an array type might be completed by
14052 // the initializer; note that later code assumes this restriction.
14053 QualType BaseDeclType = VDecl->getType();
14054 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
14055 BaseDeclType = Array->getElementType();
14056 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
14057 diag::err_typecheck_decl_incomplete_type)) {
14058 RealDecl->setInvalidDecl();
14059 return;
14060 }
14061
14062 // The variable can not have an abstract class type.
14063 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
14064 diag::err_abstract_type_in_decl,
14066 VDecl->setInvalidDecl();
14067 }
14068
14069 // C++ [module.import/6]
14070 // ...
14071 // A header unit shall not contain a definition of a non-inline function or
14072 // variable whose name has external linkage.
14073 //
14074 // We choose to allow weak & selectany definitions, as they are common in
14075 // headers, and have semantics similar to inline definitions which are allowed
14076 // in header units.
14077 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14078 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14079 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14080 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14082 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14083 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14084 VDecl->setInvalidDecl();
14085 }
14086
14087 // If adding the initializer will turn this declaration into a definition,
14088 // and we already have a definition for this variable, diagnose or otherwise
14089 // handle the situation.
14090 if (VarDecl *Def = VDecl->getDefinition())
14091 if (Def != VDecl &&
14092 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14094 checkVarDeclRedefinition(Def, VDecl))
14095 return;
14096
14097 if (getLangOpts().CPlusPlus) {
14098 // C++ [class.static.data]p4
14099 // If a static data member is of const integral or const
14100 // enumeration type, its declaration in the class definition can
14101 // specify a constant-initializer which shall be an integral
14102 // constant expression (5.19). In that case, the member can appear
14103 // in integral constant expressions. The member shall still be
14104 // defined in a namespace scope if it is used in the program and the
14105 // namespace scope definition shall not contain an initializer.
14106 //
14107 // We already performed a redefinition check above, but for static
14108 // data members we also need to check whether there was an in-class
14109 // declaration with an initializer.
14110 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14111 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14112 << VDecl->getDeclName();
14113 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14114 diag::note_previous_initializer)
14115 << 0;
14116 return;
14117 }
14118
14120 VDecl->setInvalidDecl();
14121 return;
14122 }
14123 }
14124
14125 // If the variable has an initializer and local storage, check whether
14126 // anything jumps over the initialization.
14127 if (VDecl->hasLocalStorage())
14129
14130 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14131 // a kernel function cannot be initialized."
14132 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14133 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14134 VDecl->setInvalidDecl();
14135 return;
14136 }
14137
14138 // The LoaderUninitialized attribute acts as a definition (of undef).
14139 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14140 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14141 VDecl->setInvalidDecl();
14142 return;
14143 }
14144
14145 if (getLangOpts().HLSL)
14146 if (!HLSL().handleInitialization(VDecl, Init))
14147 return;
14148
14149 // Get the decls type and save a reference for later, since
14150 // CheckInitializerTypes may change it.
14151 QualType DclT = VDecl->getType(), SavT = DclT;
14152
14153 // Expressions default to 'id' when we're in a debugger
14154 // and we are assigning it to a variable of Objective-C pointer type.
14155 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14156 Init->getType() == Context.UnknownAnyTy) {
14158 if (!Result.isUsable()) {
14159 VDecl->setInvalidDecl();
14160 return;
14161 }
14162 Init = Result.get();
14163 }
14164
14165 // Perform the initialization.
14166 bool InitializedFromParenListExpr = false;
14167 bool IsParenListInit = false;
14168 if (!VDecl->isInvalidDecl()) {
14171 VDecl->getLocation(), DirectInit, Init);
14172
14173 MultiExprArg Args = Init;
14174 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14175 Args =
14176 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14177 InitializedFromParenListExpr = true;
14178 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14179 Args = CXXDirectInit->getInitExprs();
14180 InitializedFromParenListExpr = true;
14181 }
14182
14183 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14184 /*TopLevelOfInitList=*/false,
14185 /*TreatUnavailableAsInvalid=*/false);
14186 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14187 if (!Result.isUsable()) {
14188 // If the provided initializer fails to initialize the var decl,
14189 // we attach a recovery expr for better recovery.
14190 auto RecoveryExpr =
14191 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14192 if (RecoveryExpr.get())
14193 VDecl->setInit(RecoveryExpr.get());
14194 // In general, for error recovery purposes, the initializer doesn't play
14195 // part in the valid bit of the declaration. There are a few exceptions:
14196 // 1) if the var decl has a deduced auto type, and the type cannot be
14197 // deduced by an invalid initializer;
14198 // 2) if the var decl is a decomposition decl with a non-deduced type,
14199 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14200 // Case 1) was already handled elsewhere.
14201 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14202 VDecl->setInvalidDecl();
14203 return;
14204 }
14205
14206 Init = Result.getAs<Expr>();
14207 IsParenListInit = !InitSeq.steps().empty() &&
14208 InitSeq.step_begin()->Kind ==
14210 QualType VDeclType = VDecl->getType();
14211 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14212 !VDeclType->isDependentType() &&
14213 Context.getAsIncompleteArrayType(VDeclType) &&
14214 Context.getAsIncompleteArrayType(Init->getType())) {
14215 // Bail out if it is not possible to deduce array size from the
14216 // initializer.
14217 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14218 << VDeclType;
14219 VDecl->setInvalidDecl();
14220 return;
14221 }
14222 }
14223
14224 // Check for self-references within variable initializers.
14225 // Variables declared within a function/method body (except for references)
14226 // are handled by a dataflow analysis.
14227 // This is undefined behavior in C++, but valid in C.
14228 if (getLangOpts().CPlusPlus)
14229 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14230 VDecl->getType()->isReferenceType())
14231 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14232
14233 // If the type changed, it means we had an incomplete type that was
14234 // completed by the initializer. For example:
14235 // int ary[] = { 1, 3, 5 };
14236 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14237 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14238 VDecl->setType(DclT);
14239
14240 if (!VDecl->isInvalidDecl()) {
14241 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14242
14243 if (VDecl->hasAttr<BlocksAttr>())
14244 ObjC().checkRetainCycles(VDecl, Init);
14245
14246 // It is safe to assign a weak reference into a strong variable.
14247 // Although this code can still have problems:
14248 // id x = self.weakProp;
14249 // id y = self.weakProp;
14250 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14251 // paths through the function. This should be revisited if
14252 // -Wrepeated-use-of-weak is made flow-sensitive.
14253 if (FunctionScopeInfo *FSI = getCurFunction())
14254 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14256 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14257 Init->getBeginLoc()))
14258 FSI->markSafeWeakUse(Init);
14259 }
14260
14261 // The initialization is usually a full-expression.
14262 //
14263 // FIXME: If this is a braced initialization of an aggregate, it is not
14264 // an expression, and each individual field initializer is a separate
14265 // full-expression. For instance, in:
14266 //
14267 // struct Temp { ~Temp(); };
14268 // struct S { S(Temp); };
14269 // struct T { S a, b; } t = { Temp(), Temp() }
14270 //
14271 // we should destroy the first Temp before constructing the second.
14272
14273 // Set context flag for OverflowBehaviorType initialization analysis
14275 true);
14278 /*DiscardedValue*/ false, VDecl->isConstexpr());
14279 if (!Result.isUsable()) {
14280 VDecl->setInvalidDecl();
14281 return;
14282 }
14283 Init = Result.get();
14284
14285 // Attach the initializer to the decl.
14286 VDecl->setInit(Init);
14287
14288 if (VDecl->isLocalVarDecl()) {
14289 // Don't check the initializer if the declaration is malformed.
14290 if (VDecl->isInvalidDecl()) {
14291 // do nothing
14292
14293 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14294 // This is true even in C++ for OpenCL.
14295 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14297
14298 // Otherwise, C++ does not restrict the initializer.
14299 } else if (getLangOpts().CPlusPlus) {
14300 // do nothing
14301
14302 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14303 // static storage duration shall be constant expressions or string literals.
14304 } else if (VDecl->getStorageClass() == SC_Static) {
14305 // Avoid evaluating the initializer twice for constexpr variables. It will
14306 // be evaluated later.
14307 if (!VDecl->isConstexpr())
14309
14310 // C89 is stricter than C99 for aggregate initializers.
14311 // C89 6.5.7p3: All the expressions [...] in an initializer list
14312 // for an object that has aggregate or union type shall be
14313 // constant expressions.
14314 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14316 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14317 }
14318
14319 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14320 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14321 if (VDecl->hasLocalStorage())
14322 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14323 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14324 VDecl->getLexicalDeclContext()->isRecord()) {
14325 // This is an in-class initialization for a static data member, e.g.,
14326 //
14327 // struct S {
14328 // static const int value = 17;
14329 // };
14330
14331 // C++ [class.mem]p4:
14332 // A member-declarator can contain a constant-initializer only
14333 // if it declares a static member (9.4) of const integral or
14334 // const enumeration type, see 9.4.2.
14335 //
14336 // C++11 [class.static.data]p3:
14337 // If a non-volatile non-inline const static data member is of integral
14338 // or enumeration type, its declaration in the class definition can
14339 // specify a brace-or-equal-initializer in which every initializer-clause
14340 // that is an assignment-expression is a constant expression. A static
14341 // data member of literal type can be declared in the class definition
14342 // with the constexpr specifier; if so, its declaration shall specify a
14343 // brace-or-equal-initializer in which every initializer-clause that is
14344 // an assignment-expression is a constant expression.
14345
14346 // Do nothing on dependent types.
14347 if (DclT->isDependentType()) {
14348
14349 // Allow any 'static constexpr' members, whether or not they are of literal
14350 // type. We separately check that every constexpr variable is of literal
14351 // type.
14352 } else if (VDecl->isConstexpr()) {
14353
14354 // Require constness.
14355 } else if (!DclT.isConstQualified()) {
14356 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14357 << Init->getSourceRange();
14358 VDecl->setInvalidDecl();
14359
14360 // We allow integer constant expressions in all cases.
14361 } else if (DclT->isIntegralOrEnumerationType()) {
14363 // In C++11, a non-constexpr const static data member with an
14364 // in-class initializer cannot be volatile.
14365 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14366
14367 // We allow foldable floating-point constants as an extension.
14368 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14369 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14370 // it anyway and provide a fixit to add the 'constexpr'.
14371 if (getLangOpts().CPlusPlus11) {
14372 Diag(VDecl->getLocation(),
14373 diag::ext_in_class_initializer_float_type_cxx11)
14374 << DclT << Init->getSourceRange();
14375 Diag(VDecl->getBeginLoc(),
14376 diag::note_in_class_initializer_float_type_cxx11)
14377 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14378 } else {
14379 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14380 << DclT << Init->getSourceRange();
14381
14382 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14383 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14384 << Init->getSourceRange();
14385 VDecl->setInvalidDecl();
14386 }
14387 }
14388
14389 // Suggest adding 'constexpr' in C++11 for literal types.
14390 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14391 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14392 << DclT << Init->getSourceRange()
14393 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14394 VDecl->setConstexpr(true);
14395
14396 } else {
14397 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14398 << DclT << Init->getSourceRange();
14399 VDecl->setInvalidDecl();
14400 }
14401 } else if (VDecl->isFileVarDecl()) {
14402 // In C, extern is typically used to avoid tentative definitions when
14403 // declaring variables in headers, but adding an initializer makes it a
14404 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14405 // In C++, extern is often used to give implicitly static const variables
14406 // external linkage, so don't warn in that case. If selectany is present,
14407 // this might be header code intended for C and C++ inclusion, so apply the
14408 // C++ rules.
14409 if (VDecl->getStorageClass() == SC_Extern &&
14410 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14411 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14412 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14414 Diag(VDecl->getLocation(), diag::warn_extern_init);
14415
14416 // In Microsoft C++ mode, a const variable defined in namespace scope has
14417 // external linkage by default if the variable is declared with
14418 // __declspec(dllexport).
14419 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14421 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14422 VDecl->setStorageClass(SC_Extern);
14423
14424 // C99 6.7.8p4. All file scoped initializers need to be constant.
14425 // Avoid duplicate diagnostics for constexpr variables.
14426 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14427 !VDecl->isConstexpr())
14429 }
14430
14431 QualType InitType = Init->getType();
14432 if (!InitType.isNull() &&
14436
14437 // We will represent direct-initialization similarly to copy-initialization:
14438 // int x(1); -as-> int x = 1;
14439 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14440 //
14441 // Clients that want to distinguish between the two forms, can check for
14442 // direct initializer using VarDecl::getInitStyle().
14443 // A major benefit is that clients that don't particularly care about which
14444 // exactly form was it (like the CodeGen) can handle both cases without
14445 // special case code.
14446
14447 // C++ 8.5p11:
14448 // The form of initialization (using parentheses or '=') matters
14449 // when the entity being initialized has class type.
14450 if (InitializedFromParenListExpr) {
14451 assert(DirectInit && "Call-style initializer must be direct init.");
14452 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14454 } else if (DirectInit) {
14455 // This must be list-initialization. No other way is direct-initialization.
14457 }
14458
14459 if (LangOpts.OpenMP &&
14460 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14461 VDecl->isFileVarDecl())
14462 DeclsToCheckForDeferredDiags.insert(VDecl);
14464
14465 if (LangOpts.OpenACC && !InitType.isNull())
14466 OpenACC().ActOnVariableInit(VDecl, InitType);
14467}
14468
14470 // Our main concern here is re-establishing invariants like "a
14471 // variable's type is either dependent or complete".
14472 if (!D || D->isInvalidDecl()) return;
14473
14474 VarDecl *VD = dyn_cast<VarDecl>(D);
14475 if (!VD) return;
14476
14477 // Bindings are not usable if we can't make sense of the initializer.
14478 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14479 for (auto *BD : DD->bindings())
14480 BD->setInvalidDecl();
14481
14482 // Auto types are meaningless if we can't make sense of the initializer.
14483 if (VD->getType()->isUndeducedType()) {
14484 D->setInvalidDecl();
14485 return;
14486 }
14487
14488 QualType Ty = VD->getType();
14489 if (Ty->isDependentType()) return;
14490
14491 // Require a complete type.
14493 Context.getBaseElementType(Ty),
14494 diag::err_typecheck_decl_incomplete_type)) {
14495 VD->setInvalidDecl();
14496 return;
14497 }
14498
14499 // Require a non-abstract type.
14500 if (RequireNonAbstractType(VD->getLocation(), Ty,
14501 diag::err_abstract_type_in_decl,
14503 VD->setInvalidDecl();
14504 return;
14505 }
14506
14507 // Don't bother complaining about constructors or destructors,
14508 // though.
14509}
14510
14512 // If there is no declaration, there was an error parsing it. Just ignore it.
14513 if (!RealDecl)
14514 return;
14515
14516 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14517 QualType Type = Var->getType();
14518
14519 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14520 Diag(Var->getLocation(),
14521 diag::err_amdgcn_predicate_type_is_not_constructible)
14522 << Var;
14523 Var->setInvalidDecl();
14524 return;
14525 }
14526 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14527 if (isa<DecompositionDecl>(RealDecl)) {
14528 // Point the caret to the token immediately after the closing bracket if
14529 // it can be found; otherwise fall back to the declaration's location.
14530 SourceLocation Loc = Var->getLocation();
14531 SourceLocation RSquareLoc =
14532 dyn_cast<DecompositionDecl>(RealDecl)->getRSquareLoc();
14533 if (std::optional<Token> Next = Lexer::findNextToken(
14534 RSquareLoc, PP.getSourceManager(), PP.getLangOpts()))
14535 Loc = Next->getLocation();
14536 Diag(Loc, diag::err_decomp_decl_requires_init) << Var;
14537 Var->setInvalidDecl();
14538 return;
14539 }
14540
14541 if (Type->isUndeducedType() &&
14542 DeduceVariableDeclarationType(Var, false, nullptr))
14543 return;
14544
14545 this->CheckAttributesOnDeducedType(RealDecl);
14546
14547 // C++11 [class.static.data]p3: A static data member can be declared with
14548 // the constexpr specifier; if so, its declaration shall specify
14549 // a brace-or-equal-initializer.
14550 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14551 // the definition of a variable [...] or the declaration of a static data
14552 // member.
14553 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14554 !Var->isThisDeclarationADemotedDefinition()) {
14555 if (Var->isStaticDataMember()) {
14556 // C++1z removes the relevant rule; the in-class declaration is always
14557 // a definition there.
14558 if (!getLangOpts().CPlusPlus17 &&
14559 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14560 Diag(Var->getLocation(),
14561 diag::err_constexpr_static_mem_var_requires_init)
14562 << Var;
14563 Var->setInvalidDecl();
14564 return;
14565 }
14566 } else {
14567 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14568 Var->setInvalidDecl();
14569 return;
14570 }
14571 }
14572
14573 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14574 // be initialized.
14575 if (!Var->isInvalidDecl() &&
14576 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14577 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14578 bool HasConstExprDefaultConstructor = false;
14579 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14580 for (auto *Ctor : RD->ctors()) {
14581 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14582 Ctor->getMethodQualifiers().getAddressSpace() ==
14584 HasConstExprDefaultConstructor = true;
14585 }
14586 }
14587 }
14588 if (!HasConstExprDefaultConstructor) {
14589 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14590 Var->setInvalidDecl();
14591 return;
14592 }
14593 }
14594
14595 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14596 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14597 Diag(Var->getLocation(), diag::err_specialization_const);
14598 Var->setInvalidDecl();
14599 return;
14600 }
14601
14602 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14603 if (Var->getStorageClass() == SC_Extern) {
14604 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14605 << Var;
14606 Var->setInvalidDecl();
14607 return;
14608 }
14609 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14610 diag::err_typecheck_decl_incomplete_type)) {
14611 Var->setInvalidDecl();
14612 return;
14613 }
14614 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14615 if (!RD->hasTrivialDefaultConstructor()) {
14616 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14617 Var->setInvalidDecl();
14618 return;
14619 }
14620 }
14621 // The declaration is uninitialized, no need for further checks.
14622 return;
14623 }
14624
14625 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14626 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14627 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14628 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14630 NTCUK_Init);
14631
14632 switch (DefKind) {
14634 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14635 break;
14636
14637 // We have an out-of-line definition of a static data member
14638 // that has an in-class initializer, so we type-check this like
14639 // a declaration.
14640 //
14641 [[fallthrough]];
14642
14644 // It's only a declaration.
14645
14646 // Block scope. C99 6.7p7: If an identifier for an object is
14647 // declared with no linkage (C99 6.2.2p6), the type for the
14648 // object shall be complete.
14649 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14650 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14651 RequireCompleteType(Var->getLocation(), Type,
14652 diag::err_typecheck_decl_incomplete_type))
14653 Var->setInvalidDecl();
14654
14655 // Make sure that the type is not abstract.
14656 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14657 RequireNonAbstractType(Var->getLocation(), Type,
14658 diag::err_abstract_type_in_decl,
14660 Var->setInvalidDecl();
14661 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14662 Var->getStorageClass() == SC_PrivateExtern) {
14663 Diag(Var->getLocation(), diag::warn_private_extern);
14664 Diag(Var->getLocation(), diag::note_private_extern);
14665 }
14666
14667 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14668 !Var->isInvalidDecl())
14669 ExternalDeclarations.push_back(Var);
14670
14671 return;
14672
14674 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14675 // object that has file scope without an initializer, and without a
14676 // storage-class specifier or with the storage-class specifier "static",
14677 // constitutes a tentative definition. Note: A tentative definition with
14678 // external linkage is valid (C99 6.2.2p5).
14679 if (!Var->isInvalidDecl()) {
14680 if (const IncompleteArrayType *ArrayT
14681 = Context.getAsIncompleteArrayType(Type)) {
14683 Var->getLocation(), ArrayT->getElementType(),
14684 diag::err_array_incomplete_or_sizeless_type))
14685 Var->setInvalidDecl();
14686 }
14687 if (Var->getStorageClass() == SC_Static) {
14688 // C99 6.9.2p3: If the declaration of an identifier for an object is
14689 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14690 // declared type shall not be an incomplete type.
14691 // NOTE: code such as the following
14692 // static struct s;
14693 // struct s { int a; };
14694 // is accepted by gcc. Hence here we issue a warning instead of
14695 // an error and we do not invalidate the static declaration.
14696 // NOTE: to avoid multiple warnings, only check the first declaration.
14697 if (Var->isFirstDecl())
14698 RequireCompleteType(Var->getLocation(), Type,
14699 diag::ext_typecheck_decl_incomplete_type,
14700 Type->isArrayType());
14701 }
14702 }
14703
14704 // Record the tentative definition; we're done.
14705 if (!Var->isInvalidDecl())
14706 TentativeDefinitions.push_back(Var);
14707 return;
14708 }
14709
14710 // Provide a specific diagnostic for uninitialized variable definitions
14711 // with incomplete array type, unless it is a global unbounded HLSL resource
14712 // array.
14713 if (Type->isIncompleteArrayType() &&
14714 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14716 if (Var->isConstexpr())
14717 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14718 << Var;
14719 else
14720 Diag(Var->getLocation(),
14721 diag::err_typecheck_incomplete_array_needs_initializer);
14722 Var->setInvalidDecl();
14723 return;
14724 }
14725
14726 // Provide a specific diagnostic for uninitialized variable
14727 // definitions with reference type.
14728 if (Type->isReferenceType()) {
14729 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14730 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14731 return;
14732 }
14733
14734 // Do not attempt to type-check the default initializer for a
14735 // variable with dependent type.
14736 if (Type->isDependentType())
14737 return;
14738
14739 if (Var->isInvalidDecl())
14740 return;
14741
14742 if (!Var->hasAttr<AliasAttr>()) {
14743 if (RequireCompleteType(Var->getLocation(),
14744 Context.getBaseElementType(Type),
14745 diag::err_typecheck_decl_incomplete_type)) {
14746 Var->setInvalidDecl();
14747 return;
14748 }
14749 } else {
14750 return;
14751 }
14752
14753 // The variable can not have an abstract class type.
14754 if (RequireNonAbstractType(Var->getLocation(), Type,
14755 diag::err_abstract_type_in_decl,
14757 Var->setInvalidDecl();
14758 return;
14759 }
14760
14761 // In C, if the definition is const-qualified and has no initializer, it
14762 // is left uninitialized unless it has static or thread storage duration.
14763 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14764 unsigned DiagID = diag::warn_default_init_const_unsafe;
14765 if (Var->getStorageDuration() == SD_Static ||
14766 Var->getStorageDuration() == SD_Thread)
14767 DiagID = diag::warn_default_init_const;
14768
14769 bool EmitCppCompat = !Diags.isIgnored(
14770 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14771 Var->getLocation());
14772
14773 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14774 }
14775
14776 // Check for jumps past the implicit initializer. C++0x
14777 // clarifies that this applies to a "variable with automatic
14778 // storage duration", not a "local variable".
14779 // C++11 [stmt.dcl]p3
14780 // A program that jumps from a point where a variable with automatic
14781 // storage duration is not in scope to a point where it is in scope is
14782 // ill-formed unless the variable has scalar type, class type with a
14783 // trivial default constructor and a trivial destructor, a cv-qualified
14784 // version of one of these types, or an array of one of the preceding
14785 // types and is declared without an initializer.
14786 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14787 if (const auto *CXXRecord =
14788 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14789 // Mark the function (if we're in one) for further checking even if the
14790 // looser rules of C++11 do not require such checks, so that we can
14791 // diagnose incompatibilities with C++98.
14792 if (!CXXRecord->isPOD())
14794 }
14795 }
14796 // In OpenCL, we can't initialize objects in the __local address space,
14797 // even implicitly, so don't synthesize an implicit initializer.
14798 if (getLangOpts().OpenCL &&
14799 Var->getType().getAddressSpace() == LangAS::opencl_local)
14800 return;
14801
14802 // Handle HLSL uninitialized decls
14803 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14804 return;
14805
14806 // HLSL input & push-constant variables are expected to be externally
14807 // initialized, even when marked `static`.
14808 if (getLangOpts().HLSL &&
14809 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14810 return;
14811
14812 // C++03 [dcl.init]p9:
14813 // If no initializer is specified for an object, and the
14814 // object is of (possibly cv-qualified) non-POD class type (or
14815 // array thereof), the object shall be default-initialized; if
14816 // the object is of const-qualified type, the underlying class
14817 // type shall have a user-declared default
14818 // constructor. Otherwise, if no initializer is specified for
14819 // a non- static object, the object and its subobjects, if
14820 // any, have an indeterminate initial value); if the object
14821 // or any of its subobjects are of const-qualified type, the
14822 // program is ill-formed.
14823 // C++0x [dcl.init]p11:
14824 // If no initializer is specified for an object, the object is
14825 // default-initialized; [...].
14828 = InitializationKind::CreateDefault(Var->getLocation());
14829
14830 InitializationSequence InitSeq(*this, Entity, Kind, {});
14831 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14832
14833 if (Init.get()) {
14834 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14835 // This is important for template substitution.
14836 Var->setInitStyle(VarDecl::CallInit);
14837 } else if (Init.isInvalid()) {
14838 // If default-init fails, attach a recovery-expr initializer to track
14839 // that initialization was attempted and failed.
14840 auto RecoveryExpr =
14841 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14842 if (RecoveryExpr.get())
14843 Var->setInit(RecoveryExpr.get());
14844 }
14845
14847 }
14848}
14849
14850void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
14851 // If there is no declaration, there was an error parsing it. Ignore it.
14852 if (!D)
14853 return;
14854
14855 VarDecl *VD = dyn_cast<VarDecl>(D);
14856 if (!VD) {
14857 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var)
14858 << InExpansionStmt;
14859 D->setInvalidDecl();
14860 return;
14861 }
14862
14863 VD->setCXXForRangeDecl(true);
14864
14865 // for-range-declaration cannot be given a storage class specifier.
14866 int Error = -1;
14867 switch (VD->getStorageClass()) {
14868 case SC_None:
14869 break;
14870 case SC_Extern:
14871 Error = 0;
14872 break;
14873 case SC_Static:
14874 Error = 1;
14875 break;
14876 case SC_PrivateExtern:
14877 Error = 2;
14878 break;
14879 case SC_Auto:
14880 Error = 3;
14881 break;
14882 case SC_Register:
14883 Error = 4;
14884 break;
14885 }
14886
14887 // for-range-declaration cannot be given a storage class specifier con't.
14888 switch (VD->getTSCSpec()) {
14889 case TSCS_thread_local:
14890 Error = 6;
14891 break;
14892 case TSCS___thread:
14893 case TSCS__Thread_local:
14894 case TSCS_unspecified:
14895 break;
14896 }
14897
14898 if (Error != -1) {
14899 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14900 << InExpansionStmt << VD << Error;
14901 D->setInvalidDecl();
14902 }
14903}
14904
14906 IdentifierInfo *Ident,
14907 ParsedAttributes &Attrs) {
14908 // C++1y [stmt.iter]p1:
14909 // A range-based for statement of the form
14910 // for ( for-range-identifier : for-range-initializer ) statement
14911 // is equivalent to
14912 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14913 DeclSpec DS(Attrs.getPool().getFactory());
14914
14915 const char *PrevSpec;
14916 unsigned DiagID;
14917 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14919
14921 D.SetIdentifier(Ident, IdentLoc);
14922 D.takeAttributesAppending(Attrs);
14923
14924 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14925 IdentLoc);
14926 Decl *Var = ActOnDeclarator(S, D);
14927 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14929 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14930 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14931 : IdentLoc);
14932}
14933
14936 return;
14937 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
14938 QualType MethodType = MD->getType();
14939 QualType AttributedType =
14940 Context.getAttributedType(Attr, MethodType, MethodType);
14941 TypeLocBuilder TLB;
14942 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14943 TLB.pushFullCopy(TSI->getTypeLoc());
14944 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
14945 TyLoc.setAttr(Attr);
14946 MD->setType(AttributedType);
14947 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
14948}
14949
14951 if (var->isInvalidDecl()) return;
14952
14954
14955 if (getLangOpts().OpenCL) {
14956 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14957 // initialiser
14958 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14959 !var->hasInit()) {
14960 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14961 << 1 /*Init*/;
14962 var->setInvalidDecl();
14963 return;
14964 }
14965 }
14966
14967 // In Objective-C, don't allow jumps past the implicit initialization of a
14968 // local retaining variable.
14969 if (getLangOpts().ObjC &&
14970 var->hasLocalStorage()) {
14971 switch (var->getType().getObjCLifetime()) {
14975 break;
14976
14980 break;
14981 }
14982 }
14983
14984 if (var->hasLocalStorage() &&
14985 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14987
14988 // Warn about externally-visible variables being defined without a
14989 // prior declaration. We only want to do this for global
14990 // declarations, but we also specifically need to avoid doing it for
14991 // class members because the linkage of an anonymous class can
14992 // change if it's later given a typedef name.
14993 if (var->isThisDeclarationADefinition() &&
14994 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14995 var->isExternallyVisible() && var->hasLinkage() &&
14996 !var->isInline() && !var->getDescribedVarTemplate() &&
14997 var->getStorageClass() != SC_Register &&
14999 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
15000 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
15001 var->getLocation())) {
15002 // Find a previous declaration that's not a definition.
15003 VarDecl *prev = var->getPreviousDecl();
15004 while (prev && prev->isThisDeclarationADefinition())
15005 prev = prev->getPreviousDecl();
15006
15007 if (!prev) {
15008 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
15009 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
15010 << /* variable */ 0;
15011 }
15012 }
15013
15014 // Cache the result of checking for constant initialization.
15015 std::optional<bool> CacheHasConstInit;
15016 const Expr *CacheCulprit = nullptr;
15017 auto checkConstInit = [&]() mutable {
15018 const Expr *Init = var->getInit();
15019 if (Init->isInstantiationDependent())
15020 return true;
15021
15022 if (!CacheHasConstInit)
15023 CacheHasConstInit = var->getInit()->isConstantInitializer(
15024 Context, var->getType()->isReferenceType(), &CacheCulprit);
15025 return *CacheHasConstInit;
15026 };
15027
15028 if (var->getTLSKind() == VarDecl::TLS_Static) {
15029 if (var->getType().isDestructedType()) {
15030 // GNU C++98 edits for __thread, [basic.start.term]p3:
15031 // The type of an object with thread storage duration shall not
15032 // have a non-trivial destructor.
15033 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
15035 Diag(var->getLocation(), diag::note_use_thread_local);
15036 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15037 if (!checkConstInit()) {
15038 // GNU C++98 edits for __thread, [basic.start.init]p4:
15039 // An object of thread storage duration shall not require dynamic
15040 // initialization.
15041 // FIXME: Need strict checking here.
15042 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
15043 << CacheCulprit->getSourceRange();
15045 Diag(var->getLocation(), diag::note_use_thread_local);
15046 }
15047 }
15048 }
15049
15050
15051 if (!var->getType()->isStructureType() && var->hasInit() &&
15052 isa<InitListExpr>(var->getInit())) {
15053 const auto *ILE = cast<InitListExpr>(var->getInit());
15054 unsigned NumInits = ILE->getNumInits();
15055 if (NumInits > 2)
15056 for (unsigned I = 0; I < NumInits; ++I) {
15057 const auto *Init = ILE->getInit(I);
15058 if (!Init)
15059 break;
15060 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15061 if (!SL)
15062 break;
15063
15064 unsigned NumConcat = SL->getNumConcatenated();
15065 // Diagnose missing comma in string array initialization.
15066 // Do not warn when all the elements in the initializer are concatenated
15067 // together. Do not warn for macros too.
15068 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15069 bool OnlyOneMissingComma = true;
15070 for (unsigned J = I + 1; J < NumInits; ++J) {
15071 const auto *Init = ILE->getInit(J);
15072 if (!Init)
15073 break;
15074 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15075 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15076 OnlyOneMissingComma = false;
15077 break;
15078 }
15079 }
15080
15081 if (OnlyOneMissingComma) {
15083 for (unsigned i = 0; i < NumConcat - 1; ++i)
15084 Hints.push_back(FixItHint::CreateInsertion(
15085 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15086
15087 Diag(SL->getStrTokenLoc(1),
15088 diag::warn_concatenated_literal_array_init)
15089 << Hints;
15090 Diag(SL->getBeginLoc(),
15091 diag::note_concatenated_string_literal_silence);
15092 }
15093 // In any case, stop now.
15094 break;
15095 }
15096 }
15097 }
15098
15099
15100 QualType type = var->getType();
15101
15102 if (var->hasAttr<BlocksAttr>())
15104
15105 Expr *Init = var->getInit();
15106 bool GlobalStorage = var->hasGlobalStorage();
15107 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15108 QualType baseType = Context.getBaseElementType(type);
15109 bool HasConstInit = true;
15110
15111 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15112 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15113 << var;
15114
15115 // Check whether the initializer is sufficiently constant.
15116 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15117 !type->isDependentType() && Init && !Init->isValueDependent() &&
15118 (GlobalStorage || var->isConstexpr() ||
15119 var->mightBeUsableInConstantExpressions(Context))) {
15120 // If this variable might have a constant initializer or might be usable in
15121 // constant expressions, check whether or not it actually is now. We can't
15122 // do this lazily, because the result might depend on things that change
15123 // later, such as which constexpr functions happen to be defined.
15125 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15126 // Prior to C++11, in contexts where a constant initializer is required,
15127 // the set of valid constant initializers is described by syntactic rules
15128 // in [expr.const]p2-6.
15129 // FIXME: Stricter checking for these rules would be useful for constinit /
15130 // -Wglobal-constructors.
15131 HasConstInit = checkConstInit();
15132
15133 // Compute and cache the constant value, and remember that we have a
15134 // constant initializer.
15135 if (HasConstInit) {
15136 if (var->isStaticDataMember() && !var->isInline() &&
15137 var->getLexicalDeclContext()->isRecord() &&
15138 type->isIntegralOrEnumerationType()) {
15139 // In C++98, in-class initialization for a static data member must
15140 // be an integer constant expression.
15141 if (!Init->isIntegerConstantExpr(Context)) {
15142 Diag(Init->getExprLoc(),
15143 diag::ext_in_class_initializer_non_constant)
15144 << Init->getSourceRange();
15145 }
15146 }
15147 (void)var->checkForConstantInitialization(Notes);
15148 Notes.clear();
15149 } else if (CacheCulprit) {
15150 Notes.emplace_back(CacheCulprit->getExprLoc(),
15151 PDiag(diag::note_invalid_subexpr_in_const_expr));
15152 Notes.back().second << CacheCulprit->getSourceRange();
15153 }
15154 } else {
15155 // Evaluate the initializer to see if it's a constant initializer.
15156 HasConstInit = var->checkForConstantInitialization(Notes);
15157 }
15158
15159 if (HasConstInit) {
15160 // FIXME: Consider replacing the initializer with a ConstantExpr.
15161 } else if (var->isConstexpr()) {
15162 SourceLocation DiagLoc = var->getLocation();
15163 // If the note doesn't add any useful information other than a source
15164 // location, fold it into the primary diagnostic.
15165 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15166 diag::note_invalid_subexpr_in_const_expr) {
15167 DiagLoc = Notes[0].first;
15168 Notes.clear();
15169 }
15170 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15171 << var << Init->getSourceRange();
15172 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15173 Diag(Notes[I].first, Notes[I].second);
15174 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15175 auto *Attr = var->getAttr<ConstInitAttr>();
15176 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15177 << Init->getSourceRange();
15178 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15179 << Attr->getRange() << Attr->isConstinit();
15180 for (auto &it : Notes)
15181 Diag(it.first, it.second);
15182 } else if (var->isStaticDataMember() && !var->isInline() &&
15183 var->getLexicalDeclContext()->isRecord()) {
15184 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15185 << Init->getSourceRange();
15186 for (auto &it : Notes)
15187 Diag(it.first, it.second);
15188 var->setInvalidDecl();
15189 } else if (IsGlobal &&
15190 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15191 var->getLocation())) {
15192 // Warn about globals which don't have a constant initializer. Don't
15193 // warn about globals with a non-trivial destructor because we already
15194 // warned about them.
15195 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15196 if (!(RD && !RD->hasTrivialDestructor())) {
15197 // checkConstInit() here permits trivial default initialization even in
15198 // C++11 onwards, where such an initializer is not a constant initializer
15199 // but nonetheless doesn't require a global constructor.
15200 if (!checkConstInit())
15201 Diag(var->getLocation(), diag::warn_global_constructor)
15202 << Init->getSourceRange();
15203 }
15204 }
15205 }
15206
15207 // Apply section attributes and pragmas to global variables.
15208 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15210 PragmaStack<StringLiteral *> *Stack = nullptr;
15211 int SectionFlags = ASTContext::PSF_Read;
15212 bool MSVCEnv =
15213 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15214 std::optional<QualType::NonConstantStorageReason> Reason;
15215 if (HasConstInit &&
15216 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15217 Stack = &ConstSegStack;
15218 } else {
15219 SectionFlags |= ASTContext::PSF_Write;
15220 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15221 }
15222 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15223 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15224 SectionFlags |= ASTContext::PSF_Implicit;
15225 UnifySection(SA->getName(), SectionFlags, var);
15226 } else if (Stack->CurrentValue) {
15227 if (Stack != &ConstSegStack && MSVCEnv &&
15228 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15229 var->getType().isConstQualified()) {
15230 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15231 NonConstNonReferenceType) &&
15232 "This case should've already been handled elsewhere");
15233 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15234 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15236 : *Reason);
15237 }
15238 SectionFlags |= ASTContext::PSF_Implicit;
15239 auto SectionName = Stack->CurrentValue->getString();
15240 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15241 Stack->CurrentPragmaLocation,
15242 SectionAttr::Declspec_allocate));
15243 if (UnifySection(SectionName, SectionFlags, var))
15244 var->dropAttr<SectionAttr>();
15245 }
15246
15247 // Apply the init_seg attribute if this has an initializer. If the
15248 // initializer turns out to not be dynamic, we'll end up ignoring this
15249 // attribute.
15250 if (CurInitSeg && var->getInit())
15251 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15252 CurInitSegLoc));
15253 }
15254
15255 // All the following checks are C++ only.
15256 if (!getLangOpts().CPlusPlus) {
15257 // If this variable must be emitted, add it as an initializer for the
15258 // current module.
15259 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15260 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15261 return;
15262 }
15263
15265
15266 // Require the destructor.
15267 if (!type->isDependentType())
15268 if (auto *RD = baseType->getAsCXXRecordDecl())
15270
15271 // If this variable must be emitted, add it as an initializer for the current
15272 // module.
15273 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty() &&
15274 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15275 // For named modules, we may only emit non discardable variables.
15276 !isDiscardableGVALinkage(Context.GetGVALinkageForVariable(var))))
15277 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15278
15279 // Build the bindings if this is a structured binding declaration.
15280 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15282}
15283
15285 assert(VD->isStaticLocal());
15286
15287 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15288
15289 // Find outermost function when VD is in lambda function.
15290 while (FD && !getDLLAttr(FD) &&
15291 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15292 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15293 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15294 }
15295
15296 if (!FD)
15297 return;
15298
15299 // Static locals inherit dll attributes from their function.
15300 if (Attr *A = getDLLAttr(FD)) {
15301 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15302 NewAttr->setInherited(true);
15303 VD->addAttr(NewAttr);
15304 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15305 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15306 NewAttr->setInherited(true);
15307 VD->addAttr(NewAttr);
15308
15309 // Export this function to enforce exporting this static variable even
15310 // if it is not used in this compilation unit.
15311 if (!FD->hasAttr<DLLExportAttr>())
15312 FD->addAttr(NewAttr);
15313
15314 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15315 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15316 NewAttr->setInherited(true);
15317 VD->addAttr(NewAttr);
15318 }
15319}
15320
15322 assert(VD->getTLSKind());
15323
15324 // Perform TLS alignment check here after attributes attached to the variable
15325 // which may affect the alignment have been processed. Only perform the check
15326 // if the target has a maximum TLS alignment (zero means no constraints).
15327 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15328 // Protect the check so that it's not performed on dependent types and
15329 // dependent alignments (we can't determine the alignment in that case).
15330 if (!VD->hasDependentAlignment()) {
15331 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15332 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15333 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15334 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15335 << (unsigned)MaxAlignChars.getQuantity();
15336 }
15337 }
15338 }
15339}
15340
15342 // Note that we are no longer parsing the initializer for this declaration.
15343 ParsingInitForAutoVars.erase(ThisDecl);
15344
15345 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15346 if (!VD)
15347 return;
15348
15349 // Emit any deferred warnings for the variable's initializer, even if the
15350 // variable is invalid
15351 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15352
15353 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15355 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15356 if (PragmaClangBSSSection.Valid)
15357 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15358 Context, PragmaClangBSSSection.SectionName,
15359 PragmaClangBSSSection.PragmaLocation));
15360 if (PragmaClangDataSection.Valid)
15361 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15362 Context, PragmaClangDataSection.SectionName,
15363 PragmaClangDataSection.PragmaLocation));
15364 if (PragmaClangRodataSection.Valid)
15365 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15366 Context, PragmaClangRodataSection.SectionName,
15367 PragmaClangRodataSection.PragmaLocation));
15368 if (PragmaClangRelroSection.Valid)
15369 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15370 Context, PragmaClangRelroSection.SectionName,
15371 PragmaClangRelroSection.PragmaLocation));
15372 }
15373
15374 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15375 for (auto *BD : DD->bindings()) {
15377 }
15378 }
15379
15380 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15382
15383 checkAttributesAfterMerging(*this, *VD);
15384
15385 if (VD->isStaticLocal())
15387
15388 if (VD->getTLSKind())
15390
15391 // Perform check for initializers of device-side global variables.
15392 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15393 // 7.5). We must also apply the same checks to all __shared__
15394 // variables whether they are local or not. CUDA also allows
15395 // constant initializers for __constant__ and __device__ variables.
15396 if (getLangOpts().CUDA)
15398
15399 // Grab the dllimport or dllexport attribute off of the VarDecl.
15400 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15401
15402 // Imported static data members cannot be defined out-of-line.
15403 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15404 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15406 // We allow definitions of dllimport class template static data members
15407 // with a warning.
15410 bool IsClassTemplateMember =
15412 Context->getDescribedClassTemplate();
15413
15414 Diag(VD->getLocation(),
15415 IsClassTemplateMember
15416 ? diag::warn_attribute_dllimport_static_field_definition
15417 : diag::err_attribute_dllimport_static_field_definition);
15418 Diag(IA->getLocation(), diag::note_attribute);
15419 if (!IsClassTemplateMember)
15420 VD->setInvalidDecl();
15421 }
15422 }
15423
15424 // dllimport/dllexport variables cannot be thread local, their TLS index
15425 // isn't exported with the variable.
15426 if (DLLAttr && VD->getTLSKind()) {
15427 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15428 if (F && getDLLAttr(F)) {
15429 assert(VD->isStaticLocal());
15430 // But if this is a static local in a dlimport/dllexport function, the
15431 // function will never be inlined, which means the var would never be
15432 // imported, so having it marked import/export is safe.
15433 } else {
15434 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15435 << DLLAttr;
15436 VD->setInvalidDecl();
15437 }
15438 }
15439
15440 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15441 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15442 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15443 << Attr;
15444 VD->dropAttr<UsedAttr>();
15445 }
15446 }
15447 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15448 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15449 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15450 << Attr;
15451 VD->dropAttr<RetainAttr>();
15452 }
15453 }
15454
15455 const DeclContext *DC = VD->getDeclContext();
15456 // If there's a #pragma GCC visibility in scope, and this isn't a class
15457 // member, set the visibility of this variable.
15460
15461 // FIXME: Warn on unused var template partial specializations.
15464
15465 // Now we have parsed the initializer and can update the table of magic
15466 // tag values.
15467 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15469 return;
15470
15471 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15472 const Expr *MagicValueExpr = VD->getInit();
15473 if (!MagicValueExpr) {
15474 continue;
15475 }
15476 std::optional<llvm::APSInt> MagicValueInt;
15477 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15478 Diag(I->getRange().getBegin(),
15479 diag::err_type_tag_for_datatype_not_ice)
15480 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15481 continue;
15482 }
15483 if (MagicValueInt->getActiveBits() > 64) {
15484 Diag(I->getRange().getBegin(),
15485 diag::err_type_tag_for_datatype_too_large)
15486 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15487 continue;
15488 }
15489 uint64_t MagicValue = MagicValueInt->getZExtValue();
15490 RegisterTypeTagForDatatype(I->getArgumentKind(),
15491 MagicValue,
15492 I->getMatchingCType(),
15493 I->getLayoutCompatible(),
15494 I->getMustBeNull());
15495 }
15496}
15497
15499 auto *VD = dyn_cast<VarDecl>(DD);
15500 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15501}
15502
15504 ArrayRef<Decl *> Group) {
15506
15507 if (DS.isTypeSpecOwned())
15508 Decls.push_back(DS.getRepAsDecl());
15509
15510 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15511 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15512 bool DiagnosedMultipleDecomps = false;
15513 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15514 bool DiagnosedNonDeducedAuto = false;
15515
15516 for (Decl *D : Group) {
15517 if (!D)
15518 continue;
15519 // Check if the Decl has been declared in '#pragma omp declare target'
15520 // directive and has static storage duration.
15521 if (auto *VD = dyn_cast<VarDecl>(D);
15522 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15523 VD->hasGlobalStorage())
15525 // For declarators, there are some additional syntactic-ish checks we need
15526 // to perform.
15527 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15528 if (!FirstDeclaratorInGroup)
15529 FirstDeclaratorInGroup = DD;
15530 if (!FirstDecompDeclaratorInGroup)
15531 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15532 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15533 !hasDeducedAuto(DD))
15534 FirstNonDeducedAutoInGroup = DD;
15535
15536 if (FirstDeclaratorInGroup != DD) {
15537 // A decomposition declaration cannot be combined with any other
15538 // declaration in the same group.
15539 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15540 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15541 diag::err_decomp_decl_not_alone)
15542 << FirstDeclaratorInGroup->getSourceRange()
15543 << DD->getSourceRange();
15544 DiagnosedMultipleDecomps = true;
15545 }
15546
15547 // A declarator that uses 'auto' in any way other than to declare a
15548 // variable with a deduced type cannot be combined with any other
15549 // declarator in the same group.
15550 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15551 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15552 diag::err_auto_non_deduced_not_alone)
15553 << FirstNonDeducedAutoInGroup->getType()
15555 << FirstDeclaratorInGroup->getSourceRange()
15556 << DD->getSourceRange();
15557 DiagnosedNonDeducedAuto = true;
15558 }
15559 }
15560 }
15561
15562 Decls.push_back(D);
15563 }
15564
15566 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15567 handleTagNumbering(Tag, S);
15568 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15570 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15571 }
15572 }
15573
15574 return BuildDeclaratorGroup(Decls);
15575}
15576
15579 // C++14 [dcl.spec.auto]p7: (DR1347)
15580 // If the type that replaces the placeholder type is not the same in each
15581 // deduction, the program is ill-formed.
15582 if (Group.size() > 1) {
15584 VarDecl *DeducedDecl = nullptr;
15585 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15586 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15587 if (!D || D->isInvalidDecl())
15588 break;
15589 DeducedType *DT = D->getType()->getContainedDeducedType();
15590 if (!DT || DT->getDeducedType().isNull())
15591 continue;
15592 if (Deduced.isNull()) {
15593 Deduced = DT->getDeducedType();
15594 DeducedDecl = D;
15595 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15596 auto *AT = dyn_cast<AutoType>(DT);
15597 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15598 diag::err_auto_different_deductions)
15599 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15600 << DeducedDecl->getDeclName() << DT->getDeducedType()
15601 << D->getDeclName();
15602 if (DeducedDecl->hasInit())
15603 Dia << DeducedDecl->getInit()->getSourceRange();
15604 if (D->getInit())
15605 Dia << D->getInit()->getSourceRange();
15606 D->setInvalidDecl();
15607 break;
15608 }
15609 }
15610 }
15611
15613
15614 return DeclGroupPtrTy::make(
15615 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15616}
15617
15621
15623 // Don't parse the comment if Doxygen diagnostics are ignored.
15624 if (Group.empty() || !Group[0])
15625 return;
15626
15627 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15628 Group[0]->getLocation()) &&
15629 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15630 Group[0]->getLocation()))
15631 return;
15632
15633 if (Group.size() >= 2) {
15634 // This is a decl group. Normally it will contain only declarations
15635 // produced from declarator list. But in case we have any definitions or
15636 // additional declaration references:
15637 // 'typedef struct S {} S;'
15638 // 'typedef struct S *S;'
15639 // 'struct S *pS;'
15640 // FinalizeDeclaratorGroup adds these as separate declarations.
15641 Decl *MaybeTagDecl = Group[0];
15642 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15643 Group = Group.slice(1);
15644 }
15645 }
15646
15647 // FIXME: We assume every Decl in the group is in the same file.
15648 // This is false when preprocessor constructs the group from decls in
15649 // different files (e. g. macros or #include).
15650 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15651}
15652
15654 // Check that there are no default arguments inside the type of this
15655 // parameter.
15656 if (getLangOpts().CPlusPlus)
15658
15659 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15660 if (D.getCXXScopeSpec().isSet()) {
15661 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15662 << D.getCXXScopeSpec().getRange();
15663 }
15664
15665 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15666 // simple identifier except [...irrelevant cases...].
15667 switch (D.getName().getKind()) {
15669 break;
15670
15678 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15680 break;
15681
15684 // GetNameForDeclarator would not produce a useful name in this case.
15685 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15686 break;
15687 }
15688}
15689
15691 // This only matters in C.
15692 if (getLangOpts().CPlusPlus)
15693 return;
15694
15695 // This only matters if the declaration has a type.
15696 const auto *VD = dyn_cast<ValueDecl>(D);
15697 if (!VD)
15698 return;
15699
15700 // Get the type, this only matters for tag types.
15701 QualType QT = VD->getType();
15702 const auto *TD = QT->getAsTagDecl();
15703 if (!TD)
15704 return;
15705
15706 // Check if the tag declaration is lexically declared somewhere different
15707 // from the lexical declaration of the given object, then it will be hidden
15708 // in C++ and we should warn on it.
15709 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15710 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15711 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15712 Diag(TD->getLocation(), diag::note_declared_at);
15713 }
15714}
15715
15717 SourceLocation ExplicitThisLoc) {
15718 if (!ExplicitThisLoc.isValid())
15719 return;
15720 assert(S.getLangOpts().CPlusPlus &&
15721 "explicit parameter in non-cplusplus mode");
15722 if (!S.getLangOpts().CPlusPlus23)
15723 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15724 << P->getSourceRange();
15725
15726 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15727 // parameter pack.
15728 if (P->isParameterPack()) {
15729 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15730 << P->getSourceRange();
15731 return;
15732 }
15733 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15734 if (LambdaScopeInfo *LSI = S.getCurLambda())
15735 LSI->ExplicitObjectParameter = P;
15736}
15737
15739 SourceLocation ExplicitThisLoc) {
15740 const DeclSpec &DS = D.getDeclSpec();
15741
15742 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15743 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15744 // except for the special case of a single unnamed parameter of type void
15745 // with no storage class specifier, no type qualifier, and no following
15746 // ellipsis terminator.
15747 // Clang applies the C2y rules for 'register void' in all C language modes,
15748 // same as GCC, because it's questionable what that could possibly mean.
15749
15750 // C++03 [dcl.stc]p2 also permits 'auto'.
15751 StorageClass SC = SC_None;
15753 SC = SC_Register;
15754 // In C++11, the 'register' storage class specifier is deprecated.
15755 // In C++17, it is not allowed, but we tolerate it as an extension.
15756 if (getLangOpts().CPlusPlus11) {
15758 ? diag::ext_register_storage_class
15759 : diag::warn_deprecated_register)
15761 } else if (!getLangOpts().CPlusPlus &&
15763 D.getNumTypeObjects() == 0) {
15765 diag::err_invalid_storage_class_in_func_decl)
15768 }
15769 } else if (getLangOpts().CPlusPlus &&
15771 SC = SC_Auto;
15774 diag::err_invalid_storage_class_in_func_decl);
15776 }
15777
15779 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15781 if (DS.isInlineSpecified())
15782 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15783 << getLangOpts().CPlusPlus17;
15784 if (DS.hasConstexprSpecifier())
15785 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15786 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15787
15789
15791
15793 QualType parmDeclType = TInfo->getType();
15794
15795 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15796 const IdentifierInfo *II = D.getIdentifier();
15797 if (II) {
15800 LookupName(R, S);
15801 if (!R.empty()) {
15802 NamedDecl *PrevDecl = *R.begin();
15803 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15804 // Maybe we will complain about the shadowed template parameter.
15806 // Just pretend that we didn't see the previous declaration.
15807 PrevDecl = nullptr;
15808 }
15809 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15810 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15811 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15812 // Recover by removing the name
15813 II = nullptr;
15814 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15815 D.setInvalidType(true);
15816 }
15817 }
15818 }
15819
15820 // Incomplete resource arrays are not allowed as function parameters in HLSL
15821 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15822 QualType EltTy = Context.getBaseElementType(parmDeclType);
15823 // `isCompleteType` forces completion of the element type so the resource
15824 // check is valid.
15825 if (!EltTy->isDependentType() &&
15826 isCompleteType(D.getIdentifierLoc(), EltTy) &&
15827 parmDeclType->isHLSLResourceRecordArray()) {
15829 diag::err_hlsl_incomplete_resource_array_in_function_param);
15830 D.setInvalidType(true);
15831 }
15832 }
15833
15834 // Temporarily put parameter variables in the translation unit, not
15835 // the enclosing context. This prevents them from accidentally
15836 // looking like class members in C++.
15837 ParmVarDecl *New =
15838 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15839 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15840
15841 if (D.isInvalidType())
15842 New->setInvalidDecl();
15843
15844 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15845
15846 assert(S->isFunctionPrototypeScope());
15847 assert(S->getFunctionPrototypeDepth() >= 1);
15848 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15850
15852
15853 // Add the parameter declaration into this scope.
15854 S->AddDecl(New);
15855 if (II)
15856 IdResolver.AddDecl(New);
15857
15859
15861 Diag(New->getLocation(), diag::err_module_private_local)
15864
15865 if (New->hasAttr<BlocksAttr>())
15866 Diag(New->getLocation(), diag::err_block_not_allowed_on)
15867 << diag::NotAllowedBlockVarReason::NonlocalVariable;
15868
15869 New->deduceParmAddressSpace(Context);
15870
15871 return New;
15872}
15873
15875 SourceLocation Loc,
15876 QualType T) {
15877 /* FIXME: setting StartLoc == Loc.
15878 Would it be worth to modify callers so as to provide proper source
15879 location for the unnamed parameters, embedding the parameter's type? */
15880 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15881 T, Context.getTrivialTypeSourceInfo(T, Loc),
15882 SC_None, nullptr);
15883 Param->setImplicit();
15884 return Param;
15885}
15886
15888 // Don't diagnose unused-parameter errors in template instantiations; we
15889 // will already have done so in the template itself.
15891 return;
15892
15893 for (const ParmVarDecl *Parameter : Parameters) {
15894 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15895 !Parameter->hasAttr<UnusedAttr>() &&
15896 !Parameter->getIdentifier()->isPlaceholder()) {
15897 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15898 << Parameter->getDeclName();
15899 }
15900 }
15901}
15902
15904 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15905 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15906 return;
15907
15908 // Warn if the return value is pass-by-value and larger than the specified
15909 // threshold.
15910 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15911 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15912 if (Size > LangOpts.NumLargeByValueCopy)
15913 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15914 }
15915
15916 // Warn if any parameter is pass-by-value and larger than the specified
15917 // threshold.
15918 for (const ParmVarDecl *Parameter : Parameters) {
15919 QualType T = Parameter->getType();
15920 if (T->isDependentType() || !T.isPODType(Context))
15921 continue;
15922 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15923 if (Size > LangOpts.NumLargeByValueCopy)
15924 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15925 << Parameter << Size;
15926 }
15927}
15928
15930 SourceLocation NameLoc,
15931 const IdentifierInfo *Name, QualType T,
15932 TypeSourceInfo *TSInfo, StorageClass SC) {
15933 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15934 if (getLangOpts().ObjCAutoRefCount &&
15935 T.getObjCLifetime() == Qualifiers::OCL_None &&
15936 T->isObjCLifetimeType()) {
15937
15938 Qualifiers::ObjCLifetime lifetime;
15939
15940 // Special cases for arrays:
15941 // - if it's const, use __unsafe_unretained
15942 // - otherwise, it's an error
15943 if (T->isArrayType()) {
15944 if (!T.isConstQualified()) {
15948 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15949 else
15950 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15951 << TSInfo->getTypeLoc().getSourceRange();
15952 }
15954 } else {
15955 lifetime = T->getObjCARCImplicitLifetime();
15956 }
15957 T = Context.getLifetimeQualifiedType(T, lifetime);
15958 }
15959
15960 if (getLangOpts().OpenCL) {
15961 assert(!isa<DecayedType>(T));
15962 if (T->isArrayType() && !T.hasAddressSpace()) {
15963 QualType ET = Context.getAsArrayType(T)->getElementType();
15964 if (!ET.hasAddressSpace()) {
15965 // Add the private address space to the contents of the pointer when a
15966 // pointer parameter is declared as an array and not declared.
15968 T = Context.getAddrSpaceQualType(T, ImplAS);
15969 T = QualType(Context.getAsArrayType(T), 0);
15970 }
15971 }
15972 }
15973
15974 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15975 Context.getAdjustedParameterType(T),
15976 TSInfo, SC, nullptr);
15977
15978 // Make a note if we created a new pack in the scope of a lambda, so that
15979 // we know that references to that pack must also be expanded within the
15980 // lambda scope.
15981 if (New->isParameterPack())
15982 if (auto *CSI = getEnclosingLambdaOrBlock())
15983 CSI->LocalPacks.push_back(New);
15984
15985 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15986 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15987 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15990
15991 // Parameter declarators cannot be interface types. All ObjC objects are
15992 // passed by reference.
15993 if (T->isObjCObjectType()) {
15994 SourceLocation TypeEndLoc =
15996 Diag(NameLoc,
15997 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15998 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15999 T = Context.getObjCObjectPointerType(T);
16000 New->setType(T);
16001 }
16002
16003 // __ptrauth is forbidden on parameters.
16004 if (T.getPointerAuth()) {
16005 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
16006 New->setInvalidDecl();
16007 }
16008
16009 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16010 // duration shall not be qualified by an address-space qualifier."
16011 // Since all parameters have automatic store duration, they can not have
16012 // an address space.
16013 if (T.getAddressSpace() != LangAS::Default &&
16014 // OpenCL allows function arguments declared to be an array of a type
16015 // to be qualified with an address space.
16016 !(getLangOpts().OpenCL &&
16017 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16018 // WebAssembly allows reference types as parameters. Funcref in particular
16019 // lives in a different address space.
16020 !(T->isFunctionPointerType() &&
16021 T.getAddressSpace() == LangAS::wasm_funcref) &&
16022 // HLSL allows function arguments to be qualified with an address space
16023 // if the groupshared annotation is used.
16024 !(getLangOpts().HLSL &&
16025 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16026 Diag(NameLoc, diag::err_arg_with_address_space);
16027 New->setInvalidDecl();
16028 }
16029
16030 // PPC MMA non-pointer types are not allowed as function argument types.
16031 if (Context.getTargetInfo().getTriple().isPPC64() &&
16032 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
16033 New->setInvalidDecl();
16034 }
16035
16036 return New;
16037}
16038
16040 SourceLocation LocAfterDecls) {
16042
16043 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16044 // in the declaration list shall have at least one declarator, those
16045 // declarators shall only declare identifiers from the identifier list, and
16046 // every identifier in the identifier list shall be declared.
16047 //
16048 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16049 // identifiers it names shall be declared in the declaration list."
16050 //
16051 // This is why we only diagnose in C99 and later. Note, the other conditions
16052 // listed are checked elsewhere.
16053 if (!FTI.hasPrototype) {
16054 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16055 --i;
16056 if (FTI.Params[i].Param == nullptr) {
16057 if (getLangOpts().C99) {
16058 SmallString<256> Code;
16059 llvm::raw_svector_ostream(Code)
16060 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16061 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
16062 << FTI.Params[i].Ident
16063 << FixItHint::CreateInsertion(LocAfterDecls, Code);
16064 }
16065
16066 // Implicitly declare the argument as type 'int' for lack of a better
16067 // type.
16068 AttributeFactory attrs;
16069 DeclSpec DS(attrs);
16070 const char* PrevSpec; // unused
16071 unsigned DiagID; // unused
16072 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
16073 DiagID, Context.getPrintingPolicy());
16074 // Use the identifier location for the type source range.
16075 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16076 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16079 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
16080 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
16081 }
16082 }
16083 }
16084}
16085
16086Decl *
16088 MultiTemplateParamsArg TemplateParameterLists,
16089 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16090 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16091 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16092 Scope *ParentScope = FnBodyScope->getParent();
16093
16094 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16095 // we define a non-templated function definition, we will create a declaration
16096 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16097 // The base function declaration will have the equivalent of an `omp declare
16098 // variant` annotation which specifies the mangled definition as a
16099 // specialization function under the OpenMP context defined as part of the
16100 // `omp begin declare variant`.
16102 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16104 ParentScope, D, TemplateParameterLists, Bases);
16105
16107 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16108 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16109
16110 if (!Bases.empty())
16112 Bases);
16113
16114 return Dcl;
16115}
16116
16118 Consumer.HandleInlineFunctionDefinition(D);
16119}
16120
16122 const FunctionDecl *&PossiblePrototype) {
16123 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16124 Prev = Prev->getPreviousDecl()) {
16125 // Ignore any declarations that occur in function or method
16126 // scope, because they aren't visible from the header.
16127 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16128 continue;
16129
16130 PossiblePrototype = Prev;
16131 return Prev->getType()->isFunctionProtoType();
16132 }
16133 return false;
16134}
16135
16136static bool
16138 const FunctionDecl *&PossiblePrototype) {
16139 // Don't warn about invalid declarations.
16140 if (FD->isInvalidDecl())
16141 return false;
16142
16143 // Or declarations that aren't global.
16144 if (!FD->isGlobal())
16145 return false;
16146
16147 // Don't warn about C++ member functions.
16148 if (isa<CXXMethodDecl>(FD))
16149 return false;
16150
16151 // Don't warn about 'main'.
16153 if (IdentifierInfo *II = FD->getIdentifier())
16154 if (II->isStr("main") || II->isStr("efi_main"))
16155 return false;
16156
16157 if (FD->isMSVCRTEntryPoint())
16158 return false;
16159
16160 // Don't warn about inline functions.
16161 if (FD->isInlined())
16162 return false;
16163
16164 // Don't warn about function templates.
16166 return false;
16167
16168 // Don't warn about function template specializations.
16170 return false;
16171
16172 // Don't warn for OpenCL kernels.
16173 if (FD->hasAttr<DeviceKernelAttr>())
16174 return false;
16175
16176 // Don't warn on explicitly deleted functions.
16177 if (FD->isDeleted())
16178 return false;
16179
16180 // Don't warn on implicitly local functions (such as having local-typed
16181 // parameters).
16182 if (!FD->isExternallyVisible())
16183 return false;
16184
16185 // If we were able to find a potential prototype, don't warn.
16186 if (FindPossiblePrototype(FD, PossiblePrototype))
16187 return false;
16188
16189 return true;
16190}
16191
16192void
16194 const FunctionDecl *EffectiveDefinition,
16195 SkipBodyInfo *SkipBody) {
16196 const FunctionDecl *Definition = EffectiveDefinition;
16197 if (!Definition &&
16198 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16199 return;
16200
16201 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16202 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16203 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16204 // A merged copy of the same function, instantiated as a member of
16205 // the same class, is OK.
16206 if (declaresSameEntity(OrigFD, OrigDef) &&
16207 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16209 return;
16210 }
16211 }
16212 }
16213
16215 return;
16216
16217 // Don't emit an error when this is redefinition of a typo-corrected
16218 // definition.
16220 return;
16221
16222 bool DefinitionVisible = false;
16223 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16224 (Definition->getFormalLinkage() == Linkage::Internal ||
16225 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16226 !Definition->getTemplateParameterLists().empty())) {
16227 SkipBody->ShouldSkip = true;
16228 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16229 if (!DefinitionVisible) {
16230 if (auto *TD = Definition->getDescribedFunctionTemplate())
16233 }
16234 return;
16235 }
16236
16237 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16238 Definition->getStorageClass() == SC_Extern)
16239 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16240 << FD << getLangOpts().CPlusPlus;
16241 else
16242 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16243
16244 Diag(Definition->getLocation(), diag::note_previous_definition);
16245 FD->setInvalidDecl();
16246}
16247
16249 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16250
16252 LSI->CallOperator = CallOperator;
16253 LSI->Lambda = LambdaClass;
16254 LSI->ReturnType = CallOperator->getReturnType();
16255 // When this function is called in situation where the context of the call
16256 // operator is not entered, we set AfterParameterList to false, so that
16257 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16258 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16259 // where we would set the CurContext to the lambda operator before
16260 // substituting into it. In this case the flag needs to be true such that
16261 // tryCaptureVariable can correctly handle potential captures thereof.
16262 LSI->AfterParameterList = CurContext == CallOperator;
16263 LSI->BeforeCompoundStatement = false;
16264
16265 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16266 // used at the point of dealing with potential captures.
16267 //
16268 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16269 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16270 // associated. (Technically, we could recover that list from their
16271 // instantiation patterns, but for now, the GLTemplateParameterList seems
16272 // unnecessary in these cases.)
16273 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16274 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16275 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16276
16277 if (LCD == LCD_None)
16279 else if (LCD == LCD_ByCopy)
16281 else if (LCD == LCD_ByRef)
16283 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16284
16286 LSI->Mutable = !CallOperator->isConst();
16287 if (CallOperator->isExplicitObjectMemberFunction())
16288 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16289
16290 // Add the captures to the LSI so they can be noted as already
16291 // captured within tryCaptureVar.
16292 auto I = LambdaClass->field_begin();
16293 for (const auto &C : LambdaClass->captures()) {
16294 if (C.capturesVariable()) {
16295 ValueDecl *VD = C.getCapturedVar();
16296 if (VD->isInitCapture())
16297 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16298 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16299 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16300 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16301 /*EllipsisLoc*/C.isPackExpansion()
16302 ? C.getEllipsisLoc() : SourceLocation(),
16303 I->getType(), /*Invalid*/false);
16304
16305 } else if (C.capturesThis()) {
16306 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16307 C.getCaptureKind() == LCK_StarThis);
16308 } else {
16309 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16310 I->getType());
16311 }
16312 ++I;
16313 }
16314 return LSI;
16315}
16316
16318 SkipBodyInfo *SkipBody,
16319 FnBodyKind BodyKind) {
16320 if (!D) {
16321 // Parsing the function declaration failed in some way. Push on a fake scope
16322 // anyway so we can try to parse the function body.
16325 return D;
16326 }
16327
16328 FunctionDecl *FD = nullptr;
16329
16330 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16331 FD = FunTmpl->getTemplatedDecl();
16332 else
16333 FD = cast<FunctionDecl>(D);
16334
16335 // Do not push if it is a lambda because one is already pushed when building
16336 // the lambda in ActOnStartOfLambdaDefinition().
16337 if (!isLambdaCallOperator(FD))
16339 FD);
16340
16341 // Check for defining attributes before the check for redefinition.
16342 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16343 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16344 FD->dropAttr<AliasAttr>();
16345 FD->setInvalidDecl();
16346 }
16347 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16348 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16349 FD->dropAttr<IFuncAttr>();
16350 FD->setInvalidDecl();
16351 }
16352 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16353 if (Context.getTargetInfo().getTriple().isAArch64() &&
16354 !Context.getTargetInfo().hasFeature("fmv") &&
16355 !Attr->isDefaultVersion()) {
16356 // If function multi versioning disabled skip parsing function body
16357 // defined with non-default target_version attribute
16358 if (SkipBody)
16359 SkipBody->ShouldSkip = true;
16360 return nullptr;
16361 }
16362 }
16363
16364 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16365 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16366 Ctor->isDefaultConstructor() &&
16367 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16368 // If this is an MS ABI dllexport default constructor, instantiate any
16369 // default arguments.
16370 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16372 }
16373 }
16374
16375 // See if this is a redefinition. If 'will have body' (or similar) is already
16376 // set, then these checks were already performed when it was set.
16377 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16379 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16380
16381 // If we're skipping the body, we're done. Don't enter the scope.
16382 if (SkipBody && SkipBody->ShouldSkip)
16383 return D;
16384 }
16385
16386 // Mark this function as "will have a body eventually". This lets users to
16387 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16388 // this function.
16389 FD->setWillHaveBody();
16390
16391 // If we are instantiating a generic lambda call operator, push
16392 // a LambdaScopeInfo onto the function stack. But use the information
16393 // that's already been calculated (ActOnLambdaExpr) to prime the current
16394 // LambdaScopeInfo.
16395 // When the template operator is being specialized, the LambdaScopeInfo,
16396 // has to be properly restored so that tryCaptureVariable doesn't try
16397 // and capture any new variables. In addition when calculating potential
16398 // captures during transformation of nested lambdas, it is necessary to
16399 // have the LSI properly restored.
16401 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16402 // specialized.
16404 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16405 << /*specialization*/ 0;
16407 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16408
16409 FD->setInvalidDecl();
16411 } else {
16412 assert(inTemplateInstantiation() &&
16413 "There should be an active template instantiation on the stack "
16414 "when instantiating a generic lambda!");
16416 }
16417 } else {
16418 // Enter a new function scope
16420 }
16421
16422 // Builtin functions cannot be defined.
16423 if (unsigned BuiltinID = FD->getBuiltinID()) {
16424 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16425 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16426 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16427 FD->setInvalidDecl();
16428 }
16429 }
16430
16431 // The return type of a function definition must be complete (C99 6.9.1p3).
16432 // C++23 [dcl.fct.def.general]/p2
16433 // The type of [...] the return for a function definition
16434 // shall not be a (possibly cv-qualified) class type that is incomplete
16435 // or abstract within the function body unless the function is deleted.
16436 QualType ResultType = FD->getReturnType();
16437 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16438 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16439 (RequireCompleteType(FD->getLocation(), ResultType,
16440 diag::err_func_def_incomplete_result) ||
16442 diag::err_abstract_type_in_decl,
16444 FD->setInvalidDecl();
16445
16446 if (FnBodyScope)
16447 PushDeclContext(FnBodyScope, FD);
16448
16449 // Check the validity of our function parameters
16450 if (BodyKind != FnBodyKind::Delete)
16452 /*CheckParameterNames=*/true);
16453
16454 // Add non-parameter declarations already in the function to the current
16455 // scope.
16456 if (FnBodyScope) {
16457 for (Decl *NPD : FD->decls()) {
16458 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16459 if (!NonParmDecl)
16460 continue;
16461 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16462 "parameters should not be in newly created FD yet");
16463
16464 // If the decl has a name, make it accessible in the current scope.
16465 if (NonParmDecl->getDeclName())
16466 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16467
16468 // Similarly, dive into enums and fish their constants out, making them
16469 // accessible in this scope.
16470 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16471 for (auto *EI : ED->enumerators())
16472 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16473 }
16474 }
16475 }
16476
16477 // Introduce our parameters into the function scope
16478 for (auto *Param : FD->parameters()) {
16479 Param->setOwningFunction(FD);
16480
16481 // If this has an identifier, add it to the scope stack.
16482 if (Param->getIdentifier() && FnBodyScope) {
16483 CheckShadow(FnBodyScope, Param);
16484
16485 PushOnScopeChains(Param, FnBodyScope);
16486 }
16487 }
16488
16489 // C++ [module.import/6]
16490 // ...
16491 // A header unit shall not contain a definition of a non-inline function or
16492 // variable whose name has external linkage.
16493 //
16494 // Deleted and Defaulted functions are implicitly inline (but the
16495 // inline state is not set at this point, so check the BodyKind explicitly).
16496 // We choose to allow weak & selectany definitions, as they are common in
16497 // headers, and have semantics similar to inline definitions which are allowed
16498 // in header units.
16499 // FIXME: Consider an alternate location for the test where the inlined()
16500 // state is complete.
16501 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16502 !FD->isInvalidDecl() && !FD->isInlined() &&
16503 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16504 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16505 !FD->isTemplateInstantiation() &&
16506 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16507 assert(FD->isThisDeclarationADefinition());
16508 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16509 FD->setInvalidDecl();
16510 }
16511
16512 // Ensure that the function's exception specification is instantiated.
16513 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16515
16516 // dllimport cannot be applied to non-inline function definitions.
16517 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16518 !FD->isTemplateInstantiation()) {
16519 assert(!FD->hasAttr<DLLExportAttr>());
16520 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16521 FD->setInvalidDecl();
16522 return D;
16523 }
16524
16525 // Some function attributes (like OptimizeNoneAttr) need actions before
16526 // parsing body started.
16528
16529 // We want to attach documentation to original Decl (which might be
16530 // a function template).
16532 if (getCurLexicalContext()->isObjCContainer() &&
16533 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16534 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16535 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16536
16538
16539 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16540 FnBodyScope) {
16541 // An implicit call expression is synthesized for functions declared with
16542 // the sycl_kernel_entry_point attribute. The call may resolve to a
16543 // function template, a member function template, or a call operator
16544 // of a variable template depending on the results of unqualified lookup
16545 // for 'sycl_kernel_launch' from the beginning of the function body.
16546 // Performing that lookup requires the stack of parsing scopes active
16547 // when the definition is parsed and is thus done here; the result is
16548 // cached in FunctionScopeInfo and used to synthesize the (possibly
16549 // unresolved) call expression after the function body has been parsed.
16550 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16551 if (!SKEPAttr->isInvalidAttr()) {
16552 ExprResult LaunchIdExpr =
16553 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16554 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16555 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16556 // treated as an error in the definition of 'FD'; treating it as an error
16557 // of the declaration would affect overload resolution which would
16558 // potentially result in additional errors. If construction of
16559 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16560 // a null pointer value below; that is expected.
16561 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16562 }
16563 }
16564
16565 return D;
16566}
16567
16569 if (!FD || FD->isInvalidDecl())
16570 return;
16571 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16572 FD = TD->getTemplatedDecl();
16573 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16576 CurFPFeatures.applyChanges(FPO);
16577 FpPragmaStack.CurrentValue =
16578 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16579 }
16580}
16581
16583 ReturnStmt **Returns = Scope->Returns.data();
16584
16585 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16586 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16587 if (!NRVOCandidate->isNRVOVariable()) {
16588 Diag(Returns[I]->getRetValue()->getExprLoc(),
16589 diag::warn_not_eliding_copy_on_return);
16590 Returns[I]->setNRVOCandidate(nullptr);
16591 }
16592 }
16593 }
16594}
16595
16597 // We can't delay parsing the body of a constexpr function template (yet).
16599 return false;
16600
16601 // We can't delay parsing the body of a function template with a deduced
16602 // return type (yet).
16603 if (D.getDeclSpec().hasAutoTypeSpec()) {
16604 // If the placeholder introduces a non-deduced trailing return type,
16605 // we can still delay parsing it.
16606 if (D.getNumTypeObjects()) {
16607 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16608 if (Outer.Kind == DeclaratorChunk::Function &&
16609 Outer.Fun.hasTrailingReturnType()) {
16610 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16611 return Ty.isNull() || !Ty->isUndeducedType();
16612 }
16613 }
16614 return false;
16615 }
16616
16617 return true;
16618}
16619
16621 // We cannot skip the body of a function (or function template) which is
16622 // constexpr, since we may need to evaluate its body in order to parse the
16623 // rest of the file.
16624 // We cannot skip the body of a function with an undeduced return type,
16625 // because any callers of that function need to know the type.
16626 if (const FunctionDecl *FD = D->getAsFunction()) {
16627 if (FD->isConstexpr())
16628 return false;
16629 // We can't simply call Type::isUndeducedType here, because inside template
16630 // auto can be deduced to a dependent type, which is not considered
16631 // "undeduced".
16632 if (FD->getReturnType()->getContainedDeducedType())
16633 return false;
16634 }
16635 return Consumer.shouldSkipFunctionBody(D);
16636}
16637
16639 if (!Decl)
16640 return nullptr;
16641 if (FunctionDecl *FD = Decl->getAsFunction())
16642 FD->setHasSkippedBody();
16643 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16644 MD->setHasSkippedBody();
16645 return Decl;
16646}
16647
16648/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16649/// body.
16651public:
16652 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16654 if (!IsLambda)
16655 S.PopExpressionEvaluationContext();
16656 }
16657
16658private:
16659 Sema &S;
16660 bool IsLambda = false;
16661};
16662
16664 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16665
16666 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16667 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16668 if (!Inserted)
16669 return It->second;
16670
16671 bool R = false;
16672 const BlockDecl *CurBD = BD;
16673
16674 do {
16675 R = !CurBD->doesNotEscape();
16676 if (R)
16677 break;
16678 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16679 } while (CurBD);
16680
16681 return It->second = R;
16682 };
16683
16684 // If the location where 'self' is implicitly retained is inside a escaping
16685 // block, emit a diagnostic.
16686 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16688 if (IsOrNestedInEscapingBlock(P.second))
16689 S.Diag(P.first, diag::warn_implicitly_retains_self)
16690 << FixItHint::CreateInsertion(P.first, "self->");
16691}
16692
16693static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16694 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16695 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16696}
16697
16699 return methodHasName(FD, "get_return_object");
16700}
16701
16703 return FD->isStatic() &&
16704 methodHasName(FD, "get_return_object_on_allocation_failure");
16705}
16706
16709 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16710 return;
16711 // Allow some_promise_type::get_return_object().
16713 return;
16714 if (!FD->hasAttr<CoroWrapperAttr>())
16715 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16716}
16717
16718Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16719 bool RetainFunctionScopeInfo) {
16721 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16722
16723 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16724 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16725
16726 SourceLocation AnalysisLoc;
16727 if (Body)
16728 AnalysisLoc = Body->getEndLoc();
16729 else if (FD)
16730 AnalysisLoc = FD->getEndLoc();
16732 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16733 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16734
16735 // If we skip function body, we can't tell if a function is a coroutine.
16736 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16737 if (FSI->isCoroutine())
16739 else
16741 }
16742
16743 // Diagnose invalid SYCL kernel entry point function declarations
16744 // and build SYCLKernelCallStmts for valid ones.
16745 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16746 SYCLKernelEntryPointAttr *SKEPAttr =
16747 FD->getAttr<SYCLKernelEntryPointAttr>();
16748 if (FD->isDefaulted()) {
16749 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16750 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16751 SKEPAttr->setInvalidAttr();
16752 } else if (FD->isDeleted()) {
16753 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16754 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16755 SKEPAttr->setInvalidAttr();
16756 } else if (FSI->isCoroutine()) {
16757 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16758 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16759 SKEPAttr->setInvalidAttr();
16760 } else if (Body && isa<CXXTryStmt>(Body)) {
16761 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16762 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16763 SKEPAttr->setInvalidAttr();
16764 }
16765
16766 // Build an unresolved SYCL kernel call statement for a function template,
16767 // validate that a SYCL kernel call statement was instantiated for an
16768 // (implicit or explicit) instantiation of a function template, or otherwise
16769 // build a (resolved) SYCL kernel call statement for a non-templated
16770 // function or an explicit specialization.
16771 if (Body && !SKEPAttr->isInvalidAttr()) {
16772 StmtResult SR;
16773 if (FD->isTemplateInstantiation()) {
16774 // The function body should already be a SYCLKernelCallStmt in this
16775 // case, but might not be if there were previous errors.
16776 SR = Body;
16777 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16778 // If name lookup for a template named sycl_kernel_launch failed
16779 // earlier, don't try to build a SYCL kernel call statement as that
16780 // would cause additional errors to be issued; just proceed with the
16781 // original function body.
16782 SR = Body;
16783 } else if (FD->isTemplated()) {
16785 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16786 } else {
16788 FD, cast<CompoundStmt>(Body),
16789 getCurFunction()->SYCLKernelLaunchIdExpr);
16790 }
16791 // If construction of the replacement body fails, just continue with the
16792 // original function body. An early error return here is not valid; the
16793 // current declaration context and function scopes must be popped before
16794 // returning.
16795 if (SR.isUsable())
16796 Body = SR.get();
16797 }
16798 }
16799
16800 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16801 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16802 if (FD->isDeletedAsWritten())
16803 Diag(SEAttr->getLocation(),
16804 diag::err_sycl_external_invalid_deleted_function)
16805 << SEAttr;
16806 }
16807
16808 {
16809 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16810 // one is already popped when finishing the lambda in BuildLambdaExpr().
16811 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16812 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16813 if (FD) {
16814 // The function body and the DefaultedOrDeletedInfo, if present, use
16815 // the same storage; don't overwrite the latter if the former is null
16816 // (the body is initialised to null anyway, so even if the latter isn't
16817 // present, this would still be a no-op).
16818 if (Body)
16819 FD->setBody(Body);
16820 FD->setWillHaveBody(false);
16821
16822 if (getLangOpts().CPlusPlus14) {
16823 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16824 FD->getReturnType()->isUndeducedType()) {
16825 // For a function with a deduced result type to return void,
16826 // the result type as written must be 'auto' or 'decltype(auto)',
16827 // possibly cv-qualified or constrained, but not ref-qualified.
16828 if (!FD->getReturnType()->getAs<AutoType>()) {
16829 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16830 << FD->getReturnType();
16831 FD->setInvalidDecl();
16832 } else {
16833 // Falling off the end of the function is the same as 'return;'.
16834 Expr *Dummy = nullptr;
16836 FD, dcl->getLocation(), Dummy,
16837 FD->getReturnType()->getAs<AutoType>()))
16838 FD->setInvalidDecl();
16839 }
16840 }
16841 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16842 // In C++11, we don't use 'auto' deduction rules for lambda call
16843 // operators because we don't support return type deduction.
16844 auto *LSI = getCurLambda();
16845 if (LSI->HasImplicitReturnType) {
16847
16848 // C++11 [expr.prim.lambda]p4:
16849 // [...] if there are no return statements in the compound-statement
16850 // [the deduced type is] the type void
16851 QualType RetType =
16852 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16853
16854 // Update the return type to the deduced type.
16855 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16856 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16857 Proto->getExtProtoInfo()));
16858 }
16859 }
16860
16861 // If the function implicitly returns zero (like 'main') or is naked,
16862 // don't complain about missing return statements.
16863 // Clang implicitly returns 0 in C89 mode, but that's considered an
16864 // extension. The check is necessary to ensure the expected extension
16865 // warning is emitted in C89 mode.
16866 if ((FD->hasImplicitReturnZero() &&
16867 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16868 FD->hasAttr<NakedAttr>())
16870
16871 // MSVC permits the use of pure specifier (=0) on function definition,
16872 // defined at class scope, warn about this non-standard construct.
16873 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16874 !FD->isOutOfLine())
16875 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16876
16877 if (!FD->isInvalidDecl()) {
16878 // Don't diagnose unused parameters of defaulted, deleted or naked
16879 // functions.
16880 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16881 !FD->hasAttr<NakedAttr>())
16884 FD->getReturnType(), FD);
16885
16886 // If this is a structor, we need a vtable.
16887 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16888 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16889 else if (CXXDestructorDecl *Destructor =
16890 dyn_cast<CXXDestructorDecl>(FD))
16891 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16892
16893 // Try to apply the named return value optimization. We have to check
16894 // if we can do this here because lambdas keep return statements around
16895 // to deduce an implicit return type.
16896 if (FD->getReturnType()->isRecordType() &&
16898 computeNRVO(Body, FSI);
16899 }
16900
16901 // GNU warning -Wmissing-prototypes:
16902 // Warn if a global function is defined without a previous
16903 // prototype declaration. This warning is issued even if the
16904 // definition itself provides a prototype. The aim is to detect
16905 // global functions that fail to be declared in header files.
16906 const FunctionDecl *PossiblePrototype = nullptr;
16907 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16908 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16909
16910 if (PossiblePrototype) {
16911 // We found a declaration that is not a prototype,
16912 // but that could be a zero-parameter prototype
16913 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16914 TypeLoc TL = TI->getTypeLoc();
16916 Diag(PossiblePrototype->getLocation(),
16917 diag::note_declaration_not_a_prototype)
16918 << (FD->getNumParams() != 0)
16920 FTL.getRParenLoc(), "void")
16921 : FixItHint{});
16922 }
16923 } else {
16924 // Returns true if the token beginning at this Loc is `const`.
16925 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16926 const LangOptions &LangOpts) {
16927 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16928 if (LocInfo.first.isInvalid())
16929 return false;
16930
16931 bool Invalid = false;
16932 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16933 if (Invalid)
16934 return false;
16935
16936 if (LocInfo.second > Buffer.size())
16937 return false;
16938
16939 const char *LexStart = Buffer.data() + LocInfo.second;
16940 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16941
16942 return StartTok.consume_front("const") &&
16943 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16944 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16945 };
16946
16947 auto findBeginLoc = [&]() {
16948 // If the return type has `const` qualifier, we want to insert
16949 // `static` before `const` (and not before the typename).
16950 if ((FD->getReturnType()->isAnyPointerType() &&
16953 // But only do this if we can determine where the `const` is.
16954
16955 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16956 getLangOpts()))
16957
16958 return FD->getBeginLoc();
16959 }
16960 return FD->getTypeSpecStartLoc();
16961 };
16963 diag::note_static_for_internal_linkage)
16964 << /* function */ 1
16965 << (FD->getStorageClass() == SC_None
16966 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16967 : FixItHint{});
16968 }
16969 }
16970
16971 // We might not have found a prototype because we didn't wish to warn on
16972 // the lack of a missing prototype. Try again without the checks for
16973 // whether we want to warn on the missing prototype.
16974 if (!PossiblePrototype)
16975 (void)FindPossiblePrototype(FD, PossiblePrototype);
16976
16977 // If the function being defined does not have a prototype, then we may
16978 // need to diagnose it as changing behavior in C23 because we now know
16979 // whether the function accepts arguments or not. This only handles the
16980 // case where the definition has no prototype but does have parameters
16981 // and either there is no previous potential prototype, or the previous
16982 // potential prototype also has no actual prototype. This handles cases
16983 // like:
16984 // void f(); void f(a) int a; {}
16985 // void g(a) int a; {}
16986 // See MergeFunctionDecl() for other cases of the behavior change
16987 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16988 // type without a prototype.
16989 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16990 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16991 !PossiblePrototype->isImplicit()))) {
16992 // The function definition has parameters, so this will change behavior
16993 // in C23. If there is a possible prototype, it comes before the
16994 // function definition.
16995 // FIXME: The declaration may have already been diagnosed as being
16996 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16997 // there's no way to test for the "changes behavior" condition in
16998 // SemaType.cpp when forming the declaration's function type. So, we do
16999 // this awkward dance instead.
17000 //
17001 // If we have a possible prototype and it declares a function with a
17002 // prototype, we don't want to diagnose it; if we have a possible
17003 // prototype and it has no prototype, it may have already been
17004 // diagnosed in SemaType.cpp as deprecated depending on whether
17005 // -Wstrict-prototypes is enabled. If we already warned about it being
17006 // deprecated, add a note that it also changes behavior. If we didn't
17007 // warn about it being deprecated (because the diagnostic is not
17008 // enabled), warn now that it is deprecated and changes behavior.
17009
17010 // This K&R C function definition definitely changes behavior in C23,
17011 // so diagnose it.
17012 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
17013 << /*definition*/ 1 << /* not supported in C23 */ 0;
17014
17015 // If we have a possible prototype for the function which is a user-
17016 // visible declaration, we already tested that it has no prototype.
17017 // This will change behavior in C23. This gets a warning rather than a
17018 // note because it's the same behavior-changing problem as with the
17019 // definition.
17020 if (PossiblePrototype)
17021 Diag(PossiblePrototype->getLocation(),
17022 diag::warn_non_prototype_changes_behavior)
17023 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17024 << /*definition*/ 1;
17025 }
17026
17027 // Warn on CPUDispatch with an actual body.
17028 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17029 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
17030 if (!CmpndBody->body_empty())
17031 Diag(CmpndBody->body_front()->getBeginLoc(),
17032 diag::warn_dispatch_body_ignored);
17033
17034 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
17035 const CXXMethodDecl *KeyFunction;
17036 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17037 MD->isVirtual() &&
17038 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
17039 MD == KeyFunction->getCanonicalDecl()) {
17040 // Update the key-function state if necessary for this ABI.
17041 if (FD->isInlined() &&
17042 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17043 Context.setNonKeyFunction(MD);
17044
17045 // If the newly-chosen key function is already defined, then we
17046 // need to mark the vtable as used retroactively.
17047 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
17048 const FunctionDecl *Definition;
17049 if (KeyFunction && KeyFunction->isDefined(Definition))
17050 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
17051 } else {
17052 // We just defined they key function; mark the vtable as used.
17053 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
17054 }
17055 }
17056 }
17057
17058 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17059 "Function parsing confused");
17060 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
17061 assert(MD == getCurMethodDecl() && "Method parsing confused");
17062 MD->setBody(Body);
17063 if (!MD->isInvalidDecl()) {
17065 MD->getReturnType(), MD);
17066
17067 if (Body)
17068 computeNRVO(Body, FSI);
17069 }
17070 if (FSI->ObjCShouldCallSuper) {
17071 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
17072 << MD->getSelector().getAsString();
17073 FSI->ObjCShouldCallSuper = false;
17074 }
17076 const ObjCMethodDecl *InitMethod = nullptr;
17077 bool isDesignated =
17078 MD->isDesignatedInitializerForTheInterface(&InitMethod);
17079 assert(isDesignated && InitMethod);
17080 (void)isDesignated;
17081
17082 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17083 auto IFace = MD->getClassInterface();
17084 if (!IFace)
17085 return false;
17086 auto SuperD = IFace->getSuperClass();
17087 if (!SuperD)
17088 return false;
17089 return SuperD->getIdentifier() ==
17090 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17091 };
17092 // Don't issue this warning for unavailable inits or direct subclasses
17093 // of NSObject.
17094 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17095 Diag(MD->getLocation(),
17096 diag::warn_objc_designated_init_missing_super_call);
17097 Diag(InitMethod->getLocation(),
17098 diag::note_objc_designated_init_marked_here);
17099 }
17101 }
17102 if (FSI->ObjCWarnForNoInitDelegation) {
17103 // Don't issue this warning for unavailable inits.
17104 if (!MD->isUnavailable())
17105 Diag(MD->getLocation(),
17106 diag::warn_objc_secondary_init_missing_init_call);
17107 FSI->ObjCWarnForNoInitDelegation = false;
17108 }
17109
17111 } else {
17112 // Parsing the function declaration failed in some way. Pop the fake scope
17113 // we pushed on.
17114 PopFunctionScopeInfo(ActivePolicy, dcl);
17115 return nullptr;
17116 }
17117
17118 if (Body) {
17121 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17123 }
17124
17125 assert(!FSI->ObjCShouldCallSuper &&
17126 "This should only be set for ObjC methods, which should have been "
17127 "handled in the block above.");
17128
17129 // Verify and clean out per-function state.
17130 if (Body && (!FD || !FD->isDefaulted())) {
17131 // C++ constructors that have function-try-blocks can't have return
17132 // statements in the handlers of that block. (C++ [except.handle]p14)
17133 // Verify this.
17134 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17136
17137 // Verify that gotos and switch cases don't jump into scopes illegally.
17138 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17140
17141 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17142 if (!Destructor->getParent()->isDependentType())
17144
17146 Destructor->getParent());
17147 }
17148
17149 // If any errors have occurred, clear out any temporaries that may have
17150 // been leftover. This ensures that these temporaries won't be picked up
17151 // for deletion in some later function.
17154 getDiagnostics().getSuppressAllDiagnostics()) {
17156 }
17158 // Since the body is valid, issue any analysis-based warnings that are
17159 // enabled.
17160 ActivePolicy = &WP;
17161 }
17162
17163 if (!IsInstantiation && FD &&
17164 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17165 !FD->isInvalidDecl() &&
17167 FD->setInvalidDecl();
17168
17169 if (FD && FD->hasAttr<NakedAttr>()) {
17170 for (const Stmt *S : Body->children()) {
17171 // Allow local register variables without initializer as they don't
17172 // require prologue.
17173 bool RegisterVariables = false;
17174 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17175 for (const auto *Decl : DS->decls()) {
17176 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17177 RegisterVariables =
17178 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17179 if (!RegisterVariables)
17180 break;
17181 }
17182 }
17183 }
17184 if (RegisterVariables)
17185 continue;
17186 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17187 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17188 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17189 FD->setInvalidDecl();
17190 break;
17191 }
17192 }
17193 }
17194
17195 assert(ExprCleanupObjects.size() ==
17196 ExprEvalContexts.back().NumCleanupObjects &&
17197 "Leftover temporaries in function");
17198 assert(!Cleanup.exprNeedsCleanups() &&
17199 "Unaccounted cleanups in function");
17200 assert(MaybeODRUseExprs.empty() &&
17201 "Leftover expressions for odr-use checking");
17202 }
17203 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17204 // the declaration context below. Otherwise, we're unable to transform
17205 // 'this' expressions when transforming immediate context functions.
17206
17207 if (FD)
17209
17210 if (!IsInstantiation)
17212
17213 if (!RetainFunctionScopeInfo)
17214 PopFunctionScopeInfo(ActivePolicy, dcl);
17215 // If any errors have occurred, clear out any temporaries that may have
17216 // been leftover. This ensures that these temporaries won't be picked up for
17217 // deletion in some later function.
17220 }
17221
17222 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17223 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17224 auto ES = getEmissionStatus(FD);
17228 }
17229
17230 if (FD && !FD->isDeleted())
17231 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17232
17233 return dcl;
17234}
17235
17236/// When we finish delayed parsing of an attribute, we must attach it to the
17237/// relevant Decl.
17239 ParsedAttributes &Attrs) {
17240 // Always attach attributes to the underlying decl.
17241 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17242 D = TD->getTemplatedDecl();
17243 ProcessDeclAttributeList(S, D, Attrs);
17244 ProcessAPINotes(D);
17245
17246 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17247 if (Method->isStatic())
17249}
17250
17252 IdentifierInfo &II, Scope *S) {
17253 // It is not valid to implicitly define a function in C23.
17254 assert(LangOpts.implicitFunctionsAllowed() &&
17255 "Implicit function declarations aren't allowed in this language mode");
17256
17257 // Find the scope in which the identifier is injected and the corresponding
17258 // DeclContext.
17259 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17260 // In that case, we inject the declaration into the translation unit scope
17261 // instead.
17262 Scope *BlockScope = S;
17263 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17264 BlockScope = BlockScope->getParent();
17265
17266 // Loop until we find a DeclContext that is either a function/method or the
17267 // translation unit, which are the only two valid places to implicitly define
17268 // a function. This avoids accidentally defining the function within a tag
17269 // declaration, for example.
17270 Scope *ContextScope = BlockScope;
17271 while (!ContextScope->getEntity() ||
17272 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17273 !ContextScope->getEntity()->isTranslationUnit()))
17274 ContextScope = ContextScope->getParent();
17275 ContextRAII SavedContext(*this, ContextScope->getEntity());
17276
17277 // Before we produce a declaration for an implicitly defined
17278 // function, see whether there was a locally-scoped declaration of
17279 // this name as a function or variable. If so, use that
17280 // (non-visible) declaration, and complain about it.
17281 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17282 if (ExternCPrev) {
17283 // We still need to inject the function into the enclosing block scope so
17284 // that later (non-call) uses can see it.
17285 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17286
17287 // C89 footnote 38:
17288 // If in fact it is not defined as having type "function returning int",
17289 // the behavior is undefined.
17290 if (!isa<FunctionDecl>(ExternCPrev) ||
17291 !Context.typesAreCompatible(
17292 cast<FunctionDecl>(ExternCPrev)->getType(),
17293 Context.getFunctionNoProtoType(Context.IntTy))) {
17294 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17295 << ExternCPrev << !getLangOpts().C99;
17296 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17297 return ExternCPrev;
17298 }
17299 }
17300
17301 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17302 unsigned diag_id;
17303 if (II.getName().starts_with("__builtin_"))
17304 diag_id = diag::warn_builtin_unknown;
17305 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17306 else if (getLangOpts().C99)
17307 diag_id = diag::ext_implicit_function_decl_c99;
17308 else
17309 diag_id = diag::warn_implicit_function_decl;
17310
17311 TypoCorrection Corrected;
17312 // Because typo correction is expensive, only do it if the implicit
17313 // function declaration is going to be treated as an error.
17314 //
17315 // Perform the correction before issuing the main diagnostic, as some
17316 // consumers use typo-correction callbacks to enhance the main diagnostic.
17317 if (S && !ExternCPrev &&
17318 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17320 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17321 S, nullptr, CCC, CorrectTypoKind::NonError);
17322 }
17323
17324 Diag(Loc, diag_id) << &II;
17325 if (Corrected) {
17326 // If the correction is going to suggest an implicitly defined function,
17327 // skip the correction as not being a particularly good idea.
17328 bool Diagnose = true;
17329 if (const auto *D = Corrected.getCorrectionDecl())
17330 Diagnose = !D->isImplicit();
17331 if (Diagnose)
17332 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17333 /*ErrorRecovery*/ false);
17334 }
17335
17336 // If we found a prior declaration of this function, don't bother building
17337 // another one. We've already pushed that one into scope, so there's nothing
17338 // more to do.
17339 if (ExternCPrev)
17340 return ExternCPrev;
17341
17342 // Set a Declarator for the implicit definition: int foo();
17343 const char *Dummy;
17344 AttributeFactory attrFactory;
17345 DeclSpec DS(attrFactory);
17346 unsigned DiagID;
17347 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17348 Context.getPrintingPolicy());
17349 (void)Error; // Silence warning.
17350 assert(!Error && "Error setting up implicit decl!");
17351 SourceLocation NoLoc;
17353 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17354 /*IsAmbiguous=*/false,
17355 /*LParenLoc=*/NoLoc,
17356 /*Params=*/nullptr,
17357 /*NumParams=*/0,
17358 /*EllipsisLoc=*/NoLoc,
17359 /*RParenLoc=*/NoLoc,
17360 /*RefQualifierIsLvalueRef=*/true,
17361 /*RefQualifierLoc=*/NoLoc,
17362 /*MutableLoc=*/NoLoc, EST_None,
17363 /*ESpecRange=*/SourceRange(),
17364 /*Exceptions=*/nullptr,
17365 /*ExceptionRanges=*/nullptr,
17366 /*NumExceptions=*/0,
17367 /*NoexceptExpr=*/nullptr,
17368 /*ExceptionSpecTokens=*/nullptr,
17369 /*DeclsInPrototype=*/{}, Loc, Loc,
17370 D),
17371 std::move(DS.getAttributes()), SourceLocation());
17372 D.SetIdentifier(&II, Loc);
17373
17374 // Insert this function into the enclosing block scope.
17375 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17376 FD->setImplicit();
17377
17379
17380 return FD;
17381}
17382
17384 FunctionDecl *FD) {
17385 if (FD->isInvalidDecl())
17386 return;
17387
17388 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17389 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17390 return;
17391
17392 UnsignedOrNone AlignmentParam = std::nullopt;
17393 bool IsNothrow = false;
17394 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17395 return;
17396
17397 // C++2a [basic.stc.dynamic.allocation]p4:
17398 // An allocation function that has a non-throwing exception specification
17399 // indicates failure by returning a null pointer value. Any other allocation
17400 // function never returns a null pointer value and indicates failure only by
17401 // throwing an exception [...]
17402 //
17403 // However, -fcheck-new invalidates this possible assumption, so don't add
17404 // NonNull when that is enabled.
17405 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17406 !getLangOpts().CheckNew)
17407 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17408
17409 // C++2a [basic.stc.dynamic.allocation]p2:
17410 // An allocation function attempts to allocate the requested amount of
17411 // storage. [...] If the request succeeds, the value returned by a
17412 // replaceable allocation function is a [...] pointer value p0 different
17413 // from any previously returned value p1 [...]
17414 //
17415 // However, this particular information is being added in codegen,
17416 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17417
17418 // C++2a [basic.stc.dynamic.allocation]p2:
17419 // An allocation function attempts to allocate the requested amount of
17420 // storage. If it is successful, it returns the address of the start of a
17421 // block of storage whose length in bytes is at least as large as the
17422 // requested size.
17423 if (!FD->hasAttr<AllocSizeAttr>()) {
17424 FD->addAttr(AllocSizeAttr::CreateImplicit(
17425 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17426 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17427 }
17428
17429 // C++2a [basic.stc.dynamic.allocation]p3:
17430 // For an allocation function [...], the pointer returned on a successful
17431 // call shall represent the address of storage that is aligned as follows:
17432 // (3.1) If the allocation function takes an argument of type
17433 // std​::​align_­val_­t, the storage will have the alignment
17434 // specified by the value of this argument.
17435 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17436 FD->addAttr(AllocAlignAttr::CreateImplicit(
17437 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17438 }
17439
17440 // FIXME:
17441 // C++2a [basic.stc.dynamic.allocation]p3:
17442 // For an allocation function [...], the pointer returned on a successful
17443 // call shall represent the address of storage that is aligned as follows:
17444 // (3.2) Otherwise, if the allocation function is named operator new[],
17445 // the storage is aligned for any object that does not have
17446 // new-extended alignment ([basic.align]) and is no larger than the
17447 // requested size.
17448 // (3.3) Otherwise, the storage is aligned for any object that does not
17449 // have new-extended alignment and is of the requested size.
17450}
17451
17453 if (FD->isInvalidDecl())
17454 return;
17455
17456 // If this is a built-in function, map its builtin attributes to
17457 // actual attributes.
17458 if (unsigned BuiltinID = FD->getBuiltinID()) {
17459 // Handle printf-formatting attributes.
17460 unsigned FormatIdx;
17461 bool HasVAListArg;
17462 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17463 if (!FD->hasAttr<FormatAttr>()) {
17464 const char *fmt = "printf";
17465 unsigned int NumParams = FD->getNumParams();
17466 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17467 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17468 fmt = "NSString";
17469 FD->addAttr(FormatAttr::CreateImplicit(Context,
17470 &Context.Idents.get(fmt),
17471 FormatIdx+1,
17472 HasVAListArg ? 0 : FormatIdx+2,
17473 FD->getLocation()));
17474 }
17475 }
17476 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17477 HasVAListArg)) {
17478 if (!FD->hasAttr<FormatAttr>())
17479 FD->addAttr(FormatAttr::CreateImplicit(Context,
17480 &Context.Idents.get("scanf"),
17481 FormatIdx+1,
17482 HasVAListArg ? 0 : FormatIdx+2,
17483 FD->getLocation()));
17484 }
17485
17486 // Handle automatically recognized callbacks.
17487 SmallVector<int, 4> Encoding;
17488 if (!FD->hasAttr<CallbackAttr>() &&
17489 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17490 FD->addAttr(CallbackAttr::CreateImplicit(
17491 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17492
17493 // Mark const if we don't care about errno and/or floating point exceptions
17494 // that are the only thing preventing the function from being const. This
17495 // allows IRgen to use LLVM intrinsics for such functions.
17496 bool NoExceptions =
17498 bool ConstWithoutErrnoAndExceptions =
17499 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17500 bool ConstWithoutExceptions =
17501 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17502 if (!FD->hasAttr<ConstAttr>() &&
17503 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17504 (!ConstWithoutErrnoAndExceptions ||
17505 (!getLangOpts().MathErrno && NoExceptions)) &&
17506 (!ConstWithoutExceptions || NoExceptions))
17507 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17508
17509 // We make "fma" on GNU or Windows const because we know it does not set
17510 // errno in those environments even though it could set errno based on the
17511 // C standard.
17512 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17513 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17514 !FD->hasAttr<ConstAttr>()) {
17515 switch (BuiltinID) {
17516 case Builtin::BI__builtin_fma:
17517 case Builtin::BI__builtin_fmaf:
17518 case Builtin::BI__builtin_fmal:
17519 case Builtin::BIfma:
17520 case Builtin::BIfmaf:
17521 case Builtin::BIfmal:
17522 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17523 break;
17524 default:
17525 break;
17526 }
17527 }
17528
17529 SmallVector<int, 4> Indxs;
17531 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17532 !FD->hasAttr<NonNullAttr>()) {
17534 for (int I : Indxs) {
17535 ParmVarDecl *PVD = FD->getParamDecl(I);
17536 QualType T = PVD->getType();
17537 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17538 PVD->setType(T);
17539 }
17540 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17542 for (int I : Indxs)
17543 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17544 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17545 ParamIndxs.size()));
17546 }
17547 }
17548 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17549 !FD->hasAttr<ReturnsTwiceAttr>())
17550 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17551 FD->getLocation()));
17552 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17553 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17554 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17555 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17556 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17557 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17558 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17559 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17560 // Add the appropriate attribute, depending on the CUDA compilation mode
17561 // and which target the builtin belongs to. For example, during host
17562 // compilation, aux builtins are __device__, while the rest are __host__.
17563 if (getLangOpts().CUDAIsDevice !=
17564 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17565 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17566 else
17567 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17568 }
17569
17570 // Add known guaranteed alignment for allocation functions.
17571 switch (BuiltinID) {
17572 case Builtin::BImemalign:
17573 case Builtin::BIaligned_alloc:
17574 if (!FD->hasAttr<AllocAlignAttr>())
17575 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17576 FD->getLocation()));
17577 break;
17578 default:
17579 break;
17580 }
17581
17582 // Add allocsize attribute for allocation functions.
17583 switch (BuiltinID) {
17584 case Builtin::BIcalloc:
17585 FD->addAttr(AllocSizeAttr::CreateImplicit(
17586 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17587 break;
17588 case Builtin::BImemalign:
17589 case Builtin::BIaligned_alloc:
17590 case Builtin::BIrealloc:
17591 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17592 ParamIdx(), FD->getLocation()));
17593 break;
17594 case Builtin::BImalloc:
17595 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17596 ParamIdx(), FD->getLocation()));
17597 break;
17598 default:
17599 break;
17600 }
17601 }
17602
17607
17608 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17609 // throw, add an implicit nothrow attribute to any extern "C" function we come
17610 // across.
17611 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17612 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17613 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17614 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17615 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17616 }
17617
17618 IdentifierInfo *Name = FD->getIdentifier();
17619 if (!Name)
17620 return;
17623 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17625 // Okay: this could be a libc/libm/Objective-C function we know
17626 // about.
17627 } else
17628 return;
17629
17630 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17631 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17632 // target-specific builtins, perhaps?
17633 if (!FD->hasAttr<FormatAttr>())
17634 FD->addAttr(FormatAttr::CreateImplicit(Context,
17635 &Context.Idents.get("printf"), 2,
17636 Name->isStr("vasprintf") ? 0 : 3,
17637 FD->getLocation()));
17638 }
17639
17640 if (Name->isStr("__CFStringMakeConstantString")) {
17641 // We already have a __builtin___CFStringMakeConstantString,
17642 // but builds that use -fno-constant-cfstrings don't go through that.
17643 if (!FD->hasAttr<FormatArgAttr>())
17644 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17645 FD->getLocation()));
17646 }
17647}
17648
17650 TypeSourceInfo *TInfo) {
17651 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17652 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17653
17654 if (!TInfo) {
17655 assert(D.isInvalidType() && "no declarator info for valid type");
17656 TInfo = Context.getTrivialTypeSourceInfo(T);
17657 }
17658
17659 // Scope manipulation handled by caller.
17660 TypedefDecl *NewTD =
17662 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17663
17664 // Bail out immediately if we have an invalid declaration.
17665 if (D.isInvalidType()) {
17666 NewTD->setInvalidDecl();
17667 return NewTD;
17668 }
17669
17671 if (CurContext->isFunctionOrMethod())
17672 Diag(NewTD->getLocation(), diag::err_module_private_local)
17673 << 2 << NewTD
17677 else
17678 NewTD->setModulePrivate();
17679 }
17680
17681 // C++ [dcl.typedef]p8:
17682 // If the typedef declaration defines an unnamed class (or
17683 // enum), the first typedef-name declared by the declaration
17684 // to be that class type (or enum type) is used to denote the
17685 // class type (or enum type) for linkage purposes only.
17686 // We need to check whether the type was declared in the declaration.
17687 switch (D.getDeclSpec().getTypeSpecType()) {
17688 case TST_enum:
17689 case TST_struct:
17690 case TST_interface:
17691 case TST_union:
17692 case TST_class: {
17693 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17694 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17695 break;
17696 }
17697
17698 default:
17699 break;
17700 }
17701
17702 return NewTD;
17703}
17704
17706 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17707 QualType T = TI->getType();
17708
17709 if (T->isDependentType())
17710 return false;
17711
17712 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17713 // integral type; any cv-qualification is ignored.
17714 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17715 // non-atomic version of the type specified by the type specifiers in the
17716 // specifier qualifier list.
17717 // Because of how odd C's rule is, we'll let the user know that operations
17718 // involving the enumeration type will be non-atomic.
17719 if (T->isAtomicType())
17720 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17721
17722 Qualifiers Q = T.getQualifiers();
17723 std::optional<unsigned> QualSelect;
17724 if (Q.hasConst() && Q.hasVolatile())
17725 QualSelect = diag::CVQualList::Both;
17726 else if (Q.hasConst())
17727 QualSelect = diag::CVQualList::Const;
17728 else if (Q.hasVolatile())
17729 QualSelect = diag::CVQualList::Volatile;
17730
17731 if (QualSelect)
17732 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17733
17734 T = T.getAtomicUnqualifiedType();
17735
17736 // This doesn't use 'isIntegralType' despite the error message mentioning
17737 // integral type because isIntegralType would also allow enum types in C.
17738 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17739 if (BT->isInteger())
17740 return false;
17741
17742 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17743 << T << T->isBitIntType();
17744}
17745
17747 QualType EnumUnderlyingTy, bool IsFixed,
17748 const EnumDecl *Prev) {
17749 if (IsScoped != Prev->isScoped()) {
17750 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17751 << Prev->isScoped();
17752 Diag(Prev->getLocation(), diag::note_previous_declaration);
17753 return true;
17754 }
17755
17756 if (IsFixed && Prev->isFixed()) {
17757 if (!EnumUnderlyingTy->isDependentType() &&
17758 !Prev->getIntegerType()->isDependentType() &&
17759 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17760 Prev->getIntegerType())) {
17761 // TODO: Highlight the underlying type of the redeclaration.
17762 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17763 << EnumUnderlyingTy << Prev->getIntegerType();
17764 Diag(Prev->getLocation(), diag::note_previous_declaration)
17765 << Prev->getIntegerTypeRange();
17766 return true;
17767 }
17768 } else if (IsFixed != Prev->isFixed()) {
17769 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17770 << Prev->isFixed();
17771 Diag(Prev->getLocation(), diag::note_previous_declaration);
17772 return true;
17773 }
17774
17775 return false;
17776}
17777
17778/// Get diagnostic %select index for tag kind for
17779/// redeclaration diagnostic message.
17780/// WARNING: Indexes apply to particular diagnostics only!
17781///
17782/// \returns diagnostic %select index.
17784 switch (Tag) {
17786 return 0;
17788 return 1;
17789 case TagTypeKind::Class:
17790 return 2;
17791 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17792 }
17793}
17794
17795/// Determine if tag kind is a class-key compatible with
17796/// class for redeclaration (class, struct, or __interface).
17797///
17798/// \returns true iff the tag kind is compatible.
17800{
17801 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17803}
17804
17806 if (isa<TypedefDecl>(PrevDecl))
17807 return NonTagKind::Typedef;
17808 else if (isa<TypeAliasDecl>(PrevDecl))
17809 return NonTagKind::TypeAlias;
17810 else if (isa<ClassTemplateDecl>(PrevDecl))
17811 return NonTagKind::Template;
17812 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17814 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17816 switch (TTK) {
17819 case TagTypeKind::Class:
17820 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17822 case TagTypeKind::Union:
17823 return NonTagKind::NonUnion;
17824 case TagTypeKind::Enum:
17825 return NonTagKind::NonEnum;
17826 }
17827 llvm_unreachable("invalid TTK");
17828}
17829
17831 TagTypeKind NewTag, bool isDefinition,
17832 SourceLocation NewTagLoc,
17833 const IdentifierInfo *Name) {
17834 // C++ [dcl.type.elab]p3:
17835 // The class-key or enum keyword present in the
17836 // elaborated-type-specifier shall agree in kind with the
17837 // declaration to which the name in the elaborated-type-specifier
17838 // refers. This rule also applies to the form of
17839 // elaborated-type-specifier that declares a class-name or
17840 // friend class since it can be construed as referring to the
17841 // definition of the class. Thus, in any
17842 // elaborated-type-specifier, the enum keyword shall be used to
17843 // refer to an enumeration (7.2), the union class-key shall be
17844 // used to refer to a union (clause 9), and either the class or
17845 // struct class-key shall be used to refer to a class (clause 9)
17846 // declared using the class or struct class-key.
17847 TagTypeKind OldTag = Previous->getTagKind();
17848 if (OldTag != NewTag &&
17850 return false;
17851
17852 // Tags are compatible, but we might still want to warn on mismatched tags.
17853 // Non-class tags can't be mismatched at this point.
17855 return true;
17856
17857 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17858 // by our warning analysis. We don't want to warn about mismatches with (eg)
17859 // declarations in system headers that are designed to be specialized, but if
17860 // a user asks us to warn, we should warn if their code contains mismatched
17861 // declarations.
17862 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17863 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17864 Loc);
17865 };
17866 if (IsIgnoredLoc(NewTagLoc))
17867 return true;
17868
17869 auto IsIgnored = [&](const TagDecl *Tag) {
17870 return IsIgnoredLoc(Tag->getLocation());
17871 };
17872 while (IsIgnored(Previous)) {
17873 Previous = Previous->getPreviousDecl();
17874 if (!Previous)
17875 return true;
17876 OldTag = Previous->getTagKind();
17877 }
17878
17879 bool isTemplate = false;
17880 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17881 isTemplate = Record->getDescribedClassTemplate();
17882
17884 if (OldTag != NewTag) {
17885 // In a template instantiation, do not offer fix-its for tag mismatches
17886 // since they usually mess up the template instead of fixing the problem.
17887 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17889 << getRedeclDiagFromTagKind(OldTag);
17890 // FIXME: Note previous location?
17891 }
17892 return true;
17893 }
17894
17895 if (isDefinition) {
17896 // On definitions, check all previous tags and issue a fix-it for each
17897 // one that doesn't match the current tag.
17898 if (Previous->getDefinition()) {
17899 // Don't suggest fix-its for redefinitions.
17900 return true;
17901 }
17902
17903 bool previousMismatch = false;
17904 for (const TagDecl *I : Previous->redecls()) {
17905 if (I->getTagKind() != NewTag) {
17906 // Ignore previous declarations for which the warning was disabled.
17907 if (IsIgnored(I))
17908 continue;
17909
17910 if (!previousMismatch) {
17911 previousMismatch = true;
17912 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17914 << getRedeclDiagFromTagKind(I->getTagKind());
17915 }
17916 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17918 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17920 }
17921 }
17922 return true;
17923 }
17924
17925 // Identify the prevailing tag kind: this is the kind of the definition (if
17926 // there is a non-ignored definition), or otherwise the kind of the prior
17927 // (non-ignored) declaration.
17928 const TagDecl *PrevDef = Previous->getDefinition();
17929 if (PrevDef && IsIgnored(PrevDef))
17930 PrevDef = nullptr;
17931 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17932 if (Redecl->getTagKind() != NewTag) {
17933 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17935 << getRedeclDiagFromTagKind(OldTag);
17936 Diag(Redecl->getLocation(), diag::note_previous_use);
17937
17938 // If there is a previous definition, suggest a fix-it.
17939 if (PrevDef) {
17940 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17944 }
17945 }
17946
17947 return true;
17948}
17949
17950/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17951/// from an outer enclosing namespace or file scope inside a friend declaration.
17952/// This should provide the commented out code in the following snippet:
17953/// namespace N {
17954/// struct X;
17955/// namespace M {
17956/// struct Y { friend struct /*N::*/ X; };
17957/// }
17958/// }
17960 SourceLocation NameLoc) {
17961 // While the decl is in a namespace, do repeated lookup of that name and see
17962 // if we get the same namespace back. If we do not, continue until
17963 // translation unit scope, at which point we have a fully qualified NNS.
17966 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17967 // This tag should be declared in a namespace, which can only be enclosed by
17968 // other namespaces. Bail if there's an anonymous namespace in the chain.
17969 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17970 if (!Namespace || Namespace->isAnonymousNamespace())
17971 return FixItHint();
17972 IdentifierInfo *II = Namespace->getIdentifier();
17973 Namespaces.push_back(II);
17974 NamedDecl *Lookup = SemaRef.LookupSingleName(
17975 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17976 if (Lookup == Namespace)
17977 break;
17978 }
17979
17980 // Once we have all the namespaces, reverse them to go outermost first, and
17981 // build an NNS.
17982 SmallString<64> Insertion;
17983 llvm::raw_svector_ostream OS(Insertion);
17984 if (DC->isTranslationUnit())
17985 OS << "::";
17986 std::reverse(Namespaces.begin(), Namespaces.end());
17987 for (auto *II : Namespaces)
17988 OS << II->getName() << "::";
17989 return FixItHint::CreateInsertion(NameLoc, Insertion);
17990}
17991
17992/// Determine whether a tag originally declared in context \p OldDC can
17993/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17994/// found a declaration in \p OldDC as a previous decl, perhaps through a
17995/// using-declaration).
17997 DeclContext *NewDC) {
17998 OldDC = OldDC->getRedeclContext();
17999 NewDC = NewDC->getRedeclContext();
18000
18001 if (OldDC->Equals(NewDC))
18002 return true;
18003
18004 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18005 // encloses the other).
18006 if (S.getLangOpts().MSVCCompat &&
18007 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
18008 return true;
18009
18010 return false;
18011}
18012
18014Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18015 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18016 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18017 SourceLocation ModulePrivateLoc,
18018 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18019 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18020 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18021 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18022 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18023 // If this is not a definition, it must have a name.
18024 IdentifierInfo *OrigName = Name;
18025 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18026 "Nameless record must be a definition!");
18027 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18028
18029 OwnedDecl = false;
18031 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18032
18033 // FIXME: Check member specializations more carefully.
18034 bool isMemberSpecialization = false;
18035 bool IsInjectedClassName = false;
18036 bool Invalid = false;
18037
18038 // We only need to do this matching if we have template parameters
18039 // or a scope specifier, which also conveniently avoids this work
18040 // for non-C++ cases.
18041 if (TemplateParameterLists.size() > 0 ||
18042 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18043 TemplateParameterList *TemplateParams =
18045 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
18046 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
18047
18048 // C++23 [dcl.type.elab] p2:
18049 // If an elaborated-type-specifier is the sole constituent of a
18050 // declaration, the declaration is ill-formed unless it is an explicit
18051 // specialization, an explicit instantiation or it has one of the
18052 // following forms: [...]
18053 // C++23 [dcl.enum] p1:
18054 // If the enum-head-name of an opaque-enum-declaration contains a
18055 // nested-name-specifier, the declaration shall be an explicit
18056 // specialization.
18057 //
18058 // FIXME: Class template partial specializations can be forward declared
18059 // per CWG2213, but the resolution failed to allow qualified forward
18060 // declarations. This is almost certainly unintentional, so we allow them.
18061 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18062 !isMemberSpecialization)
18063 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
18065
18066 if (TemplateParams) {
18067 if (Kind == TagTypeKind::Enum) {
18068 Diag(KWLoc, diag::err_enum_template);
18069 return true;
18070 }
18071
18072 if (TemplateParams->size() > 0) {
18073 // This is a declaration or definition of a class template (which may
18074 // be a member of another template).
18075
18076 if (Invalid)
18077 return true;
18078
18079 OwnedDecl = false;
18081 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
18082 AS, ModulePrivateLoc,
18083 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
18084 TemplateParameterLists.data(), isMemberSpecialization, SkipBody);
18085 return Result.get();
18086 } else {
18087 // The "template<>" header is extraneous.
18088 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18089 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18090 isMemberSpecialization = true;
18091 }
18092 }
18093
18094 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18095 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18096 return true;
18097 }
18098
18099 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18100 // C++23 [dcl.type.elab]p4:
18101 // If an elaborated-type-specifier appears with the friend specifier as
18102 // an entire member-declaration, the member-declaration shall have one
18103 // of the following forms:
18104 // friend class-key nested-name-specifier(opt) identifier ;
18105 // friend class-key simple-template-id ;
18106 // friend class-key nested-name-specifier template(opt)
18107 // simple-template-id ;
18108 //
18109 // Since enum is not a class-key, so declarations like "friend enum E;"
18110 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18111 // invalid, most implementations accept so we issue a pedantic warning.
18112 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18113 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18114 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18115 Diag(KWLoc, diag::note_enum_friend)
18116 << (ScopedEnum + ScopedEnumUsesClassTag);
18117 }
18118
18119 // Figure out the underlying type if this a enum declaration. We need to do
18120 // this early, because it's needed to detect if this is an incompatible
18121 // redeclaration.
18122 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18123 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18124
18125 if (Kind == TagTypeKind::Enum) {
18126 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18127 Invalid) {
18128 // No underlying type explicitly specified, or we failed to parse the
18129 // type, default to int.
18130 EnumUnderlying = Context.IntTy.getTypePtr();
18131 } else if (UnderlyingType.get()) {
18132 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18133 // integral type; any cv-qualification is ignored.
18134 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18135 // unqualified, non-atomic version of the type specified by the type
18136 // specifiers in the specifier qualifier list.
18137 TypeSourceInfo *TI = nullptr;
18138 GetTypeFromParser(UnderlyingType.get(), &TI);
18139 EnumUnderlying = TI;
18140
18142 // Recover by falling back to int.
18143 EnumUnderlying = Context.IntTy.getTypePtr();
18144
18147 EnumUnderlying = Context.IntTy.getTypePtr();
18148
18149 // If the underlying type is atomic, we need to adjust the type before
18150 // continuing. This only happens in the case we stored a TypeSourceInfo
18151 // into EnumUnderlying because the other cases are error recovery up to
18152 // this point. But because it's not possible to gin up a TypeSourceInfo
18153 // for a non-atomic type from an atomic one, we'll store into the Type
18154 // field instead. FIXME: it would be nice to have an easy way to get a
18155 // derived TypeSourceInfo which strips qualifiers including the weird
18156 // ones like _Atomic where it forms a different type.
18157 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18158 TI && TI->getType()->isAtomicType())
18159 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18160
18161 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18162 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18163 // of 'int'. However, if this is an unfixed forward declaration, don't set
18164 // the underlying type unless the user enables -fms-compatibility. This
18165 // makes unfixed forward declared enums incomplete and is more conforming.
18166 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18167 EnumUnderlying = Context.IntTy.getTypePtr();
18168 }
18169 }
18170
18171 DeclContext *SearchDC = CurContext;
18172 DeclContext *DC = CurContext;
18173 bool isStdBadAlloc = false;
18174 bool isStdAlignValT = false;
18175
18177 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18179
18180 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18181 /// implemented asks for structural equivalence checking, the returned decl
18182 /// here is passed back to the parser, allowing the tag body to be parsed.
18183 auto createTagFromNewDecl = [&]() -> TagDecl * {
18184 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18185 // If there is an identifier, use the location of the identifier as the
18186 // location of the decl, otherwise use the location of the struct/union
18187 // keyword.
18188 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18189 TagDecl *New = nullptr;
18190
18191 if (Kind == TagTypeKind::Enum) {
18192 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18193 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18194 // If this is an undefined enum, bail.
18195 if (TUK != TagUseKind::Definition && !Invalid)
18196 return nullptr;
18197 if (EnumUnderlying) {
18199 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18201 else
18202 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18203 QualType EnumTy = ED->getIntegerType();
18204 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18205 ? Context.getPromotedIntegerType(EnumTy)
18206 : EnumTy);
18207 }
18208 } else { // struct/union
18209 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18210 nullptr);
18211 }
18212
18213 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18214 // Add alignment attributes if necessary; these attributes are checked
18215 // when the ASTContext lays out the structure.
18216 //
18217 // It is important for implementing the correct semantics that this
18218 // happen here (in ActOnTag). The #pragma pack stack is
18219 // maintained as a result of parser callbacks which can occur at
18220 // many points during the parsing of a struct declaration (because
18221 // the #pragma tokens are effectively skipped over during the
18222 // parsing of the struct).
18223 if (TUK == TagUseKind::Definition &&
18224 (!SkipBody || !SkipBody->ShouldSkip)) {
18225 if (LangOpts.HLSL)
18226 RD->addAttr(PackedAttr::CreateImplicit(Context));
18229 }
18230 }
18231 New->setLexicalDeclContext(CurContext);
18232 return New;
18233 };
18234
18235 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18236 if (Name && SS.isNotEmpty()) {
18237 // We have a nested-name tag ('struct foo::bar').
18238
18239 // Check for invalid 'foo::'.
18240 if (SS.isInvalid()) {
18241 Name = nullptr;
18242 goto CreateNewDecl;
18243 }
18244
18245 // If this is a friend or a reference to a class in a dependent
18246 // context, don't try to make a decl for it.
18247 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18248 DC = computeDeclContext(SS, false);
18249 if (!DC) {
18250 IsDependent = true;
18251 return true;
18252 }
18253 } else {
18254 DC = computeDeclContext(SS, true);
18255 if (!DC) {
18256 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18257 << SS.getRange();
18258 return true;
18259 }
18260 }
18261
18262 if (RequireCompleteDeclContext(SS, DC))
18263 return true;
18264
18265 SearchDC = DC;
18266 // Look-up name inside 'foo::'.
18268
18269 if (Previous.isAmbiguous())
18270 return true;
18271
18272 if (Previous.empty()) {
18273 // Name lookup did not find anything. However, if the
18274 // nested-name-specifier refers to the current instantiation,
18275 // and that current instantiation has any dependent base
18276 // classes, we might find something at instantiation time: treat
18277 // this as a dependent elaborated-type-specifier.
18278 // But this only makes any sense for reference-like lookups.
18279 if (Previous.wasNotFoundInCurrentInstantiation() &&
18280 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18281 IsDependent = true;
18282 return true;
18283 }
18284
18285 // A tag 'foo::bar' must already exist.
18286 Diag(NameLoc, diag::err_not_tag_in_scope)
18287 << Kind << Name << DC << SS.getRange();
18288 Name = nullptr;
18289 Invalid = true;
18290 goto CreateNewDecl;
18291 }
18292 } else if (Name) {
18293 // C++14 [class.mem]p14:
18294 // If T is the name of a class, then each of the following shall have a
18295 // name different from T:
18296 // -- every member of class T that is itself a type
18297 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18298 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18299 return true;
18300
18301 // If this is a named struct, check to see if there was a previous forward
18302 // declaration or definition.
18303 // FIXME: We're looking into outer scopes here, even when we
18304 // shouldn't be. Doing so can result in ambiguities that we
18305 // shouldn't be diagnosing.
18306 LookupName(Previous, S);
18307
18308 // When declaring or defining a tag, ignore ambiguities introduced
18309 // by types using'ed into this scope.
18310 if (Previous.isAmbiguous() &&
18312 LookupResult::Filter F = Previous.makeFilter();
18313 while (F.hasNext()) {
18314 NamedDecl *ND = F.next();
18315 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18316 SearchDC->getRedeclContext()))
18317 F.erase();
18318 }
18319 F.done();
18320 }
18321
18322 // C++11 [namespace.memdef]p3:
18323 // If the name in a friend declaration is neither qualified nor
18324 // a template-id and the declaration is a function or an
18325 // elaborated-type-specifier, the lookup to determine whether
18326 // the entity has been previously declared shall not consider
18327 // any scopes outside the innermost enclosing namespace.
18328 //
18329 // MSVC doesn't implement the above rule for types, so a friend tag
18330 // declaration may be a redeclaration of a type declared in an enclosing
18331 // scope. They do implement this rule for friend functions.
18332 //
18333 // Does it matter that this should be by scope instead of by
18334 // semantic context?
18335 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18336 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18337 LookupResult::Filter F = Previous.makeFilter();
18338 bool FriendSawTagOutsideEnclosingNamespace = false;
18339 while (F.hasNext()) {
18340 NamedDecl *ND = F.next();
18342 if (DC->isFileContext() &&
18343 !EnclosingNS->Encloses(ND->getDeclContext())) {
18344 if (getLangOpts().MSVCCompat)
18345 FriendSawTagOutsideEnclosingNamespace = true;
18346 else
18347 F.erase();
18348 }
18349 }
18350 F.done();
18351
18352 // Diagnose this MSVC extension in the easy case where lookup would have
18353 // unambiguously found something outside the enclosing namespace.
18354 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18355 NamedDecl *ND = Previous.getFoundDecl();
18356 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18357 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18358 }
18359 }
18360
18361 // Note: there used to be some attempt at recovery here.
18362 if (Previous.isAmbiguous())
18363 return true;
18364
18365 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18366 // FIXME: This makes sure that we ignore the contexts associated
18367 // with C structs, unions, and enums when looking for a matching
18368 // tag declaration or definition. See the similar lookup tweak
18369 // in Sema::LookupName; is there a better way to deal with this?
18371 SearchDC = SearchDC->getParent();
18372 } else if (getLangOpts().CPlusPlus) {
18373 // Inside ObjCContainer want to keep it as a lexical decl context but go
18374 // past it (most often to TranslationUnit) to find the semantic decl
18375 // context.
18376 while (isa<ObjCContainerDecl>(SearchDC))
18377 SearchDC = SearchDC->getParent();
18378 }
18379 } else if (getLangOpts().CPlusPlus) {
18380 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18381 // TagDecl the same way as we skip it for named TagDecl.
18382 while (isa<ObjCContainerDecl>(SearchDC))
18383 SearchDC = SearchDC->getParent();
18384 }
18385
18386 if (Previous.isSingleResult() &&
18387 Previous.getFoundDecl()->isTemplateParameter()) {
18388 // Maybe we will complain about the shadowed template parameter.
18389 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18390 // Just pretend that we didn't see the previous declaration.
18391 Previous.clear();
18392 }
18393
18394 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18395 DC->Equals(getStdNamespace())) {
18396 if (Name->isStr("bad_alloc")) {
18397 // This is a declaration of or a reference to "std::bad_alloc".
18398 isStdBadAlloc = true;
18399
18400 // If std::bad_alloc has been implicitly declared (but made invisible to
18401 // name lookup), fill in this implicit declaration as the previous
18402 // declaration, so that the declarations get chained appropriately.
18403 if (Previous.empty() && StdBadAlloc)
18404 Previous.addDecl(getStdBadAlloc());
18405 } else if (Name->isStr("align_val_t")) {
18406 isStdAlignValT = true;
18407 if (Previous.empty() && StdAlignValT)
18408 Previous.addDecl(getStdAlignValT());
18409 }
18410 }
18411
18412 // If we didn't find a previous declaration, and this is a reference
18413 // (or friend reference), move to the correct scope. In C++, we
18414 // also need to do a redeclaration lookup there, just in case
18415 // there's a shadow friend decl.
18416 if (Name && Previous.empty() &&
18417 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18418 IsTemplateParamOrArg)) {
18419 if (Invalid) goto CreateNewDecl;
18420 assert(SS.isEmpty());
18421
18422 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18423 // C++ [basic.scope.pdecl]p5:
18424 // -- for an elaborated-type-specifier of the form
18425 //
18426 // class-key identifier
18427 //
18428 // if the elaborated-type-specifier is used in the
18429 // decl-specifier-seq or parameter-declaration-clause of a
18430 // function defined in namespace scope, the identifier is
18431 // declared as a class-name in the namespace that contains
18432 // the declaration; otherwise, except as a friend
18433 // declaration, the identifier is declared in the smallest
18434 // non-class, non-function-prototype scope that contains the
18435 // declaration.
18436 //
18437 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18438 // C structs and unions.
18439 //
18440 // It is an error in C++ to declare (rather than define) an enum
18441 // type, including via an elaborated type specifier. We'll
18442 // diagnose that later; for now, declare the enum in the same
18443 // scope as we would have picked for any other tag type.
18444 //
18445 // GNU C also supports this behavior as part of its incomplete
18446 // enum types extension, while GNU C++ does not.
18447 //
18448 // Find the context where we'll be declaring the tag.
18449 // FIXME: We would like to maintain the current DeclContext as the
18450 // lexical context,
18451 SearchDC = getTagInjectionContext(SearchDC);
18452
18453 // Find the scope where we'll be declaring the tag.
18455 } else {
18456 assert(TUK == TagUseKind::Friend);
18457 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18458
18459 // C++ [namespace.memdef]p3:
18460 // If a friend declaration in a non-local class first declares a
18461 // class or function, the friend class or function is a member of
18462 // the innermost enclosing namespace.
18463 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18464 : SearchDC->getEnclosingNamespaceContext();
18465 }
18466
18467 // In C++, we need to do a redeclaration lookup to properly
18468 // diagnose some problems.
18469 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18470 // hidden declaration so that we don't get ambiguity errors when using a
18471 // type declared by an elaborated-type-specifier. In C that is not correct
18472 // and we should instead merge compatible types found by lookup.
18473 if (getLangOpts().CPlusPlus) {
18474 // FIXME: This can perform qualified lookups into function contexts,
18475 // which are meaningless.
18476 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18477 LookupQualifiedName(Previous, SearchDC);
18478 } else {
18479 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18480 LookupName(Previous, S);
18481 }
18482 }
18483
18484 // If we have a known previous declaration to use, then use it.
18485 if (Previous.empty() && SkipBody && SkipBody->Previous)
18486 Previous.addDecl(SkipBody->Previous);
18487
18488 if (!Previous.empty()) {
18489 NamedDecl *PrevDecl = Previous.getFoundDecl();
18490 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18491
18492 // It's okay to have a tag decl in the same scope as a typedef
18493 // which hides a tag decl in the same scope. Finding this
18494 // with a redeclaration lookup can only actually happen in C++.
18495 //
18496 // This is also okay for elaborated-type-specifiers, which is
18497 // technically forbidden by the current standard but which is
18498 // okay according to the likely resolution of an open issue;
18499 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18500 if (getLangOpts().CPlusPlus) {
18501 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18502 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18503 if (Tag->getDeclName() == Name &&
18504 Tag->getDeclContext()->getRedeclContext()
18505 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18506 PrevDecl = Tag;
18507 Previous.clear();
18508 Previous.addDecl(Tag);
18509 Previous.resolveKind();
18510 }
18511 }
18512 }
18513 }
18514
18515 // If this is a redeclaration of a using shadow declaration, it must
18516 // declare a tag in the same context. In MSVC mode, we allow a
18517 // redefinition if either context is within the other.
18518 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18519 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18520 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18521 TUK != TagUseKind::Friend &&
18522 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18523 !(OldTag && isAcceptableTagRedeclContext(
18524 *this, OldTag->getDeclContext(), SearchDC))) {
18525 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18526 Diag(Shadow->getTargetDecl()->getLocation(),
18527 diag::note_using_decl_target);
18528 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18529 << 0;
18530 // Recover by ignoring the old declaration.
18531 Previous.clear();
18532 goto CreateNewDecl;
18533 }
18534 }
18535
18536 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18537 // If this is a use of a previous tag, or if the tag is already declared
18538 // in the same scope (so that the definition/declaration completes or
18539 // rementions the tag), reuse the decl.
18540 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18541 isDeclInScope(DirectPrevDecl, SearchDC, S,
18542 SS.isNotEmpty() || isMemberSpecialization)) {
18543
18544 if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18545 RD && RD->isInjectedClassName()) {
18546 // If lookup found the injected class name, the previous declaration
18547 // is the class being injected into.
18548 Previous.clear();
18549 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(RD->getDeclContext());
18550 Previous.addDecl(PrevDecl);
18551 Previous.resolveKind();
18552 IsInjectedClassName = true;
18553 }
18554
18555 // Make sure that this wasn't declared as an enum and now used as a
18556 // struct or something similar.
18557 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18558 TUK == TagUseKind::Definition, KWLoc,
18559 Name)) {
18560 bool SafeToContinue =
18561 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18562 Kind != TagTypeKind::Enum);
18563 if (SafeToContinue)
18564 Diag(KWLoc, diag::err_use_with_wrong_tag)
18565 << Name
18567 PrevTagDecl->getKindName());
18568 else
18569 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18570 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18571
18572 if (SafeToContinue)
18573 Kind = PrevTagDecl->getTagKind();
18574 else {
18575 // Recover by making this an anonymous redefinition.
18576 Name = nullptr;
18577 Previous.clear();
18578 Invalid = true;
18579 }
18580 }
18581
18582 if (Kind == TagTypeKind::Enum &&
18583 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18584 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18585 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18586 return PrevTagDecl;
18587
18588 QualType EnumUnderlyingTy;
18589 if (TypeSourceInfo *TI =
18590 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18591 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18592 else if (const Type *T =
18593 dyn_cast_if_present<const Type *>(EnumUnderlying))
18594 EnumUnderlyingTy = QualType(T, 0);
18595
18596 // All conflicts with previous declarations are recovered by
18597 // returning the previous declaration, unless this is a definition,
18598 // in which case we want the caller to bail out.
18599 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18600 ScopedEnum, EnumUnderlyingTy,
18601 IsFixed, PrevEnum))
18602 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18603 }
18604
18605 // C++11 [class.mem]p1:
18606 // A member shall not be declared twice in the member-specification,
18607 // except that a nested class or member class template can be declared
18608 // and then later defined.
18609 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18610 S->isDeclScope(PrevDecl)) {
18611 Diag(NameLoc, diag::ext_member_redeclared);
18612 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18613 }
18614
18615 // C++ [class.local]p3:
18616 // A class nested within a local class is a local class. A member of
18617 // a local class X shall be declared only in the definition of X or,
18618 // if the member is a nested class, in the nearest enclosing block
18619 // scope of X.
18620 if (TUK == TagUseKind::Definition && SS.isValid()) {
18621 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(PrevDecl)) {
18622 while (const auto *ParentClass =
18623 dyn_cast<CXXRecordDecl>(OutermostClass->getParent()))
18624 OutermostClass = ParentClass;
18625
18626 if (OutermostClass->isLocalClass() &&
18627 !S->isDeclScope(OutermostClass)) {
18628 Diag(NameLoc, diag::err_local_nested_class_invalid_scope)
18629 << Name << OutermostClass;
18630 Diag(OutermostClass->getLocation(), diag::note_defined_here)
18631 << OutermostClass;
18632 }
18633 }
18634 }
18635
18636 if (!Invalid) {
18637 // If this is a use, just return the declaration we found, unless
18638 // we have attributes.
18639 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18640 if (!Attrs.empty()) {
18641 // FIXME: Diagnose these attributes. For now, we create a new
18642 // declaration to hold them.
18643 } else if (TUK == TagUseKind::Reference &&
18644 (PrevTagDecl->getFriendObjectKind() ==
18646 PrevDecl->getOwningModule() != getCurrentModule()) &&
18647 SS.isEmpty()) {
18648 // This declaration is a reference to an existing entity, but
18649 // has different visibility from that entity: it either makes
18650 // a friend visible or it makes a type visible in a new module.
18651 // In either case, create a new declaration. We only do this if
18652 // the declaration would have meant the same thing if no prior
18653 // declaration were found, that is, if it was found in the same
18654 // scope where we would have injected a declaration.
18655 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18656 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18657 return PrevTagDecl;
18658 // This is in the injected scope, create a new declaration in
18659 // that scope.
18661 } else {
18662 return PrevTagDecl;
18663 }
18664 }
18665
18666 // Diagnose attempts to redefine a tag.
18667 if (TUK == TagUseKind::Definition) {
18668 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18669 // If the type is currently being defined, complain
18670 // about a nested redefinition.
18671 if (Def->isBeingDefined()) {
18672 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18673 Diag(PrevTagDecl->getLocation(),
18674 diag::note_previous_definition);
18675 Name = nullptr;
18676 Previous.clear();
18677 Invalid = true;
18678 } else {
18679 // If we're defining a specialization and the previous
18680 // definition is from an implicit instantiation, don't emit an
18681 // error here; we'll catch this in the general case below.
18682 bool IsExplicitSpecializationAfterInstantiation = false;
18683 if (isMemberSpecialization) {
18684 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18685 IsExplicitSpecializationAfterInstantiation =
18686 RD->getTemplateSpecializationKind() !=
18688 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18689 IsExplicitSpecializationAfterInstantiation =
18690 ED->getTemplateSpecializationKind() !=
18692 }
18693
18694 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18695 // do not keep more that one definition around (merge them).
18696 // However, ensure the decl passes the structural compatibility
18697 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18698 NamedDecl *Hidden = nullptr;
18699 bool HiddenDefVisible = false;
18700 if (SkipBody &&
18701 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18702 getLangOpts().C23)) {
18703 // There is a definition of this tag, but it is not visible.
18704 // We explicitly make use of C++'s one definition rule here,
18705 // and assume that this definition is identical to the hidden
18706 // one we already have. Make the existing definition visible
18707 // and use it in place of this one.
18708 if (!getLangOpts().CPlusPlus) {
18709 // Postpone making the old definition visible until after we
18710 // complete parsing the new one and do the structural
18711 // comparison.
18712 SkipBody->CheckSameAsPrevious = true;
18713 SkipBody->New = createTagFromNewDecl();
18714 SkipBody->Previous = Def;
18715
18716 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18717 return Def;
18718 }
18719
18720 SkipBody->ShouldSkip = true;
18721 SkipBody->Previous = Def;
18722 if (!HiddenDefVisible && Hidden)
18724 // Carry on and handle it like a normal definition. We'll
18725 // skip starting the definition later.
18726
18727 } else if (!IsExplicitSpecializationAfterInstantiation) {
18728 // A redeclaration in function prototype scope in C isn't
18729 // visible elsewhere, so merely issue a warning.
18730 if (!getLangOpts().CPlusPlus &&
18732 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18733 << Name;
18734 else
18735 Diag(NameLoc, diag::err_redefinition) << Name;
18737 NameLoc.isValid() ? NameLoc : KWLoc);
18738 // If this is a redefinition, recover by making this
18739 // struct be anonymous, which will make any later
18740 // references get the previous definition.
18741 Name = nullptr;
18742 Previous.clear();
18743 Invalid = true;
18744 }
18745 }
18746 }
18747
18748 // Okay, this is definition of a previously declared or referenced
18749 // tag. We're going to create a new Decl for it.
18750 }
18751
18752 // Okay, we're going to make a redeclaration. If this is some kind
18753 // of reference, make sure we build the redeclaration in the same DC
18754 // as the original, and ignore the current access specifier.
18755 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18756 IsInjectedClassName) {
18757 SearchDC = PrevTagDecl->getDeclContext();
18758 AS = AS_none;
18759 }
18760 }
18761 // If we get here we have (another) forward declaration or we
18762 // have a definition. Just create a new decl.
18763
18764 } else {
18765 // If we get here, this is a definition of a new tag type in a nested
18766 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18767 // new decl/type. We set PrevDecl to NULL so that the entities
18768 // have distinct types.
18769 Previous.clear();
18770 }
18771 // If we get here, we're going to create a new Decl. If PrevDecl
18772 // is non-NULL, it's a definition of the tag declared by
18773 // PrevDecl. If it's NULL, we have a new definition.
18774
18775 // Otherwise, PrevDecl is not a tag, but was found with tag
18776 // lookup. This is only actually possible in C++, where a few
18777 // things like templates still live in the tag namespace.
18778 } else {
18779 // Use a better diagnostic if an elaborated-type-specifier
18780 // found the wrong kind of type on the first
18781 // (non-redeclaration) lookup.
18782 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18783 !Previous.isForRedeclaration()) {
18784 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18785 Diag(NameLoc, diag::err_tag_reference_non_tag)
18786 << PrevDecl << NTK << Kind;
18787 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18788 Invalid = true;
18789
18790 // Otherwise, only diagnose if the declaration is in scope.
18791 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18792 SS.isNotEmpty() || isMemberSpecialization)) {
18793 // do nothing
18794
18795 // Diagnose implicit declarations introduced by elaborated types.
18796 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18797 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18798 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18799 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18800 Invalid = true;
18801
18802 // Otherwise it's a declaration. Call out a particularly common
18803 // case here.
18804 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18805 unsigned Kind = 0;
18806 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18807 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18808 << Name << Kind << TND->getUnderlyingType();
18809 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18810 Invalid = true;
18811
18812 // Otherwise, diagnose.
18813 } else {
18814 // The tag name clashes with something else in the target scope,
18815 // issue an error and recover by making this tag be anonymous.
18816 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18817 notePreviousDefinition(PrevDecl, NameLoc);
18818 Name = nullptr;
18819 Invalid = true;
18820 }
18821
18822 // The existing declaration isn't relevant to us; we're in a
18823 // new scope, so clear out the previous declaration.
18824 Previous.clear();
18825 }
18826 }
18827
18828CreateNewDecl:
18829
18830 TagDecl *PrevDecl = nullptr;
18831 if (Previous.isSingleResult())
18832 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18833
18834 // If there is an identifier, use the location of the identifier as the
18835 // location of the decl, otherwise use the location of the struct/union
18836 // keyword.
18837 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18838
18839 // Otherwise, create a new declaration. If there is a previous
18840 // declaration of the same entity, the two will be linked via
18841 // PrevDecl.
18842 TagDecl *New;
18843
18844 if (Kind == TagTypeKind::Enum) {
18845 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18846 // enum X { A, B, C } D; D should chain to X.
18847 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18848 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18849 ScopedEnumUsesClassTag, IsFixed);
18850
18853 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18854
18855 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18857
18858 // If this is an undefined enum, warn.
18859 if (TUK != TagUseKind::Definition && !Invalid) {
18860 TagDecl *Def;
18861 if (IsFixed && ED->isFixed()) {
18862 // C++0x: 7.2p2: opaque-enum-declaration.
18863 // Conflicts are diagnosed above. Do nothing.
18864 } else if (PrevDecl &&
18865 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18866 Diag(Loc, diag::ext_forward_ref_enum_def)
18867 << New;
18868 Diag(Def->getLocation(), diag::note_previous_definition);
18869 } else {
18870 unsigned DiagID = diag::ext_forward_ref_enum;
18871 if (getLangOpts().MSVCCompat)
18872 DiagID = diag::ext_ms_forward_ref_enum;
18873 else if (getLangOpts().CPlusPlus)
18874 DiagID = diag::err_forward_ref_enum;
18875 Diag(Loc, DiagID);
18876 }
18877 }
18878
18879 if (EnumUnderlying) {
18881 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18883 else
18884 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18885 QualType EnumTy = ED->getIntegerType();
18886 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18887 ? Context.getPromotedIntegerType(EnumTy)
18888 : EnumTy);
18889 assert(ED->isComplete() && "enum with type should be complete");
18890 }
18891 } else {
18892 // struct/union/class
18893
18894 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18895 // struct X { int A; } D; D should chain to X.
18896 if (getLangOpts().CPlusPlus) {
18897 // FIXME: Look for a way to use RecordDecl for simple structs.
18898 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18899 cast_or_null<CXXRecordDecl>(PrevDecl));
18900
18901 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18903 } else
18904 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18905 cast_or_null<RecordDecl>(PrevDecl));
18906 }
18907
18908 // Only C23 and later allow defining new types in 'offsetof()'.
18909 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18911 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18912 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18913
18914 // C++11 [dcl.type]p3:
18915 // A type-specifier-seq shall not define a class or enumeration [...].
18916 if (!Invalid && getLangOpts().CPlusPlus &&
18917 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18918 TUK == TagUseKind::Definition) {
18919 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18920 << Context.getCanonicalTagType(New);
18921 Invalid = true;
18922 }
18923
18925 DC->getDeclKind() == Decl::Enum) {
18926 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18927 << Context.getCanonicalTagType(New);
18928 Invalid = true;
18929 }
18930
18931 // Maybe add qualifier info.
18932 if (SS.isNotEmpty()) {
18933 if (SS.isSet()) {
18934 // If this is either a declaration or a definition, check the
18935 // nested-name-specifier against the current context.
18936 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18937 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18938 /*TemplateId=*/nullptr,
18939 isMemberSpecialization))
18940 Invalid = true;
18941
18942 New->setQualifierInfo(SS.getWithLocInContext(Context));
18943 if (TemplateParameterLists.size() > 0) {
18944 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18945 }
18946 }
18947 else
18948 Invalid = true;
18949 }
18950
18951 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18952 // Add alignment attributes if necessary; these attributes are checked when
18953 // the ASTContext lays out the structure.
18954 //
18955 // It is important for implementing the correct semantics that this
18956 // happen here (in ActOnTag). The #pragma pack stack is
18957 // maintained as a result of parser callbacks which can occur at
18958 // many points during the parsing of a struct declaration (because
18959 // the #pragma tokens are effectively skipped over during the
18960 // parsing of the struct).
18961 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18962 if (LangOpts.HLSL)
18963 RD->addAttr(PackedAttr::CreateImplicit(Context));
18966 }
18967 }
18968
18969 if (ModulePrivateLoc.isValid()) {
18970 if (isMemberSpecialization)
18971 Diag(New->getLocation(), diag::err_module_private_specialization)
18972 << 2
18973 << FixItHint::CreateRemoval(ModulePrivateLoc);
18974 // __module_private__ does not apply to local classes. However, we only
18975 // diagnose this as an error when the declaration specifiers are
18976 // freestanding. Here, we just ignore the __module_private__.
18977 else if (!SearchDC->isFunctionOrMethod())
18978 New->setModulePrivate();
18979 }
18980
18981 // If this is a specialization of a member class (of a class template),
18982 // check the specialization.
18983 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18984 Invalid = true;
18985
18986 // If we're declaring or defining a tag in function prototype scope in C,
18987 // note that this type can only be used within the function and add it to
18988 // the list of decls to inject into the function definition scope. However,
18989 // in C23 and later, while the type is only visible within the function, the
18990 // function can be called with a compatible type defined in the same TU, so
18991 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18992 if ((Name || Kind == TagTypeKind::Enum) &&
18993 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18994 if (getLangOpts().CPlusPlus) {
18995 // C++ [dcl.fct]p6:
18996 // Types shall not be defined in return or parameter types.
18997 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18998 Diag(Loc, diag::err_type_defined_in_param_type)
18999 << Name;
19000 Invalid = true;
19001 }
19002 if (TUK == TagUseKind::Declaration)
19003 Invalid = true;
19004 } else if (!PrevDecl) {
19005 // In C23 mode, if the declaration is complete, we do not want to
19006 // diagnose.
19007 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19008 Diag(Loc, diag::warn_decl_in_param_list)
19009 << Context.getCanonicalTagType(New);
19010 }
19011 }
19012
19013 if (Invalid)
19014 New->setInvalidDecl();
19015
19016 // Set the lexical context. If the tag has a C++ scope specifier, the
19017 // lexical context will be different from the semantic context.
19018 New->setLexicalDeclContext(CurContext);
19019
19020 // Mark this as a friend decl if applicable.
19021 // In Microsoft mode, a friend declaration also acts as a forward
19022 // declaration so we always pass true to setObjectOfFriendDecl to make
19023 // the tag name visible.
19024 if (TUK == TagUseKind::Friend)
19025 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19026
19027 // Set the access specifier.
19028 if (!Invalid && SearchDC->isRecord())
19029 SetMemberAccessSpecifier(New, PrevDecl, AS);
19030
19031 if (PrevDecl)
19033
19034 if (TUK == TagUseKind::Definition) {
19035 if (!SkipBody || !SkipBody->ShouldSkip) {
19036 New->startDefinition();
19037 } else {
19038 New->setCompleteDefinition();
19039 New->demoteThisDefinitionToDeclaration();
19040 }
19041 }
19042
19043 ProcessDeclAttributeList(S, New, Attrs);
19045
19046 // If this has an identifier, add it to the scope stack.
19047 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19048 // We might be replacing an existing declaration in the lookup tables;
19049 // if so, borrow its access specifier.
19050 if (PrevDecl)
19051 New->setAccess(PrevDecl->getAccess());
19052
19053 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19055 if (Name) // can be null along some error paths
19056 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19057 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
19058 } else if (Name) {
19059 S = getNonFieldDeclScope(S);
19060 PushOnScopeChains(New, S, true);
19061 } else {
19062 CurContext->addDecl(New);
19063 }
19064
19065 // If this is the C FILE type, notify the AST context.
19066 if (IdentifierInfo *II = New->getIdentifier())
19067 if (!New->isInvalidDecl() &&
19068 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19069 II->isStr("FILE"))
19070 Context.setFILEDecl(New);
19071
19072 if (PrevDecl)
19073 mergeDeclAttributes(New, PrevDecl);
19074
19075 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
19078 }
19079
19080 // If there's a #pragma GCC visibility in scope, set the visibility of this
19081 // record.
19083
19084 // If this is not a definition, process API notes for it now.
19085 if (TUK != TagUseKind::Definition)
19087
19088 if (isMemberSpecialization && !New->isInvalidDecl())
19090
19091 OwnedDecl = true;
19092 // In C++, don't return an invalid declaration. We can't recover well from
19093 // the cases where we make the type anonymous.
19094 if (Invalid && getLangOpts().CPlusPlus) {
19095 if (New->isBeingDefined())
19096 if (auto RD = dyn_cast<RecordDecl>(New))
19097 RD->completeDefinition();
19098 return true;
19099 } else if (SkipBody && SkipBody->ShouldSkip) {
19100 return SkipBody->Previous;
19101 } else {
19102 return New;
19103 }
19104}
19105
19108 TagDecl *Tag = cast<TagDecl>(TagD);
19109
19110 // Enter the tag context.
19111 PushDeclContext(S, Tag);
19112
19114
19115 // If there's a #pragma GCC visibility in scope, set the visibility of this
19116 // record.
19118}
19119
19121 SkipBodyInfo &SkipBody) {
19122 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19123 return false;
19124
19125 // Make the previous decl visible.
19127 CleanupMergedEnum(S, SkipBody.New);
19128 return true;
19129}
19130
19132 SourceLocation FinalLoc,
19133 bool IsFinalSpelledSealed,
19134 bool IsAbstract,
19135 SourceLocation LBraceLoc) {
19138
19139 FieldCollector->StartClass();
19140
19141 if (!Record->getIdentifier())
19142 return;
19143
19144 if (IsAbstract)
19145 Record->markAbstract();
19146
19147 if (FinalLoc.isValid()) {
19148 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19149 IsFinalSpelledSealed
19150 ? FinalAttr::Keyword_sealed
19151 : FinalAttr::Keyword_final));
19152 }
19153
19154 // C++ [class]p2:
19155 // [...] The class-name is also inserted into the scope of the
19156 // class itself; this is known as the injected-class-name. For
19157 // purposes of access checking, the injected-class-name is treated
19158 // as if it were a public member name.
19159 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19160 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19161 Record->getLocation(), Record->getIdentifier());
19162 InjectedClassName->setImplicit();
19163 InjectedClassName->setAccess(AS_public);
19164 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19165 InjectedClassName->setDescribedClassTemplate(Template);
19166
19167 PushOnScopeChains(InjectedClassName, S);
19168 assert(InjectedClassName->isInjectedClassName() &&
19169 "Broken injected-class-name");
19170}
19171
19173 SourceRange BraceRange) {
19175 TagDecl *Tag = cast<TagDecl>(TagD);
19176 Tag->setBraceRange(BraceRange);
19177
19178 // Make sure we "complete" the definition even it is invalid.
19179 if (Tag->isBeingDefined()) {
19180 assert(Tag->isInvalidDecl() && "We should already have completed it");
19181 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19182 RD->completeDefinition();
19183 }
19184
19185 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19186 FieldCollector->FinishClass();
19187 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19188 auto *Def = RD->getDefinition();
19189 assert(Def && "The record is expected to have a completed definition");
19190 unsigned NumInitMethods = 0;
19191 for (auto *Method : Def->methods()) {
19192 if (!Method->getIdentifier())
19193 continue;
19194 if (Method->getName() == "__init")
19195 NumInitMethods++;
19196 }
19197 if (NumInitMethods > 1 || !Def->hasInitMethod())
19198 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19199 }
19200
19201 // If we're defining a dynamic class in a module interface unit, we always
19202 // need to produce the vtable for it, even if the vtable is not used in the
19203 // current TU.
19204 //
19205 // The case where the current class is not dynamic is handled in
19206 // MarkVTableUsed.
19207 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19208 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19209 }
19210
19211 // Exit this scope of this tag's definition.
19213
19214 if (getCurLexicalContext()->isObjCContainer() &&
19215 Tag->getDeclContext()->isFileContext())
19216 Tag->setTopLevelDeclInObjCContainer();
19217
19218 // Notify the consumer that we've defined a tag.
19219 if (!Tag->isInvalidDecl())
19220 Consumer.HandleTagDeclDefinition(Tag);
19221
19222 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19223 // from XLs and instead matches the XL #pragma pack(1) behavior.
19224 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19225 AlignPackStack.hasValue()) {
19226 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19227 // Only diagnose #pragma align(packed).
19228 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19229 return;
19230 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19231 if (!RD)
19232 return;
19233 // Only warn if there is at least 1 bitfield member.
19234 if (llvm::any_of(RD->fields(),
19235 [](const FieldDecl *FD) { return FD->isBitField(); }))
19236 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19237 }
19238}
19239
19242 TagDecl *Tag = cast<TagDecl>(TagD);
19243 Tag->setInvalidDecl();
19244
19245 // Make sure we "complete" the definition even it is invalid.
19246 if (Tag->isBeingDefined()) {
19247 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19248 RD->completeDefinition();
19249 }
19250
19251 // We're undoing ActOnTagStartDefinition here, not
19252 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19253 // the FieldCollector.
19254
19256}
19257
19258// Note that FieldName may be null for anonymous bitfields.
19260 const IdentifierInfo *FieldName,
19261 QualType FieldTy, bool IsMsStruct,
19262 Expr *BitWidth) {
19263 assert(BitWidth);
19264 if (BitWidth->containsErrors())
19265 return ExprError();
19266
19267 // C99 6.7.2.1p4 - verify the field type.
19268 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19269 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19270 // Handle incomplete and sizeless types with a specific error.
19271 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19272 diag::err_field_incomplete_or_sizeless))
19273 return ExprError();
19274 if (FieldName)
19275 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19276 << FieldName << FieldTy << BitWidth->getSourceRange();
19277 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19278 << FieldTy << BitWidth->getSourceRange();
19280 return ExprError();
19281
19282 // If the bit-width is type- or value-dependent, don't try to check
19283 // it now.
19284 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19285 return BitWidth;
19286
19287 llvm::APSInt Value;
19288 ExprResult ICE =
19290 if (ICE.isInvalid())
19291 return ICE;
19292 BitWidth = ICE.get();
19293
19294 // Zero-width bitfield is ok for anonymous field.
19295 if (Value == 0 && FieldName)
19296 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19297 << FieldName << BitWidth->getSourceRange();
19298
19299 if (Value.isSigned() && Value.isNegative()) {
19300 if (FieldName)
19301 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19302 << FieldName << toString(Value, 10);
19303 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19304 << toString(Value, 10);
19305 }
19306
19307 // The size of the bit-field must not exceed our maximum permitted object
19308 // size.
19309 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19310 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19311 << !FieldName << FieldName << toString(Value, 10);
19312 }
19313
19314 if (!FieldTy->isDependentType()) {
19315 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19316 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19317 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19318
19319 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19320 // ABI.
19321 bool CStdConstraintViolation =
19322 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19323 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19324 if (CStdConstraintViolation || MSBitfieldViolation) {
19325 unsigned DiagWidth =
19326 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19327 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19328 << (bool)FieldName << FieldName << toString(Value, 10)
19329 << !CStdConstraintViolation << DiagWidth;
19330 }
19331
19332 // Warn on types where the user might conceivably expect to get all
19333 // specified bits as value bits: that's all integral types other than
19334 // 'bool'.
19335 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19336 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19337 << FieldName << Value << (unsigned)TypeWidth;
19338 }
19339 }
19340
19341 if (isa<ConstantExpr>(BitWidth))
19342 return BitWidth;
19343 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19344}
19345
19347 Declarator &D, Expr *BitfieldWidth) {
19348 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19349 D, BitfieldWidth,
19350 /*InitStyle=*/ICIS_NoInit, AS_public);
19351 return Res;
19352}
19353
19355 SourceLocation DeclStart,
19356 Declarator &D, Expr *BitWidth,
19357 InClassInitStyle InitStyle,
19358 AccessSpecifier AS) {
19359 if (D.isDecompositionDeclarator()) {
19361 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19362 << Decomp.getSourceRange();
19363 return nullptr;
19364 }
19365
19366 const IdentifierInfo *II = D.getIdentifier();
19367 SourceLocation Loc = DeclStart;
19368 if (II) Loc = D.getIdentifierLoc();
19369
19371 QualType T = TInfo->getType();
19372 if (getLangOpts().CPlusPlus) {
19374
19377 D.setInvalidType();
19378 T = Context.IntTy;
19379 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19380 }
19381 }
19382
19384
19386 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19387 << getLangOpts().CPlusPlus17;
19390 diag::err_invalid_thread)
19392
19393 // Check to see if this name was declared as a member previously
19394 NamedDecl *PrevDecl = nullptr;
19395 LookupResult Previous(*this, II, Loc, LookupMemberName,
19397 LookupName(Previous, S);
19398 switch (Previous.getResultKind()) {
19401 PrevDecl = Previous.getAsSingle<NamedDecl>();
19402 break;
19403
19405 PrevDecl = Previous.getRepresentativeDecl();
19406 break;
19407
19411 break;
19412 }
19413 Previous.suppressDiagnostics();
19414
19415 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19416 // Maybe we will complain about the shadowed template parameter.
19418 // Just pretend that we didn't see the previous declaration.
19419 PrevDecl = nullptr;
19420 }
19421
19422 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19423 PrevDecl = nullptr;
19424
19425 bool Mutable
19426 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19427 SourceLocation TSSL = D.getBeginLoc();
19428 FieldDecl *NewFD
19429 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19430 TSSL, AS, PrevDecl, &D);
19431
19432 if (NewFD->isInvalidDecl())
19433 Record->setInvalidDecl();
19434
19436 NewFD->setModulePrivate();
19437
19438 if (NewFD->isInvalidDecl() && PrevDecl) {
19439 // Don't introduce NewFD into scope; there's already something
19440 // with the same name in the same scope.
19441 } else if (II) {
19442 PushOnScopeChains(NewFD, S);
19443 } else
19444 Record->addDecl(NewFD);
19445
19446 return NewFD;
19447}
19448
19450 TypeSourceInfo *TInfo,
19452 bool Mutable, Expr *BitWidth,
19453 InClassInitStyle InitStyle,
19454 SourceLocation TSSL,
19455 AccessSpecifier AS, NamedDecl *PrevDecl,
19456 Declarator *D) {
19457 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19458 bool InvalidDecl = false;
19459 if (D) InvalidDecl = D->isInvalidType();
19460
19461 // If we receive a broken type, recover by assuming 'int' and
19462 // marking this declaration as invalid.
19463 if (T.isNull() || T->containsErrors()) {
19464 InvalidDecl = true;
19465 T = Context.IntTy;
19466 }
19467
19468 QualType EltTy = Context.getBaseElementType(T);
19469 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19470 bool isIncomplete =
19471 LangOpts.HLSL // HLSL allows sizeless builtin types
19472 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19473 : RequireCompleteSizedType(Loc, EltTy,
19474 diag::err_field_incomplete_or_sizeless);
19475 if (isIncomplete) {
19476 // Fields of incomplete type force their record to be invalid.
19477 Record->setInvalidDecl();
19478 InvalidDecl = true;
19479 } else {
19480 NamedDecl *Def;
19481 EltTy->isIncompleteType(&Def);
19482 if (Def && Def->isInvalidDecl()) {
19483 Record->setInvalidDecl();
19484 InvalidDecl = true;
19485 }
19486 }
19487 }
19488
19489 // TR 18037 does not allow fields to be declared with address space
19490 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19491 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19492 Diag(Loc, diag::err_field_with_address_space);
19493 Record->setInvalidDecl();
19494 InvalidDecl = true;
19495 }
19496
19497 if (LangOpts.OpenCL) {
19498 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19499 // used as structure or union field: image, sampler, event or block types.
19500 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19501 T->isBlockPointerType()) {
19502 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19503 Record->setInvalidDecl();
19504 InvalidDecl = true;
19505 }
19506 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19507 // is enabled.
19508 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19509 "__cl_clang_bitfields", LangOpts)) {
19510 Diag(Loc, diag::err_opencl_bitfields);
19511 InvalidDecl = true;
19512 }
19513 }
19514
19515 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19516 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19517 T.hasQualifiers()) {
19518 InvalidDecl = true;
19519 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19520 }
19521
19522 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19523 // than a variably modified type.
19524 if (!InvalidDecl && T->isVariablyModifiedType()) {
19526 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19527 InvalidDecl = true;
19528 }
19529
19530 // Fields can not have abstract class types
19531 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19532 diag::err_abstract_type_in_decl,
19534 InvalidDecl = true;
19535
19536 if (InvalidDecl)
19537 BitWidth = nullptr;
19538 // If this is declared as a bit-field, check the bit-field.
19539 if (BitWidth) {
19540 BitWidth =
19541 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19542 if (!BitWidth) {
19543 InvalidDecl = true;
19544 BitWidth = nullptr;
19545 }
19546 }
19547
19548 // Check that 'mutable' is consistent with the type of the declaration.
19549 if (!InvalidDecl && Mutable) {
19550 unsigned DiagID = 0;
19551 if (T->isReferenceType())
19552 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19553 : diag::err_mutable_reference;
19554 else if (T.isConstQualified())
19555 DiagID = diag::err_mutable_const;
19556
19557 if (DiagID) {
19558 SourceLocation ErrLoc = Loc;
19559 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19560 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19561 Diag(ErrLoc, DiagID);
19562 if (DiagID != diag::ext_mutable_reference) {
19563 Mutable = false;
19564 InvalidDecl = true;
19565 }
19566 }
19567 }
19568
19569 // C++11 [class.union]p8 (DR1460):
19570 // At most one variant member of a union may have a
19571 // brace-or-equal-initializer.
19572 if (InitStyle != ICIS_NoInit)
19574
19575 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19576 BitWidth, Mutable, InitStyle);
19577 if (InvalidDecl)
19578 NewFD->setInvalidDecl();
19579
19580 if (!InvalidDecl)
19582
19583 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19584 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19585 Diag(Loc, diag::err_duplicate_member) << II;
19586 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19587 NewFD->setInvalidDecl();
19588 }
19589
19590 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19591 if (Record->isUnion()) {
19592 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19593 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19594
19595 // C++ [class.union]p1: An object of a class with a non-trivial
19596 // constructor, a non-trivial copy constructor, a non-trivial
19597 // destructor, or a non-trivial copy assignment operator
19598 // cannot be a member of a union, nor can an array of such
19599 // objects.
19600 if (CheckNontrivialField(NewFD))
19601 NewFD->setInvalidDecl();
19602 }
19603
19604 // C++ [class.union]p1: If a union contains a member of reference type,
19605 // the program is ill-formed, except when compiling with MSVC extensions
19606 // enabled.
19607 if (EltTy->isReferenceType()) {
19608 const bool HaveMSExt =
19609 getLangOpts().MicrosoftExt &&
19611
19612 Diag(NewFD->getLocation(),
19613 HaveMSExt ? diag::ext_union_member_of_reference_type
19614 : diag::err_union_member_of_reference_type)
19615 << NewFD->getDeclName() << EltTy;
19616 if (!HaveMSExt)
19617 NewFD->setInvalidDecl();
19618 }
19619 }
19620 }
19621
19622 // FIXME: We need to pass in the attributes given an AST
19623 // representation, not a parser representation.
19624 if (D) {
19625 // FIXME: The current scope is almost... but not entirely... correct here.
19626 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19627
19628 if (NewFD->hasAttrs())
19630 }
19631
19632 // In auto-retain/release, infer strong retension for fields of
19633 // retainable type.
19634 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19635 NewFD->setInvalidDecl();
19636
19637 if (T.isObjCGCWeak())
19638 Diag(Loc, diag::warn_attribute_weak_on_field);
19639
19640 // PPC MMA non-pointer types are not allowed as field types.
19641 if (Context.getTargetInfo().getTriple().isPPC64() &&
19642 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19643 NewFD->setInvalidDecl();
19644
19645 NewFD->setAccess(AS);
19646 return NewFD;
19647}
19648
19650 assert(FD);
19651 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19652
19653 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19654 return false;
19655
19656 QualType EltTy = Context.getBaseElementType(FD->getType());
19657 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19658 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19659 // We check for copy constructors before constructors
19660 // because otherwise we'll never get complaints about
19661 // copy constructors.
19662
19664 // We're required to check for any non-trivial constructors. Since the
19665 // implicit default constructor is suppressed if there are any
19666 // user-declared constructors, we just need to check that there is a
19667 // trivial default constructor and a trivial copy constructor. (We don't
19668 // worry about move constructors here, since this is a C++98 check.)
19669 if (RDecl->hasNonTrivialCopyConstructor())
19671 else if (!RDecl->hasTrivialDefaultConstructor())
19673 else if (RDecl->hasNonTrivialCopyAssignment())
19675 else if (RDecl->hasNonTrivialDestructor())
19677
19678 if (member != CXXSpecialMemberKind::Invalid) {
19679 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19680 RDecl->hasObjectMember()) {
19681 // Objective-C++ ARC: it is an error to have a non-trivial field of
19682 // a union. However, system headers in Objective-C programs
19683 // occasionally have Objective-C lifetime objects within unions,
19684 // and rather than cause the program to fail, we make those
19685 // members unavailable.
19686 SourceLocation Loc = FD->getLocation();
19687 if (getSourceManager().isInSystemHeader(Loc)) {
19688 if (!FD->hasAttr<UnavailableAttr>())
19689 FD->addAttr(UnavailableAttr::CreateImplicit(
19690 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19691 return false;
19692 }
19693 }
19694
19695 Diag(FD->getLocation(),
19697 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19698 : diag::err_illegal_union_or_anon_struct_member)
19699 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19700 DiagnoseNontrivial(RDecl, member);
19701 return !getLangOpts().CPlusPlus11;
19702 }
19703 }
19704
19705 return false;
19706}
19707
19709 SmallVectorImpl<Decl *> &AllIvarDecls) {
19710 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19711 return;
19712
19713 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19714 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19715
19716 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19717 return;
19718 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19719 if (!ID) {
19720 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19721 if (!CD->IsClassExtension())
19722 return;
19723 }
19724 // No need to add this to end of @implementation.
19725 else
19726 return;
19727 }
19728 // All conditions are met. Add a new bitfield to the tail end of ivars.
19729 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19730 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19731 Expr *BitWidth =
19732 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19733
19734 Ivar = ObjCIvarDecl::Create(
19735 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19736 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19737 ObjCIvarDecl::Private, BitWidth, true);
19738 AllIvarDecls.push_back(Ivar);
19739}
19740
19741/// [class.dtor]p4:
19742/// At the end of the definition of a class, overload resolution is
19743/// performed among the prospective destructors declared in that class with
19744/// an empty argument list to select the destructor for the class, also
19745/// known as the selected destructor.
19746///
19747/// We do the overload resolution here, then mark the selected constructor in the AST.
19748/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19750 if (!Record->hasUserDeclaredDestructor()) {
19751 return;
19752 }
19753
19754 SourceLocation Loc = Record->getLocation();
19756
19757 for (auto *Decl : Record->decls()) {
19758 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19759 if (DD->isInvalidDecl())
19760 continue;
19761 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19762 OCS);
19763 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19764 }
19765 }
19766
19767 if (OCS.empty()) {
19768 return;
19769 }
19771 unsigned Msg = 0;
19772 OverloadCandidateDisplayKind DisplayKind;
19773
19774 switch (OCS.BestViableFunction(S, Loc, Best)) {
19775 case OR_Success:
19776 case OR_Deleted:
19777 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19778 break;
19779
19780 case OR_Ambiguous:
19781 Msg = diag::err_ambiguous_destructor;
19782 DisplayKind = OCD_AmbiguousCandidates;
19783 break;
19784
19786 Msg = diag::err_no_viable_destructor;
19787 DisplayKind = OCD_AllCandidates;
19788 break;
19789 }
19790
19791 if (Msg) {
19792 // OpenCL have got their own thing going with destructors. It's slightly broken,
19793 // but we allow it.
19794 if (!S.LangOpts.OpenCL) {
19795 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19796 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19797 Record->setInvalidDecl();
19798 }
19799 // It's a bit hacky: At this point we've raised an error but we want the
19800 // rest of the compiler to continue somehow working. However almost
19801 // everything we'll try to do with the class will depend on there being a
19802 // destructor. So let's pretend the first one is selected and hope for the
19803 // best.
19804 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19805 }
19806}
19807
19808/// [class.mem.special]p5
19809/// Two special member functions are of the same kind if:
19810/// - they are both default constructors,
19811/// - they are both copy or move constructors with the same first parameter
19812/// type, or
19813/// - they are both copy or move assignment operators with the same first
19814/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19816 CXXMethodDecl *M1,
19817 CXXMethodDecl *M2,
19819 // We don't want to compare templates to non-templates: See
19820 // https://github.com/llvm/llvm-project/issues/59206
19822 return bool(M1->getDescribedFunctionTemplate()) ==
19824 // FIXME: better resolve CWG
19825 // https://cplusplus.github.io/CWG/issues/2787.html
19826 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19827 M2->getNonObjectParameter(0)->getType()))
19828 return false;
19829 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19831 return false;
19832
19833 return true;
19834}
19835
19836/// [class.mem.special]p6:
19837/// An eligible special member function is a special member function for which:
19838/// - the function is not deleted,
19839/// - the associated constraints, if any, are satisfied, and
19840/// - no special member function of the same kind whose associated constraints
19841/// [CWG2595], if any, are satisfied is more constrained.
19845 SmallVector<bool, 4> SatisfactionStatus;
19846
19847 for (CXXMethodDecl *Method : Methods) {
19848 if (!Method->getTrailingRequiresClause())
19849 SatisfactionStatus.push_back(true);
19850 else {
19851 ConstraintSatisfaction Satisfaction;
19852 if (S.CheckFunctionConstraints(Method, Satisfaction))
19853 SatisfactionStatus.push_back(false);
19854 else
19855 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19856 }
19857 }
19858
19859 for (size_t i = 0; i < Methods.size(); i++) {
19860 if (!SatisfactionStatus[i])
19861 continue;
19862 CXXMethodDecl *Method = Methods[i];
19863 CXXMethodDecl *OrigMethod = Method;
19864 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19865 OrigMethod = cast<CXXMethodDecl>(MF);
19866
19868 bool AnotherMethodIsMoreConstrained = false;
19869 for (size_t j = 0; j < Methods.size(); j++) {
19870 if (i == j || !SatisfactionStatus[j])
19871 continue;
19872 CXXMethodDecl *OtherMethod = Methods[j];
19873 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19874 OtherMethod = cast<CXXMethodDecl>(MF);
19875
19876 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19877 CSM))
19878 continue;
19879
19881 if (!Other)
19882 continue;
19883 if (!Orig) {
19884 AnotherMethodIsMoreConstrained = true;
19885 break;
19886 }
19887 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19888 AnotherMethodIsMoreConstrained)) {
19889 // There was an error with the constraints comparison. Exit the loop
19890 // and don't consider this function eligible.
19891 AnotherMethodIsMoreConstrained = true;
19892 }
19893 if (AnotherMethodIsMoreConstrained)
19894 break;
19895 }
19896 // FIXME: Do not consider deleted methods as eligible after implementing
19897 // DR1734 and DR1496.
19898 if (!AnotherMethodIsMoreConstrained) {
19899 Method->setIneligibleOrNotSelected(false);
19900 Record->addedEligibleSpecialMemberFunction(Method,
19901 1 << llvm::to_underlying(CSM));
19902 }
19903 }
19904}
19905
19908 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19909 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19910 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19911 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19912 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19913
19914 for (auto *Decl : Record->decls()) {
19915 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19916 if (!MD) {
19917 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19918 if (FTD)
19919 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19920 }
19921 if (!MD)
19922 continue;
19923 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19924 if (CD->isInvalidDecl())
19925 continue;
19926 if (CD->isDefaultConstructor())
19927 DefaultConstructors.push_back(MD);
19928 else if (CD->isCopyConstructor())
19929 CopyConstructors.push_back(MD);
19930 else if (CD->isMoveConstructor())
19931 MoveConstructors.push_back(MD);
19932 } else if (MD->isCopyAssignmentOperator()) {
19933 CopyAssignmentOperators.push_back(MD);
19934 } else if (MD->isMoveAssignmentOperator()) {
19935 MoveAssignmentOperators.push_back(MD);
19936 }
19937 }
19938
19939 SetEligibleMethods(S, Record, DefaultConstructors,
19941 SetEligibleMethods(S, Record, CopyConstructors,
19943 SetEligibleMethods(S, Record, MoveConstructors,
19945 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19947 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19949}
19950
19951bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19952 // Check to see if a FieldDecl is a pointer to a function.
19953 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19954 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19955 if (!FD) {
19956 // Check whether this is a forward declaration that was inserted by
19957 // Clang. This happens when a non-forward declared / defined type is
19958 // used, e.g.:
19959 //
19960 // struct foo {
19961 // struct bar *(*f)();
19962 // struct bar *(*g)();
19963 // };
19964 //
19965 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19966 // incomplete definition.
19967 if (const auto *TD = dyn_cast<TagDecl>(D))
19968 return !TD->isCompleteDefinition();
19969 return false;
19970 }
19971 QualType FieldType = FD->getType().getDesugaredType(Context);
19972 if (isa<PointerType>(FieldType)) {
19973 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19974 return PointeeType.getDesugaredType(Context)->isFunctionType();
19975 }
19976 // If a member is a struct entirely of function pointers, that counts too.
19977 if (const auto *Record = FieldType->getAsRecordDecl();
19978 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19979 return true;
19980 return false;
19981 };
19982
19983 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19984}
19985
19986void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19987 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19988 SourceLocation RBrac,
19989 const ParsedAttributesView &Attrs) {
19990 assert(EnclosingDecl && "missing record or interface decl");
19991
19992 // If this is an Objective-C @implementation or category and we have
19993 // new fields here we should reset the layout of the interface since
19994 // it will now change.
19995 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19996 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19997 switch (DC->getKind()) {
19998 default: break;
19999 case Decl::ObjCCategory:
20000 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
20001 break;
20002 case Decl::ObjCImplementation:
20003 Context.
20004 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
20005 break;
20006 }
20007 }
20008
20009 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
20010 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
20011
20012 // Start counting up the number of named members; make sure to include
20013 // members of anonymous structs and unions in the total.
20014 unsigned NumNamedMembers = 0;
20015 if (Record) {
20016 for (const auto *I : Record->decls()) {
20017 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
20018 if (IFD->getDeclName())
20019 ++NumNamedMembers;
20020 }
20021 }
20022
20023 // Verify that all the fields are okay.
20025 const FieldDecl *PreviousField = nullptr;
20026 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20027 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
20028 FieldDecl *FD = cast<FieldDecl>(*i);
20029
20030 // Get the type for the field.
20031 const Type *FDTy = FD->getType().getTypePtr();
20032
20033 if (!FD->isAnonymousStructOrUnion()) {
20034 // Remember all fields written by the user.
20035 RecFields.push_back(FD);
20036 }
20037
20038 // If the field is already invalid for some reason, don't emit more
20039 // diagnostics about it.
20040 if (FD->isInvalidDecl()) {
20041 EnclosingDecl->setInvalidDecl();
20042 continue;
20043 }
20044
20045 // C99 6.7.2.1p2:
20046 // A structure or union shall not contain a member with
20047 // incomplete or function type (hence, a structure shall not
20048 // contain an instance of itself, but may contain a pointer to
20049 // an instance of itself), except that the last member of a
20050 // structure with more than one named member may have incomplete
20051 // array type; such a structure (and any union containing,
20052 // possibly recursively, a member that is such a structure)
20053 // shall not be a member of a structure or an element of an
20054 // array.
20055 bool IsLastField = (i + 1 == Fields.end());
20056 if (FDTy->isFunctionType()) {
20057 // Field declared as a function.
20058 Diag(FD->getLocation(), diag::err_field_declared_as_function)
20059 << FD->getDeclName();
20060 FD->setInvalidDecl();
20061 EnclosingDecl->setInvalidDecl();
20062 continue;
20063 } else if (FDTy->isIncompleteArrayType() &&
20064 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
20065 if (Record) {
20066 // Flexible array member.
20067 // Microsoft and g++ is more permissive regarding flexible array.
20068 // It will accept flexible array in union and also
20069 // as the sole element of a struct/class.
20070 unsigned DiagID = 0;
20071 if (!Record->isUnion() && !IsLastField) {
20072 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
20073 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20074 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
20075 FD->setInvalidDecl();
20076 EnclosingDecl->setInvalidDecl();
20077 continue;
20078 } else if (Record->isUnion())
20079 DiagID = getLangOpts().MicrosoftExt
20080 ? diag::ext_flexible_array_union_ms
20081 : diag::ext_flexible_array_union_gnu;
20082 else if (NumNamedMembers < 1)
20083 DiagID = getLangOpts().MicrosoftExt
20084 ? diag::ext_flexible_array_empty_aggregate_ms
20085 : diag::ext_flexible_array_empty_aggregate_gnu;
20086
20087 if (DiagID)
20088 Diag(FD->getLocation(), DiagID)
20089 << FD->getDeclName() << Record->getTagKind();
20090 // While the layout of types that contain virtual bases is not specified
20091 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20092 // virtual bases after the derived members. This would make a flexible
20093 // array member declared at the end of an object not adjacent to the end
20094 // of the type.
20095 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20096 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
20097 << FD->getDeclName() << Record->getTagKind();
20098 if (!getLangOpts().C99)
20099 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
20100 << FD->getDeclName() << Record->getTagKind();
20101
20102 // If the element type has a non-trivial destructor, we would not
20103 // implicitly destroy the elements, so disallow it for now.
20104 //
20105 // FIXME: GCC allows this. We should probably either implicitly delete
20106 // the destructor of the containing class, or just allow this.
20107 QualType BaseElem = Context.getBaseElementType(FD->getType());
20108 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20109 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
20110 << FD->getDeclName() << FD->getType();
20111 FD->setInvalidDecl();
20112 EnclosingDecl->setInvalidDecl();
20113 continue;
20114 }
20115 // Okay, we have a legal flexible array member at the end of the struct.
20116 Record->setHasFlexibleArrayMember(true);
20117 } else {
20118 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20119 // unless they are followed by another ivar. That check is done
20120 // elsewhere, after synthesized ivars are known.
20121 }
20122 } else if (!FDTy->isDependentType() &&
20123 (LangOpts.HLSL // HLSL allows sizeless builtin types
20125 diag::err_incomplete_type)
20127 FD->getLocation(), FD->getType(),
20128 diag::err_field_incomplete_or_sizeless))) {
20129 // Incomplete type
20130 FD->setInvalidDecl();
20131 EnclosingDecl->setInvalidDecl();
20132 continue;
20133 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20134 if (Record && RD->hasFlexibleArrayMember()) {
20135 // A type which contains a flexible array member is considered to be a
20136 // flexible array member.
20137 Record->setHasFlexibleArrayMember(true);
20138 if (!Record->isUnion()) {
20139 // If this is a struct/class and this is not the last element, reject
20140 // it. Note that GCC supports variable sized arrays in the middle of
20141 // structures.
20142 if (!IsLastField)
20143 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20144 << FD->getDeclName() << FD->getType();
20145 else {
20146 // We support flexible arrays at the end of structs in
20147 // other structs as an extension.
20148 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20149 << FD->getDeclName();
20150 }
20151 }
20152 }
20153 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20155 diag::err_abstract_type_in_decl,
20157 // Ivars can not have abstract class types
20158 FD->setInvalidDecl();
20159 }
20160 if (Record && RD->hasObjectMember())
20161 Record->setHasObjectMember(true);
20162 if (Record && RD->hasVolatileMember())
20163 Record->setHasVolatileMember(true);
20164 } else if (FDTy->isObjCObjectType()) {
20165 /// A field cannot be an Objective-c object
20166 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20168 QualType T = Context.getObjCObjectPointerType(FD->getType());
20169 FD->setType(T);
20170 } else if (Record && Record->isUnion() &&
20172 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20173 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20175 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20176 // For backward compatibility, fields of C unions declared in system
20177 // headers that have non-trivial ObjC ownership qualifications are marked
20178 // as unavailable unless the qualifier is explicit and __strong. This can
20179 // break ABI compatibility between programs compiled with ARC and MRR, but
20180 // is a better option than rejecting programs using those unions under
20181 // ARC.
20182 FD->addAttr(UnavailableAttr::CreateImplicit(
20183 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20184 FD->getLocation()));
20185 } else if (getLangOpts().ObjC &&
20186 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20187 !Record->hasObjectMember()) {
20188 if (FD->getType()->isObjCObjectPointerType() ||
20189 FD->getType().isObjCGCStrong())
20190 Record->setHasObjectMember(true);
20191 else if (Context.getAsArrayType(FD->getType())) {
20192 QualType BaseType = Context.getBaseElementType(FD->getType());
20193 if (const auto *RD = BaseType->getAsRecordDecl();
20194 RD && RD->hasObjectMember())
20195 Record->setHasObjectMember(true);
20196 else if (BaseType->isObjCObjectPointerType() ||
20197 BaseType.isObjCGCStrong())
20198 Record->setHasObjectMember(true);
20199 }
20200 }
20201
20202 if (Record && !getLangOpts().CPlusPlus &&
20203 !shouldIgnoreForRecordTriviality(FD)) {
20204 QualType FT = FD->getType();
20206 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20208 Record->isUnion())
20209 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20210 }
20213 Record->setNonTrivialToPrimitiveCopy(true);
20214 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20215 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20216 }
20217 if (FD->hasAttr<ExplicitInitAttr>())
20218 Record->setHasUninitializedExplicitInitFields(true);
20219 if (FT.isDestructedType()) {
20220 Record->setNonTrivialToPrimitiveDestroy(true);
20221 Record->setParamDestroyedInCallee(true);
20222 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20223 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20224 }
20225
20226 if (const auto *RD = FT->getAsRecordDecl()) {
20227 if (RD->getArgPassingRestrictions() ==
20229 Record->setArgPassingRestrictions(
20231 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20232 Record->setArgPassingRestrictions(
20234 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20235 Q && Q.isAddressDiscriminated()) {
20236 Record->setArgPassingRestrictions(
20238 Record->setNonTrivialToPrimitiveCopy(true);
20239 }
20240 }
20241
20242 if (Record && FD->getType().isVolatileQualified())
20243 Record->setHasVolatileMember(true);
20244 bool ReportMSBitfieldStoragePacking =
20245 Record && PreviousField &&
20246 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20247 Record->getLocation());
20248 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20249 return FD->isBitField() && !FD->getType()->isDependentType();
20250 };
20251
20252 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20253 IsNonDependentBitField(PreviousField)) {
20254 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20255 CharUnits PreviousFieldStorageSize =
20256 Context.getTypeSizeInChars(PreviousField->getType());
20257 if (FDStorageSize != PreviousFieldStorageSize) {
20258 Diag(FD->getLocation(),
20259 diag::warn_ms_bitfield_mismatched_storage_packing)
20260 << FD << FD->getType() << FDStorageSize.getQuantity()
20261 << PreviousFieldStorageSize.getQuantity();
20262 Diag(PreviousField->getLocation(),
20263 diag::note_ms_bitfield_mismatched_storage_size_previous)
20264 << PreviousField << PreviousField->getType();
20265 }
20266 }
20267 // Keep track of the number of named members.
20268 if (FD->getIdentifier())
20269 ++NumNamedMembers;
20270 }
20271
20272 // Okay, we successfully defined 'Record'.
20273 if (Record) {
20274 bool Completed = false;
20275 if (S) {
20276 Scope *Parent = S->getParent();
20277 if (Parent && Parent->isTypeAliasScope() &&
20278 Parent->isTemplateParamScope())
20279 Record->setInvalidDecl();
20280 }
20281
20282 if (CXXRecord) {
20283 if (!CXXRecord->isInvalidDecl()) {
20284 // Set access bits correctly on the directly-declared conversions.
20286 I = CXXRecord->conversion_begin(),
20287 E = CXXRecord->conversion_end(); I != E; ++I)
20288 I.setAccess((*I)->getAccess());
20289 }
20290
20291 // Add any implicitly-declared members to this class.
20293
20294 if (!CXXRecord->isDependentType()) {
20295 if (!CXXRecord->isInvalidDecl()) {
20296 // If we have virtual base classes, we may end up finding multiple
20297 // final overriders for a given virtual function. Check for this
20298 // problem now.
20299 if (CXXRecord->getNumVBases()) {
20300 CXXFinalOverriderMap FinalOverriders;
20301 CXXRecord->getFinalOverriders(FinalOverriders);
20302
20303 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20304 MEnd = FinalOverriders.end();
20305 M != MEnd; ++M) {
20306 for (OverridingMethods::iterator SO = M->second.begin(),
20307 SOEnd = M->second.end();
20308 SO != SOEnd; ++SO) {
20309 assert(SO->second.size() > 0 &&
20310 "Virtual function without overriding functions?");
20311 if (SO->second.size() == 1)
20312 continue;
20313
20314 // C++ [class.virtual]p2:
20315 // In a derived class, if a virtual member function of a base
20316 // class subobject has more than one final overrider the
20317 // program is ill-formed.
20318 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20319 << (const NamedDecl *)M->first << Record;
20320 Diag(M->first->getLocation(),
20321 diag::note_overridden_virtual_function);
20323 OM = SO->second.begin(),
20324 OMEnd = SO->second.end();
20325 OM != OMEnd; ++OM)
20326 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20327 << (const NamedDecl *)M->first << OM->Method->getParent();
20328
20329 Record->setInvalidDecl();
20330 }
20331 }
20332 CXXRecord->completeDefinition(&FinalOverriders);
20333 Completed = true;
20334 }
20335 }
20336 ComputeSelectedDestructor(*this, CXXRecord);
20338 }
20339 }
20340
20341 if (!Completed)
20342 Record->completeDefinition();
20343
20344 // Handle attributes before checking the layout.
20346
20347 // Maybe randomize the record's decls. We automatically randomize a record
20348 // of function pointers, unless it has the "no_randomize_layout" attribute.
20349 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20350 !Record->isRandomized() && !Record->isUnion() &&
20351 (Record->hasAttr<RandomizeLayoutAttr>() ||
20352 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20353 EntirelyFunctionPointers(Record)))) {
20354 SmallVector<Decl *, 32> NewDeclOrdering;
20356 NewDeclOrdering))
20357 Record->reorderDecls(NewDeclOrdering);
20358 }
20359
20360 // We may have deferred checking for a deleted destructor. Check now.
20361 if (CXXRecord) {
20362 auto *Dtor = CXXRecord->getDestructor();
20363 if (Dtor && Dtor->isImplicit() &&
20365 CXXRecord->setImplicitDestructorIsDeleted();
20366 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20367 }
20368 }
20369
20370 if (Record->hasAttrs()) {
20372
20373 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20375 IA->getRange(), IA->getBestCase(),
20376 IA->getInheritanceModel());
20377 }
20378
20379 // Check if the structure/union declaration is a type that can have zero
20380 // size in C. For C this is a language extension, for C++ it may cause
20381 // compatibility problems.
20382 bool CheckForZeroSize;
20383 if (!getLangOpts().CPlusPlus) {
20384 CheckForZeroSize = true;
20385 } else {
20386 // For C++ filter out types that cannot be referenced in C code.
20388 CheckForZeroSize =
20389 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20390 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20391 CXXRecord->isCLike();
20392 }
20393 if (CheckForZeroSize) {
20394 bool ZeroSize = true;
20395 bool IsEmpty = true;
20396 unsigned NonBitFields = 0;
20397 for (RecordDecl::field_iterator I = Record->field_begin(),
20398 E = Record->field_end();
20399 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20400 IsEmpty = false;
20401 if (I->isUnnamedBitField()) {
20402 if (!I->isZeroLengthBitField())
20403 ZeroSize = false;
20404 } else {
20405 ++NonBitFields;
20406 QualType FieldType = I->getType();
20407 if (FieldType->isIncompleteType() ||
20408 !Context.getTypeSizeInChars(FieldType).isZero())
20409 ZeroSize = false;
20410 }
20411 }
20412
20413 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20414 // allowed in C++, but warn if its declaration is inside
20415 // extern "C" block.
20416 if (ZeroSize) {
20417 Diag(RecLoc, getLangOpts().CPlusPlus ?
20418 diag::warn_zero_size_struct_union_in_extern_c :
20419 diag::warn_zero_size_struct_union_compat)
20420 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20421 }
20422
20423 // Structs without named members are extension in C (C99 6.7.2.1p7),
20424 // but are accepted by GCC. In C2y, this became implementation-defined
20425 // (C2y 6.7.3.2p10).
20426 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20427 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20428 : diag::ext_no_named_members_in_struct_union)
20429 << Record->isUnion();
20430 }
20431 }
20432 } else {
20433 ObjCIvarDecl **ClsFields =
20434 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20435 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20436 ID->setEndOfDefinitionLoc(RBrac);
20437 // Add ivar's to class's DeclContext.
20438 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20439 ClsFields[i]->setLexicalDeclContext(ID);
20440 ID->addDecl(ClsFields[i]);
20441 }
20442 // Must enforce the rule that ivars in the base classes may not be
20443 // duplicates.
20444 if (ID->getSuperClass())
20445 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20446 } else if (ObjCImplementationDecl *IMPDecl =
20447 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20448 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20449 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20450 // Ivar declared in @implementation never belongs to the implementation.
20451 // Only it is in implementation's lexical context.
20452 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20453 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20454 RBrac);
20455 IMPDecl->setIvarLBraceLoc(LBrac);
20456 IMPDecl->setIvarRBraceLoc(RBrac);
20457 } else if (ObjCCategoryDecl *CDecl =
20458 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20459 // case of ivars in class extension; all other cases have been
20460 // reported as errors elsewhere.
20461 // FIXME. Class extension does not have a LocEnd field.
20462 // CDecl->setLocEnd(RBrac);
20463 // Add ivar's to class extension's DeclContext.
20464 // Diagnose redeclaration of private ivars.
20465 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20466 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20467 if (IDecl) {
20468 if (const ObjCIvarDecl *ClsIvar =
20469 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20470 Diag(ClsFields[i]->getLocation(),
20471 diag::err_duplicate_ivar_declaration);
20472 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20473 continue;
20474 }
20475 for (const auto *Ext : IDecl->known_extensions()) {
20476 if (const ObjCIvarDecl *ClsExtIvar
20477 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20478 Diag(ClsFields[i]->getLocation(),
20479 diag::err_duplicate_ivar_declaration);
20480 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20481 continue;
20482 }
20483 }
20484 }
20485 ClsFields[i]->setLexicalDeclContext(CDecl);
20486 CDecl->addDecl(ClsFields[i]);
20487 }
20488 CDecl->setIvarLBraceLoc(LBrac);
20489 CDecl->setIvarRBraceLoc(RBrac);
20490 }
20491 }
20494}
20495
20496// Given an integral type, return the next larger integral type
20497// (or a NULL type of no such type exists).
20499 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20500 // enum checking below.
20501 assert((T->isIntegralType(Context) ||
20502 T->isEnumeralType()) && "Integral type required!");
20503 const unsigned NumTypes = 4;
20504 QualType SignedIntegralTypes[NumTypes] = {
20505 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20506 };
20507 QualType UnsignedIntegralTypes[NumTypes] = {
20508 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20509 Context.UnsignedLongLongTy
20510 };
20511
20512 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20513 // bits but a 64-bit standard type can still represent its incremented
20514 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20515 // bit-precise type either.
20516 unsigned BitWidth = Context.getIntWidth(T);
20517 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20518 : UnsignedIntegralTypes;
20519 for (unsigned I = 0; I != NumTypes; ++I)
20520 if (Context.getTypeSize(Types[I]) > BitWidth)
20521 return Types[I];
20522
20523 return QualType();
20524}
20525
20527 EnumConstantDecl *LastEnumConst,
20528 SourceLocation IdLoc,
20529 IdentifierInfo *Id,
20530 Expr *Val) {
20531 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20532 llvm::APSInt EnumVal(IntWidth);
20533 QualType EltTy;
20534
20536 Val = nullptr;
20537
20538 if (Val)
20539 Val = DefaultLvalueConversion(Val).get();
20540
20541 if (Val) {
20542 if (Enum->isDependentType() || Val->isTypeDependent() ||
20543 Val->containsErrors())
20544 EltTy = Context.DependentTy;
20545 else {
20546 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20547 // underlying type, but do allow it in all other contexts.
20548 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20549 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20550 // constant-expression in the enumerator-definition shall be a converted
20551 // constant expression of the underlying type.
20552 EltTy = Enum->getIntegerType();
20554 Val, EltTy, EnumVal, CCEKind::Enumerator);
20555 if (Converted.isInvalid())
20556 Val = nullptr;
20557 else
20558 Val = Converted.get();
20559 } else if (!Val->isValueDependent() &&
20560 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20562 .get())) {
20563 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20564 } else {
20565 if (Enum->isComplete()) {
20566 EltTy = Enum->getIntegerType();
20567
20568 // In Obj-C and Microsoft mode, require the enumeration value to be
20569 // representable in the underlying type of the enumeration. In C++11,
20570 // we perform a non-narrowing conversion as part of converted constant
20571 // expression checking.
20572 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20573 if (Context.getTargetInfo()
20574 .getTriple()
20575 .isWindowsMSVCEnvironment()) {
20576 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20577 } else {
20578 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20579 }
20580 }
20581
20582 // Cast to the underlying type.
20583 Val = ImpCastExprToType(Val, EltTy,
20584 EltTy->isBooleanType() ? CK_IntegralToBoolean
20585 : CK_IntegralCast)
20586 .get();
20587 } else if (getLangOpts().CPlusPlus) {
20588 // C++11 [dcl.enum]p5:
20589 // If the underlying type is not fixed, the type of each enumerator
20590 // is the type of its initializing value:
20591 // - If an initializer is specified for an enumerator, the
20592 // initializing value has the same type as the expression.
20593 EltTy = Val->getType();
20594 } else {
20595 // C99 6.7.2.2p2:
20596 // The expression that defines the value of an enumeration constant
20597 // shall be an integer constant expression that has a value
20598 // representable as an int.
20599
20600 // Complain if the value is not representable in an int.
20601 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20602 Diag(IdLoc, getLangOpts().C23
20603 ? diag::warn_c17_compat_enum_value_not_int
20604 : diag::ext_c23_enum_value_not_int)
20605 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20606 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20607 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20608 // Force the type of the expression to 'int'.
20609 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20610 }
20611 EltTy = Val->getType();
20612 }
20613 }
20614 }
20615 }
20616
20617 if (!Val) {
20618 if (Enum->isDependentType())
20619 EltTy = Context.DependentTy;
20620 else if (!LastEnumConst) {
20621 // C++0x [dcl.enum]p5:
20622 // If the underlying type is not fixed, the type of each enumerator
20623 // is the type of its initializing value:
20624 // - If no initializer is specified for the first enumerator, the
20625 // initializing value has an unspecified integral type.
20626 //
20627 // GCC uses 'int' for its unspecified integral type, as does
20628 // C99 6.7.2.2p3.
20629 if (Enum->isFixed()) {
20630 EltTy = Enum->getIntegerType();
20631 }
20632 else {
20633 EltTy = Context.IntTy;
20634 }
20635 } else {
20636 // Assign the last value + 1.
20637 EnumVal = LastEnumConst->getInitVal();
20638 ++EnumVal;
20639 EltTy = LastEnumConst->getType();
20640
20641 // Check for overflow on increment.
20642 if (EnumVal < LastEnumConst->getInitVal()) {
20643 // C++0x [dcl.enum]p5:
20644 // If the underlying type is not fixed, the type of each enumerator
20645 // is the type of its initializing value:
20646 //
20647 // - Otherwise the type of the initializing value is the same as
20648 // the type of the initializing value of the preceding enumerator
20649 // unless the incremented value is not representable in that type,
20650 // in which case the type is an unspecified integral type
20651 // sufficient to contain the incremented value. If no such type
20652 // exists, the program is ill-formed.
20654 if (T.isNull() || Enum->isFixed()) {
20655 // There is no integral type larger enough to represent this
20656 // value. Complain, then allow the value to wrap around.
20657 EnumVal = LastEnumConst->getInitVal();
20658 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20659 ++EnumVal;
20660 if (Enum->isFixed())
20661 // When the underlying type is fixed, this is ill-formed.
20662 Diag(IdLoc, diag::err_enumerator_wrapped)
20663 << toString(EnumVal, 10)
20664 << EltTy;
20665 else
20666 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20667 << toString(EnumVal, 10);
20668 } else {
20669 EltTy = T;
20670 }
20671
20672 // Retrieve the last enumerator's value, extent that type to the
20673 // type that is supposed to be large enough to represent the incremented
20674 // value, then increment.
20675 EnumVal = LastEnumConst->getInitVal();
20676 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20677 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20678 ++EnumVal;
20679
20680 // If we're not in C++, diagnose the overflow of enumerator values,
20681 // which in C99 means that the enumerator value is not representable in
20682 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20683 // are representable in some larger integral type and we allow it in
20684 // older language modes as an extension.
20685 // Exclude fixed enumerators since they are diagnosed with an error for
20686 // this case.
20687 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20688 Diag(IdLoc, getLangOpts().C23
20689 ? diag::warn_c17_compat_enum_value_not_int
20690 : diag::ext_c23_enum_value_not_int)
20691 << 1 << toString(EnumVal, 10) << 1;
20692 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20693 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20694 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20695 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20696 : diag::ext_c23_enum_value_not_int)
20697 << 1 << toString(EnumVal, 10) << 1;
20698 }
20699 }
20700 }
20701
20702 if (!EltTy->isDependentType()) {
20703 // Make the enumerator value match the signedness and size of the
20704 // enumerator's type.
20705 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20706 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20707 }
20708
20709 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20710 Val, EnumVal);
20711}
20712
20714 SourceLocation IILoc) {
20715 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20717 return SkipBodyInfo();
20718
20719 // We have an anonymous enum definition. Look up the first enumerator to
20720 // determine if we should merge the definition with an existing one and
20721 // skip the body.
20722 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20724 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20725 if (!PrevECD)
20726 return SkipBodyInfo();
20727
20728 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20729 NamedDecl *Hidden;
20730 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20732 Skip.Previous = Hidden;
20733 return Skip;
20734 }
20735
20736 return SkipBodyInfo();
20737}
20738
20739Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20740 SourceLocation IdLoc, IdentifierInfo *Id,
20741 const ParsedAttributesView &Attrs,
20742 SourceLocation EqualLoc, Expr *Val,
20743 SkipBodyInfo *SkipBody) {
20744 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20745 EnumConstantDecl *LastEnumConst =
20746 cast_or_null<EnumConstantDecl>(lastEnumConst);
20747
20748 // The scope passed in may not be a decl scope. Zip up the scope tree until
20749 // we find one that is.
20750 S = getNonFieldDeclScope(S);
20751
20752 // Verify that there isn't already something declared with this name in this
20753 // scope.
20754 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20756 LookupName(R, S);
20757 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20758
20759 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20760 // Maybe we will complain about the shadowed template parameter.
20761 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20762 // Just pretend that we didn't see the previous declaration.
20763 PrevDecl = nullptr;
20764 }
20765
20766 // C++ [class.mem]p15:
20767 // If T is the name of a class, then each of the following shall have a name
20768 // different from T:
20769 // - every enumerator of every member of class T that is an unscoped
20770 // enumerated type
20771 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20773 DeclarationNameInfo(Id, IdLoc)))
20774 return nullptr;
20775
20777 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20778 if (!New)
20779 return nullptr;
20780
20781 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20782 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20783 // Check for other kinds of shadowing not already handled.
20784 CheckShadow(New, PrevDecl, R);
20785 }
20786
20787 // When in C++, we may get a TagDecl with the same name; in this case the
20788 // enum constant will 'hide' the tag.
20789 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20790 "Received TagDecl when not in C++!");
20791 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20792 if (isa<EnumConstantDecl>(PrevDecl))
20793 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20794 else
20795 Diag(IdLoc, diag::err_redefinition) << Id;
20796 notePreviousDefinition(PrevDecl, IdLoc);
20797 return nullptr;
20798 }
20799 }
20800
20801 // Process attributes.
20802 ProcessDeclAttributeList(S, New, Attrs);
20805
20806 // Register this decl in the current scope stack.
20807 New->setAccess(TheEnumDecl->getAccess());
20809
20811
20812 return New;
20813}
20814
20815// Returns true when the enum initial expression does not trigger the
20816// duplicate enum warning. A few common cases are exempted as follows:
20817// Element2 = Element1
20818// Element2 = Element1 + 1
20819// Element2 = Element1 - 1
20820// Where Element2 and Element1 are from the same enum.
20822 Expr *InitExpr = ECD->getInitExpr();
20823 if (!InitExpr)
20824 return true;
20825 InitExpr = InitExpr->IgnoreImpCasts();
20826
20827 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20828 if (!BO->isAdditiveOp())
20829 return true;
20830 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20831 if (!IL)
20832 return true;
20833 if (IL->getValue() != 1)
20834 return true;
20835
20836 InitExpr = BO->getLHS();
20837 }
20838
20839 // This checks if the elements are from the same enum.
20840 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20841 if (!DRE)
20842 return true;
20843
20844 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20845 if (!EnumConstant)
20846 return true;
20847
20849 Enum)
20850 return true;
20851
20852 return false;
20853}
20854
20855// Emits a warning when an element is implicitly set a value that
20856// a previous element has already been set to.
20858 EnumDecl *Enum, QualType EnumType) {
20859 // Avoid anonymous enums
20860 if (!Enum->getIdentifier())
20861 return;
20862
20863 // Only check for small enums.
20864 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20865 return;
20866
20867 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20868 return;
20869
20870 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20871 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20872
20873 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20874
20875 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20876 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20877
20878 // Use int64_t as a key to avoid needing special handling for map keys.
20879 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20880 llvm::APSInt Val = D->getInitVal();
20881 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20882 };
20883
20884 DuplicatesVector DupVector;
20885 ValueToVectorMap EnumMap;
20886
20887 // Populate the EnumMap with all values represented by enum constants without
20888 // an initializer.
20889 for (auto *Element : Elements) {
20890 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20891
20892 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20893 // this constant. Skip this enum since it may be ill-formed.
20894 if (!ECD) {
20895 return;
20896 }
20897
20898 // Constants with initializers are handled in the next loop.
20899 if (ECD->getInitExpr())
20900 continue;
20901
20902 // Duplicate values are handled in the next loop.
20903 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20904 }
20905
20906 if (EnumMap.size() == 0)
20907 return;
20908
20909 // Create vectors for any values that has duplicates.
20910 for (auto *Element : Elements) {
20911 // The last loop returned if any constant was null.
20913 if (!ValidDuplicateEnum(ECD, Enum))
20914 continue;
20915
20916 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20917 if (Iter == EnumMap.end())
20918 continue;
20919
20920 DeclOrVector& Entry = Iter->second;
20921 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20922 // Ensure constants are different.
20923 if (D == ECD)
20924 continue;
20925
20926 // Create new vector and push values onto it.
20927 auto Vec = std::make_unique<ECDVector>();
20928 Vec->push_back(D);
20929 Vec->push_back(ECD);
20930
20931 // Update entry to point to the duplicates vector.
20932 Entry = Vec.get();
20933
20934 // Store the vector somewhere we can consult later for quick emission of
20935 // diagnostics.
20936 DupVector.emplace_back(std::move(Vec));
20937 continue;
20938 }
20939
20940 ECDVector *Vec = cast<ECDVector *>(Entry);
20941 // Make sure constants are not added more than once.
20942 if (*Vec->begin() == ECD)
20943 continue;
20944
20945 Vec->push_back(ECD);
20946 }
20947
20948 // Emit diagnostics.
20949 for (const auto &Vec : DupVector) {
20950 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20951
20952 // Emit warning for one enum constant.
20953 auto *FirstECD = Vec->front();
20954 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20955 << FirstECD << toString(FirstECD->getInitVal(), 10)
20956 << FirstECD->getSourceRange();
20957
20958 // Emit one note for each of the remaining enum constants with
20959 // the same value.
20960 for (auto *ECD : llvm::drop_begin(*Vec))
20961 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20962 << ECD << toString(ECD->getInitVal(), 10)
20963 << ECD->getSourceRange();
20964 }
20965}
20966
20967bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20968 bool AllowMask) const {
20969 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20970 assert(ED->isCompleteDefinition() && "expected enum definition");
20971
20972 llvm::APInt FlagBits = FlagBitsCache.at(ED);
20973
20974 // A value is in a flag enum if either its bits are a subset of the enum's
20975 // flag bits (the first condition) or we are allowing masks and the same is
20976 // true of its complement (the second condition). When masks are allowed, we
20977 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20978 //
20979 // While it's true that any value could be used as a mask, the assumption is
20980 // that a mask will have all of the insignificant bits set. Anything else is
20981 // likely a logic error.
20982 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20983 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20984}
20985
20986// Emits a warning when a suspicious comparison operator is used along side
20987// binary operators in enum initializers.
20989 const EnumDecl *Enum) {
20990 bool HasBitwiseOp = false;
20991 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20992
20993 // Iterate over all the enum values, gather suspisious comparison ops and
20994 // whether any enum initialisers contain a binary operator.
20995 for (const auto *ECD : Enum->enumerators()) {
20996 const Expr *InitExpr = ECD->getInitExpr();
20997 if (!InitExpr)
20998 continue;
20999
21000 const Expr *E = InitExpr->IgnoreParenImpCasts();
21001
21002 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
21003 BinaryOperatorKind Op = BinOp->getOpcode();
21004
21005 // Check for bitwise ops (<<, >>, &, |)
21006 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21007 HasBitwiseOp = true;
21008 } else if (Op == BO_LT || Op == BO_GT) {
21009 // Check for the typo pattern (Comparison < or >)
21010 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21011 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
21012 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21013 if (IntLiteral->getValue() == 1)
21014 SuspiciousCompares.push_back(BinOp);
21015 }
21016 }
21017 }
21018 }
21019
21020 // If we found a bitwise op and some sus compares, iterate over the compares
21021 // and warn.
21022 if (HasBitwiseOp) {
21023 for (const auto *BinOp : SuspiciousCompares) {
21024 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21027 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21028
21029 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
21030 << BinOp->getOpcodeStr() << SuggestedOp;
21031
21032 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
21033 << SuggestedOp
21034 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
21035 }
21036 }
21037}
21038
21040 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21041 const ParsedAttributesView &Attrs) {
21042 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
21043 CanQualType EnumType = Context.getCanonicalTagType(Enum);
21044
21045 ProcessDeclAttributeList(S, Enum, Attrs);
21047
21048 if (Enum->isDependentType()) {
21049 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21050 EnumConstantDecl *ECD =
21051 cast_or_null<EnumConstantDecl>(Elements[i]);
21052 if (!ECD) continue;
21053
21054 ECD->setType(EnumType);
21055 }
21056
21057 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
21058 return;
21059 }
21060
21061 // Verify that all the values are okay, compute the size of the values, and
21062 // reverse the list.
21063 unsigned NumNegativeBits = 0;
21064 unsigned NumPositiveBits = 0;
21065 bool MembersRepresentableByInt =
21066 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
21067
21068 // Figure out the type that should be used for this enum.
21069 QualType BestType;
21070 unsigned BestWidth;
21071
21072 // C++0x N3000 [conv.prom]p3:
21073 // An rvalue of an unscoped enumeration type whose underlying
21074 // type is not fixed can be converted to an rvalue of the first
21075 // of the following types that can represent all the values of
21076 // the enumeration: int, unsigned int, long int, unsigned long
21077 // int, long long int, or unsigned long long int.
21078 // C99 6.4.4.3p2:
21079 // An identifier declared as an enumeration constant has type int.
21080 // The C99 rule is modified by C23.
21081 QualType BestPromotionType;
21082
21083 bool Packed = Enum->hasAttr<PackedAttr>();
21084 // -fshort-enums is the equivalent to specifying the packed attribute on all
21085 // enum definitions.
21086 if (LangOpts.ShortEnums)
21087 Packed = true;
21088
21089 // If the enum already has a type because it is fixed or dictated by the
21090 // target, promote that type instead of analyzing the enumerators.
21091 if (Enum->isComplete()) {
21092 BestType = Enum->getIntegerType();
21093 if (Context.isPromotableIntegerType(BestType))
21094 BestPromotionType = Context.getPromotedIntegerType(BestType);
21095 else
21096 BestPromotionType = BestType;
21097
21098 BestWidth = Context.getIntWidth(BestType);
21099 } else {
21100 bool EnumTooLarge = Context.computeBestEnumTypes(
21101 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21102 BestWidth = Context.getIntWidth(BestType);
21103 if (EnumTooLarge)
21104 Diag(Enum->getLocation(), diag::ext_enum_too_large);
21105 }
21106
21107 // Loop over all of the enumerator constants, changing their types to match
21108 // the type of the enum if needed.
21109 for (auto *D : Elements) {
21110 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21111 if (!ECD) continue; // Already issued a diagnostic.
21112
21113 // C99 says the enumerators have int type, but we allow, as an
21114 // extension, the enumerators to be larger than int size. If each
21115 // enumerator value fits in an int, type it as an int, otherwise type it the
21116 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21117 // that X has type 'int', not 'unsigned'.
21118
21119 // Determine whether the value fits into an int.
21120 llvm::APSInt InitVal = ECD->getInitVal();
21121
21122 // If it fits into an integer type, force it. Otherwise force it to match
21123 // the enum decl type.
21124 QualType NewTy;
21125 unsigned NewWidth;
21126 bool NewSign;
21127 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21128 MembersRepresentableByInt) {
21129 // C23 6.7.3.3.3p15:
21130 // The enumeration member type for an enumerated type without fixed
21131 // underlying type upon completion is:
21132 // - int if all the values of the enumeration are representable as an
21133 // int; or,
21134 // - the enumerated type
21135 NewTy = Context.IntTy;
21136 NewWidth = Context.getTargetInfo().getIntWidth();
21137 NewSign = true;
21138 } else if (ECD->getType() == BestType) {
21139 // Already the right type!
21140 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21141 // C++ [dcl.enum]p4: Following the closing brace of an
21142 // enum-specifier, each enumerator has the type of its
21143 // enumeration.
21144 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21145 // with fixed underlying type is the enumerated type.
21146 ECD->setType(EnumType);
21147 continue;
21148 } else {
21149 NewTy = BestType;
21150 NewWidth = BestWidth;
21151 NewSign = BestType->isSignedIntegerOrEnumerationType();
21152 }
21153
21154 // Adjust the APSInt value.
21155 InitVal = InitVal.extOrTrunc(NewWidth);
21156 InitVal.setIsSigned(NewSign);
21157 ECD->setInitVal(Context, InitVal);
21158
21159 // Adjust the Expr initializer and type.
21160 if (ECD->getInitExpr() &&
21161 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21162 ECD->setInitExpr(ImplicitCastExpr::Create(
21163 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21164 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21165 if (getLangOpts().CPlusPlus ||
21166 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21167 // C++ [dcl.enum]p4: Following the closing brace of an
21168 // enum-specifier, each enumerator has the type of its
21169 // enumeration.
21170 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21171 // with fixed underlying type is the enumerated type.
21172 ECD->setType(EnumType);
21173 else
21174 ECD->setType(NewTy);
21175 }
21176
21177 Enum->completeDefinition(BestType, BestPromotionType,
21178 NumPositiveBits, NumNegativeBits);
21179
21180 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21182
21183 if (Enum->hasAttr<FlagEnumAttr>()) {
21184 auto R = FlagBitsCache.try_emplace(Enum);
21185 llvm::APInt &FlagBits = R.first->second;
21186
21187 if (R.second) {
21188 for (auto *E : Enum->enumerators()) {
21189 const auto &EVal = E->getInitVal();
21190 // Only single-bit enumerators introduce new flag values.
21191 if (EVal.isPowerOf2())
21192 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
21193 }
21194 }
21195 }
21196
21197 if (Enum->isClosedFlag()) {
21198 for (Decl *D : Elements) {
21199 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21200 if (!ECD) continue; // Already issued a diagnostic.
21201
21202 llvm::APSInt InitVal = ECD->getInitVal();
21203 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21204 !IsValueInFlagEnum(Enum, InitVal, true))
21205 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21206 << ECD << Enum;
21207 }
21208 }
21209
21210 // Now that the enum type is defined, ensure it's not been underaligned.
21211 if (Enum->hasAttrs())
21213}
21214
21216 SourceLocation EndLoc) {
21217
21219 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21220 CurContext->addDecl(New);
21221 return New;
21222}
21223
21225 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21226 CurContext->addDecl(New);
21227 PushDeclContext(S, New);
21229 PushCompoundScope(false);
21230 return New;
21231}
21232
21234 if (Statement)
21235 D->setStmt(Statement);
21239}
21240
21242 IdentifierInfo* AliasName,
21243 SourceLocation PragmaLoc,
21244 SourceLocation NameLoc,
21245 SourceLocation AliasNameLoc) {
21246 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21248 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21250 AsmLabelAttr *Attr =
21251 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21252
21253 // If a declaration that:
21254 // 1) declares a function or a variable
21255 // 2) has external linkage
21256 // already exists, add a label attribute to it.
21257 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21258 if (isDeclExternC(PrevDecl))
21259 PrevDecl->addAttr(Attr);
21260 else
21261 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21262 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21263 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21264 } else
21265 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21266}
21267
21269 SourceLocation PragmaLoc,
21270 SourceLocation NameLoc) {
21271 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
21272
21273 if (PrevDecl) {
21274 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
21275 } else {
21276 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21277 }
21278}
21279
21281 IdentifierInfo* AliasName,
21282 SourceLocation PragmaLoc,
21283 SourceLocation NameLoc,
21284 SourceLocation AliasNameLoc) {
21285 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21287 WeakInfo W = WeakInfo(Name, NameLoc);
21288
21289 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21290 if (!PrevDecl->hasAttr<AliasAttr>())
21291 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21293 } else {
21294 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21295 }
21296}
21297
21299 bool Final) {
21300 assert(FD && "Expected non-null FunctionDecl");
21301
21302 // Templates are emitted when they're instantiated.
21303 if (FD->isDependentContext())
21305
21306 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21307 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21308 FD->hasAttr<SYCLExternalAttr>()))
21310
21311 // Check whether this function is an externally visible definition.
21312 auto IsEmittedForExternalSymbol = [this, FD]() {
21313 // We have to check the GVA linkage of the function's *definition* -- if we
21314 // only have a declaration, we don't know whether or not the function will
21315 // be emitted, because (say) the definition could include "inline".
21316 const FunctionDecl *Def = FD->getDefinition();
21317
21318 // We can't compute linkage when we skip function bodies.
21319 return Def && !Def->hasSkippedBody() &&
21321 getASTContext().GetGVALinkageForFunction(Def));
21322 };
21323
21324 if (LangOpts.OpenMPIsTargetDevice) {
21325 // In OpenMP device mode we will not emit host only functions, or functions
21326 // we don't need due to their linkage.
21327 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21328 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21329 // DevTy may be changed later by
21330 // #pragma omp declare target to(*) device_type(*).
21331 // Therefore DevTy having no value does not imply host. The emission status
21332 // will be checked again at the end of compilation unit with Final = true.
21333 if (DevTy)
21334 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21336 // If we have an explicit value for the device type, or we are in a target
21337 // declare context, we need to emit all extern and used symbols.
21338 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21339 if (IsEmittedForExternalSymbol())
21341 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21342 // we'll omit it.
21343 if (Final)
21345 } else if (LangOpts.OpenMP > 45) {
21346 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21347 // function. In 5.0, no_host was introduced which might cause a function to
21348 // be omitted.
21349 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21350 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21351 if (DevTy)
21352 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21354 }
21355
21356 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21358
21359 if (LangOpts.CUDA) {
21360 // When compiling for device, host functions are never emitted. Similarly,
21361 // when compiling for host, device and global functions are never emitted.
21362 // (Technically, we do emit a host-side stub for global functions, but this
21363 // doesn't count for our purposes here.)
21365 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21367 if (!LangOpts.CUDAIsDevice &&
21370
21371 if (IsEmittedForExternalSymbol())
21373 }
21374
21375 // Otherwise, the function is known-emitted if it's in our set of
21376 // known-emitted functions.
21378}
21379
21381 // Host-side references to a __global__ function refer to the stub, so the
21382 // function itself is never emitted and therefore should not be marked.
21383 // If we have host fn calls kernel fn calls host+device, the HD function
21384 // does not get instantiated on the host. We model this by omitting at the
21385 // call to the kernel from the callgraph. This ensures that, when compiling
21386 // for host, only HD functions actually called from the host get marked as
21387 // known-emitted.
21388 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21390}
21391
21393 bool &Visible) {
21394 Visible = hasVisibleDefinition(D, Suggested);
21395 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21396 // for declaratins which is attached to named modules.
21397 // We only did this if the current module is named module as we have better
21398 // diagnostics for declarations in global module and named modules.
21399 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21400 D->isInNamedModule())
21401 return false;
21402 // The redefinition of D in the **current** TU is allowed if D is invisible or
21403 // D is defined in the global module of other module units.
21404 return D->isInAnotherModuleUnit() || !Visible;
21405}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2210
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:82
#define SM(sm)
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:181
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:236
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:848
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:612
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const ValueDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:631
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:863
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void CheckForComparisonInEnumInitializer(SemaBase &Sema, const EnumDecl *Enum)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkModularFormatAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:869
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
IdentifierTable & Idents
Definition ASTContext.h:808
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
@ GE_Missing_type
Missing a type.
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3588
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1810
Expr * getSizeExpr() const
Definition TypeLoc.h:1830
TypeLoc getElementLoc() const
Definition TypeLoc.h:1838
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1818
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
QualType getElementType() const
Definition TypeBase.h:3833
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:106
SourceLocation getLocation() const
Definition Attr.h:99
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:622
AttributeFactory & getFactory() const
Definition ParsedAttr.h:718
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4513
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4501
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
StringRef getOpcodeStr() const
Definition Expr.h:4110
Expr * getRHS() const
Definition Expr.h:4096
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4716
bool doesNotEscape() const
Definition Decl.h:4867
This class is used for builtin types like 'int'.
Definition TypeBase.h:3229
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
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:383
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:195
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1694
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3018
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3283
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2383
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3158
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2805
bool isVirtual() const
Definition DeclCXX.h:2200
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2319
bool isConst() const
Definition DeclCXX.h:2197
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2254
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1573
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
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:615
capture_const_range captures() const
Definition DeclCXX.h:1102
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1153
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1064
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1124
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
bool isCallToStdMove() const
Definition Expr.cpp:3653
Expr * getCallee()
Definition Expr.h:3096
arg_range arguments()
Definition Expr.h:3201
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3859
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:251
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:291
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3915
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1409
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
bool isFileContext() const
Definition DeclBase.h:2197
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2607
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2159
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
bool isNamespace() const
Definition DeclBase.h:2219
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2202
bool isRecord() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
DeclContext * getNonTransparentContext()
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
ValueDecl * getDecl()
Definition Expr.h:1344
SourceLocation getBeginLoc() const
Definition Expr.h:1355
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:704
bool isModulePrivateSpecified() const
Definition DeclSpec.h:885
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
bool hasAutoTypeSpec() const
Definition DeclSpec.h:629
static const TST TST_typename
Definition DeclSpec.h:279
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:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
void ClearStorageClassSpecs()
Definition DeclSpec.h:546
bool isNoreturnSpecified() const
Definition DeclSpec.h:717
TST getTypeSpecType() const
Definition DeclSpec.h:568
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:541
SCS getStorageClassSpec() const
Definition DeclSpec.h:532
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:849
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:609
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:608
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:765
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:651
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:764
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:718
bool isExternInLinkageSpec() const
Definition DeclSpec.h:536
static const TST TST_union
Definition DeclSpec.h:275
SCS
storage-class-specifier
Definition DeclSpec.h:224
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:710
static const TST TST_int
Definition DeclSpec.h:258
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:886
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:581
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:844
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:533
ParsedAttributes & getAttributes()
Definition DeclSpec.h:929
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:680
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:652
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:711
Expr * getRepAsExpr() const
Definition DeclSpec.h:589
static const TST TST_enum
Definition DeclSpec.h:274
static const TST TST_decltype
Definition DeclSpec.h:284
static bool isDeclRep(TST T)
Definition DeclSpec.h:497
bool isInlineSpecified() const
Definition DeclSpec.h:693
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:653
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
static const TST TST_void
Definition DeclSpec.h:252
void ClearConstexprSpec()
Definition DeclSpec.h:897
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:532
static const TST TST_atomic
Definition DeclSpec.h:294
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:542
Decl * getRepAsDecl() const
Definition DeclSpec.h:585
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:655
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:705
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:892
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:616
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:848
static const TSCS TSCS_thread_local
Definition DeclSpec.h:240
static const TST TST_error
Definition DeclSpec.h:301
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:700
bool isTypeSpecOwned() const
Definition DeclSpec.h:575
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:696
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:654
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:877
bool hasExplicitSpecifier() const
Definition DeclSpec.h:707
bool hasConstexprSpecifier() const
Definition DeclSpec.h:893
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:888
static const TST TST_struct
Definition DeclSpec.h:276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1078
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1093
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:344
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:581
bool hasAttrs() const
Definition DeclBase.h:526
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:528
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:783
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1168
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:646
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:910
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1236
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1235
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:604
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2823
bool isInvalidDecl() const
Definition DeclBase.h:596
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1186
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:602
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:456
attr_range attrs() const
Definition DeclBase.h:543
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1639
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1252
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
Kind getKind() const
Definition DeclBase.h:450
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2067
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2071
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2017
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2051
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2001
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2557
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2499
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2148
Expr * getAsmLabel() const
Definition DeclSpec.h:2803
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2842
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2784
void setRedeclaration(bool Val)
Definition DeclSpec.h:2865
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2437
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2440
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2185
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2734
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2777
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2814
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2764
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2495
bool isRedeclaration() const
Definition DeclSpec.h:2866
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2787
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2169
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2184
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2838
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2167
bool hasInitializer() const
Definition DeclSpec.h:2847
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2834
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2163
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2454
bool isInvalidType() const
Definition DeclSpec.h:2815
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2183
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2427
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2850
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2155
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2588
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2431
A decomposition declaration.
Definition DeclCXX.h:4270
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, SourceLocation RSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3742
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1889
SourceRange getSourceRange() const
Definition DeclSpec.h:1937
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1935
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2544
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3467
llvm::APSInt getInitVal() const
Definition Decl.h:3487
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5716
const Expr * getInitExpr() const
Definition Decl.h:3485
Represents an enum.
Definition Decl.h:4055
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4273
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4237
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4240
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4287
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5074
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5113
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4282
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5088
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4223
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4135
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4228
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
This represents one expression.
Definition Expr.h:112
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:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3358
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4715
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4700
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4761
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5849
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
Represents a function declaration or definition.
Definition Decl.h:2029
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2729
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2225
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2512
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4185
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3713
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4178
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4173
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3278
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2350
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2741
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2720
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4004
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3742
param_iterator param_end()
Definition Decl.h:2827
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2961
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2735
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3686
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2425
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2413
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3594
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4293
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2484
void setWillHaveBody(bool V=true)
Definition Decl.h:2726
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2632
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2479
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4303
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3727
param_iterator param_begin()
Definition Decl.h:2826
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2863
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2362
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2576
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3178
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3355
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4237
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2928
bool isStatic() const
Definition Decl.h:2969
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4526
void setTrivial(bool IT)
Definition Decl.h:2414
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4124
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2506
bool isDeletedAsWritten() const
Definition Decl.h:2580
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2389
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3598
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2393
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2464
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2385
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2719
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2318
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3348
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2956
bool param_empty() const
Definition Decl.h:2825
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3203
void setRangeEnd(SourceLocation E)
Definition Decl.h:2254
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3682
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2421
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2457
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4549
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2973
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4118
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2509
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4397
void setDefaulted(bool D=true)
Definition Decl.h:2422
bool isConsteval() const
Definition Decl.h:2518
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:2902
void setBody(Stmt *B)
Definition Decl.cpp:3271
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3612
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3149
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2495
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4145
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3806
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2247
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3179
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2471
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:3226
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2939
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3668
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2725
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5342
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5374
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5896
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5206
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
unsigned getNumParams() const
Definition TypeBase.h:5684
QualType getParamType(unsigned i) const
Definition TypeBase.h:5686
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5903
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5719
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5810
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5695
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5691
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Wrapper for source info for functions.
Definition TypeLoc.h:1675
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4713
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4825
CallingConv getCC() const
Definition TypeBase.h:4772
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4791
unsigned getRegParm() const
Definition TypeBase.h:4765
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4761
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4784
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4805
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4819
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
ExtInfo getExtInfo() const
Definition TypeBase.h:4958
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3708
unsigned getRegParmType() const
Definition TypeBase.h:4945
CallingConv getCallConv() const
Definition TypeBase.h:4957
QualType getReturnType() const
Definition TypeBase.h:4942
bool getCmseNSCallAttr() const
Definition TypeBase.h:4956
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2081
Represents a C array with an unspecified size.
Definition TypeBase.h:4008
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5743
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2604
child_range children()
Definition Expr.h:5510
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
Represents the declaration of a label.
Definition Decl.h:524
bool isResolvedMSAsmLabel() const
Definition Decl.h:559
LabelStmt * getStmt() const
Definition Decl.h:548
bool isMSAsmLabel() const
Definition Decl.h:558
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2086
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool isCompatibleWithMSVC() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1432
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1376
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3036
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
Describes a module or submodule.
Definition Module.h:340
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
Module * Parent
The parent of this module.
Definition Module.h:389
bool isPrivateModule() const
Definition Module.h:448
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:882
bool isModulePartition() const
Is this a module partition.
Definition Module.h:871
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:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:423
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:479
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:429
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1873
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
bool isExternallyVisible() const
Definition Decl.h:433
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1132
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:643
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2775
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:948
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1303
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h: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
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:895
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1459
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3367
Represents a parameter to a function.
Definition Decl.h:1819
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1879
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1883
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1852
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1911
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2936
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2959
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
AttributePool & getPool() const
Definition ParsedAttr.h:944
PipeType - OpenCL20.
Definition TypeBase.h:8307
Pointer-authentication qualifiers.
Definition TypeBase.h:153
bool isAddressDiscriminated() const
Definition TypeBase.h:266
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1525
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8567
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3027
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:111
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:3093
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8615
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3077
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1449
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8562
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8610
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8546
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1325
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2792
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1509
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1514
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8429
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8436
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4796
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasConst() const
Definition TypeBase.h:458
bool hasVolatile() const
Definition TypeBase.h:468
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
bool empty() const
Definition TypeBase.h:648
Represents a struct/union/class.
Definition Decl.h:4369
field_range fields() const
Definition Decl.h:4572
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5232
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4569
field_iterator field_begin() const
Definition Decl.cpp:5275
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7515
void setMemberSpecialization()
Note that this member template is a specialization.
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5374
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3672
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3169
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3212
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:395
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:414
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:325
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:335
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:614
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
void setLookupEntity(DeclContext *E)
Definition Scope.h:400
unsigned getMSLastManglingNumber() const
Definition Scope.h:372
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
unsigned getMSCurManglingNumber() const
Definition Scope.h:378
bool decl_empty() const
Definition Scope.h:346
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:329
Scope * getDeclParent()
Definition Scope.h:321
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:605
decl_range decls() const
Definition Scope.h:342
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition Scope.cpp:106
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:473
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:406
void applyNRVO()
Definition Scope.cpp:171
Scope * getTemplateParamParent()
Definition Scope.h:318
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void DiagnoseUnguardedBuiltinUsage(FunctionDecl *FD)
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1446
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:741
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:829
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:894
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:984
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:748
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:714
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:817
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:784
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:728
void ActOnVariableDeclarator(VarDecl *VD)
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
StmtResult BuildUnresolvedSYCLKernelCallStmt(CompoundStmt *Body, Expr *LaunchIdExpr)
Builds an UnresolvedSYCLKernelCallStmt to wrap 'Body'.
Definition SemaSYCL.cpp:819
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body, Expr *LaunchIdExpr)
Builds a SYCLKernelCallStmt to wrap 'Body' and to be used as the body of 'FD'.
Definition SemaSYCL.cpp:774
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:281
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:298
ExprResult BuildSYCLKernelLaunchIdExpr(FunctionDecl *FD, QualType KernelName)
Builds an expression for the lookup of a 'sycl_kernel_launch' template with 'KernelName' as an explic...
Definition SemaSYCL.cpp:428
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:340
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:319
bool IsAlignAttr() const
Definition Sema.h:1927
Mode getAlignMode() const
Definition Sema.h:1929
A RAII object to temporarily push a declaration context.
Definition Sema.h:3538
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1390
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1402
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3764
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3774
static NameClassification Unknown()
Definition Sema.h:3744
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3748
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3792
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3780
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3754
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3786
static NameClassification UndeclaredNonType()
Definition Sema.h:3760
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3768
static NameClassification Error()
Definition Sema.h:3740
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12607
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12641
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1452
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3642
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13203
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2684
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1143
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8337
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6406
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9423
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9427
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9446
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9462
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9459
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9435
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9430
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
void ActOnPopScope(SourceLocation Loc, Scope *S)
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
void deduceOpenCLAddressSpace(VarDecl *decl)
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1537
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4814
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1853
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6598
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1477
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:940
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2084
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2078
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
@ Default
= default ;
Definition Sema.h:4217
@ Delete
deleted-function-body
Definition Sema.h:4223
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1562
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1754
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:689
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1310
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2366
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:938
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4441
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1522
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1377
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2081
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:3632
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:941
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void CheckCoroutineWrapper(FunctionDecl *FD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2077
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:774
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1214
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1759
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12305
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8455
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2475
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4652
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition Sema.h:936
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2493
void PopCompoundScope()
Definition Sema.cpp:2626
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14564
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14567
@ UPPC_Initializer
An initializer.
Definition Sema.h:14579
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14573
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14552
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14591
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14576
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14555
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14558
const LangOptions & getLangOpts() const
Definition Sema.h:934
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2587
SourceLocation CurInitSegLoc
Definition Sema.h:2120
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3649
SemaOpenACC & OpenACC()
Definition Sema.h:1527
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1309
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2265
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1308
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2702
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15660
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1487
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1854
SemaRISCV & RISCV()
Definition Sema.h:1552
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15837
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:216
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition Sema.h:1567
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2066
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7065
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2076
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1147
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:912
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4829
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1345
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2621
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
bool CheckNontrivialField(FieldDecl *FD)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7062
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15654
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3615
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2119
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9955
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1450
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1532
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1733
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3646
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14095
SourceManager & getSourceManager() const
Definition Sema.h:939
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_enum attribute.
Definition Sema.h:3589
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1855
@ NTCUK_Destruct
Definition Sema.h:4156
@ NTCUK_Init
Definition Sema.h:4155
@ NTCUK_Copy
Definition Sema.h:4157
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1852
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6859
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15609
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2642
RedeclarationKind forRedeclarationInCurContext() const
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6620
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:641
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:276
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1311
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4715
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7069
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1350
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1880
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9984
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
SemaPPC & PPC()
Definition Sema.h:1542
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:76
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1269
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3639
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3619
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8410
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
DiagnosticsEngine & Diags
Definition Sema.h:1312
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:935
FPOptions CurFPFeatures
Definition Sema.h:1306
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1109
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2075
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
@ TPC_FriendFunctionTemplate
Definition Sema.h:11737
@ TPC_ClassTemplateMember
Definition Sema.h:11735
@ TPC_FunctionTemplate
Definition Sema.h:11734
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11738
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
friend class InitializationSequence
Definition Sema.h:1592
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
Definition Sema.cpp:976
void DiagnoseUnusedDecl(const NamedDecl *ND)
void PopDeclContext()
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6636
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3608
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2248
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1851
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6330
@ AbstractReturnType
Definition Sema.h:6328
@ AbstractFieldType
Definition Sema.h:6331
@ AbstractIvarType
Definition Sema.h:6332
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8459
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6517
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1302
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition Sema.h:3585
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
SemaWasm & Wasm()
Definition Sema.h:1577
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
IdentifierResolver IdResolver
Definition Sema.h:3531
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2633
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:732
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:149
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8418
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1301
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:3887
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SemaARM & ARM()
Definition Sema.h:1457
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8755
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1951
StringRef getString() const
Definition Expr.h:1873
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:4047
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4929
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3857
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3843
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
bool isStruct() const
Definition Decl.h:3969
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4901
bool isUnion() const
Definition Decl.h:3972
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3994
TagKind getTagKind() const
Definition Decl.h:3961
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3907
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
bool isOneOf(Ts... Ks) const
Definition Token.h:105
bool isNot(tok::TokenKind K) const
Definition Token.h:111
A declaration that models statements at global scope.
Definition Decl.h:4679
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5867
void setStmt(Stmt *S)
Definition Decl.cpp:5887
Represents a declaration of a type.
Definition Decl.h:3557
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1468
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:888
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8460
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8471
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isStructureType() const
Definition Type.cpp:715
bool isDependentSizedArrayType() const
Definition TypeBase.h:8845
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
bool isFunctionReferenceType() const
Definition TypeBase.h:8800
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9279
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3117
bool isIncompleteArrayType() const
Definition TypeBase.h:8833
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9395
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8829
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9259
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8825
bool isFunctionPointerType() const
Definition TypeBase.h:8793
bool isPointerType() const
Definition TypeBase.h:8726
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isHLSLIntangibleType() const
Definition Type.cpp:5527
bool isScalarType() const
Definition TypeBase.h:9198
bool isVariableArrayType() const
Definition TypeBase.h:8837
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9214
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isImageType() const
Definition TypeBase.h:8990
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2964
bool isOpenCLSpecificType() const
Definition TypeBase.h:9026
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2507
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:9096
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2113
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2655
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2841
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9272
bool isAtomicType() const
Definition TypeBase.h:8918
bool isFunctionProtoType() const
Definition TypeBase.h:2662
bool isObjCIdType() const
Definition TypeBase.h:8938
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2865
bool isObjCObjectType() const
Definition TypeBase.h:8909
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9235
bool isEventT() const
Definition TypeBase.h:8974
bool isPointerOrReferenceType() const
Definition TypeBase.h:8730
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8722
bool isObjCObjectPointerType() const
Definition TypeBase.h:8905
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8811
bool isFloatingType() const
Definition Type.cpp:2393
bool isAnyPointerType() const
Definition TypeBase.h:8734
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2118
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9129
bool isRecordType() const
Definition TypeBase.h:8853
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5518
bool isUnionType() const
Definition Type.cpp:755
bool isReserveIDT() const
Definition TypeBase.h:8986
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5156
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3711
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5766
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3656
QualType getUnderlyingType() const
Definition Decl.h:3661
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3667
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6251
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1088
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1120
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1124
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1176
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1128
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1149
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1297
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1132
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1146
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1135
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1116
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1170
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1140
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:785
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5593
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5587
Represents a variable declaration or definition.
Definition Decl.h:932
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2773
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2132
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1549
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1593
TLSKind getTLSKind() const
Definition Decl.cpp:2149
bool hasInit() const
Definition Decl.cpp:2379
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1476
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2241
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2171
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2442
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2238
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1602
bool isCXXCondDecl() const
Definition Decl.h:1635
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:943
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:946
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:940
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2144
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1617
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1247
void assignAddressSpace(const ASTContext &Ctxt, LangAS AS)
Apply a deduced address space, if one isn't already set.
Definition Decl.cpp:2905
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2347
void setInlineSpecified()
Definition Decl.h:1582
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2735
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1365
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1179
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1575
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1183
const Expr * getInit() const
Definition Decl.h:1391
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1238
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2410
void setConstexpr(bool IC)
Definition Decl.h:1596
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:955
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:958
void setInit(Expr *I)
Definition Decl.cpp:2458
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2326
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1321
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1318
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1324
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2778
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2226
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1274
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1174
void setImplicitlyInline()
Definition Decl.h:1587
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1500
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1612
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2682
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1285
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:2742
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1381
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4065
Expr * getSizeExpr() const
Definition TypeBase.h:4079
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:676
bool isVariableCapture() const
Definition ScopeInfo.h:651
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:746
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:733
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:722
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1099
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:738
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:499
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
Expr * SYCLKernelLaunchIdExpr
An unresolved identifier lookup expression for an implicit call to a SYCL kernel launch function in a...
Definition ScopeInfo.h:255
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:887
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:918
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:884
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:951
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:899
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
constexpr bool isInitializedByPipeline(LangAS AS)
Definition HLSLRuntime.h:34
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:82
@ TST_class
Definition Specifiers.h:83
@ TST_union
Definition Specifiers.h:81
@ TST_enum
Definition Specifiers.h:80
@ TST_interface
Definition Specifiers.h:84
ImplicitTypenameContext
Definition DeclSpec.h:1984
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:63
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:272
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
@ TemplateTemplateArgument
Definition Sema.h:613
NonTrivialCUnionContext
Definition Sema.h:532
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:628
@ None
Don't merge availability attributes at all.
Definition Sema.h:630
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:642
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:639
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1084
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1082
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1080
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1076
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1074
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1072
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1066
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1078
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1068
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1070
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_protected
Definition Specifiers.h:126
@ AS_none
Definition Specifiers.h:128
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Auto
Definition Specifiers.h:257
@ SC_PrivateExtern
Definition Specifiers.h:254
@ SC_Extern
Definition Specifiers.h:252
@ SC_Register
Definition Specifiers.h:258
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:242
@ TSCS_unspecified
Definition Specifiers.h:237
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:245
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:239
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:343
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:616
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:320
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6030
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6035
@ Struct
The "struct" keyword.
Definition TypeBase.h:6032
@ Class
The "class" keyword.
Definition TypeBase.h:6041
@ Union
The "union" keyword.
Definition TypeBase.h:6038
@ Enum
The "enum" keyword.
Definition TypeBase.h:6044
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4362
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1815
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1810
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
MultiVersionKind
Definition Decl.h:2008
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_X86StdCall
Definition Specifiers.h:281
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:840
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6026
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6016
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6023
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1774
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:88
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:1521
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1672
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1496
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1455
const IdentifierInfo * Ident
Definition DeclSpec.h:1427
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1336
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1756
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1737
FunctionTypeInfo Fun
Definition DeclSpec.h:1735
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1784
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
Extra information about a function prototype.
Definition TypeBase.h:5491
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5518
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6069
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3371
An element in an Objective-C dictionary literal.
Definition ExprObjC.h:295
Expr * Value
The value of the dictionary element.
Definition ExprObjC.h:300
Expr * Key
The key for the dictionary element.
Definition ExprObjC.h:297
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
std::vector< std::string > Features
Definition TargetInfo.h:61
Describes how types, statements, expressions, and declarations should be printed.
ValueType CurrentValue
Definition Sema.h:2051
SourceLocation CurrentPragmaLocation
Definition Sema.h:2052
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * Previous
Definition Sema.h:356
NamedDecl * New
Definition Sema.h:357
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105
SourceLocation SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new",...
Definition DeclSpec.h:1108
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1099