clang 22.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"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaARM.h"
49#include "clang/Sema/SemaCUDA.h"
50#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaObjC.h"
55#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/ArrayRef.h"
62#include "llvm/ADT/STLForwardCompat.h"
63#include "llvm/ADT/ScopeExit.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/SmallString.h"
66#include "llvm/ADT/StringExtras.h"
67#include "llvm/ADT/StringRef.h"
68#include "llvm/Support/SaveAndRestore.h"
69#include "llvm/TargetParser/Triple.h"
70#include <algorithm>
71#include <cstring>
72#include <optional>
73#include <unordered_map>
74
75using namespace clang;
76using namespace sema;
77
79 if (OwnedType) {
80 Decl *Group[2] = { OwnedType, Ptr };
82 }
83
85}
86
87namespace {
88
89class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
90 public:
91 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
92 bool AllowTemplates = false,
93 bool AllowNonTemplates = true)
94 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
95 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
96 WantExpressionKeywords = false;
97 WantCXXNamedCasts = false;
98 WantRemainingKeywords = false;
99 }
100
101 bool ValidateCandidate(const TypoCorrection &candidate) override {
102 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
103 if (!AllowInvalidDecl && ND->isInvalidDecl())
104 return false;
105
106 if (getAsTypeTemplateDecl(ND))
107 return AllowTemplates;
108
109 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
110 if (!IsType)
111 return false;
112
113 if (AllowNonTemplates)
114 return true;
115
116 // An injected-class-name of a class template (specialization) is valid
117 // as a template or as a non-template.
118 if (AllowTemplates) {
119 auto *RD = dyn_cast<CXXRecordDecl>(ND);
120 if (!RD || !RD->isInjectedClassName())
121 return false;
122 RD = cast<CXXRecordDecl>(RD->getDeclContext());
123 return RD->getDescribedClassTemplate() ||
125 }
126
127 return false;
128 }
129
130 return !WantClassName && candidate.isKeyword();
131 }
132
133 std::unique_ptr<CorrectionCandidateCallback> clone() override {
134 return std::make_unique<TypeNameValidatorCCC>(*this);
135 }
136
137 private:
138 bool AllowInvalidDecl;
139 bool WantClassName;
140 bool AllowTemplates;
141 bool AllowNonTemplates;
142};
143
144} // end anonymous namespace
145
147 TypeDecl *TD, SourceLocation NameLoc) {
148 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
149 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
150 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
151 FoundRD->isInjectedClassName() &&
152 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
153 Diag(NameLoc,
155 ? diag::ext_out_of_line_qualified_id_type_names_constructor
156 : diag::err_out_of_line_qualified_id_type_names_constructor)
157 << TD->getIdentifier() << /*Type=*/1
158 << 0 /*if any keyword was present, it was 'typename'*/;
159 }
160
161 DiagnoseUseOfDecl(TD, NameLoc);
162 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
163}
164
165namespace {
166enum class UnqualifiedTypeNameLookupResult {
167 NotFound,
168 FoundNonType,
169 FoundType
170};
171} // end anonymous namespace
172
173/// Tries to perform unqualified lookup of the type decls in bases for
174/// dependent class.
175/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176/// type decl, \a FoundType if only type decls are found.
177static UnqualifiedTypeNameLookupResult
179 SourceLocation NameLoc,
180 const CXXRecordDecl *RD) {
181 if (!RD->hasDefinition())
182 return UnqualifiedTypeNameLookupResult::NotFound;
183 // Look for type decls in base classes.
184 UnqualifiedTypeNameLookupResult FoundTypeDecl =
185 UnqualifiedTypeNameLookupResult::NotFound;
186 for (const auto &Base : RD->bases()) {
187 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
188 if (BaseRD) {
189 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
190 Base.getType().getCanonicalType())) {
191 // Look for type decls in dependent base classes that have known primary
192 // templates.
193 if (!TST->isDependentType())
194 continue;
195 auto *TD = TST->getTemplateName().getAsTemplateDecl();
196 if (!TD)
197 continue;
198 if (auto *BasePrimaryTemplate =
199 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201 BaseRD = BasePrimaryTemplate;
202 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
204 CTD->findPartialSpecialization(Base.getType()))
205 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206 BaseRD = PS;
207 }
208 }
209 }
210 if (BaseRD) {
211 for (NamedDecl *ND : BaseRD->lookup(&II)) {
212 if (!isa<TypeDecl>(ND))
213 return UnqualifiedTypeNameLookupResult::FoundNonType;
214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215 }
216 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218 case UnqualifiedTypeNameLookupResult::FoundNonType:
219 return UnqualifiedTypeNameLookupResult::FoundNonType;
220 case UnqualifiedTypeNameLookupResult::FoundType:
221 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222 break;
223 case UnqualifiedTypeNameLookupResult::NotFound:
224 break;
225 }
226 }
227 }
228 }
229
230 return FoundTypeDecl;
231}
232
234 const IdentifierInfo &II,
235 SourceLocation NameLoc) {
236 // Lookup in the parent class template context, if any.
237 const CXXRecordDecl *RD = nullptr;
238 UnqualifiedTypeNameLookupResult FoundTypeDecl =
239 UnqualifiedTypeNameLookupResult::NotFound;
240 for (DeclContext *DC = S.CurContext;
241 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242 DC = DC->getParent()) {
243 // Look for type decls in dependent base classes that have known primary
244 // templates.
245 RD = dyn_cast<CXXRecordDecl>(DC);
246 if (RD && RD->getDescribedClassTemplate())
247 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248 }
249 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250 return nullptr;
251
252 // We found some types in dependent base classes. Recover as if the user
253 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
254 // allowed. We'll fully resolve the lookup during template instantiation.
255 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
256
257 ASTContext &Context = S.Context;
258 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
259 QualType T =
260 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
261
262 CXXScopeSpec SS;
263 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264
265 TypeLocBuilder Builder;
266 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267 DepTL.setNameLoc(NameLoc);
269 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271}
272
274 Scope *S, CXXScopeSpec *SS, bool isClassName,
275 bool HasTrailingDot, ParsedType ObjectTypePtr,
276 bool IsCtorOrDtorName,
277 bool WantNontrivialTypeSourceInfo,
278 bool IsClassTemplateDeductionContext,
279 ImplicitTypenameContext AllowImplicitTypename,
280 IdentifierInfo **CorrectedII) {
281 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
282 // FIXME: Consider allowing this outside C++1z mode as an extension.
283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
285 !HasTrailingDot;
286
287 // Determine where we will perform name lookup.
288 DeclContext *LookupCtx = nullptr;
289 if (ObjectTypePtr) {
290 QualType ObjectType = ObjectTypePtr.get();
291 if (ObjectType->isRecordType())
292 LookupCtx = computeDeclContext(ObjectType);
293 } else if (SS && SS->isNotEmpty()) {
294 LookupCtx = computeDeclContext(*SS, false);
295
296 if (!LookupCtx) {
297 if (isDependentScopeSpecifier(*SS)) {
298 // C++ [temp.res]p3:
299 // A qualified-id that refers to a type and in which the
300 // nested-name-specifier depends on a template-parameter (14.6.2)
301 // shall be prefixed by the keyword typename to indicate that the
302 // qualified-id denotes a type, forming an
303 // elaborated-type-specifier (7.1.5.3).
304 //
305 // We therefore do not perform any name lookup if the result would
306 // refer to a member of an unknown specialization.
307 // In C++2a, in several contexts a 'typename' is not required. Also
308 // allow this as an extension.
309 if (IsImplicitTypename) {
310 if (AllowImplicitTypename == ImplicitTypenameContext::No)
311 return nullptr;
312 SourceLocation QualifiedLoc = SS->getRange().getBegin();
313 // FIXME: Defer the diagnostic after we build the type and use it.
314 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
315 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
316 SS->getScopeRep(), &II);
318 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
319 }
320
321 // We know from the grammar that this name refers to a type,
322 // so build a dependent node to describe the type.
323 if (WantNontrivialTypeSourceInfo)
324 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
325 (ImplicitTypenameContext)IsImplicitTypename)
326 .get();
327
330 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
332 SourceLocation(), QualifierLoc, II, NameLoc);
333 return ParsedType::make(T);
334 }
335
336 return nullptr;
337 }
338
339 if (!LookupCtx->isDependentContext() &&
340 RequireCompleteDeclContext(*SS, LookupCtx))
341 return nullptr;
342 }
343
344 // In the case where we know that the identifier is a class name, we know that
345 // it is a type declaration (struct, class, union or enum) so we can use tag
346 // name lookup.
347 //
348 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
349 // the component name of the type-name or simple-template-id is type-only.
350 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
351 LookupResult Result(*this, &II, NameLoc, Kind);
352 if (LookupCtx) {
353 // Perform "qualified" name lookup into the declaration context we
354 // computed, which is either the type of the base of a member access
355 // expression or the declaration context associated with a prior
356 // nested-name-specifier.
357 LookupQualifiedName(Result, LookupCtx);
358
359 if (ObjectTypePtr && Result.empty()) {
360 // C++ [basic.lookup.classref]p3:
361 // If the unqualified-id is ~type-name, the type-name is looked up
362 // in the context of the entire postfix-expression. If the type T of
363 // the object expression is of a class type C, the type-name is also
364 // looked up in the scope of class C. At least one of the lookups shall
365 // find a name that refers to (possibly cv-qualified) T.
366 LookupName(Result, S);
367 }
368 } else {
369 // Perform unqualified name lookup.
370 LookupName(Result, S);
371
372 // For unqualified lookup in a class template in MSVC mode, look into
373 // dependent base classes where the primary class template is known.
374 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
375 if (ParsedType TypeInBase =
376 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
377 return TypeInBase;
378 }
379 }
380
381 NamedDecl *IIDecl = nullptr;
382 UsingShadowDecl *FoundUsingShadow = nullptr;
383 switch (Result.getResultKind()) {
385 if (CorrectedII) {
386 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
387 AllowDeducedTemplate);
388 TypoCorrection Correction =
389 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
391 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
393 bool MemberOfUnknownSpecialization;
395 TemplateName.setIdentifier(NewII, NameLoc);
397 CXXScopeSpec NewSS, *NewSSPtr = SS;
398 if (SS && NNS) {
399 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
400 NewSSPtr = &NewSS;
401 }
402 if (Correction && (NNS || NewII != &II) &&
403 // Ignore a correction to a template type as the to-be-corrected
404 // identifier is not a template (typo correction for template names
405 // is handled elsewhere).
406 !(getLangOpts().CPlusPlus && NewSSPtr &&
407 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
408 Template, MemberOfUnknownSpecialization))) {
409 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
410 isClassName, HasTrailingDot, ObjectTypePtr,
411 IsCtorOrDtorName,
412 WantNontrivialTypeSourceInfo,
413 IsClassTemplateDeductionContext);
414 if (Ty) {
415 diagnoseTypo(Correction,
416 PDiag(diag::err_unknown_type_or_class_name_suggest)
417 << Result.getLookupName() << isClassName);
418 if (SS && NNS)
419 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
420 *CorrectedII = NewII;
421 return Ty;
422 }
423 }
424 }
425 Result.suppressDiagnostics();
426 return nullptr;
428 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
429 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
430 SS->getScopeRep(), &II);
431 TypeLocBuilder TLB;
435 TL.setNameLoc(NameLoc);
437 }
438 [[fallthrough]];
441 Result.suppressDiagnostics();
442 return nullptr;
443
445 // Recover from type-hiding ambiguities by hiding the type. We'll
446 // do the lookup again when looking for an object, and we can
447 // diagnose the error then. If we don't do this, then the error
448 // about hiding the type will be immediately followed by an error
449 // that only makes sense if the identifier was treated like a type.
450 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
451 Result.suppressDiagnostics();
452 return nullptr;
453 }
454
455 // Look to see if we have a type anywhere in the list of results.
456 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
457 Res != ResEnd; ++Res) {
458 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
460 RealRes) ||
461 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
462 if (!IIDecl ||
463 // Make the selection of the recovery decl deterministic.
464 RealRes->getLocation() < IIDecl->getLocation()) {
465 IIDecl = RealRes;
466 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
467 }
468 }
469 }
470
471 if (!IIDecl) {
472 // None of the entities we found is a type, so there is no way
473 // to even assume that the result is a type. In this case, don't
474 // complain about the ambiguity. The parser will either try to
475 // perform this lookup again (e.g., as an object name), which
476 // will produce the ambiguity, or will complain that it expected
477 // a type name.
478 Result.suppressDiagnostics();
479 return nullptr;
480 }
481
482 // We found a type within the ambiguous lookup; diagnose the
483 // ambiguity and then return that type. This might be the right
484 // answer, or it might not be, but it suppresses any attempt to
485 // perform the name lookup again.
486 break;
487
489 IIDecl = Result.getFoundDecl();
490 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
491 break;
492 }
493
494 assert(IIDecl && "Didn't find decl");
495
496 TypeLocBuilder TLB;
497 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
498 checkTypeDeclType(LookupCtx,
499 IsImplicitTypename ? DiagCtorKind::Implicit
501 TD, NameLoc);
502 QualType T;
503 if (FoundUsingShadow) {
505 SS ? SS->getScopeRep() : std::nullopt,
506 FoundUsingShadow);
507 if (!WantNontrivialTypeSourceInfo)
508 return ParsedType::make(T);
509 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
512 NameLoc);
513 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
515 SS ? SS->getScopeRep() : std::nullopt, Tag,
516 /*OwnsTag=*/false);
517 if (!WantNontrivialTypeSourceInfo)
518 return ParsedType::make(T);
519 auto TL = TLB.push<TagTypeLoc>(T);
521 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
523 TL.setNameLoc(NameLoc);
524 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
525 TN && !isa<ObjCTypeParamDecl>(TN)) {
526 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
527 SS ? SS->getScopeRep() : std::nullopt, TN);
528 if (!WantNontrivialTypeSourceInfo)
529 return ParsedType::make(T);
530 TLB.push<TypedefTypeLoc>(T).set(
531 /*ElaboratedKeywordLoc=*/SourceLocation(),
533 NameLoc);
534 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
535 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
536 SS ? SS->getScopeRep() : std::nullopt,
537 UD);
538 if (!WantNontrivialTypeSourceInfo)
539 return ParsedType::make(T);
540 TLB.push<UnresolvedUsingTypeLoc>(T).set(
541 /*ElaboratedKeywordLoc=*/SourceLocation(),
543 NameLoc);
544 } else {
545 T = Context.getTypeDeclType(TD);
546 if (!WantNontrivialTypeSourceInfo)
547 return ParsedType::make(T);
549 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
550 else
551 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
552 }
554 }
555 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
556 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
557 if (!HasTrailingDot) {
558 // FIXME: Support UsingType for this case.
559 QualType T = Context.getObjCInterfaceType(IDecl);
560 if (!WantNontrivialTypeSourceInfo)
561 return ParsedType::make(T);
562 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
563 TL.setNameLoc(NameLoc);
564 // FIXME: Pass in this source location.
565 TL.setNameEndLoc(NameLoc);
567 }
568 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
569 (void)DiagnoseUseOfDecl(UD, NameLoc);
570 // Recover with 'int'
571 return ParsedType::make(Context.IntTy);
572 } else if (AllowDeducedTemplate) {
573 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
574 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
575 // FIXME: Support UsingType here.
576 TemplateName Template = Context.getQualifiedTemplateName(
577 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
578 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
579 QualType T = Context.getDeducedTemplateSpecializationType(
583 TL.setNameLoc(NameLoc);
584 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
587 }
588 }
589
590 // As it's not plausibly a type, suppress diagnostics.
591 Result.suppressDiagnostics();
592 return nullptr;
593}
594
595// Builds a fake NNS for the given decl context.
598 for (;; DC = DC->getLookupParent()) {
599 DC = DC->getPrimaryContext();
600 auto *ND = dyn_cast<NamespaceDecl>(DC);
601 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
602 return NestedNameSpecifier(Context, ND, std::nullopt);
603 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
604 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
607 }
608 llvm_unreachable("something isn't in TU scope?");
609}
610
611/// Find the parent class with dependent bases of the innermost enclosing method
612/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
613/// up allowing unqualified dependent type names at class-level, which MSVC
614/// correctly rejects.
615static const CXXRecordDecl *
617 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
618 DC = DC->getPrimaryContext();
619 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
620 if (MD->getParent()->hasAnyDependentBases())
621 return MD->getParent();
622 }
623 return nullptr;
624}
625
627 SourceLocation NameLoc,
628 bool IsTemplateTypeArg) {
629 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
630
631 NestedNameSpecifier NNS = std::nullopt;
632 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
633 // If we weren't able to parse a default template argument, delay lookup
634 // until instantiation time by making a non-dependent DependentTypeName. We
635 // pretend we saw a NestedNameSpecifier referring to the current scope, and
636 // lookup is retried.
637 // FIXME: This hurts our diagnostic quality, since we get errors like "no
638 // type named 'Foo' in 'current_namespace'" when the user didn't write any
639 // name specifiers.
641 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
642 } else if (const CXXRecordDecl *RD =
644 // Build a DependentNameType that will perform lookup into RD at
645 // instantiation time.
646 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
647
648 // Diagnose that this identifier was undeclared, and retry the lookup during
649 // template instantiation.
650 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
651 << RD;
652 } else {
653 // This is not a situation that we should recover from.
654 return ParsedType();
655 }
656
657 QualType T =
658 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
659
660 // Build type location information. We synthesized the qualifier, so we have
661 // to build a fake NestedNameSpecifierLoc.
662 NestedNameSpecifierLocBuilder NNSLocBuilder;
663 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
664 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
665
666 TypeLocBuilder Builder;
667 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
668 DepTL.setNameLoc(NameLoc);
670 DepTL.setQualifierLoc(QualifierLoc);
671 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
672}
673
675 // Do a tag name lookup in this scope.
676 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
677 LookupName(R, S, false);
680 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
681 switch (TD->getTagKind()) {
687 return DeclSpec::TST_union;
689 return DeclSpec::TST_class;
691 return DeclSpec::TST_enum;
692 }
693 }
694
696}
697
699 if (!CurContext->isRecord())
700 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
701
702 switch (SS->getScopeRep().getKind()) {
704 return true;
706 QualType T(SS->getScopeRep().getAsType(), 0);
707 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
708 if (Context.hasSameUnqualifiedType(T, Base.getType()))
709 return true;
710 [[fallthrough]];
711 }
712 default:
713 return S->isFunctionPrototypeScope();
714 }
715}
716
718 SourceLocation IILoc,
719 Scope *S,
720 CXXScopeSpec *SS,
721 ParsedType &SuggestedType,
722 bool IsTemplateName) {
723 // Don't report typename errors for editor placeholders.
724 if (II->isEditorPlaceholder())
725 return;
726 // We don't have anything to suggest (yet).
727 SuggestedType = nullptr;
728
729 // There may have been a typo in the name of the type. Look up typo
730 // results, in case we have something that we can suggest.
731 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
732 /*AllowTemplates=*/IsTemplateName,
733 /*AllowNonTemplates=*/!IsTemplateName);
734 if (TypoCorrection Corrected =
737 // FIXME: Support error recovery for the template-name case.
738 bool CanRecover = !IsTemplateName;
739 if (Corrected.isKeyword()) {
740 // We corrected to a keyword.
741 diagnoseTypo(Corrected,
742 PDiag(IsTemplateName ? diag::err_no_template_suggest
743 : diag::err_unknown_typename_suggest)
744 << II);
745 II = Corrected.getCorrectionAsIdentifierInfo();
746 } else {
747 // We found a similarly-named type or interface; suggest that.
748 if (!SS || !SS->isSet()) {
749 diagnoseTypo(Corrected,
750 PDiag(IsTemplateName ? diag::err_no_template_suggest
751 : diag::err_unknown_typename_suggest)
752 << II, CanRecover);
753 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
754 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
755 bool DroppedSpecifier =
756 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
757 diagnoseTypo(Corrected,
758 PDiag(IsTemplateName
759 ? diag::err_no_member_template_suggest
760 : diag::err_unknown_nested_typename_suggest)
761 << II << DC << DroppedSpecifier << SS->getRange(),
762 CanRecover);
763 } else {
764 llvm_unreachable("could not have corrected a typo here");
765 }
766
767 if (!CanRecover)
768 return;
769
770 CXXScopeSpec tmpSS;
771 if (Corrected.getCorrectionSpecifier())
772 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
773 SourceRange(IILoc));
774 // FIXME: Support class template argument deduction here.
775 SuggestedType =
776 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
777 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
778 /*IsCtorOrDtorName=*/false,
779 /*WantNontrivialTypeSourceInfo=*/true);
780 }
781 return;
782 }
783
784 if (getLangOpts().CPlusPlus && !IsTemplateName) {
785 // See if II is a class template that the user forgot to pass arguments to.
786 UnqualifiedId Name;
787 Name.setIdentifier(II, IILoc);
788 CXXScopeSpec EmptySS;
789 TemplateTy TemplateResult;
790 bool MemberOfUnknownSpecialization;
791 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
792 Name, nullptr, true, TemplateResult,
793 MemberOfUnknownSpecialization) == TNK_Type_template) {
794 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
795 return;
796 }
797 }
798
799 // FIXME: Should we move the logic that tries to recover from a missing tag
800 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
801
802 if (!SS || (!SS->isSet() && !SS->isInvalid()))
803 Diag(IILoc, IsTemplateName ? diag::err_no_template
804 : diag::err_unknown_typename)
805 << II;
806 else if (DeclContext *DC = computeDeclContext(*SS, false))
807 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
808 : diag::err_typename_nested_not_found)
809 << II << DC << SS->getRange();
810 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
811 SuggestedType =
812 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
813 } else if (isDependentScopeSpecifier(*SS)) {
814 unsigned DiagID = diag::err_typename_missing;
815 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
816 DiagID = diag::ext_typename_missing;
817
818 SuggestedType =
819 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
820
821 Diag(SS->getRange().getBegin(), DiagID)
822 << GetTypeFromParser(SuggestedType)
823 << SourceRange(SS->getRange().getBegin(), IILoc)
824 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
825 } else {
826 assert(SS && SS->isInvalid() &&
827 "Invalid scope specifier has already been diagnosed");
828 }
829}
830
831/// Determine whether the given result set contains either a type name
832/// or
833static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
834 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
835 NextToken.is(tok::less);
836
837 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
839 return true;
840
841 if (CheckTemplate && isa<TemplateDecl>(*I))
842 return true;
843 }
844
845 return false;
846}
847
848static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
849 Scope *S, CXXScopeSpec &SS,
850 IdentifierInfo *&Name,
851 SourceLocation NameLoc) {
852 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
853 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
854 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
855 StringRef FixItTagName;
856 switch (Tag->getTagKind()) {
858 FixItTagName = "class ";
859 break;
860
862 FixItTagName = "enum ";
863 break;
864
866 FixItTagName = "struct ";
867 break;
868
870 FixItTagName = "__interface ";
871 break;
872
874 FixItTagName = "union ";
875 break;
876 }
877
878 StringRef TagName = FixItTagName.drop_back();
879 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
880 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
881 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
882
883 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
884 I != IEnd; ++I)
885 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
886 << Name << TagName;
887
888 // Replace lookup results with just the tag decl.
889 Result.clear(Sema::LookupTagName);
890 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
891 return true;
892 }
893
894 return false;
895}
896
898 IdentifierInfo *&Name,
899 SourceLocation NameLoc,
900 const Token &NextToken,
902 DeclarationNameInfo NameInfo(Name, NameLoc);
903 ObjCMethodDecl *CurMethod = getCurMethodDecl();
904
905 assert(NextToken.isNot(tok::coloncolon) &&
906 "parse nested name specifiers before calling ClassifyName");
907 if (getLangOpts().CPlusPlus && SS.isSet() &&
908 isCurrentClassName(*Name, S, &SS)) {
909 // Per [class.qual]p2, this names the constructors of SS, not the
910 // injected-class-name. We don't have a classification for that.
911 // There's not much point caching this result, since the parser
912 // will reject it later.
914 }
915
916 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
917 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
918 /*AllowBuiltinCreation=*/!CurMethod);
919
920 if (SS.isInvalid())
922
923 // For unqualified lookup in a class template in MSVC mode, look into
924 // dependent base classes where the primary class template is known.
925 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
926 if (ParsedType TypeInBase =
927 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
928 return TypeInBase;
929 }
930
931 // Perform lookup for Objective-C instance variables (including automatically
932 // synthesized instance variables), if we're in an Objective-C method.
933 // FIXME: This lookup really, really needs to be folded in to the normal
934 // unqualified lookup mechanism.
935 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
936 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
937 if (Ivar.isInvalid())
939 if (Ivar.isUsable())
941
942 // We defer builtin creation until after ivar lookup inside ObjC methods.
943 if (Result.empty())
945 }
946
947 bool SecondTry = false;
948 bool IsFilteredTemplateName = false;
949
950Corrected:
951 switch (Result.getResultKind()) {
953 // If an unqualified-id is followed by a '(', then we have a function
954 // call.
955 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
956 // In C++, this is an ADL-only call.
957 // FIXME: Reference?
960
961 // C90 6.3.2.2:
962 // If the expression that precedes the parenthesized argument list in a
963 // function call consists solely of an identifier, and if no
964 // declaration is visible for this identifier, the identifier is
965 // implicitly declared exactly as if, in the innermost block containing
966 // the function call, the declaration
967 //
968 // extern int identifier ();
969 //
970 // appeared.
971 //
972 // We also allow this in C99 as an extension. However, this is not
973 // allowed in all language modes as functions without prototypes may not
974 // be supported.
975 if (getLangOpts().implicitFunctionsAllowed()) {
976 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
978 }
979 }
980
981 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
982 // In C++20 onwards, this could be an ADL-only call to a function
983 // template, and we're required to assume that this is a template name.
984 //
985 // FIXME: Find a way to still do typo correction in this case.
987 Context.getAssumedTemplateName(NameInfo.getName());
989 }
990
991 // In C, we first see whether there is a tag type by the same name, in
992 // which case it's likely that the user just forgot to write "enum",
993 // "struct", or "union".
994 if (!getLangOpts().CPlusPlus && !SecondTry &&
995 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
996 break;
997 }
998
999 // Perform typo correction to determine if there is another name that is
1000 // close to this name.
1001 if (!SecondTry && CCC) {
1002 SecondTry = true;
1003 if (TypoCorrection Corrected =
1004 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1005 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1006 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1007 unsigned QualifiedDiag = diag::err_no_member_suggest;
1008
1009 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1010 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1011 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1012 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1013 UnqualifiedDiag = diag::err_no_template_suggest;
1014 QualifiedDiag = diag::err_no_member_template_suggest;
1015 } else if (UnderlyingFirstDecl &&
1016 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1017 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1018 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1019 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1020 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1021 }
1022
1023 if (SS.isEmpty()) {
1024 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1025 } else {// FIXME: is this even reachable? Test it.
1026 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1027 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1028 Name->getName() == CorrectedStr;
1029 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1030 << Name << computeDeclContext(SS, false)
1031 << DroppedSpecifier << SS.getRange());
1032 }
1033
1034 // Update the name, so that the caller has the new name.
1035 Name = Corrected.getCorrectionAsIdentifierInfo();
1036
1037 // Typo correction corrected to a keyword.
1038 if (Corrected.isKeyword())
1039 return Name;
1040
1041 // Also update the LookupResult...
1042 // FIXME: This should probably go away at some point
1043 Result.clear();
1044 Result.setLookupName(Corrected.getCorrection());
1045 if (FirstDecl)
1046 Result.addDecl(FirstDecl);
1047
1048 // If we found an Objective-C instance variable, let
1049 // LookupInObjCMethod build the appropriate expression to
1050 // reference the ivar.
1051 // FIXME: This is a gross hack.
1052 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1053 DeclResult R =
1054 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1055 if (R.isInvalid())
1057 if (R.isUsable())
1058 return NameClassification::NonType(Ivar);
1059 }
1060
1061 goto Corrected;
1062 }
1063 }
1064
1065 // We failed to correct; just fall through and let the parser deal with it.
1066 Result.suppressDiagnostics();
1068
1070 // We performed name lookup into the current instantiation, and there were
1071 // dependent bases, so we treat this result the same way as any other
1072 // dependent nested-name-specifier.
1073
1074 // C++ [temp.res]p2:
1075 // A name used in a template declaration or definition and that is
1076 // dependent on a template-parameter is assumed not to name a type
1077 // unless the applicable name lookup finds a type name or the name is
1078 // qualified by the keyword typename.
1079 //
1080 // FIXME: If the next token is '<', we might want to ask the parser to
1081 // perform some heroics to see if we actually have a
1082 // template-argument-list, which would indicate a missing 'template'
1083 // keyword here.
1085 }
1086
1090 break;
1091
1093 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1094 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1095 /*AllowDependent=*/false)) {
1096 // C++ [temp.local]p3:
1097 // A lookup that finds an injected-class-name (10.2) can result in an
1098 // ambiguity in certain cases (for example, if it is found in more than
1099 // one base class). If all of the injected-class-names that are found
1100 // refer to specializations of the same class template, and if the name
1101 // is followed by a template-argument-list, the reference refers to the
1102 // class template itself and not a specialization thereof, and is not
1103 // ambiguous.
1104 //
1105 // This filtering can make an ambiguous result into an unambiguous one,
1106 // so try again after filtering out template names.
1108 if (!Result.isAmbiguous()) {
1109 IsFilteredTemplateName = true;
1110 break;
1111 }
1112 }
1113
1114 // Diagnose the ambiguity and return an error.
1116 }
1117
1118 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1119 (IsFilteredTemplateName ||
1121 Result, /*AllowFunctionTemplates=*/true,
1122 /*AllowDependent=*/false,
1123 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1125 // C++ [temp.names]p3:
1126 // After name lookup (3.4) finds that a name is a template-name or that
1127 // an operator-function-id or a literal- operator-id refers to a set of
1128 // overloaded functions any member of which is a function template if
1129 // this is followed by a <, the < is always taken as the delimiter of a
1130 // template-argument-list and never as the less-than operator.
1131 // C++2a [temp.names]p2:
1132 // A name is also considered to refer to a template if it is an
1133 // unqualified-id followed by a < and name lookup finds either one
1134 // or more functions or finds nothing.
1135 if (!IsFilteredTemplateName)
1137
1138 bool IsFunctionTemplate;
1139 bool IsVarTemplate;
1141 if (Result.end() - Result.begin() > 1) {
1142 IsFunctionTemplate = true;
1143 Template = Context.getOverloadedTemplateName(Result.begin(),
1144 Result.end());
1145 } else if (!Result.empty()) {
1147 *Result.begin(), /*AllowFunctionTemplates=*/true,
1148 /*AllowDependent=*/false));
1149 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1150 IsVarTemplate = isa<VarTemplateDecl>(TD);
1151
1152 UsingShadowDecl *FoundUsingShadow =
1153 dyn_cast<UsingShadowDecl>(*Result.begin());
1154 assert(!FoundUsingShadow ||
1155 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1156 Template = Context.getQualifiedTemplateName(
1157 SS.getScopeRep(),
1158 /*TemplateKeyword=*/false,
1159 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1160 } else {
1161 // All results were non-template functions. This is a function template
1162 // name.
1163 IsFunctionTemplate = true;
1164 Template = Context.getAssumedTemplateName(NameInfo.getName());
1165 }
1166
1167 if (IsFunctionTemplate) {
1168 // Function templates always go through overload resolution, at which
1169 // point we'll perform the various checks (e.g., accessibility) we need
1170 // to based on which function we selected.
1171 Result.suppressDiagnostics();
1172
1174 }
1175
1176 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1178 }
1179
1180 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1181 QualType T;
1182 TypeLocBuilder TLB;
1183 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1184 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1185 USD);
1186 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1187 SS.getWithLocInContext(Context), NameLoc);
1188 } else {
1189 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1190 Type);
1191 if (isa<TagType>(T)) {
1192 auto TTL = TLB.push<TagTypeLoc>(T);
1194 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1195 TTL.setNameLoc(NameLoc);
1196 } else if (isa<TypedefType>(T)) {
1197 TLB.push<TypedefTypeLoc>(T).set(
1198 /*ElaboratedKeywordLoc=*/SourceLocation(),
1199 SS.getWithLocInContext(Context), NameLoc);
1200 } else if (isa<UnresolvedUsingType>(T)) {
1201 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1202 /*ElaboratedKeywordLoc=*/SourceLocation(),
1203 SS.getWithLocInContext(Context), NameLoc);
1204 } else {
1205 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1206 }
1207 }
1209 };
1210
1211 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1212 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1213 DiagnoseUseOfDecl(Type, NameLoc);
1214 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1215 return BuildTypeFor(Type, *Result.begin());
1216 }
1217
1218 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1219 if (!Class) {
1220 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1221 if (ObjCCompatibleAliasDecl *Alias =
1222 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1223 Class = Alias->getClassInterface();
1224 }
1225
1226 if (Class) {
1227 DiagnoseUseOfDecl(Class, NameLoc);
1228
1229 if (NextToken.is(tok::period)) {
1230 // Interface. <something> is parsed as a property reference expression.
1231 // Just return "unknown" as a fall-through for now.
1232 Result.suppressDiagnostics();
1234 }
1235
1236 QualType T = Context.getObjCInterfaceType(Class);
1237 return ParsedType::make(T);
1238 }
1239
1241 // We want to preserve the UsingShadowDecl for concepts.
1242 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1246 }
1247
1248 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1249 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1251 }
1252
1253 // We can have a type template here if we're classifying a template argument.
1258
1259 // Check for a tag type hidden by a non-type decl in a few cases where it
1260 // seems likely a type is wanted instead of the non-type that was found.
1261 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1262 if ((NextToken.is(tok::identifier) ||
1263 (NextIsOp &&
1264 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1265 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1266 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1267 DiagnoseUseOfDecl(Type, NameLoc);
1268 return BuildTypeFor(Type, *Result.begin());
1269 }
1270
1271 // If we already know which single declaration is referenced, just annotate
1272 // that declaration directly. Defer resolving even non-overloaded class
1273 // member accesses, as we need to defer certain access checks until we know
1274 // the context.
1275 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1276 if (Result.isSingleResult() && !ADL &&
1277 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1278 return NameClassification::NonType(Result.getRepresentativeDecl());
1279
1280 // Otherwise, this is an overload set that we will need to resolve later.
1281 Result.suppressDiagnostics();
1283 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1284 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1285 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1286}
1287
1290 SourceLocation NameLoc) {
1291 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1292 CXXScopeSpec SS;
1293 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1294 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1295}
1296
1299 IdentifierInfo *Name,
1300 SourceLocation NameLoc,
1301 bool IsAddressOfOperand) {
1302 DeclarationNameInfo NameInfo(Name, NameLoc);
1303 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1304 NameInfo, IsAddressOfOperand,
1305 /*TemplateArgs=*/nullptr);
1306}
1307
1310 SourceLocation NameLoc,
1311 const Token &NextToken) {
1312 if (getCurMethodDecl() && SS.isEmpty())
1313 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1314 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1315
1316 // Reconstruct the lookup result.
1317 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1318 Result.addDecl(Found);
1319 Result.resolveKind();
1320
1321 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1322 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1323}
1324
1326 // For an implicit class member access, transform the result into a member
1327 // access expression if necessary.
1328 auto *ULE = cast<UnresolvedLookupExpr>(E);
1329 if ((*ULE->decls_begin())->isCXXClassMember()) {
1330 CXXScopeSpec SS;
1331 SS.Adopt(ULE->getQualifierLoc());
1332
1333 // Reconstruct the lookup result.
1334 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1336 Result.setNamingClass(ULE->getNamingClass());
1337 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1338 Result.addDecl(*I, I.getAccess());
1339 Result.resolveKind();
1341 nullptr, S);
1342 }
1343
1344 // Otherwise, this is already in the form we needed, and no further checks
1345 // are necessary.
1346 return ULE;
1347}
1348
1368
1370 assert(DC->getLexicalParent() == CurContext &&
1371 "The next DeclContext should be lexically contained in the current one.");
1372 CurContext = DC;
1373 S->setEntity(DC);
1374}
1375
1377 assert(CurContext && "DeclContext imbalance!");
1378
1379 CurContext = CurContext->getLexicalParent();
1380 assert(CurContext && "Popped translation unit!");
1381}
1382
1384 Decl *D) {
1385 // Unlike PushDeclContext, the context to which we return is not necessarily
1386 // the containing DC of TD, because the new context will be some pre-existing
1387 // TagDecl definition instead of a fresh one.
1388 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1389 CurContext = cast<TagDecl>(D)->getDefinition();
1390 assert(CurContext && "skipping definition of undefined tag");
1391 // Start lookups from the parent of the current context; we don't want to look
1392 // into the pre-existing complete definition.
1393 S->setEntity(CurContext->getLookupParent());
1394 return Result;
1395}
1396
1400
1402 // C++0x [basic.lookup.unqual]p13:
1403 // A name used in the definition of a static data member of class
1404 // X (after the qualified-id of the static member) is looked up as
1405 // if the name was used in a member function of X.
1406 // C++0x [basic.lookup.unqual]p14:
1407 // If a variable member of a namespace is defined outside of the
1408 // scope of its namespace then any name used in the definition of
1409 // the variable member (after the declarator-id) is looked up as
1410 // if the definition of the variable member occurred in its
1411 // namespace.
1412 // Both of these imply that we should push a scope whose context
1413 // is the semantic context of the declaration. We can't use
1414 // PushDeclContext here because that context is not necessarily
1415 // lexically contained in the current context. Fortunately,
1416 // the containing scope should have the appropriate information.
1417
1418 assert(!S->getEntity() && "scope already has entity");
1419
1420#ifndef NDEBUG
1421 Scope *Ancestor = S->getParent();
1422 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1423 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1424#endif
1425
1426 CurContext = DC;
1427 S->setEntity(DC);
1428
1429 if (S->getParent()->isTemplateParamScope()) {
1430 // Also set the corresponding entities for all immediately-enclosing
1431 // template parameter scopes.
1433 }
1434}
1435
1437 assert(S->getEntity() == CurContext && "Context imbalance!");
1438
1439 // Switch back to the lexical context. The safety of this is
1440 // enforced by an assert in EnterDeclaratorContext.
1441 Scope *Ancestor = S->getParent();
1442 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1443 CurContext = Ancestor->getEntity();
1444
1445 // We don't need to do anything with the scope, which is going to
1446 // disappear.
1447}
1448
1450 assert(S->isTemplateParamScope() &&
1451 "expected to be initializing a template parameter scope");
1452
1453 // C++20 [temp.local]p7:
1454 // In the definition of a member of a class template that appears outside
1455 // of the class template definition, the name of a member of the class
1456 // template hides the name of a template-parameter of any enclosing class
1457 // templates (but not a template-parameter of the member if the member is a
1458 // class or function template).
1459 // C++20 [temp.local]p9:
1460 // In the definition of a class template or in the definition of a member
1461 // of such a template that appears outside of the template definition, for
1462 // each non-dependent base class (13.8.2.1), if the name of the base class
1463 // or the name of a member of the base class is the same as the name of a
1464 // template-parameter, the base class name or member name hides the
1465 // template-parameter name (6.4.10).
1466 //
1467 // This means that a template parameter scope should be searched immediately
1468 // after searching the DeclContext for which it is a template parameter
1469 // scope. For example, for
1470 // template<typename T> template<typename U> template<typename V>
1471 // void N::A<T>::B<U>::f(...)
1472 // we search V then B<U> (and base classes) then U then A<T> (and base
1473 // classes) then T then N then ::.
1474 unsigned ScopeDepth = getTemplateDepth(S);
1475 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1476 DeclContext *SearchDCAfterScope = DC;
1477 for (; DC; DC = DC->getLookupParent()) {
1478 if (const TemplateParameterList *TPL =
1479 cast<Decl>(DC)->getDescribedTemplateParams()) {
1480 unsigned DCDepth = TPL->getDepth() + 1;
1481 if (DCDepth > ScopeDepth)
1482 continue;
1483 if (ScopeDepth == DCDepth)
1484 SearchDCAfterScope = DC = DC->getLookupParent();
1485 break;
1486 }
1487 }
1488 S->setLookupEntity(SearchDCAfterScope);
1489 }
1490}
1491
1493 // We assume that the caller has already called
1494 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1495 FunctionDecl *FD = D->getAsFunction();
1496 if (!FD)
1497 return;
1498
1499 // Same implementation as PushDeclContext, but enters the context
1500 // from the lexical parent, rather than the top-level class.
1501 assert(CurContext == FD->getLexicalParent() &&
1502 "The next DeclContext should be lexically contained in the current one.");
1503 CurContext = FD;
1505
1506 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1507 ParmVarDecl *Param = FD->getParamDecl(P);
1508 // If the parameter has an identifier, then add it to the scope
1509 if (Param->getIdentifier()) {
1510 S->AddDecl(Param);
1511 IdResolver.AddDecl(Param);
1512 }
1513 }
1514}
1515
1517 // Same implementation as PopDeclContext, but returns to the lexical parent,
1518 // rather than the top-level class.
1519 assert(CurContext && "DeclContext imbalance!");
1520 CurContext = CurContext->getLexicalParent();
1521 assert(CurContext && "Popped translation unit!");
1522}
1523
1524/// Determine whether overloading is allowed for a new function
1525/// declaration considering prior declarations of the same name.
1526///
1527/// This routine determines whether overloading is possible, not
1528/// whether a new declaration actually overloads a previous one.
1529/// It will return true in C++ (where overloads are always permitted)
1530/// or, as a C extension, when either the new declaration or a
1531/// previous one is declared with the 'overloadable' attribute.
1533 ASTContext &Context,
1534 const FunctionDecl *New) {
1535 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1536 return true;
1537
1538 // Multiversion function declarations are not overloads in the
1539 // usual sense of that term, but lookup will report that an
1540 // overload set was found if more than one multiversion function
1541 // declaration is present for the same name. It is therefore
1542 // inadequate to assume that some prior declaration(s) had
1543 // the overloadable attribute; checking is required. Since one
1544 // declaration is permitted to omit the attribute, it is necessary
1545 // to check at least two; hence the 'any_of' check below. Note that
1546 // the overloadable attribute is implicitly added to declarations
1547 // that were required to have it but did not.
1548 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1549 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1550 return ND->hasAttr<OverloadableAttr>();
1551 });
1552 } else if (Previous.getResultKind() == LookupResultKind::Found)
1553 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1554
1555 return false;
1556}
1557
1558void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1559 // Move up the scope chain until we find the nearest enclosing
1560 // non-transparent context. The declaration will be introduced into this
1561 // scope.
1562 while (S->getEntity() && S->getEntity()->isTransparentContext())
1563 S = S->getParent();
1564
1565 // Add scoped declarations into their context, so that they can be
1566 // found later. Declarations without a context won't be inserted
1567 // into any context.
1568 if (AddToContext)
1569 CurContext->addDecl(D);
1570
1571 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1572 // are function-local declarations.
1573 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1574 return;
1575
1576 // Template instantiations should also not be pushed into scope.
1577 if (isa<FunctionDecl>(D) &&
1578 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1579 return;
1580
1581 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1582 S->AddDecl(D);
1583 return;
1584 }
1585 // If this replaces anything in the current scope,
1587 IEnd = IdResolver.end();
1588 for (; I != IEnd; ++I) {
1589 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1590 S->RemoveDecl(*I);
1591 IdResolver.RemoveDecl(*I);
1592
1593 // Should only need to replace one decl.
1594 break;
1595 }
1596 }
1597
1598 S->AddDecl(D);
1599
1600 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1601 // Implicitly-generated labels may end up getting generated in an order that
1602 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1603 // the label at the appropriate place in the identifier chain.
1604 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1605 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1606 if (IDC == CurContext) {
1607 if (!S->isDeclScope(*I))
1608 continue;
1609 } else if (IDC->Encloses(CurContext))
1610 break;
1611 }
1612
1613 IdResolver.InsertDeclAfter(I, D);
1614 } else {
1615 IdResolver.AddDecl(D);
1616 }
1618}
1619
1621 bool AllowInlineNamespace) const {
1622 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1623}
1624
1626 DeclContext *TargetDC = DC->getPrimaryContext();
1627 do {
1628 if (DeclContext *ScopeDC = S->getEntity())
1629 if (ScopeDC->getPrimaryContext() == TargetDC)
1630 return S;
1631 } while ((S = S->getParent()));
1632
1633 return nullptr;
1634}
1635
1637 DeclContext*,
1638 ASTContext&);
1639
1641 bool ConsiderLinkage,
1642 bool AllowInlineNamespace) {
1644 while (F.hasNext()) {
1645 NamedDecl *D = F.next();
1646
1647 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1648 continue;
1649
1650 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1651 continue;
1652
1653 F.erase();
1654 }
1655
1656 F.done();
1657}
1658
1660 if (auto *VD = dyn_cast<VarDecl>(D))
1661 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1662 if (auto *FD = dyn_cast<FunctionDecl>(D))
1663 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1664 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1665 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1666
1667 return false;
1668}
1669
1671 // [module.interface]p7:
1672 // A declaration is attached to a module as follows:
1673 // - If the declaration is a non-dependent friend declaration that nominates a
1674 // function with a declarator-id that is a qualified-id or template-id or that
1675 // nominates a class other than with an elaborated-type-specifier with neither
1676 // a nested-name-specifier nor a simple-template-id, it is attached to the
1677 // module to which the friend is attached ([basic.link]).
1678 if (New->getFriendObjectKind() &&
1679 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1680 New->setLocalOwningModule(Old->getOwningModule());
1682 return false;
1683 }
1684
1685 // Although we have questions for the module ownership of implicit
1686 // instantiations, it should be sure that we shouldn't diagnose the
1687 // redeclaration of incorrect module ownership for different implicit
1688 // instantiations in different modules. We will diagnose the redeclaration of
1689 // incorrect module ownership for the template itself.
1691 return false;
1692
1693 Module *NewM = New->getOwningModule();
1694 Module *OldM = Old->getOwningModule();
1695
1696 if (NewM && NewM->isPrivateModule())
1697 NewM = NewM->Parent;
1698 if (OldM && OldM->isPrivateModule())
1699 OldM = OldM->Parent;
1700
1701 if (NewM == OldM)
1702 return false;
1703
1704 if (NewM && OldM) {
1705 // A module implementation unit has visibility of the decls in its
1706 // implicitly imported interface.
1707 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1708 return false;
1709
1710 // Partitions are part of the module, but a partition could import another
1711 // module, so verify that the PMIs agree.
1712 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1713 getASTContext().isInSameModule(NewM, OldM))
1714 return false;
1715 }
1716
1717 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1718 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1719 if (NewIsModuleInterface || OldIsModuleInterface) {
1720 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1721 // if a declaration of D [...] appears in the purview of a module, all
1722 // other such declarations shall appear in the purview of the same module
1723 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1724 << New
1725 << NewIsModuleInterface
1726 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1727 << OldIsModuleInterface
1728 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1729 Diag(Old->getLocation(), diag::note_previous_declaration);
1730 New->setInvalidDecl();
1731 return true;
1732 }
1733
1734 return false;
1735}
1736
1738 // [module.interface]p1:
1739 // An export-declaration shall inhabit a namespace scope.
1740 //
1741 // So it is meaningless to talk about redeclaration which is not at namespace
1742 // scope.
1743 if (!New->getLexicalDeclContext()
1744 ->getNonTransparentContext()
1745 ->isFileContext() ||
1746 !Old->getLexicalDeclContext()
1748 ->isFileContext())
1749 return false;
1750
1751 bool IsNewExported = New->isInExportDeclContext();
1752 bool IsOldExported = Old->isInExportDeclContext();
1753
1754 // It should be irrevelant if both of them are not exported.
1755 if (!IsNewExported && !IsOldExported)
1756 return false;
1757
1758 if (IsOldExported)
1759 return false;
1760
1761 // If the Old declaration are not attached to named modules
1762 // and the New declaration are attached to global module.
1763 // It should be fine to allow the export since it doesn't change
1764 // the linkage of declarations. See
1765 // https://github.com/llvm/llvm-project/issues/98583 for details.
1766 if (!Old->isInNamedModule() && New->getOwningModule() &&
1767 New->getOwningModule()->isImplicitGlobalModule())
1768 return false;
1769
1770 assert(IsNewExported);
1771
1772 auto Lk = Old->getFormalLinkage();
1773 int S = 0;
1774 if (Lk == Linkage::Internal)
1775 S = 1;
1776 else if (Lk == Linkage::Module)
1777 S = 2;
1778 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1779 Diag(Old->getLocation(), diag::note_previous_declaration);
1780 return true;
1781}
1782
1785 return true;
1786
1788 return true;
1789
1790 return false;
1791}
1792
1794 const NamedDecl *Old) const {
1795 assert(getASTContext().isSameEntity(New, Old) &&
1796 "New and Old are not the same definition, we should diagnostic it "
1797 "immediately instead of checking it.");
1798 assert(const_cast<Sema *>(this)->isReachable(New) &&
1799 const_cast<Sema *>(this)->isReachable(Old) &&
1800 "We shouldn't see unreachable definitions here.");
1801
1802 Module *NewM = New->getOwningModule();
1803 Module *OldM = Old->getOwningModule();
1804
1805 // We only checks for named modules here. The header like modules is skipped.
1806 // FIXME: This is not right if we import the header like modules in the module
1807 // purview.
1808 //
1809 // For example, assuming "header.h" provides definition for `D`.
1810 // ```C++
1811 // //--- M.cppm
1812 // export module M;
1813 // import "header.h"; // or #include "header.h" but import it by clang modules
1814 // actually.
1815 //
1816 // //--- Use.cpp
1817 // import M;
1818 // import "header.h"; // or uses clang modules.
1819 // ```
1820 //
1821 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1822 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1823 // reject it. But the current implementation couldn't detect the case since we
1824 // don't record the information about the importee modules.
1825 //
1826 // But this might not be painful in practice. Since the design of C++20 Named
1827 // Modules suggests us to use headers in global module fragment instead of
1828 // module purview.
1829 if (NewM && NewM->isHeaderLikeModule())
1830 NewM = nullptr;
1831 if (OldM && OldM->isHeaderLikeModule())
1832 OldM = nullptr;
1833
1834 if (!NewM && !OldM)
1835 return true;
1836
1837 // [basic.def.odr]p14.3
1838 // Each such definition shall not be attached to a named module
1839 // ([module.unit]).
1840 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1841 return true;
1842
1843 // Then New and Old lives in the same TU if their share one same module unit.
1844 if (NewM)
1845 NewM = NewM->getTopLevelModule();
1846 if (OldM)
1847 OldM = OldM->getTopLevelModule();
1848 return OldM == NewM;
1849}
1850
1852 if (D->getDeclContext()->isFileContext())
1853 return false;
1854
1855 return isa<UsingShadowDecl>(D) ||
1858}
1859
1860/// Removes using shadow declarations not at class scope from the lookup
1861/// results.
1864 while (F.hasNext())
1866 F.erase();
1867
1868 F.done();
1869}
1870
1871/// Check for this common pattern:
1872/// @code
1873/// class S {
1874/// S(const S&); // DO NOT IMPLEMENT
1875/// void operator=(const S&); // DO NOT IMPLEMENT
1876/// };
1877/// @endcode
1879 // FIXME: Should check for private access too but access is set after we get
1880 // the decl here.
1882 return false;
1883
1884 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1885 return CD->isCopyConstructor();
1886 return D->isCopyAssignmentOperator();
1887}
1888
1889bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1890 const DeclContext *DC = D->getDeclContext();
1891 while (!DC->isTranslationUnit()) {
1892 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1893 if (!RD->hasNameForLinkage())
1894 return true;
1895 }
1896 DC = DC->getParent();
1897 }
1898
1899 return !D->isExternallyVisible();
1900}
1901
1902// FIXME: This needs to be refactored; some other isInMainFile users want
1903// these semantics.
1904static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1906 return false;
1907 return S.SourceMgr.isInMainFile(Loc);
1908}
1909
1911 assert(D);
1912
1913 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1914 return false;
1915
1916 // Ignore all entities declared within templates, and out-of-line definitions
1917 // of members of class templates.
1918 if (D->getDeclContext()->isDependentContext() ||
1920 return false;
1921
1922 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1923 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1924 return false;
1925 // A non-out-of-line declaration of a member specialization was implicitly
1926 // instantiated; it's the out-of-line declaration that we're interested in.
1927 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1928 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1929 return false;
1930
1931 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1932 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1933 return false;
1934 } else {
1935 // 'static inline' functions are defined in headers; don't warn.
1936 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1937 return false;
1938 }
1939
1940 if (FD->doesThisDeclarationHaveABody() &&
1941 Context.DeclMustBeEmitted(FD))
1942 return false;
1943 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1944 // Constants and utility variables are defined in headers with internal
1945 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1946 // like "inline".)
1947 if (!isMainFileLoc(*this, VD->getLocation()))
1948 return false;
1949
1950 if (Context.DeclMustBeEmitted(VD))
1951 return false;
1952
1953 if (VD->isStaticDataMember() &&
1954 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1955 return false;
1956 if (VD->isStaticDataMember() &&
1957 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1958 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1959 return false;
1960
1961 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1962 return false;
1963 } else {
1964 return false;
1965 }
1966
1967 // Only warn for unused decls internal to the translation unit.
1968 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1969 // for inline functions defined in the main source file, for instance.
1970 return mightHaveNonExternalLinkage(D);
1971}
1972
1974 if (!D)
1975 return;
1976
1977 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1978 const FunctionDecl *First = FD->getFirstDecl();
1980 return; // First should already be in the vector.
1981 }
1982
1983 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1984 const VarDecl *First = VD->getFirstDecl();
1986 return; // First should already be in the vector.
1987 }
1988
1990 UnusedFileScopedDecls.push_back(D);
1991}
1992
1993static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1994 const NamedDecl *D) {
1995 if (D->isInvalidDecl())
1996 return false;
1997
1998 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1999 // For a decomposition declaration, warn if none of the bindings are
2000 // referenced, instead of if the variable itself is referenced (which
2001 // it is, by the bindings' expressions).
2002 bool IsAllIgnored = true;
2003 for (const auto *BD : DD->bindings()) {
2004 if (BD->isReferenced())
2005 return false;
2006 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2007 BD->hasAttr<UnusedAttr>());
2008 }
2009 if (IsAllIgnored)
2010 return false;
2011 } else if (!D->getDeclName()) {
2012 return false;
2013 } else if (D->isReferenced() || D->isUsed()) {
2014 return false;
2015 }
2016
2017 if (D->isPlaceholderVar(LangOpts))
2018 return false;
2019
2020 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2021 D->hasAttr<CleanupAttr>())
2022 return false;
2023
2024 if (isa<LabelDecl>(D))
2025 return true;
2026
2027 // Except for labels, we only care about unused decls that are local to
2028 // functions.
2029 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2030 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2031 // For dependent types, the diagnostic is deferred.
2032 WithinFunction =
2033 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2034 if (!WithinFunction)
2035 return false;
2036
2037 if (isa<TypedefNameDecl>(D))
2038 return true;
2039
2040 // White-list anything that isn't a local variable.
2042 return false;
2043
2044 // Types of valid local variables should be complete, so this should succeed.
2045 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2046
2047 const Expr *Init = VD->getInit();
2048 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2049 Init = Cleanups->getSubExpr();
2050
2051 const auto *Ty = VD->getType().getTypePtr();
2052
2053 // Only look at the outermost level of typedef.
2054 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2055 // Allow anything marked with __attribute__((unused)).
2056 if (TT->getDecl()->hasAttr<UnusedAttr>())
2057 return false;
2058 }
2059
2060 // Warn for reference variables whose initializtion performs lifetime
2061 // extension.
2062 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2063 MTE && MTE->getExtendingDecl()) {
2064 Ty = VD->getType().getNonReferenceType().getTypePtr();
2065 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2066 }
2067
2068 // If we failed to complete the type for some reason, or if the type is
2069 // dependent, don't diagnose the variable.
2070 if (Ty->isIncompleteType() || Ty->isDependentType())
2071 return false;
2072
2073 // Look at the element type to ensure that the warning behaviour is
2074 // consistent for both scalars and arrays.
2075 Ty = Ty->getBaseElementTypeUnsafe();
2076
2077 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2078 if (Tag->hasAttr<UnusedAttr>())
2079 return false;
2080
2081 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2082 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2083 return false;
2084
2085 if (Init) {
2086 const auto *Construct =
2087 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2088 if (Construct && !Construct->isElidable()) {
2089 const CXXConstructorDecl *CD = Construct->getConstructor();
2090 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2091 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2092 return false;
2093 }
2094
2095 // Suppress the warning if we don't know how this is constructed, and
2096 // it could possibly be non-trivial constructor.
2097 if (Init->isTypeDependent()) {
2098 for (const CXXConstructorDecl *Ctor : RD->ctors())
2099 if (!Ctor->isTrivial())
2100 return false;
2101 }
2102
2103 // Suppress the warning if the constructor is unresolved because
2104 // its arguments are dependent.
2106 return false;
2107 }
2108 }
2109 }
2110
2111 // TODO: __attribute__((unused)) templates?
2112 }
2113
2114 return true;
2115}
2116
2118 FixItHint &Hint) {
2119 if (isa<LabelDecl>(D)) {
2121 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2122 /*SkipTrailingWhitespaceAndNewline=*/false);
2123 if (AfterColon.isInvalid())
2124 return;
2126 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2127 }
2128}
2129
2132 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2133}
2134
2136 DiagReceiverTy DiagReceiver) {
2137 if (D->isDependentType())
2138 return;
2139
2140 for (auto *TmpD : D->decls()) {
2141 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2142 DiagnoseUnusedDecl(T, DiagReceiver);
2143 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2144 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2145 }
2146}
2147
2150 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2151}
2152
2155 return;
2156
2157 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2158 // typedefs can be referenced later on, so the diagnostics are emitted
2159 // at end-of-translation-unit.
2161 return;
2162 }
2163
2164 FixItHint Hint;
2166
2167 unsigned DiagID;
2168 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2169 DiagID = diag::warn_unused_exception_param;
2170 else if (isa<LabelDecl>(D))
2171 DiagID = diag::warn_unused_label;
2172 else
2173 DiagID = diag::warn_unused_variable;
2174
2175 SourceLocation DiagLoc = D->getLocation();
2176 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2177}
2178
2180 DiagReceiverTy DiagReceiver) {
2181 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2182 // it's not really unused.
2183 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2184 return;
2185
2186 // In C++, `_` variables behave as if they were maybe_unused
2187 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2188 return;
2189
2190 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2191
2192 if (Ty->isReferenceType() || Ty->isDependentType())
2193 return;
2194
2195 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2196 if (Tag->hasAttr<UnusedAttr>())
2197 return;
2198 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2199 // mimic gcc's behavior.
2200 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2201 RD && !RD->hasAttr<WarnUnusedAttr>())
2202 return;
2203 }
2204
2205 // Don't warn about __block Objective-C pointer variables, as they might
2206 // be assigned in the block but not used elsewhere for the purpose of lifetime
2207 // extension.
2208 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2209 return;
2210
2211 // Don't warn about Objective-C pointer variables with precise lifetime
2212 // semantics; they can be used to ensure ARC releases the object at a known
2213 // time, which may mean assignment but no other references.
2214 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2215 return;
2216
2217 auto iter = RefsMinusAssignments.find(VD);
2218 if (iter == RefsMinusAssignments.end())
2219 return;
2220
2221 assert(iter->getSecond() >= 0 &&
2222 "Found a negative number of references to a VarDecl");
2223 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2224 // Assume the given VarDecl is "used" if its ref count stored in
2225 // `RefMinusAssignments` is positive, with one exception.
2226 //
2227 // For a C++ variable whose decl (with initializer) entirely consist the
2228 // condition expression of a if/while/for construct,
2229 // Clang creates a DeclRefExpr for the condition expression rather than a
2230 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2231 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2232 // used in the body of the if/while/for construct.
2233 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2234 if (!UnusedCXXCondDecl)
2235 return;
2236 }
2237
2238 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2239 : diag::warn_unused_but_set_variable;
2240 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2241}
2242
2244 Sema::DiagReceiverTy DiagReceiver) {
2245 // Verify that we have no forward references left. If so, there was a goto
2246 // or address of a label taken, but no definition of it. Label fwd
2247 // definitions are indicated with a null substmt which is also not a resolved
2248 // MS inline assembly label name.
2249 bool Diagnose = false;
2250 if (L->isMSAsmLabel())
2251 Diagnose = !L->isResolvedMSAsmLabel();
2252 else
2253 Diagnose = L->getStmt() == nullptr;
2254 if (Diagnose)
2255 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2256 << L);
2257}
2258
2260 S->applyNRVO();
2261
2262 if (S->decl_empty()) return;
2264 "Scope shouldn't contain decls!");
2265
2266 /// We visit the decls in non-deterministic order, but we want diagnostics
2267 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2268 /// and sort the diagnostics before emitting them, after we visited all decls.
2269 struct LocAndDiag {
2270 SourceLocation Loc;
2271 std::optional<SourceLocation> PreviousDeclLoc;
2273 };
2275 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2276 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2277 };
2278 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2279 SourceLocation PreviousDeclLoc,
2280 PartialDiagnostic PD) {
2281 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2282 };
2283
2284 for (auto *TmpD : S->decls()) {
2285 assert(TmpD && "This decl didn't get pushed??");
2286
2287 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2288 NamedDecl *D = cast<NamedDecl>(TmpD);
2289
2290 // Diagnose unused variables in this scope.
2292 DiagnoseUnusedDecl(D, addDiag);
2293 if (const auto *RD = dyn_cast<RecordDecl>(D))
2294 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2295 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2296 DiagnoseUnusedButSetDecl(VD, addDiag);
2297 RefsMinusAssignments.erase(VD);
2298 }
2299 }
2300
2301 if (!D->getDeclName()) continue;
2302
2303 // If this was a forward reference to a label, verify it was defined.
2304 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2305 CheckPoppedLabel(LD, *this, addDiag);
2306
2307 // Partial translation units that are created in incremental processing must
2308 // not clean up the IdResolver because PTUs should take into account the
2309 // declarations that came from previous PTUs.
2310 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2312 IdResolver.RemoveDecl(D);
2313
2314 // Warn on it if we are shadowing a declaration.
2315 auto ShadowI = ShadowingDecls.find(D);
2316 if (ShadowI != ShadowingDecls.end()) {
2317 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2318 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2319 PDiag(diag::warn_ctor_parm_shadows_field)
2320 << D << FD << FD->getParent());
2321 }
2322 ShadowingDecls.erase(ShadowI);
2323 }
2324 }
2325
2326 llvm::sort(DeclDiags,
2327 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2328 // The particular order for diagnostics is not important, as long
2329 // as the order is deterministic. Using the raw location is going
2330 // to generally be in source order unless there are macro
2331 // expansions involved.
2332 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2333 });
2334 for (const LocAndDiag &D : DeclDiags) {
2335 Diag(D.Loc, D.PD);
2336 if (D.PreviousDeclLoc)
2337 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2338 }
2339}
2340
2342 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2343 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2344 (S->isClassScope() && !getLangOpts().CPlusPlus))
2345 S = S->getParent();
2346 return S;
2347}
2348
2349static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2351 switch (Error) {
2353 return "";
2355 return BuiltinInfo.getHeaderName(ID);
2357 return "stdio.h";
2359 return "setjmp.h";
2361 return "ucontext.h";
2362 }
2363 llvm_unreachable("unhandled error kind");
2364}
2365
2367 unsigned ID, SourceLocation Loc) {
2368 DeclContext *Parent = Context.getTranslationUnitDecl();
2369
2370 if (getLangOpts().CPlusPlus) {
2372 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2373 CLinkageDecl->setImplicit();
2374 Parent->addDecl(CLinkageDecl);
2375 Parent = CLinkageDecl;
2376 }
2377
2379 if (Context.BuiltinInfo.isImmediate(ID)) {
2380 assert(getLangOpts().CPlusPlus20 &&
2381 "consteval builtins should only be available in C++20 mode");
2382 ConstexprKind = ConstexprSpecKind::Consteval;
2383 }
2384
2386 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2387 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2388 Type->isFunctionProtoType(), ConstexprKind);
2389 New->setImplicit();
2390 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2391
2392 // Create Decl objects for each parameter, adding them to the
2393 // FunctionDecl.
2394 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2396 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2398 Context, New, SourceLocation(), SourceLocation(), nullptr,
2399 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2400 parm->setScopeInfo(0, i);
2401 Params.push_back(parm);
2402 }
2403 New->setParams(Params);
2404 }
2405
2407 return New;
2408}
2409
2411 Scope *S, bool ForRedeclaration,
2412 SourceLocation Loc) {
2414
2416 QualType R = Context.GetBuiltinType(ID, Error);
2417 if (Error) {
2418 if (!ForRedeclaration)
2419 return nullptr;
2420
2421 // If we have a builtin without an associated type we should not emit a
2422 // warning when we were not able to find a type for it.
2424 Context.BuiltinInfo.allowTypeMismatch(ID))
2425 return nullptr;
2426
2427 // If we could not find a type for setjmp it is because the jmp_buf type was
2428 // not defined prior to the setjmp declaration.
2430 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2431 << Context.BuiltinInfo.getName(ID);
2432 return nullptr;
2433 }
2434
2435 // Generally, we emit a warning that the declaration requires the
2436 // appropriate header.
2437 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2438 << getHeaderName(Context.BuiltinInfo, ID, Error)
2439 << Context.BuiltinInfo.getName(ID);
2440 return nullptr;
2441 }
2442
2443 if (!ForRedeclaration &&
2444 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2445 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2446 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2447 : diag::ext_implicit_lib_function_decl)
2448 << Context.BuiltinInfo.getName(ID) << R;
2449 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2450 Diag(Loc, diag::note_include_header_or_declare)
2451 << Header << Context.BuiltinInfo.getName(ID);
2452 }
2453
2454 if (R.isNull())
2455 return nullptr;
2456
2457 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2459
2460 // TUScope is the translation-unit scope to insert this function into.
2461 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2462 // relate Scopes to DeclContexts, and probably eliminate CurContext
2463 // entirely, but we're not there yet.
2464 DeclContext *SavedContext = CurContext;
2465 CurContext = New->getDeclContext();
2467 CurContext = SavedContext;
2468 return New;
2469}
2470
2471/// Typedef declarations don't have linkage, but they still denote the same
2472/// entity if their types are the same.
2473/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2474/// isSameEntity.
2475static void
2478 // This is only interesting when modules are enabled.
2479 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2480 return;
2481
2482 // Empty sets are uninteresting.
2483 if (Previous.empty())
2484 return;
2485
2486 LookupResult::Filter Filter = Previous.makeFilter();
2487 while (Filter.hasNext()) {
2488 NamedDecl *Old = Filter.next();
2489
2490 // Non-hidden declarations are never ignored.
2491 if (S.isVisible(Old))
2492 continue;
2493
2494 // Declarations of the same entity are not ignored, even if they have
2495 // different linkages.
2496 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2497 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2498 Decl->getUnderlyingType()))
2499 continue;
2500
2501 // If both declarations give a tag declaration a typedef name for linkage
2502 // purposes, then they declare the same entity.
2503 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2504 Decl->getAnonDeclWithTypedefName())
2505 continue;
2506 }
2507
2508 Filter.erase();
2509 }
2510
2511 Filter.done();
2512}
2513
2515 QualType OldType;
2516 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2517 OldType = OldTypedef->getUnderlyingType();
2518 else
2519 OldType = Context.getTypeDeclType(Old);
2520 QualType NewType = New->getUnderlyingType();
2521
2522 if (NewType->isVariablyModifiedType()) {
2523 // Must not redefine a typedef with a variably-modified type.
2524 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2525 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2526 << Kind << NewType;
2527 if (Old->getLocation().isValid())
2528 notePreviousDefinition(Old, New->getLocation());
2529 New->setInvalidDecl();
2530 return true;
2531 }
2532
2533 if (OldType != NewType &&
2534 !OldType->isDependentType() &&
2535 !NewType->isDependentType() &&
2536 !Context.hasSameType(OldType, NewType)) {
2537 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2538 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2539 << Kind << NewType << OldType;
2540 if (Old->getLocation().isValid())
2541 notePreviousDefinition(Old, New->getLocation());
2542 New->setInvalidDecl();
2543 return true;
2544 }
2545 return false;
2546}
2547
2549 LookupResult &OldDecls) {
2550 // If the new decl is known invalid already, don't bother doing any
2551 // merging checks.
2552 if (New->isInvalidDecl()) return;
2553
2554 // Allow multiple definitions for ObjC built-in typedefs.
2555 // FIXME: Verify the underlying types are equivalent!
2556 if (getLangOpts().ObjC) {
2557 const IdentifierInfo *TypeID = New->getIdentifier();
2558 switch (TypeID->getLength()) {
2559 default: break;
2560 case 2:
2561 {
2562 if (!TypeID->isStr("id"))
2563 break;
2564 QualType T = New->getUnderlyingType();
2565 if (!T->isPointerType())
2566 break;
2567 if (!T->isVoidPointerType()) {
2568 QualType PT = T->castAs<PointerType>()->getPointeeType();
2569 if (!PT->isStructureType())
2570 break;
2571 }
2572 Context.setObjCIdRedefinitionType(T);
2573 // Install the built-in type for 'id', ignoring the current definition.
2574 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2575 Context.getObjCIdType());
2576 return;
2577 }
2578 case 5:
2579 if (!TypeID->isStr("Class"))
2580 break;
2581 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2582 // Install the built-in type for 'Class', ignoring the current definition.
2583 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2584 Context.getObjCClassType());
2585 return;
2586 case 3:
2587 if (!TypeID->isStr("SEL"))
2588 break;
2589 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2590 // Install the built-in type for 'SEL', ignoring the current definition.
2591 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2592 Context.getObjCSelType());
2593 return;
2594 }
2595 // Fall through - the typedef name was not a builtin type.
2596 }
2597
2598 // Verify the old decl was also a type.
2599 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2600 if (!Old) {
2601 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2602 << New->getDeclName();
2603
2604 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2605 if (OldD->getLocation().isValid())
2606 notePreviousDefinition(OldD, New->getLocation());
2607
2608 return New->setInvalidDecl();
2609 }
2610
2611 // If the old declaration is invalid, just give up here.
2612 if (Old->isInvalidDecl())
2613 return New->setInvalidDecl();
2614
2615 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2616 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2617 auto *NewTag = New->getAnonDeclWithTypedefName();
2618 NamedDecl *Hidden = nullptr;
2619 if (OldTag && NewTag &&
2620 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2621 !hasVisibleDefinition(OldTag, &Hidden)) {
2622 // There is a definition of this tag, but it is not visible. Use it
2623 // instead of our tag.
2624 if (OldTD->isModed())
2625 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2626 OldTD->getUnderlyingType());
2627 else
2628 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2629
2630 // Make the old tag definition visible.
2632
2634 }
2635 }
2636
2637 // If the typedef types are not identical, reject them in all languages and
2638 // with any extensions enabled.
2639 if (isIncompatibleTypedef(Old, New))
2640 return;
2641
2642 // The types match. Link up the redeclaration chain and merge attributes if
2643 // the old declaration was a typedef.
2644 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2645 New->setPreviousDecl(Typedef);
2647 }
2648
2649 if (getLangOpts().MicrosoftExt)
2650 return;
2651
2652 if (getLangOpts().CPlusPlus) {
2653 // C++ [dcl.typedef]p2:
2654 // In a given non-class scope, a typedef specifier can be used to
2655 // redefine the name of any type declared in that scope to refer
2656 // to the type to which it already refers.
2658 return;
2659
2660 // C++0x [dcl.typedef]p4:
2661 // In a given class scope, a typedef specifier can be used to redefine
2662 // any class-name declared in that scope that is not also a typedef-name
2663 // to refer to the type to which it already refers.
2664 //
2665 // This wording came in via DR424, which was a correction to the
2666 // wording in DR56, which accidentally banned code like:
2667 //
2668 // struct S {
2669 // typedef struct A { } A;
2670 // };
2671 //
2672 // in the C++03 standard. We implement the C++0x semantics, which
2673 // allow the above but disallow
2674 //
2675 // struct S {
2676 // typedef int I;
2677 // typedef int I;
2678 // };
2679 //
2680 // since that was the intent of DR56.
2681 if (!isa<TypedefNameDecl>(Old))
2682 return;
2683
2684 Diag(New->getLocation(), diag::err_redefinition)
2685 << New->getDeclName();
2686 notePreviousDefinition(Old, New->getLocation());
2687 return New->setInvalidDecl();
2688 }
2689
2690 // Modules always permit redefinition of typedefs, as does C11.
2691 if (getLangOpts().Modules || getLangOpts().C11)
2692 return;
2693
2694 // If we have a redefinition of a typedef in C, emit a warning. This warning
2695 // is normally mapped to an error, but can be controlled with
2696 // -Wtypedef-redefinition. If either the original or the redefinition is
2697 // in a system header, don't emit this for compatibility with GCC.
2698 if (getDiagnostics().getSuppressSystemWarnings() &&
2699 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2700 (Old->isImplicit() ||
2701 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2702 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2703 return;
2704
2705 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2706 << New->getDeclName();
2707 notePreviousDefinition(Old, New->getLocation());
2708}
2709
2711 // If this was an unscoped enumeration, yank all of its enumerators
2712 // out of the scope.
2713 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2714 Scope *EnumScope = getNonFieldDeclScope(S);
2715 for (auto *ECD : ED->enumerators()) {
2716 assert(EnumScope->isDeclScope(ECD));
2717 EnumScope->RemoveDecl(ECD);
2718 IdResolver.RemoveDecl(ECD);
2719 }
2720 }
2721}
2722
2723/// DeclhasAttr - returns true if decl Declaration already has the target
2724/// attribute.
2725static bool DeclHasAttr(const Decl *D, const Attr *A) {
2726 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2727 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2728 for (const auto *i : D->attrs())
2729 if (i->getKind() == A->getKind()) {
2730 if (Ann) {
2731 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2732 return true;
2733 continue;
2734 }
2735 // FIXME: Don't hardcode this check
2736 if (OA && isa<OwnershipAttr>(i))
2737 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2738 return true;
2739 }
2740
2741 return false;
2742}
2743
2745 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2746 return VD->isThisDeclarationADefinition();
2747 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2748 return TD->isCompleteDefinition() || TD->isBeingDefined();
2749 return true;
2750}
2751
2752/// Merge alignment attributes from \p Old to \p New, taking into account the
2753/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2754///
2755/// \return \c true if any attributes were added to \p New.
2756static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2757 // Look for alignas attributes on Old, and pick out whichever attribute
2758 // specifies the strictest alignment requirement.
2759 AlignedAttr *OldAlignasAttr = nullptr;
2760 AlignedAttr *OldStrictestAlignAttr = nullptr;
2761 unsigned OldAlign = 0;
2762 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2763 // FIXME: We have no way of representing inherited dependent alignments
2764 // in a case like:
2765 // template<int A, int B> struct alignas(A) X;
2766 // template<int A, int B> struct alignas(B) X {};
2767 // For now, we just ignore any alignas attributes which are not on the
2768 // definition in such a case.
2769 if (I->isAlignmentDependent())
2770 return false;
2771
2772 if (I->isAlignas())
2773 OldAlignasAttr = I;
2774
2775 unsigned Align = I->getAlignment(S.Context);
2776 if (Align > OldAlign) {
2777 OldAlign = Align;
2778 OldStrictestAlignAttr = I;
2779 }
2780 }
2781
2782 // Look for alignas attributes on New.
2783 AlignedAttr *NewAlignasAttr = nullptr;
2784 unsigned NewAlign = 0;
2785 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2786 if (I->isAlignmentDependent())
2787 return false;
2788
2789 if (I->isAlignas())
2790 NewAlignasAttr = I;
2791
2792 unsigned Align = I->getAlignment(S.Context);
2793 if (Align > NewAlign)
2794 NewAlign = Align;
2795 }
2796
2797 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2798 // Both declarations have 'alignas' attributes. We require them to match.
2799 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2800 // fall short. (If two declarations both have alignas, they must both match
2801 // every definition, and so must match each other if there is a definition.)
2802
2803 // If either declaration only contains 'alignas(0)' specifiers, then it
2804 // specifies the natural alignment for the type.
2805 if (OldAlign == 0 || NewAlign == 0) {
2806 QualType Ty;
2807 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2808 Ty = VD->getType();
2809 else
2811
2812 if (OldAlign == 0)
2813 OldAlign = S.Context.getTypeAlign(Ty);
2814 if (NewAlign == 0)
2815 NewAlign = S.Context.getTypeAlign(Ty);
2816 }
2817
2818 if (OldAlign != NewAlign) {
2819 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2822 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2823 }
2824 }
2825
2826 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2827 // C++11 [dcl.align]p6:
2828 // if any declaration of an entity has an alignment-specifier,
2829 // every defining declaration of that entity shall specify an
2830 // equivalent alignment.
2831 // C11 6.7.5/7:
2832 // If the definition of an object does not have an alignment
2833 // specifier, any other declaration of that object shall also
2834 // have no alignment specifier.
2835 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2836 << OldAlignasAttr;
2837 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2838 << OldAlignasAttr;
2839 }
2840
2841 bool AnyAdded = false;
2842
2843 // Ensure we have an attribute representing the strictest alignment.
2844 if (OldAlign > NewAlign) {
2845 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2846 Clone->setInherited(true);
2847 New->addAttr(Clone);
2848 AnyAdded = true;
2849 }
2850
2851 // Ensure we have an alignas attribute if the old declaration had one.
2852 if (OldAlignasAttr && !NewAlignasAttr &&
2853 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2854 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2855 Clone->setInherited(true);
2856 New->addAttr(Clone);
2857 AnyAdded = true;
2858 }
2859
2860 return AnyAdded;
2861}
2862
2863#define WANT_DECL_MERGE_LOGIC
2864#include "clang/Sema/AttrParsedAttrImpl.inc"
2865#undef WANT_DECL_MERGE_LOGIC
2866
2868 const InheritableAttr *Attr,
2870 // Diagnose any mutual exclusions between the attribute that we want to add
2871 // and attributes that already exist on the declaration.
2872 if (!DiagnoseMutualExclusions(S, D, Attr))
2873 return false;
2874
2875 // This function copies an attribute Attr from a previous declaration to the
2876 // new declaration D if the new declaration doesn't itself have that attribute
2877 // yet or if that attribute allows duplicates.
2878 // If you're adding a new attribute that requires logic different from
2879 // "use explicit attribute on decl if present, else use attribute from
2880 // previous decl", for example if the attribute needs to be consistent
2881 // between redeclarations, you need to call a custom merge function here.
2882 InheritableAttr *NewAttr = nullptr;
2883 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2884 NewAttr = S.mergeAvailabilityAttr(
2885 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2886 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2887 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2888 AA->getPriority(), AA->getEnvironment());
2889 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2890 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2891 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2892 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2893 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2894 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2895 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2896 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2897 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2898 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2899 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2900 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2901 FA->getFirstArg());
2902 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2903 NewAttr = S.mergeFormatMatchesAttr(
2904 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2905 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2906 NewAttr = S.mergeModularFormatAttr(
2907 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2908 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2909 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2910 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2911 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2912 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2913 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2914 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2915 IA->getInheritanceModel());
2916 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2917 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2918 &S.Context.Idents.get(AA->getSpelling()));
2919 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2922 // CUDA target attributes are part of function signature for
2923 // overloading purposes and must not be merged.
2924 return false;
2925 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2926 NewAttr = S.mergeMinSizeAttr(D, *MA);
2927 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2928 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2929 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2930 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2931 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2932 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2933 else if (isa<AlignedAttr>(Attr))
2934 // AlignedAttrs are handled separately, because we need to handle all
2935 // such attributes on a declaration at the same time.
2936 NewAttr = nullptr;
2941 NewAttr = nullptr;
2942 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2943 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2944 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2945 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2946 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2947 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2948 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2949 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2950 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2951 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2952 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2953 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2954 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2955 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2956 NT->getZ());
2957 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2958 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2959 WS->getPreferred(),
2960 WS->getSpelledArgsCount());
2961 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2962 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2963 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2964 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2965 else if (isa<SuppressAttr>(Attr))
2966 // Do nothing. Each redeclaration should be suppressed separately.
2967 NewAttr = nullptr;
2968 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2969 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2970 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2971 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2972
2973 if (NewAttr) {
2974 NewAttr->setInherited(true);
2975 D->addAttr(NewAttr);
2976 if (isa<MSInheritanceAttr>(NewAttr))
2978 return true;
2979 }
2980
2981 return false;
2982}
2983
2984static const NamedDecl *getDefinition(const Decl *D) {
2985 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2986 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2987 return Def;
2988 return nullptr;
2989 }
2990 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2991 const VarDecl *Def = VD->getDefinition();
2992 if (Def)
2993 return Def;
2994 return VD->getActingDefinition();
2995 }
2996 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2997 const FunctionDecl *Def = nullptr;
2998 if (FD->isDefined(Def, true))
2999 return Def;
3000 }
3001 return nullptr;
3002}
3003
3004static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3005 for (const auto *Attribute : D->attrs())
3006 if (Attribute->getKind() == Kind)
3007 return true;
3008 return false;
3009}
3010
3011/// checkNewAttributesAfterDef - If we already have a definition, check that
3012/// there are no new attributes in this declaration.
3013static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3014 if (!New->hasAttrs())
3015 return;
3016
3017 const NamedDecl *Def = getDefinition(Old);
3018 if (!Def || Def == New)
3019 return;
3020
3021 AttrVec &NewAttributes = New->getAttrs();
3022 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3023 Attr *NewAttribute = NewAttributes[I];
3024
3025 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3026 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3027 SkipBodyInfo SkipBody;
3028 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3029
3030 // If we're skipping this definition, drop the "alias" attribute.
3031 if (SkipBody.ShouldSkip) {
3032 NewAttributes.erase(NewAttributes.begin() + I);
3033 --E;
3034 continue;
3035 }
3036 } else {
3037 VarDecl *VD = cast<VarDecl>(New);
3038 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3040 ? diag::err_alias_after_tentative
3041 : diag::err_redefinition;
3042 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3043 if (Diag == diag::err_redefinition)
3044 S.notePreviousDefinition(Def, VD->getLocation());
3045 else
3046 S.Diag(Def->getLocation(), diag::note_previous_definition);
3047 VD->setInvalidDecl();
3048 }
3049 ++I;
3050 continue;
3051 }
3052
3053 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3054 // Tentative definitions are only interesting for the alias check above.
3055 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3056 ++I;
3057 continue;
3058 }
3059 }
3060
3061 if (hasAttribute(Def, NewAttribute->getKind())) {
3062 ++I;
3063 continue; // regular attr merging will take care of validating this.
3064 }
3065
3066 if (isa<C11NoReturnAttr>(NewAttribute)) {
3067 // C's _Noreturn is allowed to be added to a function after it is defined.
3068 ++I;
3069 continue;
3070 } else if (isa<UuidAttr>(NewAttribute)) {
3071 // msvc will allow a subsequent definition to add an uuid to a class
3072 ++I;
3073 continue;
3075 NewAttribute) &&
3076 NewAttribute->isStandardAttributeSyntax()) {
3077 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3078 // deprecated attribute can later be re-declared with the attribute and
3079 // vice-versa.
3080 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3081 // maybe_unused attribute can later be redeclared with the attribute and
3082 // vice versa.
3083 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3084 // nodiscard attribute can later be redeclared with the attribute and
3085 // vice-versa.
3086 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3087 ++I;
3088 continue;
3089 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3090 if (AA->isAlignas()) {
3091 // C++11 [dcl.align]p6:
3092 // if any declaration of an entity has an alignment-specifier,
3093 // every defining declaration of that entity shall specify an
3094 // equivalent alignment.
3095 // C11 6.7.5/7:
3096 // If the definition of an object does not have an alignment
3097 // specifier, any other declaration of that object shall also
3098 // have no alignment specifier.
3099 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3100 << AA;
3101 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3102 << AA;
3103 NewAttributes.erase(NewAttributes.begin() + I);
3104 --E;
3105 continue;
3106 }
3107 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3108 // If there is a C definition followed by a redeclaration with this
3109 // attribute then there are two different definitions. In C++, prefer the
3110 // standard diagnostics.
3111 if (!S.getLangOpts().CPlusPlus) {
3112 S.Diag(NewAttribute->getLocation(),
3113 diag::err_loader_uninitialized_redeclaration);
3114 S.Diag(Def->getLocation(), diag::note_previous_definition);
3115 NewAttributes.erase(NewAttributes.begin() + I);
3116 --E;
3117 continue;
3118 }
3119 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3120 cast<VarDecl>(New)->isInline() &&
3121 !cast<VarDecl>(New)->isInlineSpecified()) {
3122 // Don't warn about applying selectany to implicitly inline variables.
3123 // Older compilers and language modes would require the use of selectany
3124 // to make such variables inline, and it would have no effect if we
3125 // honored it.
3126 ++I;
3127 continue;
3128 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3129 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3130 // declarations after definitions.
3131 ++I;
3132 continue;
3133 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3134 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3135 // error since the definition will have already been created without
3136 // the semantic effects of the attribute having been applied.
3137 S.Diag(NewAttribute->getLocation(),
3138 diag::err_sycl_entry_point_after_definition)
3139 << NewAttribute;
3140 S.Diag(Def->getLocation(), diag::note_previous_definition);
3141 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3142 ++I;
3143 continue;
3144 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3145 // SYCLExternalAttr may be added after a definition.
3146 ++I;
3147 continue;
3148 }
3149
3150 S.Diag(NewAttribute->getLocation(),
3151 diag::warn_attribute_precede_definition);
3152 S.Diag(Def->getLocation(), diag::note_previous_definition);
3153 NewAttributes.erase(NewAttributes.begin() + I);
3154 --E;
3155 }
3156}
3157
3158static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3159 const ConstInitAttr *CIAttr,
3160 bool AttrBeforeInit) {
3161 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3162
3163 // Figure out a good way to write this specifier on the old declaration.
3164 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3165 // enough of the attribute list spelling information to extract that without
3166 // heroics.
3167 std::string SuitableSpelling;
3168 if (S.getLangOpts().CPlusPlus20)
3169 SuitableSpelling = std::string(
3170 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3171 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3172 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3173 InsertLoc, {tok::l_square, tok::l_square,
3174 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3175 S.PP.getIdentifierInfo("require_constant_initialization"),
3176 tok::r_square, tok::r_square}));
3177 if (SuitableSpelling.empty())
3178 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3179 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3180 S.PP.getIdentifierInfo("require_constant_initialization"),
3181 tok::r_paren, tok::r_paren}));
3182 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3183 SuitableSpelling = "constinit";
3184 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3185 SuitableSpelling = "[[clang::require_constant_initialization]]";
3186 if (SuitableSpelling.empty())
3187 SuitableSpelling = "__attribute__((require_constant_initialization))";
3188 SuitableSpelling += " ";
3189
3190 if (AttrBeforeInit) {
3191 // extern constinit int a;
3192 // int a = 0; // error (missing 'constinit'), accepted as extension
3193 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3194 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3195 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3196 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3197 } else {
3198 // int a = 0;
3199 // constinit extern int a; // error (missing 'constinit')
3200 S.Diag(CIAttr->getLocation(),
3201 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3202 : diag::warn_require_const_init_added_too_late)
3203 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3204 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3205 << CIAttr->isConstinit()
3206 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3207 }
3208}
3209
3212 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3213 UsedAttr *NewAttr = OldAttr->clone(Context);
3214 NewAttr->setInherited(true);
3215 New->addAttr(NewAttr);
3216 }
3217 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3218 RetainAttr *NewAttr = OldAttr->clone(Context);
3219 NewAttr->setInherited(true);
3220 New->addAttr(NewAttr);
3221 }
3222
3223 if (!Old->hasAttrs() && !New->hasAttrs())
3224 return;
3225
3226 // [dcl.constinit]p1:
3227 // If the [constinit] specifier is applied to any declaration of a
3228 // variable, it shall be applied to the initializing declaration.
3229 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3230 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3231 if (bool(OldConstInit) != bool(NewConstInit)) {
3232 const auto *OldVD = cast<VarDecl>(Old);
3233 auto *NewVD = cast<VarDecl>(New);
3234
3235 // Find the initializing declaration. Note that we might not have linked
3236 // the new declaration into the redeclaration chain yet.
3237 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3238 if (!InitDecl &&
3239 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3240 InitDecl = NewVD;
3241
3242 if (InitDecl == NewVD) {
3243 // This is the initializing declaration. If it would inherit 'constinit',
3244 // that's ill-formed. (Note that we do not apply this to the attribute
3245 // form).
3246 if (OldConstInit && OldConstInit->isConstinit())
3247 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3248 /*AttrBeforeInit=*/true);
3249 } else if (NewConstInit) {
3250 // This is the first time we've been told that this declaration should
3251 // have a constant initializer. If we already saw the initializing
3252 // declaration, this is too late.
3253 if (InitDecl && InitDecl != NewVD) {
3254 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3255 /*AttrBeforeInit=*/false);
3256 NewVD->dropAttr<ConstInitAttr>();
3257 }
3258 }
3259 }
3260
3261 // Attributes declared post-definition are currently ignored.
3262 checkNewAttributesAfterDef(*this, New, Old);
3263
3264 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3265 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3266 if (!OldA->isEquivalent(NewA)) {
3267 // This redeclaration changes __asm__ label.
3268 Diag(New->getLocation(), diag::err_different_asm_label);
3269 Diag(OldA->getLocation(), diag::note_previous_declaration);
3270 }
3271 } else if (Old->isUsed()) {
3272 // This redeclaration adds an __asm__ label to a declaration that has
3273 // already been ODR-used.
3274 Diag(New->getLocation(), diag::err_late_asm_label_name)
3275 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3276 }
3277 }
3278
3279 // Re-declaration cannot add abi_tag's.
3280 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3281 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3282 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3283 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3284 Diag(NewAbiTagAttr->getLocation(),
3285 diag::err_new_abi_tag_on_redeclaration)
3286 << NewTag;
3287 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3288 }
3289 }
3290 } else {
3291 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3292 Diag(Old->getLocation(), diag::note_previous_declaration);
3293 }
3294 }
3295
3296 // This redeclaration adds a section attribute.
3297 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3298 if (auto *VD = dyn_cast<VarDecl>(New)) {
3299 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3300 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3301 Diag(Old->getLocation(), diag::note_previous_declaration);
3302 }
3303 }
3304 }
3305
3306 // Redeclaration adds code-seg attribute.
3307 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3308 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3309 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3310 Diag(New->getLocation(), diag::warn_mismatched_section)
3311 << 0 /*codeseg*/;
3312 Diag(Old->getLocation(), diag::note_previous_declaration);
3313 }
3314
3315 if (!Old->hasAttrs())
3316 return;
3317
3318 bool foundAny = New->hasAttrs();
3319
3320 // Ensure that any moving of objects within the allocated map is done before
3321 // we process them.
3322 if (!foundAny) New->setAttrs(AttrVec());
3323
3324 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3325 // Ignore deprecated/unavailable/availability attributes if requested.
3327 if (isa<DeprecatedAttr>(I) ||
3330 switch (AMK) {
3332 continue;
3333
3338 LocalAMK = AMK;
3339 break;
3340 }
3341 }
3342
3343 // Already handled.
3344 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3345 continue;
3346
3348 if (auto *FD = dyn_cast<FunctionDecl>(New);
3349 FD &&
3350 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3351 continue; // Don't propagate inferred noreturn attributes to explicit
3352 }
3353
3354 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3355 foundAny = true;
3356 }
3357
3358 if (mergeAlignedAttrs(*this, New, Old))
3359 foundAny = true;
3360
3361 if (!foundAny) New->dropAttrs();
3362}
3363
3365 for (const Attr *A : D->attrs())
3366 checkAttrIsTypeDependent(D, A);
3367}
3368
3369// Returns the number of added attributes.
3370template <class T>
3371static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3372 Sema &S) {
3373 unsigned found = 0;
3374 for (const auto *I : From->specific_attrs<T>()) {
3375 if (!DeclHasAttr(To, I)) {
3376 T *newAttr = cast<T>(I->clone(S.Context));
3377 newAttr->setInherited(true);
3378 To->addAttr(newAttr);
3379 ++found;
3380 }
3381 }
3382 return found;
3383}
3384
3385template <class F>
3386static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3387 F &&propagator) {
3388 if (!From->hasAttrs()) {
3389 return;
3390 }
3391
3392 bool foundAny = To->hasAttrs();
3393
3394 // Ensure that any moving of objects within the allocated map is
3395 // done before we process them.
3396 if (!foundAny)
3397 To->setAttrs(AttrVec());
3398
3399 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3400
3401 if (!foundAny)
3402 To->dropAttrs();
3403}
3404
3405/// mergeParamDeclAttributes - Copy attributes from the old parameter
3406/// to the new one.
3408 const ParmVarDecl *oldDecl,
3409 Sema &S) {
3410 // C++11 [dcl.attr.depend]p2:
3411 // The first declaration of a function shall specify the
3412 // carries_dependency attribute for its declarator-id if any declaration
3413 // of the function specifies the carries_dependency attribute.
3414 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3415 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3416 S.Diag(CDA->getLocation(),
3417 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3418 // Find the first declaration of the parameter.
3419 // FIXME: Should we build redeclaration chains for function parameters?
3420 const FunctionDecl *FirstFD =
3421 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3422 const ParmVarDecl *FirstVD =
3423 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3424 S.Diag(FirstVD->getLocation(),
3425 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3426 }
3427
3429 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3430 unsigned found = 0;
3431 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3432 // Propagate the lifetimebound attribute from parameters to the
3433 // most recent declaration. Note that this doesn't include the implicit
3434 // 'this' parameter, as the attribute is applied to the function type in
3435 // that case.
3436 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3437 return found;
3438 });
3439}
3440
3442 const ASTContext &Ctx) {
3443
3444 auto NoSizeInfo = [&Ctx](QualType Ty) {
3445 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3446 return true;
3447 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3448 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3449 return false;
3450 };
3451
3452 // `type[]` is equivalent to `type *` and `type[*]`.
3453 if (NoSizeInfo(Old) && NoSizeInfo(New))
3454 return true;
3455
3456 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3457 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3458 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3459 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3460 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3461 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3462 return false;
3463 return true;
3464 }
3465
3466 // Only compare size, ignore Size modifiers and CVR.
3467 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3468 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3470 }
3471
3472 // Don't try to compare dependent sized array
3473 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3474 return true;
3475 }
3476
3477 return Old == New;
3478}
3479
3480static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3481 const ParmVarDecl *OldParam,
3482 Sema &S) {
3483 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3484 if (auto Newnullability = NewParam->getType()->getNullability()) {
3485 if (*Oldnullability != *Newnullability) {
3486 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3488 *Newnullability,
3490 != 0))
3492 *Oldnullability,
3494 != 0));
3495 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3496 }
3497 } else {
3498 QualType NewT = NewParam->getType();
3499 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3500 NewParam->setType(NewT);
3501 }
3502 }
3503 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3504 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3505 if (OldParamDT && NewParamDT &&
3506 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3507 QualType OldParamOT = OldParamDT->getOriginalType();
3508 QualType NewParamOT = NewParamDT->getOriginalType();
3509 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3510 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3511 << NewParam << NewParamOT;
3512 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3513 << OldParamOT;
3514 }
3515 }
3516}
3517
3518namespace {
3519
3520/// Used in MergeFunctionDecl to keep track of function parameters in
3521/// C.
3522struct GNUCompatibleParamWarning {
3523 ParmVarDecl *OldParm;
3524 ParmVarDecl *NewParm;
3525 QualType PromotedType;
3526};
3527
3528} // end anonymous namespace
3529
3530// Determine whether the previous declaration was a definition, implicit
3531// declaration, or a declaration.
3532template <typename T>
3533static std::pair<diag::kind, SourceLocation>
3535 diag::kind PrevDiag;
3536 SourceLocation OldLocation = Old->getLocation();
3537 if (Old->isThisDeclarationADefinition())
3538 PrevDiag = diag::note_previous_definition;
3539 else if (Old->isImplicit()) {
3540 PrevDiag = diag::note_previous_implicit_declaration;
3541 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3542 if (FD->getBuiltinID())
3543 PrevDiag = diag::note_previous_builtin_declaration;
3544 }
3545 if (OldLocation.isInvalid())
3546 OldLocation = New->getLocation();
3547 } else
3548 PrevDiag = diag::note_previous_declaration;
3549 return std::make_pair(PrevDiag, OldLocation);
3550}
3551
3552/// canRedefineFunction - checks if a function can be redefined. Currently,
3553/// only extern inline functions can be redefined, and even then only in
3554/// GNU89 mode.
3555static bool canRedefineFunction(const FunctionDecl *FD,
3556 const LangOptions& LangOpts) {
3557 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3558 !LangOpts.CPlusPlus &&
3559 FD->isInlineSpecified() &&
3560 FD->getStorageClass() == SC_Extern);
3561}
3562
3563const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3564 const AttributedType *AT = T->getAs<AttributedType>();
3565 while (AT && !AT->isCallingConv())
3566 AT = AT->getModifiedType()->getAs<AttributedType>();
3567 return AT;
3568}
3569
3570template <typename T>
3571static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3572 const DeclContext *DC = Old->getDeclContext();
3573 if (DC->isRecord())
3574 return false;
3575
3576 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3577 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3578 return true;
3579 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3580 return true;
3581 return false;
3582}
3583
3584template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3585static bool isExternC(VarTemplateDecl *) { return false; }
3586static bool isExternC(FunctionTemplateDecl *) { return false; }
3587
3588/// Check whether a redeclaration of an entity introduced by a
3589/// using-declaration is valid, given that we know it's not an overload
3590/// (nor a hidden tag declaration).
3591template<typename ExpectedDecl>
3593 ExpectedDecl *New) {
3594 // C++11 [basic.scope.declarative]p4:
3595 // Given a set of declarations in a single declarative region, each of
3596 // which specifies the same unqualified name,
3597 // -- they shall all refer to the same entity, or all refer to functions
3598 // and function templates; or
3599 // -- exactly one declaration shall declare a class name or enumeration
3600 // name that is not a typedef name and the other declarations shall all
3601 // refer to the same variable or enumerator, or all refer to functions
3602 // and function templates; in this case the class name or enumeration
3603 // name is hidden (3.3.10).
3604
3605 // C++11 [namespace.udecl]p14:
3606 // If a function declaration in namespace scope or block scope has the
3607 // same name and the same parameter-type-list as a function introduced
3608 // by a using-declaration, and the declarations do not declare the same
3609 // function, the program is ill-formed.
3610
3611 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3612 if (Old &&
3613 !Old->getDeclContext()->getRedeclContext()->Equals(
3614 New->getDeclContext()->getRedeclContext()) &&
3615 !(isExternC(Old) && isExternC(New)))
3616 Old = nullptr;
3617
3618 if (!Old) {
3619 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3620 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3621 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3622 return true;
3623 }
3624 return false;
3625}
3626
3628 const FunctionDecl *B) {
3629 assert(A->getNumParams() == B->getNumParams());
3630
3631 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3632 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3633 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3634 if (AttrA == AttrB)
3635 return true;
3636 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3637 AttrA->isDynamic() == AttrB->isDynamic();
3638 };
3639
3640 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3641}
3642
3643/// If necessary, adjust the semantic declaration context for a qualified
3644/// declaration to name the correct inline namespace within the qualifier.
3646 DeclaratorDecl *OldD) {
3647 // The only case where we need to update the DeclContext is when
3648 // redeclaration lookup for a qualified name finds a declaration
3649 // in an inline namespace within the context named by the qualifier:
3650 //
3651 // inline namespace N { int f(); }
3652 // int ::f(); // Sema DC needs adjusting from :: to N::.
3653 //
3654 // For unqualified declarations, the semantic context *can* change
3655 // along the redeclaration chain (for local extern declarations,
3656 // extern "C" declarations, and friend declarations in particular).
3657 if (!NewD->getQualifier())
3658 return;
3659
3660 // NewD is probably already in the right context.
3661 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3662 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3663 if (NamedDC->Equals(SemaDC))
3664 return;
3665
3666 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3667 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3668 "unexpected context for redeclaration");
3669
3670 auto *LexDC = NewD->getLexicalDeclContext();
3671 auto FixSemaDC = [=](NamedDecl *D) {
3672 if (!D)
3673 return;
3674 D->setDeclContext(SemaDC);
3675 D->setLexicalDeclContext(LexDC);
3676 };
3677
3678 FixSemaDC(NewD);
3679 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3680 FixSemaDC(FD->getDescribedFunctionTemplate());
3681 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3682 FixSemaDC(VD->getDescribedVarTemplate());
3683}
3684
3686 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3687 // Verify the old decl was also a function.
3688 FunctionDecl *Old = OldD->getAsFunction();
3689 if (!Old) {
3690 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3691 // We don't need to check the using friend pattern from other module unit
3692 // since we should have diagnosed such cases in its unit already.
3693 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3694 Diag(New->getLocation(), diag::err_using_decl_friend);
3695 Diag(Shadow->getTargetDecl()->getLocation(),
3696 diag::note_using_decl_target);
3697 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3698 << 0;
3699 return true;
3700 }
3701
3702 // Check whether the two declarations might declare the same function or
3703 // function template.
3704 if (FunctionTemplateDecl *NewTemplate =
3705 New->getDescribedFunctionTemplate()) {
3707 NewTemplate))
3708 return true;
3709 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3710 ->getAsFunction();
3711 } else {
3712 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3713 return true;
3714 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3715 }
3716 } else {
3717 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3718 << New->getDeclName();
3719 notePreviousDefinition(OldD, New->getLocation());
3720 return true;
3721 }
3722 }
3723
3724 // If the old declaration was found in an inline namespace and the new
3725 // declaration was qualified, update the DeclContext to match.
3727
3728 // If the old declaration is invalid, just give up here.
3729 if (Old->isInvalidDecl())
3730 return true;
3731
3732 // Disallow redeclaration of some builtins.
3733 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3734 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3735 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3736 << Old << Old->getType();
3737 return true;
3738 }
3739
3740 diag::kind PrevDiag;
3741 SourceLocation OldLocation;
3742 std::tie(PrevDiag, OldLocation) =
3744
3745 // Don't complain about this if we're in GNU89 mode and the old function
3746 // is an extern inline function.
3747 // Don't complain about specializations. They are not supposed to have
3748 // storage classes.
3749 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3750 New->getStorageClass() == SC_Static &&
3751 Old->hasExternalFormalLinkage() &&
3752 !New->getTemplateSpecializationInfo() &&
3754 if (getLangOpts().MicrosoftExt) {
3755 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3756 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3757 } else {
3758 Diag(New->getLocation(), diag::err_static_non_static) << New;
3759 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3760 return true;
3761 }
3762 }
3763
3764 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3765 if (!Old->hasAttr<InternalLinkageAttr>()) {
3766 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3767 << ILA;
3768 Diag(Old->getLocation(), diag::note_previous_declaration);
3769 New->dropAttr<InternalLinkageAttr>();
3770 }
3771
3772 if (auto *EA = New->getAttr<ErrorAttr>()) {
3773 if (!Old->hasAttr<ErrorAttr>()) {
3774 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3775 Diag(Old->getLocation(), diag::note_previous_declaration);
3776 New->dropAttr<ErrorAttr>();
3777 }
3778 }
3779
3781 return true;
3782
3783 if (!getLangOpts().CPlusPlus) {
3784 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3785 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3786 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3787 << New << OldOvl;
3788
3789 // Try our best to find a decl that actually has the overloadable
3790 // attribute for the note. In most cases (e.g. programs with only one
3791 // broken declaration/definition), this won't matter.
3792 //
3793 // FIXME: We could do this if we juggled some extra state in
3794 // OverloadableAttr, rather than just removing it.
3795 const Decl *DiagOld = Old;
3796 if (OldOvl) {
3797 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3798 const auto *A = D->getAttr<OverloadableAttr>();
3799 return A && !A->isImplicit();
3800 });
3801 // If we've implicitly added *all* of the overloadable attrs to this
3802 // chain, emitting a "previous redecl" note is pointless.
3803 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3804 }
3805
3806 if (DiagOld)
3807 Diag(DiagOld->getLocation(),
3808 diag::note_attribute_overloadable_prev_overload)
3809 << OldOvl;
3810
3811 if (OldOvl)
3812 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3813 else
3814 New->dropAttr<OverloadableAttr>();
3815 }
3816 }
3817
3818 // It is not permitted to redeclare an SME function with different SME
3819 // attributes.
3820 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3821 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3822 << New->getType() << Old->getType();
3823 Diag(OldLocation, diag::note_previous_declaration);
3824 return true;
3825 }
3826
3827 // If a function is first declared with a calling convention, but is later
3828 // declared or defined without one, all following decls assume the calling
3829 // convention of the first.
3830 //
3831 // It's OK if a function is first declared without a calling convention,
3832 // but is later declared or defined with the default calling convention.
3833 //
3834 // To test if either decl has an explicit calling convention, we look for
3835 // AttributedType sugar nodes on the type as written. If they are missing or
3836 // were canonicalized away, we assume the calling convention was implicit.
3837 //
3838 // Note also that we DO NOT return at this point, because we still have
3839 // other tests to run.
3840 QualType OldQType = Context.getCanonicalType(Old->getType());
3841 QualType NewQType = Context.getCanonicalType(New->getType());
3842 const FunctionType *OldType = cast<FunctionType>(OldQType);
3843 const FunctionType *NewType = cast<FunctionType>(NewQType);
3844 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3845 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3846 bool RequiresAdjustment = false;
3847
3848 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3850 const FunctionType *FT =
3851 First->getType().getCanonicalType()->castAs<FunctionType>();
3853 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3854 if (!NewCCExplicit) {
3855 // Inherit the CC from the previous declaration if it was specified
3856 // there but not here.
3857 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3858 RequiresAdjustment = true;
3859 } else if (Old->getBuiltinID()) {
3860 // Builtin attribute isn't propagated to the new one yet at this point,
3861 // so we check if the old one is a builtin.
3862
3863 // Calling Conventions on a Builtin aren't really useful and setting a
3864 // default calling convention and cdecl'ing some builtin redeclarations is
3865 // common, so warn and ignore the calling convention on the redeclaration.
3866 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3867 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3869 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3870 RequiresAdjustment = true;
3871 } else {
3872 // Calling conventions aren't compatible, so complain.
3873 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3874 Diag(New->getLocation(), diag::err_cconv_change)
3875 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3876 << !FirstCCExplicit
3877 << (!FirstCCExplicit ? "" :
3879
3880 // Put the note on the first decl, since it is the one that matters.
3881 Diag(First->getLocation(), diag::note_previous_declaration);
3882 return true;
3883 }
3884 }
3885
3886 // FIXME: diagnose the other way around?
3887 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3888 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3889 RequiresAdjustment = true;
3890 }
3891
3892 // If the declaration is marked with cfi_unchecked_callee but the definition
3893 // isn't, the definition is also cfi_unchecked_callee.
3894 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3895 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3896 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3897 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3898
3899 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3900 EPI2.CFIUncheckedCallee = true;
3901 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3902 FPT2->getParamTypes(), EPI2);
3903 NewType = cast<FunctionType>(NewQType);
3904 New->setType(NewQType);
3905 }
3906 }
3907 }
3908
3909 // Merge regparm attribute.
3910 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3911 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3912 if (NewTypeInfo.getHasRegParm()) {
3913 Diag(New->getLocation(), diag::err_regparm_mismatch)
3914 << NewType->getRegParmType()
3915 << OldType->getRegParmType();
3916 Diag(OldLocation, diag::note_previous_declaration);
3917 return true;
3918 }
3919
3920 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3921 RequiresAdjustment = true;
3922 }
3923
3924 // Merge ns_returns_retained attribute.
3925 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3926 if (NewTypeInfo.getProducesResult()) {
3927 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3928 << "'ns_returns_retained'";
3929 Diag(OldLocation, diag::note_previous_declaration);
3930 return true;
3931 }
3932
3933 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3934 RequiresAdjustment = true;
3935 }
3936
3937 if (OldTypeInfo.getNoCallerSavedRegs() !=
3938 NewTypeInfo.getNoCallerSavedRegs()) {
3939 if (NewTypeInfo.getNoCallerSavedRegs()) {
3940 AnyX86NoCallerSavedRegistersAttr *Attr =
3941 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3942 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3943 Diag(OldLocation, diag::note_previous_declaration);
3944 return true;
3945 }
3946
3947 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3948 RequiresAdjustment = true;
3949 }
3950
3951 if (RequiresAdjustment) {
3952 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3953 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3954 New->setType(QualType(AdjustedType, 0));
3955 NewQType = Context.getCanonicalType(New->getType());
3956 }
3957
3958 // If this redeclaration makes the function inline, we may need to add it to
3959 // UndefinedButUsed.
3960 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3961 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3962 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3963 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3964 SourceLocation()));
3965
3966 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3967 // about it.
3968 if (New->hasAttr<GNUInlineAttr>() &&
3969 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3970 UndefinedButUsed.erase(Old->getCanonicalDecl());
3971 }
3972
3973 // If pass_object_size params don't match up perfectly, this isn't a valid
3974 // redeclaration.
3975 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3977 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3978 << New->getDeclName();
3979 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3980 return true;
3981 }
3982
3983 QualType OldQTypeForComparison = OldQType;
3984 if (Context.hasAnyFunctionEffects()) {
3985 const auto OldFX = Old->getFunctionEffects();
3986 const auto NewFX = New->getFunctionEffects();
3987 if (OldFX != NewFX) {
3988 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3989 for (const auto &Diff : Diffs) {
3990 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3991 Diag(New->getLocation(),
3992 diag::warn_mismatched_func_effect_redeclaration)
3993 << Diff.effectName();
3994 Diag(Old->getLocation(), diag::note_previous_declaration);
3995 }
3996 }
3997 // Following a warning, we could skip merging effects from the previous
3998 // declaration, but that would trigger an additional "conflicting types"
3999 // error.
4000 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4002 FunctionEffectSet MergedFX =
4003 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4004 if (!MergeErrs.empty())
4005 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4006 Old->getLocation());
4007
4008 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4009 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4010 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4011 NewFPT->getParamTypes(), EPI);
4012
4013 New->setType(ModQT);
4014 NewQType = New->getType();
4015
4016 // Revise OldQTForComparison to include the merged effects,
4017 // so as not to fail due to differences later.
4018 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4019 EPI = OldFPT->getExtProtoInfo();
4020 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4021 OldQTypeForComparison = Context.getFunctionType(
4022 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4023 }
4024 if (OldFX.empty()) {
4025 // A redeclaration may add the attribute to a previously seen function
4026 // body which needs to be verified.
4027 maybeAddDeclWithEffects(Old, MergedFX);
4028 }
4029 }
4030 }
4031 }
4032
4033 if (getLangOpts().CPlusPlus) {
4034 OldQType = Context.getCanonicalType(Old->getType());
4035 NewQType = Context.getCanonicalType(New->getType());
4036
4037 // Go back to the type source info to compare the declared return types,
4038 // per C++1y [dcl.type.auto]p13:
4039 // Redeclarations or specializations of a function or function template
4040 // with a declared return type that uses a placeholder type shall also
4041 // use that placeholder, not a deduced type.
4042 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4043 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4044 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4045 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4046 OldDeclaredReturnType)) {
4047 QualType ResQT;
4048 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4049 OldDeclaredReturnType->isObjCObjectPointerType())
4050 // FIXME: This does the wrong thing for a deduced return type.
4051 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4052 if (ResQT.isNull()) {
4053 if (New->isCXXClassMember() && New->isOutOfLine())
4054 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4055 << New << New->getReturnTypeSourceRange();
4056 else if (Old->isExternC() && New->isExternC() &&
4057 !Old->hasAttr<OverloadableAttr>() &&
4058 !New->hasAttr<OverloadableAttr>())
4059 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4060 else
4061 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4062 << New->getReturnTypeSourceRange();
4063 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4064 << Old->getReturnTypeSourceRange();
4065 return true;
4066 }
4067 else
4068 NewQType = ResQT;
4069 }
4070
4071 QualType OldReturnType = OldType->getReturnType();
4072 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4073 if (OldReturnType != NewReturnType) {
4074 // If this function has a deduced return type and has already been
4075 // defined, copy the deduced value from the old declaration.
4076 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4077 if (OldAT && OldAT->isDeduced()) {
4078 QualType DT = OldAT->getDeducedType();
4079 if (DT.isNull()) {
4080 New->setType(SubstAutoTypeDependent(New->getType()));
4081 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4082 } else {
4083 New->setType(SubstAutoType(New->getType(), DT));
4084 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4085 }
4086 }
4087 }
4088
4089 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4090 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4091 if (OldMethod && NewMethod) {
4092 // Preserve triviality.
4093 NewMethod->setTrivial(OldMethod->isTrivial());
4094
4095 // MSVC allows explicit template specialization at class scope:
4096 // 2 CXXMethodDecls referring to the same function will be injected.
4097 // We don't want a redeclaration error.
4098 bool IsClassScopeExplicitSpecialization =
4099 OldMethod->isFunctionTemplateSpecialization() &&
4101 bool isFriend = NewMethod->getFriendObjectKind();
4102
4103 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4104 !IsClassScopeExplicitSpecialization) {
4105 // -- Member function declarations with the same name and the
4106 // same parameter types cannot be overloaded if any of them
4107 // is a static member function declaration.
4108 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4109 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4110 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4111 return true;
4112 }
4113
4114 // C++ [class.mem]p1:
4115 // [...] A member shall not be declared twice in the
4116 // member-specification, except that a nested class or member
4117 // class template can be declared and then later defined.
4118 if (!inTemplateInstantiation()) {
4119 unsigned NewDiag;
4120 if (isa<CXXConstructorDecl>(OldMethod))
4121 NewDiag = diag::err_constructor_redeclared;
4122 else if (isa<CXXDestructorDecl>(NewMethod))
4123 NewDiag = diag::err_destructor_redeclared;
4124 else if (isa<CXXConversionDecl>(NewMethod))
4125 NewDiag = diag::err_conv_function_redeclared;
4126 else
4127 NewDiag = diag::err_member_redeclared;
4128
4129 Diag(New->getLocation(), NewDiag);
4130 } else {
4131 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4132 << New << New->getType();
4133 }
4134 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4135 return true;
4136
4137 // Complain if this is an explicit declaration of a special
4138 // member that was initially declared implicitly.
4139 //
4140 // As an exception, it's okay to befriend such methods in order
4141 // to permit the implicit constructor/destructor/operator calls.
4142 } else if (OldMethod->isImplicit()) {
4143 if (isFriend) {
4144 NewMethod->setImplicit();
4145 } else {
4146 Diag(NewMethod->getLocation(),
4147 diag::err_definition_of_implicitly_declared_member)
4148 << New << getSpecialMember(OldMethod);
4149 return true;
4150 }
4151 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4152 Diag(NewMethod->getLocation(),
4153 diag::err_definition_of_explicitly_defaulted_member)
4154 << getSpecialMember(OldMethod);
4155 return true;
4156 }
4157 }
4158
4159 // C++1z [over.load]p2
4160 // Certain function declarations cannot be overloaded:
4161 // -- Function declarations that differ only in the return type,
4162 // the exception specification, or both cannot be overloaded.
4163
4164 // Check the exception specifications match. This may recompute the type of
4165 // both Old and New if it resolved exception specifications, so grab the
4166 // types again after this. Because this updates the type, we do this before
4167 // any of the other checks below, which may update the "de facto" NewQType
4168 // but do not necessarily update the type of New.
4170 return true;
4171
4172 // C++11 [dcl.attr.noreturn]p1:
4173 // The first declaration of a function shall specify the noreturn
4174 // attribute if any declaration of that function specifies the noreturn
4175 // attribute.
4176 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4177 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4178 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4179 << NRA;
4180 Diag(Old->getLocation(), diag::note_previous_declaration);
4181 }
4182
4183 // C++11 [dcl.attr.depend]p2:
4184 // The first declaration of a function shall specify the
4185 // carries_dependency attribute for its declarator-id if any declaration
4186 // of the function specifies the carries_dependency attribute.
4187 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4188 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4189 Diag(CDA->getLocation(),
4190 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4191 Diag(Old->getFirstDecl()->getLocation(),
4192 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4193 }
4194
4195 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4196 // When a function is declared with SYCL_EXTERNAL, that macro must be
4197 // used on the first declaration of that function in the translation unit.
4198 // Redeclarations of the function in the same translation unit may
4199 // optionally use SYCL_EXTERNAL, but this is not required.
4200 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4201 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4202 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4203 << SEA;
4204 Diag(Old->getLocation(), diag::note_previous_declaration);
4205 }
4206
4207 // (C++98 8.3.5p3):
4208 // All declarations for a function shall agree exactly in both the
4209 // return type and the parameter-type-list.
4210 // We also want to respect all the extended bits except noreturn.
4211
4212 // noreturn should now match unless the old type info didn't have it.
4213 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4214 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4215 const FunctionType *OldTypeForComparison
4216 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4217 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4218 assert(OldQTypeForComparison.isCanonical());
4219 }
4220
4222 // As a special case, retain the language linkage from previous
4223 // declarations of a friend function as an extension.
4224 //
4225 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4226 // and is useful because there's otherwise no way to specify language
4227 // linkage within class scope.
4228 //
4229 // Check cautiously as the friend object kind isn't yet complete.
4230 if (New->getFriendObjectKind() != Decl::FOK_None) {
4231 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4232 Diag(OldLocation, PrevDiag);
4233 } else {
4234 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4235 Diag(OldLocation, PrevDiag);
4236 return true;
4237 }
4238 }
4239
4240 // HLSL check parameters for matching ABI specifications.
4241 if (getLangOpts().HLSL) {
4242 if (HLSL().CheckCompatibleParameterABI(New, Old))
4243 return true;
4244
4245 // If no errors are generated when checking parameter ABIs we can check if
4246 // the two declarations have the same type ignoring the ABIs and if so,
4247 // the declarations can be merged. This case for merging is only valid in
4248 // HLSL because there are no valid cases of merging mismatched parameter
4249 // ABIs except the HLSL implicit in and explicit in.
4250 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4251 NewQType))
4252 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4253 // Fall through for conflicting redeclarations and redefinitions.
4254 }
4255
4256 // If the function types are compatible, merge the declarations. Ignore the
4257 // exception specifier because it was already checked above in
4258 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4259 // about incompatible types under -fms-compatibility.
4260 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4261 NewQType))
4262 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4263
4264 // If the types are imprecise (due to dependent constructs in friends or
4265 // local extern declarations), it's OK if they differ. We'll check again
4266 // during instantiation.
4267 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4268 return false;
4269
4270 // Fall through for conflicting redeclarations and redefinitions.
4271 }
4272
4273 // C: Function types need to be compatible, not identical. This handles
4274 // duplicate function decls like "void f(int); void f(enum X);" properly.
4275 if (!getLangOpts().CPlusPlus) {
4276 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4277 // type is specified by a function definition that contains a (possibly
4278 // empty) identifier list, both shall agree in the number of parameters
4279 // and the type of each parameter shall be compatible with the type that
4280 // results from the application of default argument promotions to the
4281 // type of the corresponding identifier. ...
4282 // This cannot be handled by ASTContext::typesAreCompatible() because that
4283 // doesn't know whether the function type is for a definition or not when
4284 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4285 // we need to cover here is that the number of arguments agree as the
4286 // default argument promotion rules were already checked by
4287 // ASTContext::typesAreCompatible().
4288 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4289 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4290 if (Old->hasInheritedPrototype())
4291 Old = Old->getCanonicalDecl();
4292 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4293 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4294 return true;
4295 }
4296
4297 // If we are merging two functions where only one of them has a prototype,
4298 // we may have enough information to decide to issue a diagnostic that the
4299 // function without a prototype will change behavior in C23. This handles
4300 // cases like:
4301 // void i(); void i(int j);
4302 // void i(int j); void i();
4303 // void i(); void i(int j) {}
4304 // See ActOnFinishFunctionBody() for other cases of the behavior change
4305 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4306 // type without a prototype.
4307 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4308 !New->isImplicit() && !Old->isImplicit()) {
4309 const FunctionDecl *WithProto, *WithoutProto;
4310 if (New->hasWrittenPrototype()) {
4311 WithProto = New;
4312 WithoutProto = Old;
4313 } else {
4314 WithProto = Old;
4315 WithoutProto = New;
4316 }
4317
4318 if (WithProto->getNumParams() != 0) {
4319 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4320 // The one without the prototype will be changing behavior in C23, so
4321 // warn about that one so long as it's a user-visible declaration.
4322 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4323 if (WithoutProto == New)
4324 IsWithoutProtoADef = NewDeclIsDefn;
4325 else
4326 IsWithProtoADef = NewDeclIsDefn;
4327 Diag(WithoutProto->getLocation(),
4328 diag::warn_non_prototype_changes_behavior)
4329 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4330 << (WithoutProto == Old) << IsWithProtoADef;
4331
4332 // The reason the one without the prototype will be changing behavior
4333 // is because of the one with the prototype, so note that so long as
4334 // it's a user-visible declaration. There is one exception to this:
4335 // when the new declaration is a definition without a prototype, the
4336 // old declaration with a prototype is not the cause of the issue,
4337 // and that does not need to be noted because the one with a
4338 // prototype will not change behavior in C23.
4339 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4340 !IsWithoutProtoADef)
4341 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4342 }
4343 }
4344 }
4345
4346 if (Context.typesAreCompatible(OldQType, NewQType)) {
4347 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4348 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4349 const FunctionProtoType *OldProto = nullptr;
4350 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4351 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4352 // The old declaration provided a function prototype, but the
4353 // new declaration does not. Merge in the prototype.
4354 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4355 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4356 OldProto->getParamTypes(),
4357 OldProto->getExtProtoInfo());
4358 New->setType(NewQType);
4359 New->setHasInheritedPrototype();
4360
4361 // Synthesize parameters with the same types.
4363 for (const auto &ParamType : OldProto->param_types()) {
4365 Context, New, SourceLocation(), SourceLocation(), nullptr,
4366 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4367 Param->setScopeInfo(0, Params.size());
4368 Param->setImplicit();
4369 Params.push_back(Param);
4370 }
4371
4372 New->setParams(Params);
4373 }
4374
4375 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4376 }
4377 }
4378
4379 // Check if the function types are compatible when pointer size address
4380 // spaces are ignored.
4381 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4382 return false;
4383
4384 // GNU C permits a K&R definition to follow a prototype declaration
4385 // if the declared types of the parameters in the K&R definition
4386 // match the types in the prototype declaration, even when the
4387 // promoted types of the parameters from the K&R definition differ
4388 // from the types in the prototype. GCC then keeps the types from
4389 // the prototype.
4390 //
4391 // If a variadic prototype is followed by a non-variadic K&R definition,
4392 // the K&R definition becomes variadic. This is sort of an edge case, but
4393 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4394 // C99 6.9.1p8.
4395 if (!getLangOpts().CPlusPlus &&
4396 Old->hasPrototype() && !New->hasPrototype() &&
4397 New->getType()->getAs<FunctionProtoType>() &&
4398 Old->getNumParams() == New->getNumParams()) {
4401 const FunctionProtoType *OldProto
4402 = Old->getType()->getAs<FunctionProtoType>();
4403 const FunctionProtoType *NewProto
4404 = New->getType()->getAs<FunctionProtoType>();
4405
4406 // Determine whether this is the GNU C extension.
4407 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4408 NewProto->getReturnType());
4409 bool LooseCompatible = !MergedReturn.isNull();
4410 for (unsigned Idx = 0, End = Old->getNumParams();
4411 LooseCompatible && Idx != End; ++Idx) {
4412 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4413 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4414 if (Context.typesAreCompatible(OldParm->getType(),
4415 NewProto->getParamType(Idx))) {
4416 ArgTypes.push_back(NewParm->getType());
4417 } else if (Context.typesAreCompatible(OldParm->getType(),
4418 NewParm->getType(),
4419 /*CompareUnqualified=*/true)) {
4420 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4421 NewProto->getParamType(Idx) };
4422 Warnings.push_back(Warn);
4423 ArgTypes.push_back(NewParm->getType());
4424 } else
4425 LooseCompatible = false;
4426 }
4427
4428 if (LooseCompatible) {
4429 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4430 Diag(Warnings[Warn].NewParm->getLocation(),
4431 diag::ext_param_promoted_not_compatible_with_prototype)
4432 << Warnings[Warn].PromotedType
4433 << Warnings[Warn].OldParm->getType();
4434 if (Warnings[Warn].OldParm->getLocation().isValid())
4435 Diag(Warnings[Warn].OldParm->getLocation(),
4436 diag::note_previous_declaration);
4437 }
4438
4439 if (MergeTypeWithOld)
4440 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4441 OldProto->getExtProtoInfo()));
4442 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4443 }
4444
4445 // Fall through to diagnose conflicting types.
4446 }
4447
4448 // A function that has already been declared has been redeclared or
4449 // defined with a different type; show an appropriate diagnostic.
4450
4451 // If the previous declaration was an implicitly-generated builtin
4452 // declaration, then at the very least we should use a specialized note.
4453 unsigned BuiltinID;
4454 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4455 // If it's actually a library-defined builtin function like 'malloc'
4456 // or 'printf', just warn about the incompatible redeclaration.
4457 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4458 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4459 Diag(OldLocation, diag::note_previous_builtin_declaration)
4460 << Old << Old->getType();
4461 return false;
4462 }
4463
4464 PrevDiag = diag::note_previous_builtin_declaration;
4465 }
4466
4467 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4468 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4469 return true;
4470}
4471
4473 Scope *S, bool MergeTypeWithOld) {
4474 // Merge the attributes
4476
4477 // Merge "pure" flag.
4478 if (Old->isPureVirtual())
4479 New->setIsPureVirtual();
4480
4481 // Merge "used" flag.
4482 if (Old->getMostRecentDecl()->isUsed(false))
4483 New->setIsUsed();
4484
4485 // Merge attributes from the parameters. These can mismatch with K&R
4486 // declarations.
4487 if (New->getNumParams() == Old->getNumParams())
4488 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4489 ParmVarDecl *NewParam = New->getParamDecl(i);
4490 ParmVarDecl *OldParam = Old->getParamDecl(i);
4491 mergeParamDeclAttributes(NewParam, OldParam, *this);
4492 mergeParamDeclTypes(NewParam, OldParam, *this);
4493 }
4494
4495 if (getLangOpts().CPlusPlus)
4496 return MergeCXXFunctionDecl(New, Old, S);
4497
4498 // Merge the function types so the we get the composite types for the return
4499 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4500 // was visible.
4501 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4502 if (!Merged.isNull() && MergeTypeWithOld)
4503 New->setType(Merged);
4504
4505 return false;
4506}
4507
4509 ObjCMethodDecl *oldMethod) {
4510 // Merge the attributes, including deprecated/unavailable
4511 AvailabilityMergeKind MergeKind =
4513 ? (oldMethod->isOptional()
4516 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4519
4520 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4521
4522 // Merge attributes from the parameters.
4524 oe = oldMethod->param_end();
4526 ni = newMethod->param_begin(), ne = newMethod->param_end();
4527 ni != ne && oi != oe; ++ni, ++oi)
4528 mergeParamDeclAttributes(*ni, *oi, *this);
4529
4530 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4531}
4532
4534 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4535
4536 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4537 ? diag::err_redefinition_different_type
4538 : diag::err_redeclaration_different_type)
4539 << New->getDeclName() << New->getType() << Old->getType();
4540
4541 diag::kind PrevDiag;
4542 SourceLocation OldLocation;
4543 std::tie(PrevDiag, OldLocation)
4545 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4546 New->setInvalidDecl();
4547}
4548
4550 bool MergeTypeWithOld) {
4551 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4552 return;
4553
4554 QualType MergedT;
4555 if (getLangOpts().CPlusPlus) {
4556 if (New->getType()->isUndeducedType()) {
4557 // We don't know what the new type is until the initializer is attached.
4558 return;
4559 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4560 // These could still be something that needs exception specs checked.
4561 return MergeVarDeclExceptionSpecs(New, Old);
4562 }
4563 // C++ [basic.link]p10:
4564 // [...] the types specified by all declarations referring to a given
4565 // object or function shall be identical, except that declarations for an
4566 // array object can specify array types that differ by the presence or
4567 // absence of a major array bound (8.3.4).
4568 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4569 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4570 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4571
4572 // We are merging a variable declaration New into Old. If it has an array
4573 // bound, and that bound differs from Old's bound, we should diagnose the
4574 // mismatch.
4575 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4576 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4577 PrevVD = PrevVD->getPreviousDecl()) {
4578 QualType PrevVDTy = PrevVD->getType();
4579 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4580 continue;
4581
4582 if (!Context.hasSameType(New->getType(), PrevVDTy))
4583 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4584 }
4585 }
4586
4587 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4588 if (Context.hasSameType(OldArray->getElementType(),
4589 NewArray->getElementType()))
4590 MergedT = New->getType();
4591 }
4592 // FIXME: Check visibility. New is hidden but has a complete type. If New
4593 // has no array bound, it should not inherit one from Old, if Old is not
4594 // visible.
4595 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4596 if (Context.hasSameType(OldArray->getElementType(),
4597 NewArray->getElementType()))
4598 MergedT = Old->getType();
4599 }
4600 }
4601 else if (New->getType()->isObjCObjectPointerType() &&
4602 Old->getType()->isObjCObjectPointerType()) {
4603 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4604 Old->getType());
4605 }
4606 } else {
4607 // C 6.2.7p2:
4608 // All declarations that refer to the same object or function shall have
4609 // compatible type.
4610 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4611 }
4612 if (MergedT.isNull()) {
4613 // It's OK if we couldn't merge types if either type is dependent, for a
4614 // block-scope variable. In other cases (static data members of class
4615 // templates, variable templates, ...), we require the types to be
4616 // equivalent.
4617 // FIXME: The C++ standard doesn't say anything about this.
4618 if ((New->getType()->isDependentType() ||
4619 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4620 // If the old type was dependent, we can't merge with it, so the new type
4621 // becomes dependent for now. We'll reproduce the original type when we
4622 // instantiate the TypeSourceInfo for the variable.
4623 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4624 New->setType(Context.DependentTy);
4625 return;
4626 }
4627 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4628 }
4629
4630 // Don't actually update the type on the new declaration if the old
4631 // declaration was an extern declaration in a different scope.
4632 if (MergeTypeWithOld)
4633 New->setType(MergedT);
4634}
4635
4636static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4638 // C11 6.2.7p4:
4639 // For an identifier with internal or external linkage declared
4640 // in a scope in which a prior declaration of that identifier is
4641 // visible, if the prior declaration specifies internal or
4642 // external linkage, the type of the identifier at the later
4643 // declaration becomes the composite type.
4644 //
4645 // If the variable isn't visible, we do not merge with its type.
4646 if (Previous.isShadowed())
4647 return false;
4648
4649 if (S.getLangOpts().CPlusPlus) {
4650 // C++11 [dcl.array]p3:
4651 // If there is a preceding declaration of the entity in the same
4652 // scope in which the bound was specified, an omitted array bound
4653 // is taken to be the same as in that earlier declaration.
4654 return NewVD->isPreviousDeclInSameBlockScope() ||
4655 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4657 } else {
4658 // If the old declaration was function-local, don't merge with its
4659 // type unless we're in the same function.
4660 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4661 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4662 }
4663}
4664
4666 // If the new decl is already invalid, don't do any other checking.
4667 if (New->isInvalidDecl())
4668 return;
4669
4670 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4671 return;
4672
4673 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4674
4675 // Verify the old decl was also a variable or variable template.
4676 VarDecl *Old = nullptr;
4677 VarTemplateDecl *OldTemplate = nullptr;
4678 if (Previous.isSingleResult()) {
4679 if (NewTemplate) {
4680 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4681 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4682
4683 if (auto *Shadow =
4684 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4685 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4686 return New->setInvalidDecl();
4687 } else {
4688 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4689
4690 if (auto *Shadow =
4691 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4692 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4693 return New->setInvalidDecl();
4694 }
4695 }
4696 if (!Old) {
4697 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4698 << New->getDeclName();
4699 notePreviousDefinition(Previous.getRepresentativeDecl(),
4700 New->getLocation());
4701 return New->setInvalidDecl();
4702 }
4703
4704 // If the old declaration was found in an inline namespace and the new
4705 // declaration was qualified, update the DeclContext to match.
4707
4708 // Ensure the template parameters are compatible.
4709 if (NewTemplate &&
4711 OldTemplate->getTemplateParameters(),
4712 /*Complain=*/true, TPL_TemplateMatch))
4713 return New->setInvalidDecl();
4714
4715 // C++ [class.mem]p1:
4716 // A member shall not be declared twice in the member-specification [...]
4717 //
4718 // Here, we need only consider static data members.
4719 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4720 Diag(New->getLocation(), diag::err_duplicate_member)
4721 << New->getIdentifier();
4722 Diag(Old->getLocation(), diag::note_previous_declaration);
4723 New->setInvalidDecl();
4724 }
4725
4727 // Warn if an already-defined variable is made a weak_import in a subsequent
4728 // declaration
4729 if (New->hasAttr<WeakImportAttr>())
4730 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4731 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4732 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4733 Diag(D->getLocation(), diag::note_previous_definition);
4734 // Remove weak_import attribute on new declaration.
4735 New->dropAttr<WeakImportAttr>();
4736 break;
4737 }
4738 }
4739
4740 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4741 if (!Old->hasAttr<InternalLinkageAttr>()) {
4742 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4743 << ILA;
4744 Diag(Old->getLocation(), diag::note_previous_declaration);
4745 New->dropAttr<InternalLinkageAttr>();
4746 }
4747
4748 // Merge the types.
4749 VarDecl *MostRecent = Old->getMostRecentDecl();
4750 if (MostRecent != Old) {
4751 MergeVarDeclTypes(New, MostRecent,
4752 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4753 if (New->isInvalidDecl())
4754 return;
4755 }
4756
4758 if (New->isInvalidDecl())
4759 return;
4760
4761 diag::kind PrevDiag;
4762 SourceLocation OldLocation;
4763 std::tie(PrevDiag, OldLocation) =
4765
4766 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4767 if (New->getStorageClass() == SC_Static &&
4768 !New->isStaticDataMember() &&
4769 Old->hasExternalFormalLinkage()) {
4770 if (getLangOpts().MicrosoftExt) {
4771 Diag(New->getLocation(), diag::ext_static_non_static)
4772 << New->getDeclName();
4773 Diag(OldLocation, PrevDiag);
4774 } else {
4775 Diag(New->getLocation(), diag::err_static_non_static)
4776 << New->getDeclName();
4777 Diag(OldLocation, PrevDiag);
4778 return New->setInvalidDecl();
4779 }
4780 }
4781 // C99 6.2.2p4:
4782 // For an identifier declared with the storage-class specifier
4783 // extern in a scope in which a prior declaration of that
4784 // identifier is visible,23) if the prior declaration specifies
4785 // internal or external linkage, the linkage of the identifier at
4786 // the later declaration is the same as the linkage specified at
4787 // the prior declaration. If no prior declaration is visible, or
4788 // if the prior declaration specifies no linkage, then the
4789 // identifier has external linkage.
4790 if (New->hasExternalStorage() && Old->hasLinkage())
4791 /* Okay */;
4792 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4793 !New->isStaticDataMember() &&
4795 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4796 Diag(OldLocation, PrevDiag);
4797 return New->setInvalidDecl();
4798 }
4799
4800 // Check if extern is followed by non-extern and vice-versa.
4801 if (New->hasExternalStorage() &&
4802 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4803 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4804 Diag(OldLocation, PrevDiag);
4805 return New->setInvalidDecl();
4806 }
4807 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4808 !New->hasExternalStorage()) {
4809 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4810 Diag(OldLocation, PrevDiag);
4811 return New->setInvalidDecl();
4812 }
4813
4815 return;
4816
4817 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4818
4819 // FIXME: The test for external storage here seems wrong? We still
4820 // need to check for mismatches.
4821 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4822 // Don't complain about out-of-line definitions of static members.
4823 !(Old->getLexicalDeclContext()->isRecord() &&
4824 !New->getLexicalDeclContext()->isRecord())) {
4825 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4826 Diag(OldLocation, PrevDiag);
4827 return New->setInvalidDecl();
4828 }
4829
4830 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4831 if (VarDecl *Def = Old->getDefinition()) {
4832 // C++1z [dcl.fcn.spec]p4:
4833 // If the definition of a variable appears in a translation unit before
4834 // its first declaration as inline, the program is ill-formed.
4835 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4836 Diag(Def->getLocation(), diag::note_previous_definition);
4837 }
4838 }
4839
4840 // If this redeclaration makes the variable inline, we may need to add it to
4841 // UndefinedButUsed.
4842 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4843 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4844 !Old->isInAnotherModuleUnit())
4845 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4846 SourceLocation()));
4847
4848 if (New->getTLSKind() != Old->getTLSKind()) {
4849 if (!Old->getTLSKind()) {
4850 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4851 Diag(OldLocation, PrevDiag);
4852 } else if (!New->getTLSKind()) {
4853 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4854 Diag(OldLocation, PrevDiag);
4855 } else {
4856 // Do not allow redeclaration to change the variable between requiring
4857 // static and dynamic initialization.
4858 // FIXME: GCC allows this, but uses the TLS keyword on the first
4859 // declaration to determine the kind. Do we need to be compatible here?
4860 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4861 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4862 Diag(OldLocation, PrevDiag);
4863 }
4864 }
4865
4866 // C++ doesn't have tentative definitions, so go right ahead and check here.
4867 if (getLangOpts().CPlusPlus) {
4868 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4869 Old->getCanonicalDecl()->isConstexpr()) {
4870 // This definition won't be a definition any more once it's been merged.
4871 Diag(New->getLocation(),
4872 diag::warn_deprecated_redundant_constexpr_static_def);
4873 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4874 VarDecl *Def = Old->getDefinition();
4875 if (Def && checkVarDeclRedefinition(Def, New))
4876 return;
4877 }
4878 } else {
4879 // C++ may not have a tentative definition rule, but it has a different
4880 // rule about what constitutes a definition in the first place. See
4881 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4882 // contains the extern specifier and doesn't have an initializer, it's fine
4883 // in C++.
4884 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4885 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4886 << New;
4887 Diag(Old->getLocation(), diag::note_previous_declaration);
4888 }
4889 }
4890
4892 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4893 Diag(OldLocation, PrevDiag);
4894 New->setInvalidDecl();
4895 return;
4896 }
4897
4898 // Merge "used" flag.
4899 if (Old->getMostRecentDecl()->isUsed(false))
4900 New->setIsUsed();
4901
4902 // Keep a chain of previous declarations.
4903 New->setPreviousDecl(Old);
4904 if (NewTemplate)
4905 NewTemplate->setPreviousDecl(OldTemplate);
4906
4907 // Inherit access appropriately.
4908 New->setAccess(Old->getAccess());
4909 if (NewTemplate)
4910 NewTemplate->setAccess(New->getAccess());
4911
4912 if (Old->isInline())
4913 New->setImplicitlyInline();
4914}
4915
4918 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4919 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4920 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4921 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4922 auto &HSI = PP.getHeaderSearchInfo();
4923 StringRef HdrFilename =
4924 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4925
4926 auto noteFromModuleOrInclude = [&](Module *Mod,
4927 SourceLocation IncLoc) -> bool {
4928 // Redefinition errors with modules are common with non modular mapped
4929 // headers, example: a non-modular header H in module A that also gets
4930 // included directly in a TU. Pointing twice to the same header/definition
4931 // is confusing, try to get better diagnostics when modules is on.
4932 if (IncLoc.isValid()) {
4933 if (Mod) {
4934 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4935 << HdrFilename.str() << Mod->getFullModuleName();
4936 if (!Mod->DefinitionLoc.isInvalid())
4937 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4938 << Mod->getFullModuleName();
4939 } else {
4940 Diag(IncLoc, diag::note_redefinition_include_same_file)
4941 << HdrFilename.str();
4942 }
4943 return true;
4944 }
4945
4946 return false;
4947 };
4948
4949 // Is it the same file and same offset? Provide more information on why
4950 // this leads to a redefinition error.
4951 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4952 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4953 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4954 bool EmittedDiag =
4955 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4956 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4957
4958 // If the header has no guards, emit a note suggesting one.
4959 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4960 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4961
4962 if (EmittedDiag)
4963 return;
4964 }
4965
4966 // Redefinition coming from different files or couldn't do better above.
4967 if (Old->getLocation().isValid())
4968 Diag(Old->getLocation(), diag::note_previous_definition);
4969}
4970
4972 if (!hasVisibleDefinition(Old) &&
4973 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4975 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4976 New->getDeclContext()->isDependentContext() ||
4977 New->hasAttr<SelectAnyAttr>())) {
4978 // The previous definition is hidden, and multiple definitions are
4979 // permitted (in separate TUs). Demote this to a declaration.
4980 New->demoteThisDefinitionToDeclaration();
4981
4982 // Make the canonical definition visible.
4983 if (auto *OldTD = Old->getDescribedVarTemplate())
4986 return false;
4987 } else {
4988 Diag(New->getLocation(), diag::err_redefinition) << New;
4989 notePreviousDefinition(Old, New->getLocation());
4990 New->setInvalidDecl();
4991 return true;
4992 }
4993}
4994
4996 DeclSpec &DS,
4997 const ParsedAttributesView &DeclAttrs,
4998 RecordDecl *&AnonRecord) {
5000 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5001}
5002
5003// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5004// disambiguate entities defined in different scopes.
5005// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5006// compatibility.
5007// We will pick our mangling number depending on which version of MSVC is being
5008// targeted.
5009static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5013}
5014
5015void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5016 if (!Context.getLangOpts().CPlusPlus)
5017 return;
5018
5019 if (isa<CXXRecordDecl>(Tag->getParent())) {
5020 // If this tag is the direct child of a class, number it if
5021 // it is anonymous.
5022 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5023 return;
5025 Context.getManglingNumberContext(Tag->getParent());
5026 Context.setManglingNumber(
5027 Tag, MCtx.getManglingNumber(
5028 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5029 return;
5030 }
5031
5032 // If this tag isn't a direct child of a class, number it if it is local.
5034 Decl *ManglingContextDecl;
5035 std::tie(MCtx, ManglingContextDecl) =
5036 getCurrentMangleNumberContext(Tag->getDeclContext());
5037 if (MCtx) {
5038 Context.setManglingNumber(
5039 Tag, MCtx->getManglingNumber(
5040 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5041 }
5042}
5043
5044namespace {
5045struct NonCLikeKind {
5046 enum {
5047 None,
5048 BaseClass,
5049 DefaultMemberInit,
5050 Lambda,
5051 Friend,
5052 OtherMember,
5053 Invalid,
5054 } Kind = None;
5055 SourceRange Range;
5056
5057 explicit operator bool() { return Kind != None; }
5058};
5059}
5060
5061/// Determine whether a class is C-like, according to the rules of C++
5062/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5063static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5064 if (RD->isInvalidDecl())
5065 return {NonCLikeKind::Invalid, {}};
5066
5067 // C++ [dcl.typedef]p9: [P1766R1]
5068 // An unnamed class with a typedef name for linkage purposes shall not
5069 //
5070 // -- have any base classes
5071 if (RD->getNumBases())
5072 return {NonCLikeKind::BaseClass,
5074 RD->bases_end()[-1].getEndLoc())};
5075 bool Invalid = false;
5076 for (Decl *D : RD->decls()) {
5077 // Don't complain about things we already diagnosed.
5078 if (D->isInvalidDecl()) {
5079 Invalid = true;
5080 continue;
5081 }
5082
5083 // -- have any [...] default member initializers
5084 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5085 if (FD->hasInClassInitializer()) {
5086 auto *Init = FD->getInClassInitializer();
5087 return {NonCLikeKind::DefaultMemberInit,
5088 Init ? Init->getSourceRange() : D->getSourceRange()};
5089 }
5090 continue;
5091 }
5092
5093 // FIXME: We don't allow friend declarations. This violates the wording of
5094 // P1766, but not the intent.
5095 if (isa<FriendDecl>(D))
5096 return {NonCLikeKind::Friend, D->getSourceRange()};
5097
5098 // -- declare any members other than non-static data members, member
5099 // enumerations, or member classes,
5101 isa<EnumDecl>(D))
5102 continue;
5103 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5104 if (!MemberRD) {
5105 if (D->isImplicit())
5106 continue;
5107 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5108 }
5109
5110 // -- contain a lambda-expression,
5111 if (MemberRD->isLambda())
5112 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5113
5114 // and all member classes shall also satisfy these requirements
5115 // (recursively).
5116 if (MemberRD->isThisDeclarationADefinition()) {
5117 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5118 return Kind;
5119 }
5120 }
5121
5122 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5123}
5124
5126 TypedefNameDecl *NewTD) {
5127 if (TagFromDeclSpec->isInvalidDecl())
5128 return;
5129
5130 // Do nothing if the tag already has a name for linkage purposes.
5131 if (TagFromDeclSpec->hasNameForLinkage())
5132 return;
5133
5134 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5135 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5136
5137 // The type must match the tag exactly; no qualifiers allowed.
5138 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5139 Context.getCanonicalTagType(TagFromDeclSpec))) {
5140 if (getLangOpts().CPlusPlus)
5141 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5142 return;
5143 }
5144
5145 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5146 // An unnamed class with a typedef name for linkage purposes shall [be
5147 // C-like].
5148 //
5149 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5150 // shouldn't happen, but there are constructs that the language rule doesn't
5151 // disallow for which we can't reasonably avoid computing linkage early.
5152 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5153 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5154 : NonCLikeKind();
5155 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5156 if (NonCLike || ChangesLinkage) {
5157 if (NonCLike.Kind == NonCLikeKind::Invalid)
5158 return;
5159
5160 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5161 if (ChangesLinkage) {
5162 // If the linkage changes, we can't accept this as an extension.
5163 if (NonCLike.Kind == NonCLikeKind::None)
5164 DiagID = diag::err_typedef_changes_linkage;
5165 else
5166 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5167 }
5168
5169 SourceLocation FixitLoc =
5170 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5171 llvm::SmallString<40> TextToInsert;
5172 TextToInsert += ' ';
5173 TextToInsert += NewTD->getIdentifier()->getName();
5174
5175 Diag(FixitLoc, DiagID)
5176 << isa<TypeAliasDecl>(NewTD)
5177 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5178 if (NonCLike.Kind != NonCLikeKind::None) {
5179 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5180 << NonCLike.Kind - 1 << NonCLike.Range;
5181 }
5182 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5183 << NewTD << isa<TypeAliasDecl>(NewTD);
5184
5185 if (ChangesLinkage)
5186 return;
5187 }
5188
5189 // Otherwise, set this as the anon-decl typedef for the tag.
5190 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5191
5192 // Now that we have a name for the tag, process API notes again.
5193 ProcessAPINotes(TagFromDeclSpec);
5194}
5195
5196static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5198 switch (T) {
5200 return 0;
5202 return 1;
5204 return 2;
5206 return 3;
5207 case DeclSpec::TST_enum:
5208 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5209 if (ED->isScopedUsingClassTag())
5210 return 5;
5211 if (ED->isScoped())
5212 return 6;
5213 }
5214 return 4;
5215 default:
5216 llvm_unreachable("unexpected type specifier");
5217 }
5218}
5219
5221 DeclSpec &DS,
5222 const ParsedAttributesView &DeclAttrs,
5223 MultiTemplateParamsArg TemplateParams,
5224 bool IsExplicitInstantiation,
5225 RecordDecl *&AnonRecord,
5226 SourceLocation EllipsisLoc) {
5227 Decl *TagD = nullptr;
5228 TagDecl *Tag = nullptr;
5234 TagD = DS.getRepAsDecl();
5235
5236 if (!TagD) // We probably had an error
5237 return nullptr;
5238
5239 // Note that the above type specs guarantee that the
5240 // type rep is a Decl, whereas in many of the others
5241 // it's a Type.
5242 if (isa<TagDecl>(TagD))
5243 Tag = cast<TagDecl>(TagD);
5244 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5245 Tag = CTD->getTemplatedDecl();
5246 }
5247
5248 if (Tag) {
5249 handleTagNumbering(Tag, S);
5250 Tag->setFreeStanding();
5251 if (Tag->isInvalidDecl())
5252 return Tag;
5253 }
5254
5255 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5256 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5257 // or incomplete types shall not be restrict-qualified."
5258 if (TypeQuals & DeclSpec::TQ_restrict)
5260 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5261 << DS.getSourceRange();
5262 }
5263
5264 if (DS.isInlineSpecified())
5265 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5266 << getLangOpts().CPlusPlus17;
5267
5268 if (DS.hasConstexprSpecifier()) {
5269 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5270 // and definitions of functions and variables.
5271 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5272 // the declaration of a function or function template
5273 if (Tag)
5274 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5276 << static_cast<int>(DS.getConstexprSpecifier());
5277 else if (getLangOpts().C23)
5278 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5279 else
5280 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5281 << static_cast<int>(DS.getConstexprSpecifier());
5282 // Don't emit warnings after this error.
5283 return TagD;
5284 }
5285
5287
5288 if (DS.isFriendSpecified()) {
5289 // If we're dealing with a decl but not a TagDecl, assume that
5290 // whatever routines created it handled the friendship aspect.
5291 if (TagD && !Tag)
5292 return nullptr;
5293 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5294 }
5295
5296 assert(EllipsisLoc.isInvalid() &&
5297 "Friend ellipsis but not friend-specified?");
5298
5299 // Track whether this decl-specifier declares anything.
5300 bool DeclaresAnything = true;
5301
5302 // Handle anonymous struct definitions.
5303 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5304 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5306 if (getLangOpts().CPlusPlus ||
5307 Record->getDeclContext()->isRecord()) {
5308 // If CurContext is a DeclContext that can contain statements,
5309 // RecursiveASTVisitor won't visit the decls that
5310 // BuildAnonymousStructOrUnion() will put into CurContext.
5311 // Also store them here so that they can be part of the
5312 // DeclStmt that gets created in this case.
5313 // FIXME: Also return the IndirectFieldDecls created by
5314 // BuildAnonymousStructOr union, for the same reason?
5315 if (CurContext->isFunctionOrMethod())
5316 AnonRecord = Record;
5317 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5318 Context.getPrintingPolicy());
5319 }
5320
5321 DeclaresAnything = false;
5322 }
5323 }
5324
5325 // C11 6.7.2.1p2:
5326 // A struct-declaration that does not declare an anonymous structure or
5327 // anonymous union shall contain a struct-declarator-list.
5328 //
5329 // This rule also existed in C89 and C99; the grammar for struct-declaration
5330 // did not permit a struct-declaration without a struct-declarator-list.
5331 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5333 // Check for Microsoft C extension: anonymous struct/union member.
5334 // Handle 2 kinds of anonymous struct/union:
5335 // struct STRUCT;
5336 // union UNION;
5337 // and
5338 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5339 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5340 if ((Tag && Tag->getDeclName()) ||
5342 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5343 : DS.getRepAsType().get()->getAsRecordDecl();
5344 if (Record && getLangOpts().MicrosoftExt) {
5345 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5346 << Record->isUnion() << DS.getSourceRange();
5348 }
5349
5350 DeclaresAnything = false;
5351 }
5352 }
5353
5354 // Skip all the checks below if we have a type error.
5356 (TagD && TagD->isInvalidDecl()))
5357 return TagD;
5358
5359 if (getLangOpts().CPlusPlus &&
5361 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5362 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5363 !Enum->isInvalidDecl())
5364 DeclaresAnything = false;
5365
5366 if (!DS.isMissingDeclaratorOk()) {
5367 // Customize diagnostic for a typedef missing a name.
5369 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5370 << DS.getSourceRange();
5371 else
5372 DeclaresAnything = false;
5373 }
5374
5375 if (DS.isModulePrivateSpecified() &&
5376 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5377 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5378 << Tag->getTagKind()
5380
5382
5383 // C 6.7/2:
5384 // A declaration [...] shall declare at least a declarator [...], a tag,
5385 // or the members of an enumeration.
5386 // C++ [dcl.dcl]p3:
5387 // [If there are no declarators], and except for the declaration of an
5388 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5389 // names into the program, or shall redeclare a name introduced by a
5390 // previous declaration.
5391 if (!DeclaresAnything) {
5392 // In C, we allow this as a (popular) extension / bug. Don't bother
5393 // producing further diagnostics for redundant qualifiers after this.
5394 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5395 ? diag::err_no_declarators
5396 : diag::ext_no_declarators)
5397 << DS.getSourceRange();
5398 return TagD;
5399 }
5400
5401 // C++ [dcl.stc]p1:
5402 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5403 // init-declarator-list of the declaration shall not be empty.
5404 // C++ [dcl.fct.spec]p1:
5405 // If a cv-qualifier appears in a decl-specifier-seq, the
5406 // init-declarator-list of the declaration shall not be empty.
5407 //
5408 // Spurious qualifiers here appear to be valid in C.
5409 unsigned DiagID = diag::warn_standalone_specifier;
5410 if (getLangOpts().CPlusPlus)
5411 DiagID = diag::ext_standalone_specifier;
5412
5413 // Note that a linkage-specification sets a storage class, but
5414 // 'extern "C" struct foo;' is actually valid and not theoretically
5415 // useless.
5416 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5417 if (SCS == DeclSpec::SCS_mutable)
5418 // Since mutable is not a viable storage class specifier in C, there is
5419 // no reason to treat it as an extension. Instead, diagnose as an error.
5420 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5421 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5422 Diag(DS.getStorageClassSpecLoc(), DiagID)
5424 }
5425
5429 if (DS.getTypeQualifiers()) {
5431 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5433 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5434 // Restrict is covered above.
5436 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5438 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5439 }
5440
5441 // Warn about ignored type attributes, for example:
5442 // __attribute__((aligned)) struct A;
5443 // Attributes should be placed after tag to apply to type declaration.
5444 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5445 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5446 if (TypeSpecType == DeclSpec::TST_class ||
5447 TypeSpecType == DeclSpec::TST_struct ||
5448 TypeSpecType == DeclSpec::TST_interface ||
5449 TypeSpecType == DeclSpec::TST_union ||
5450 TypeSpecType == DeclSpec::TST_enum) {
5451
5452 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5453 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5454 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5455 DiagnosticId = diag::warn_attribute_ignored;
5456 else if (AL.isRegularKeywordAttribute())
5457 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5458 else
5459 DiagnosticId = diag::warn_declspec_attribute_ignored;
5460 Diag(AL.getLoc(), DiagnosticId)
5461 << AL << GetDiagnosticTypeSpecifierID(DS);
5462 };
5463
5464 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5465 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5466 }
5467 }
5468
5469 return TagD;
5470}
5471
5472/// We are trying to inject an anonymous member into the given scope;
5473/// check if there's an existing declaration that can't be overloaded.
5474///
5475/// \return true if this is a forbidden redeclaration
5476static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5477 DeclContext *Owner,
5478 DeclarationName Name,
5479 SourceLocation NameLoc, bool IsUnion,
5480 StorageClass SC) {
5481 LookupResult R(SemaRef, Name, NameLoc,
5485 if (!SemaRef.LookupName(R, S)) return false;
5486
5487 // Pick a representative declaration.
5489 assert(PrevDecl && "Expected a non-null Decl");
5490
5491 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5492 return false;
5493
5494 if (SC == StorageClass::SC_None &&
5495 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5496 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5497 if (!Owner->isRecord())
5498 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5499 return false;
5500 }
5501
5502 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5503 << IsUnion << Name;
5504 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5505
5506 return true;
5507}
5508
5510 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5512}
5513
5515 if (!getLangOpts().CPlusPlus)
5516 return;
5517
5518 // This function can be parsed before we have validated the
5519 // structure as an anonymous struct
5520 if (Record->isAnonymousStructOrUnion())
5521 return;
5522
5523 const NamedDecl *First = 0;
5524 for (const Decl *D : Record->decls()) {
5525 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5526 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5527 continue;
5528 if (!First)
5529 First = ND;
5530 else
5532 }
5533}
5534
5535/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5536/// anonymous struct or union AnonRecord into the owning context Owner
5537/// and scope S. This routine will be invoked just after we realize
5538/// that an unnamed union or struct is actually an anonymous union or
5539/// struct, e.g.,
5540///
5541/// @code
5542/// union {
5543/// int i;
5544/// float f;
5545/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5546/// // f into the surrounding scope.x
5547/// @endcode
5548///
5549/// This routine is recursive, injecting the names of nested anonymous
5550/// structs/unions into the owning context and scope as well.
5551static bool
5553 RecordDecl *AnonRecord, AccessSpecifier AS,
5554 StorageClass SC,
5555 SmallVectorImpl<NamedDecl *> &Chaining) {
5556 bool Invalid = false;
5557
5558 // Look every FieldDecl and IndirectFieldDecl with a name.
5559 for (auto *D : AnonRecord->decls()) {
5560 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5561 cast<NamedDecl>(D)->getDeclName()) {
5562 ValueDecl *VD = cast<ValueDecl>(D);
5563 // C++ [class.union]p2:
5564 // The names of the members of an anonymous union shall be
5565 // distinct from the names of any other entity in the
5566 // scope in which the anonymous union is declared.
5567
5568 bool FieldInvalid = CheckAnonMemberRedeclaration(
5569 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5570 AnonRecord->isUnion(), SC);
5571 if (FieldInvalid)
5572 Invalid = true;
5573
5574 // Inject the IndirectFieldDecl even if invalid, because later
5575 // diagnostics may depend on it being present, see findDefaultInitializer.
5576
5577 // C++ [class.union]p2:
5578 // For the purpose of name lookup, after the anonymous union
5579 // definition, the members of the anonymous union are
5580 // considered to have been defined in the scope in which the
5581 // anonymous union is declared.
5582 unsigned OldChainingSize = Chaining.size();
5583 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5584 Chaining.append(IF->chain_begin(), IF->chain_end());
5585 else
5586 Chaining.push_back(VD);
5587
5588 assert(Chaining.size() >= 2);
5589 NamedDecl **NamedChain =
5590 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5591 for (unsigned i = 0; i < Chaining.size(); i++)
5592 NamedChain[i] = Chaining[i];
5593
5595 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5596 VD->getType(), {NamedChain, Chaining.size()});
5597
5598 for (const auto *Attr : VD->attrs())
5599 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5600
5601 IndirectField->setAccess(AS);
5602 IndirectField->setImplicit();
5603 IndirectField->setInvalidDecl(FieldInvalid);
5604 SemaRef.PushOnScopeChains(IndirectField, S);
5605
5606 // That includes picking up the appropriate access specifier.
5607 if (AS != AS_none)
5608 IndirectField->setAccess(AS);
5609
5610 Chaining.resize(OldChainingSize);
5611 }
5612 }
5613
5614 return Invalid;
5615}
5616
5617/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5618/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5619/// illegal input values are mapped to SC_None.
5620static StorageClass
5622 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5623 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5624 "Parser allowed 'typedef' as storage class VarDecl.");
5625 switch (StorageClassSpec) {
5628 if (DS.isExternInLinkageSpec())
5629 return SC_None;
5630 return SC_Extern;
5631 case DeclSpec::SCS_static: return SC_Static;
5632 case DeclSpec::SCS_auto: return SC_Auto;
5635 // Illegal SCSs map to None: error reporting is up to the caller.
5636 case DeclSpec::SCS_mutable: // Fall through.
5637 case DeclSpec::SCS_typedef: return SC_None;
5638 }
5639 llvm_unreachable("unknown storage class specifier");
5640}
5641
5643 assert(Record->hasInClassInitializer());
5644
5645 for (const auto *I : Record->decls()) {
5646 const auto *FD = dyn_cast<FieldDecl>(I);
5647 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5648 FD = IFD->getAnonField();
5649 if (FD && FD->hasInClassInitializer())
5650 return FD->getLocation();
5651 }
5652
5653 llvm_unreachable("couldn't find in-class initializer");
5654}
5655
5657 SourceLocation DefaultInitLoc) {
5658 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5659 return;
5660
5661 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5662 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5663}
5664
5666 CXXRecordDecl *AnonUnion) {
5667 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5668 return;
5669
5671}
5672
5674 AccessSpecifier AS,
5676 const PrintingPolicy &Policy) {
5677 DeclContext *Owner = Record->getDeclContext();
5678
5679 // Diagnose whether this anonymous struct/union is an extension.
5680 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5681 Diag(Record->getLocation(), diag::ext_anonymous_union);
5682 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5683 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5684 else if (!Record->isUnion() && !getLangOpts().C11)
5685 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5686
5687 // C and C++ require different kinds of checks for anonymous
5688 // structs/unions.
5689 bool Invalid = false;
5690 if (getLangOpts().CPlusPlus) {
5691 const char *PrevSpec = nullptr;
5692 if (Record->isUnion()) {
5693 // C++ [class.union]p6:
5694 // C++17 [class.union.anon]p2:
5695 // Anonymous unions declared in a named namespace or in the
5696 // global namespace shall be declared static.
5697 unsigned DiagID;
5698 DeclContext *OwnerScope = Owner->getRedeclContext();
5700 (OwnerScope->isTranslationUnit() ||
5701 (OwnerScope->isNamespace() &&
5702 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5703 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5704 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5705
5706 // Recover by adding 'static'.
5708 PrevSpec, DiagID, Policy);
5709 }
5710 // C++ [class.union]p6:
5711 // A storage class is not allowed in a declaration of an
5712 // anonymous union in a class scope.
5714 isa<RecordDecl>(Owner)) {
5716 diag::err_anonymous_union_with_storage_spec)
5718
5719 // Recover by removing the storage specifier.
5722 PrevSpec, DiagID, Context.getPrintingPolicy());
5723 }
5724 }
5725
5726 // Ignore const/volatile/restrict qualifiers.
5727 if (DS.getTypeQualifiers()) {
5729 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5730 << Record->isUnion() << "const"
5734 diag::ext_anonymous_struct_union_qualified)
5735 << Record->isUnion() << "volatile"
5739 diag::ext_anonymous_struct_union_qualified)
5740 << Record->isUnion() << "restrict"
5744 diag::ext_anonymous_struct_union_qualified)
5745 << Record->isUnion() << "_Atomic"
5749 diag::ext_anonymous_struct_union_qualified)
5750 << Record->isUnion() << "__unaligned"
5752
5754 }
5755
5756 // C++ [class.union]p2:
5757 // The member-specification of an anonymous union shall only
5758 // define non-static data members. [Note: nested types and
5759 // functions cannot be declared within an anonymous union. ]
5760 for (auto *Mem : Record->decls()) {
5761 // Ignore invalid declarations; we already diagnosed them.
5762 if (Mem->isInvalidDecl())
5763 continue;
5764
5765 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5766 // C++ [class.union]p3:
5767 // An anonymous union shall not have private or protected
5768 // members (clause 11).
5769 assert(FD->getAccess() != AS_none);
5770 if (FD->getAccess() != AS_public) {
5771 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5772 << Record->isUnion() << (FD->getAccess() == AS_protected);
5773 Invalid = true;
5774 }
5775
5776 // C++ [class.union]p1
5777 // An object of a class with a non-trivial constructor, a non-trivial
5778 // copy constructor, a non-trivial destructor, or a non-trivial copy
5779 // assignment operator cannot be a member of a union, nor can an
5780 // array of such objects.
5781 if (CheckNontrivialField(FD))
5782 Invalid = true;
5783 } else if (Mem->isImplicit()) {
5784 // Any implicit members are fine.
5785 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5786 // This is a type that showed up in an
5787 // elaborated-type-specifier inside the anonymous struct or
5788 // union, but which actually declares a type outside of the
5789 // anonymous struct or union. It's okay.
5790 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5791 if (!MemRecord->isAnonymousStructOrUnion() &&
5792 MemRecord->getDeclName()) {
5793 // Visual C++ allows type definition in anonymous struct or union.
5794 if (getLangOpts().MicrosoftExt)
5795 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5796 << Record->isUnion();
5797 else {
5798 // This is a nested type declaration.
5799 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5800 << Record->isUnion();
5801 Invalid = true;
5802 }
5803 } else {
5804 // This is an anonymous type definition within another anonymous type.
5805 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5806 // not part of standard C++.
5807 Diag(MemRecord->getLocation(),
5808 diag::ext_anonymous_record_with_anonymous_type)
5809 << Record->isUnion();
5810 }
5811 } else if (isa<AccessSpecDecl>(Mem)) {
5812 // Any access specifier is fine.
5813 } else if (isa<StaticAssertDecl>(Mem)) {
5814 // In C++1z, static_assert declarations are also fine.
5815 } else {
5816 // We have something that isn't a non-static data
5817 // member. Complain about it.
5818 unsigned DK = diag::err_anonymous_record_bad_member;
5819 if (isa<TypeDecl>(Mem))
5820 DK = diag::err_anonymous_record_with_type;
5821 else if (isa<FunctionDecl>(Mem))
5822 DK = diag::err_anonymous_record_with_function;
5823 else if (isa<VarDecl>(Mem))
5824 DK = diag::err_anonymous_record_with_static;
5825
5826 // Visual C++ allows type definition in anonymous struct or union.
5827 if (getLangOpts().MicrosoftExt &&
5828 DK == diag::err_anonymous_record_with_type)
5829 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5830 << Record->isUnion();
5831 else {
5832 Diag(Mem->getLocation(), DK) << Record->isUnion();
5833 Invalid = true;
5834 }
5835 }
5836 }
5837
5838 // C++11 [class.union]p8 (DR1460):
5839 // At most one variant member of a union may have a
5840 // brace-or-equal-initializer.
5841 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5842 Owner->isRecord())
5845 }
5846
5847 if (!Record->isUnion() && !Owner->isRecord()) {
5848 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5849 << getLangOpts().CPlusPlus;
5850 Invalid = true;
5851 }
5852
5853 // C++ [dcl.dcl]p3:
5854 // [If there are no declarators], and except for the declaration of an
5855 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5856 // names into the program
5857 // C++ [class.mem]p2:
5858 // each such member-declaration shall either declare at least one member
5859 // name of the class or declare at least one unnamed bit-field
5860 //
5861 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5862 if (getLangOpts().CPlusPlus && Record->field_empty())
5863 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5864
5865 // Mock up a declarator.
5869 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5870
5871 // Create a declaration for this anonymous struct/union.
5872 NamedDecl *Anon = nullptr;
5873 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5874 Anon = FieldDecl::Create(
5875 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5876 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5877 /*BitWidth=*/nullptr, /*Mutable=*/false,
5878 /*InitStyle=*/ICIS_NoInit);
5879 Anon->setAccess(AS);
5880 ProcessDeclAttributes(S, Anon, Dc);
5881
5882 if (getLangOpts().CPlusPlus)
5883 FieldCollector->Add(cast<FieldDecl>(Anon));
5884 } else {
5885 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5886 if (SCSpec == DeclSpec::SCS_mutable) {
5887 // mutable can only appear on non-static class members, so it's always
5888 // an error here
5889 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5890 Invalid = true;
5891 SC = SC_None;
5892 }
5893
5894 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5895 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5896 Context.getCanonicalTagType(Record), TInfo, SC);
5897 if (Invalid)
5898 Anon->setInvalidDecl();
5899
5900 ProcessDeclAttributes(S, Anon, Dc);
5901
5902 // Default-initialize the implicit variable. This initialization will be
5903 // trivial in almost all cases, except if a union member has an in-class
5904 // initializer:
5905 // union { int n = 0; };
5907 }
5908 Anon->setImplicit();
5909
5910 // Mark this as an anonymous struct/union type.
5911 Record->setAnonymousStructOrUnion(true);
5912
5913 // Add the anonymous struct/union object to the current
5914 // context. We'll be referencing this object when we refer to one of
5915 // its members.
5916 Owner->addDecl(Anon);
5917
5918 // Inject the members of the anonymous struct/union into the owning
5919 // context and into the identifier resolver chain for name lookup
5920 // purposes.
5922 Chain.push_back(Anon);
5923
5924 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5925 Chain))
5926 Invalid = true;
5927
5928 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5929 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5931 Decl *ManglingContextDecl;
5932 std::tie(MCtx, ManglingContextDecl) =
5933 getCurrentMangleNumberContext(NewVD->getDeclContext());
5934 if (MCtx) {
5935 Context.setManglingNumber(
5936 NewVD, MCtx->getManglingNumber(
5937 NewVD, getMSManglingNumber(getLangOpts(), S)));
5938 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5939 }
5940 }
5941 }
5942
5943 if (Invalid)
5944 Anon->setInvalidDecl();
5945
5946 return Anon;
5947}
5948
5950 RecordDecl *Record) {
5951 assert(Record && "expected a record!");
5952
5953 // Mock up a declarator.
5956 assert(TInfo && "couldn't build declarator info for anonymous struct");
5957
5958 auto *ParentDecl = cast<RecordDecl>(CurContext);
5959 CanQualType RecTy = Context.getCanonicalTagType(Record);
5960
5961 // Create a declaration for this anonymous struct.
5962 NamedDecl *Anon =
5963 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5964 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5965 /*BitWidth=*/nullptr, /*Mutable=*/false,
5966 /*InitStyle=*/ICIS_NoInit);
5967 Anon->setImplicit();
5968
5969 // Add the anonymous struct object to the current context.
5970 CurContext->addDecl(Anon);
5971
5972 // Inject the members of the anonymous struct into the current
5973 // context and into the identifier resolver chain for name lookup
5974 // purposes.
5976 Chain.push_back(Anon);
5977
5978 RecordDecl *RecordDef = Record->getDefinition();
5979 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5980 diag::err_field_incomplete_or_sizeless) ||
5982 *this, S, CurContext, RecordDef, AS_none,
5984 Anon->setInvalidDecl();
5985 ParentDecl->setInvalidDecl();
5986 }
5987
5988 return Anon;
5989}
5990
5994
5997 DeclarationNameInfo NameInfo;
5998 NameInfo.setLoc(Name.StartLocation);
5999
6000 switch (Name.getKind()) {
6001
6004 NameInfo.setName(Name.Identifier);
6005 return NameInfo;
6006
6008 // C++ [temp.deduct.guide]p3:
6009 // The simple-template-id shall name a class template specialization.
6010 // The template-name shall be the same identifier as the template-name
6011 // of the simple-template-id.
6012 // These together intend to imply that the template-name shall name a
6013 // class template.
6014 // FIXME: template<typename T> struct X {};
6015 // template<typename T> using Y = X<T>;
6016 // Y(int) -> Y<int>;
6017 // satisfies these rules but does not name a class template.
6018 TemplateName TN = Name.TemplateName.get().get();
6019 auto *Template = TN.getAsTemplateDecl();
6021 Diag(Name.StartLocation,
6022 diag::err_deduction_guide_name_not_class_template)
6023 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6024 if (Template)
6026 return DeclarationNameInfo();
6027 }
6028
6029 NameInfo.setName(
6030 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6031 return NameInfo;
6032 }
6033
6035 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6039 return NameInfo;
6040
6042 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6043 Name.Identifier));
6045 return NameInfo;
6046
6048 TypeSourceInfo *TInfo;
6050 if (Ty.isNull())
6051 return DeclarationNameInfo();
6052 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6053 Context.getCanonicalType(Ty)));
6054 NameInfo.setNamedTypeInfo(TInfo);
6055 return NameInfo;
6056 }
6057
6059 TypeSourceInfo *TInfo;
6060 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6061 if (Ty.isNull())
6062 return DeclarationNameInfo();
6063 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6064 Context.getCanonicalType(Ty)));
6065 NameInfo.setNamedTypeInfo(TInfo);
6066 return NameInfo;
6067 }
6068
6070 // In well-formed code, we can only have a constructor
6071 // template-id that refers to the current context, so go there
6072 // to find the actual type being constructed.
6073 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6074 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6075 return DeclarationNameInfo();
6076
6077 // Determine the type of the class being constructed.
6078 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6079
6080 // FIXME: Check two things: that the template-id names the same type as
6081 // CurClassType, and that the template-id does not occur when the name
6082 // was qualified.
6083
6084 NameInfo.setName(
6085 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6086 // FIXME: should we retrieve TypeSourceInfo?
6087 NameInfo.setNamedTypeInfo(nullptr);
6088 return NameInfo;
6089 }
6090
6092 TypeSourceInfo *TInfo;
6093 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6094 if (Ty.isNull())
6095 return DeclarationNameInfo();
6096 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6097 Context.getCanonicalType(Ty)));
6098 NameInfo.setNamedTypeInfo(TInfo);
6099 return NameInfo;
6100 }
6101
6103 TemplateName TName = Name.TemplateId->Template.get();
6104 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6105 return Context.getNameForTemplate(TName, TNameLoc);
6106 }
6107
6108 } // switch (Name.getKind())
6109
6110 llvm_unreachable("Unknown name kind");
6111}
6112
6114 do {
6115 if (Ty->isPointerOrReferenceType())
6116 Ty = Ty->getPointeeType();
6117 else if (Ty->isArrayType())
6119 else
6120 return Ty.withoutLocalFastQualifiers();
6121 } while (true);
6122}
6123
6124/// hasSimilarParameters - Determine whether the C++ functions Declaration
6125/// and Definition have "nearly" matching parameters. This heuristic is
6126/// used to improve diagnostics in the case where an out-of-line function
6127/// definition doesn't match any declaration within the class or namespace.
6128/// Also sets Params to the list of indices to the parameters that differ
6129/// between the declaration and the definition. If hasSimilarParameters
6130/// returns true and Params is empty, then all of the parameters match.
6134 SmallVectorImpl<unsigned> &Params) {
6135 Params.clear();
6136 if (Declaration->param_size() != Definition->param_size())
6137 return false;
6138 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6139 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6140 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6141
6142 // The parameter types are identical
6143 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6144 continue;
6145
6146 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6147 QualType DefParamBaseTy = getCoreType(DefParamTy);
6148 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6149 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6150
6151 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6152 (DeclTyName && DeclTyName == DefTyName))
6153 Params.push_back(Idx);
6154 else // The two parameters aren't even close
6155 return false;
6156 }
6157
6158 return true;
6159}
6160
6161/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6162/// declarator needs to be rebuilt in the current instantiation.
6163/// Any bits of declarator which appear before the name are valid for
6164/// consideration here. That's specifically the type in the decl spec
6165/// and the base type in any member-pointer chunks.
6167 DeclarationName Name) {
6168 // The types we specifically need to rebuild are:
6169 // - typenames, typeofs, and decltypes
6170 // - types which will become injected class names
6171 // Of course, we also need to rebuild any type referencing such a
6172 // type. It's safest to just say "dependent", but we call out a
6173 // few cases here.
6174
6175 DeclSpec &DS = D.getMutableDeclSpec();
6176 switch (DS.getTypeSpecType()) {
6180#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6181#include "clang/Basic/TransformTypeTraits.def"
6182 case DeclSpec::TST_atomic: {
6183 // Grab the type from the parser.
6184 TypeSourceInfo *TSI = nullptr;
6185 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6186 if (T.isNull() || !T->isInstantiationDependentType()) break;
6187
6188 // Make sure there's a type source info. This isn't really much
6189 // of a waste; most dependent types should have type source info
6190 // attached already.
6191 if (!TSI)
6193
6194 // Rebuild the type in the current instantiation.
6196 if (!TSI) return true;
6197
6198 // Store the new type back in the decl spec.
6199 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6200 DS.UpdateTypeRep(LocType);
6201 break;
6202 }
6203
6207 Expr *E = DS.getRepAsExpr();
6209 if (Result.isInvalid()) return true;
6210 DS.UpdateExprRep(Result.get());
6211 break;
6212 }
6213
6214 default:
6215 // Nothing to do for these decl specs.
6216 break;
6217 }
6218
6219 // It doesn't matter what order we do this in.
6220 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6221 DeclaratorChunk &Chunk = D.getTypeObject(I);
6222
6223 // The only type information in the declarator which can come
6224 // before the declaration name is the base type of a member
6225 // pointer.
6227 continue;
6228
6229 // Rebuild the scope specifier in-place.
6230 CXXScopeSpec &SS = Chunk.Mem.Scope();
6232 return true;
6233 }
6234
6235 return false;
6236}
6237
6238/// Returns true if the declaration is declared in a system header or from a
6239/// system macro.
6240static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6241 return SM.isInSystemHeader(D->getLocation()) ||
6242 SM.isInSystemMacro(D->getLocation());
6243}
6244
6246 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6247 // of system decl.
6248 if (D->getPreviousDecl() || D->isImplicit())
6249 return;
6252 !isFromSystemHeader(Context.getSourceManager(), D)) {
6253 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6254 << D << static_cast<int>(Status);
6255 }
6256}
6257
6260
6261 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6262 // declaration only if the `bind_to_declaration` extension is set.
6264 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6265 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6266 llvm::omp::TraitProperty::
6267 implementation_extension_bind_to_declaration))
6269 S, D, MultiTemplateParamsArg(), Bases);
6270
6272
6273 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6274 Dcl && Dcl->getDeclContext()->isFileContext())
6276
6277 if (!Bases.empty())
6279 Bases);
6280
6281 return Dcl;
6282}
6283
6285 DeclarationNameInfo NameInfo) {
6286 DeclarationName Name = NameInfo.getName();
6287
6288 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6289 while (Record && Record->isAnonymousStructOrUnion())
6290 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6291 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6292 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6293 return true;
6294 }
6295
6296 return false;
6297}
6298
6300 DeclarationName Name,
6301 SourceLocation Loc,
6302 TemplateIdAnnotation *TemplateId,
6303 bool IsMemberSpecialization) {
6304 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6305 "without nested-name-specifier");
6306 DeclContext *Cur = CurContext;
6307 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6308 Cur = Cur->getParent();
6309
6310 // If the user provided a superfluous scope specifier that refers back to the
6311 // class in which the entity is already declared, diagnose and ignore it.
6312 //
6313 // class X {
6314 // void X::f();
6315 // };
6316 //
6317 // Note, it was once ill-formed to give redundant qualification in all
6318 // contexts, but that rule was removed by DR482.
6319 if (Cur->Equals(DC)) {
6320 if (Cur->isRecord()) {
6321 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6322 : diag::err_member_extra_qualification)
6323 << Name << FixItHint::CreateRemoval(SS.getRange());
6324 SS.clear();
6325 } else {
6326 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6327 }
6328 return false;
6329 }
6330
6331 // Check whether the qualifying scope encloses the scope of the original
6332 // declaration. For a template-id, we perform the checks in
6333 // CheckTemplateSpecializationScope.
6334 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6335 if (Cur->isRecord())
6336 Diag(Loc, diag::err_member_qualification)
6337 << Name << SS.getRange();
6338 else if (isa<TranslationUnitDecl>(DC))
6339 Diag(Loc, diag::err_invalid_declarator_global_scope)
6340 << Name << SS.getRange();
6341 else if (isa<FunctionDecl>(Cur))
6342 Diag(Loc, diag::err_invalid_declarator_in_function)
6343 << Name << SS.getRange();
6344 else if (isa<BlockDecl>(Cur))
6345 Diag(Loc, diag::err_invalid_declarator_in_block)
6346 << Name << SS.getRange();
6347 else if (isa<ExportDecl>(Cur)) {
6348 if (!isa<NamespaceDecl>(DC))
6349 Diag(Loc, diag::err_export_non_namespace_scope_name)
6350 << Name << SS.getRange();
6351 else
6352 // The cases that DC is not NamespaceDecl should be handled in
6353 // CheckRedeclarationExported.
6354 return false;
6355 } else
6356 Diag(Loc, diag::err_invalid_declarator_scope)
6357 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6358
6359 return true;
6360 }
6361
6362 if (Cur->isRecord()) {
6363 // Cannot qualify members within a class.
6364 Diag(Loc, diag::err_member_qualification)
6365 << Name << SS.getRange();
6366 SS.clear();
6367
6368 // C++ constructors and destructors with incorrect scopes can break
6369 // our AST invariants by having the wrong underlying types. If
6370 // that's the case, then drop this declaration entirely.
6373 !Context.hasSameType(
6374 Name.getCXXNameType(),
6375 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6376 return true;
6377
6378 return false;
6379 }
6380
6381 // C++23 [temp.names]p5:
6382 // The keyword template shall not appear immediately after a declarative
6383 // nested-name-specifier.
6384 //
6385 // First check the template-id (if any), and then check each component of the
6386 // nested-name-specifier in reverse order.
6387 //
6388 // FIXME: nested-name-specifiers in friend declarations are declarative,
6389 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6390 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6391 Diag(Loc, diag::ext_template_after_declarative_nns)
6393
6395 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6396 TL = std::exchange(NextTL, TypeLoc())) {
6397 SourceLocation TemplateKeywordLoc;
6398 switch (TL.getTypeLocClass()) {
6399 case TypeLoc::TemplateSpecialization: {
6400 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6401 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6402 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6403 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6404 << TST.getLocalSourceRange();
6405 break;
6406 }
6407 case TypeLoc::Decltype:
6408 case TypeLoc::PackIndexing: {
6409 const Type *T = TL.getTypePtr();
6410 // C++23 [expr.prim.id.qual]p2:
6411 // [...] A declarative nested-name-specifier shall not have a
6412 // computed-type-specifier.
6413 //
6414 // CWG2858 changed this from 'decltype-specifier' to
6415 // 'computed-type-specifier'.
6416 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6417 << T->isDecltypeType() << TL.getSourceRange();
6418 break;
6419 }
6420 case TypeLoc::DependentName:
6421 NextTL =
6422 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6423 break;
6424 default:
6425 break;
6426 }
6427 if (TemplateKeywordLoc.isValid())
6428 Diag(Loc, diag::ext_template_after_declarative_nns)
6429 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6430 }
6431
6432 return false;
6433}
6434
6436 MultiTemplateParamsArg TemplateParamLists) {
6437 // TODO: consider using NameInfo for diagnostic.
6439 DeclarationName Name = NameInfo.getName();
6440
6441 // All of these full declarators require an identifier. If it doesn't have
6442 // one, the ParsedFreeStandingDeclSpec action should be used.
6443 if (D.isDecompositionDeclarator()) {
6444 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6445 } else if (!Name) {
6446 if (!D.isInvalidType()) // Reject this if we think it is valid.
6447 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6449 return nullptr;
6451 return nullptr;
6452
6453 DeclContext *DC = CurContext;
6454 if (D.getCXXScopeSpec().isInvalid())
6455 D.setInvalidType();
6456 else if (D.getCXXScopeSpec().isSet()) {
6459 return nullptr;
6460
6461 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6462 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6463 if (!DC || isa<EnumDecl>(DC)) {
6464 // If we could not compute the declaration context, it's because the
6465 // declaration context is dependent but does not refer to a class,
6466 // class template, or class template partial specialization. Complain
6467 // and return early, to avoid the coming semantic disaster.
6469 diag::err_template_qualified_declarator_no_match)
6471 << D.getCXXScopeSpec().getRange();
6472 return nullptr;
6473 }
6474 bool IsDependentContext = DC->isDependentContext();
6475
6476 if (!IsDependentContext &&
6478 return nullptr;
6479
6480 // If a class is incomplete, do not parse entities inside it.
6483 diag::err_member_def_undefined_record)
6484 << Name << DC << D.getCXXScopeSpec().getRange();
6485 return nullptr;
6486 }
6487 if (!D.getDeclSpec().isFriendSpecified()) {
6488 TemplateIdAnnotation *TemplateId =
6490 ? D.getName().TemplateId
6491 : nullptr;
6493 D.getIdentifierLoc(), TemplateId,
6494 /*IsMemberSpecialization=*/false)) {
6495 if (DC->isRecord())
6496 return nullptr;
6497
6498 D.setInvalidType();
6499 }
6500 }
6501
6502 // Check whether we need to rebuild the type of the given
6503 // declaration in the current instantiation.
6504 if (EnteringContext && IsDependentContext &&
6505 TemplateParamLists.size() != 0) {
6506 ContextRAII SavedContext(*this, DC);
6507 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6508 D.setInvalidType();
6509 }
6510 }
6511
6513 QualType R = TInfo->getType();
6514
6517 D.setInvalidType();
6518
6519 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6521
6522 // See if this is a redefinition of a variable in the same scope.
6523 if (!D.getCXXScopeSpec().isSet()) {
6524 bool IsLinkageLookup = false;
6525 bool CreateBuiltins = false;
6526
6527 // If the declaration we're planning to build will be a function
6528 // or object with linkage, then look for another declaration with
6529 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6530 //
6531 // If the declaration we're planning to build will be declared with
6532 // external linkage in the translation unit, create any builtin with
6533 // the same name.
6535 /* Do nothing*/;
6536 else if (CurContext->isFunctionOrMethod() &&
6538 R->isFunctionType())) {
6539 IsLinkageLookup = true;
6540 CreateBuiltins =
6541 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6542 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6544 CreateBuiltins = true;
6545
6546 if (IsLinkageLookup) {
6548 Previous.setRedeclarationKind(
6550 }
6551
6552 LookupName(Previous, S, CreateBuiltins);
6553 } else { // Something like "int foo::x;"
6555
6556 // C++ [dcl.meaning]p1:
6557 // When the declarator-id is qualified, the declaration shall refer to a
6558 // previously declared member of the class or namespace to which the
6559 // qualifier refers (or, in the case of a namespace, of an element of the
6560 // inline namespace set of that namespace (7.3.1)) or to a specialization
6561 // thereof; [...]
6562 //
6563 // Note that we already checked the context above, and that we do not have
6564 // enough information to make sure that Previous contains the declaration
6565 // we want to match. For example, given:
6566 //
6567 // class X {
6568 // void f();
6569 // void f(float);
6570 // };
6571 //
6572 // void X::f(int) { } // ill-formed
6573 //
6574 // In this case, Previous will point to the overload set
6575 // containing the two f's declared in X, but neither of them
6576 // matches.
6577
6579 }
6580
6581 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6582 TPD && TPD->isTemplateParameter()) {
6583 // Older versions of clang allowed the names of function/variable templates
6584 // to shadow the names of their template parameters. For the compatibility
6585 // purposes we detect such cases and issue a default-to-error warning that
6586 // can be disabled with -Wno-strict-primary-template-shadow.
6587 if (!D.isInvalidType()) {
6588 bool AllowForCompatibility = false;
6589 if (Scope *DeclParent = S->getDeclParent();
6590 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6591 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6592 TemplateParamParent->isDeclScope(TPD);
6593 }
6595 AllowForCompatibility);
6596 }
6597
6598 // Just pretend that we didn't see the previous declaration.
6599 Previous.clear();
6600 }
6601
6602 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6603 // Forget that the previous declaration is the injected-class-name.
6604 Previous.clear();
6605
6606 // In C++, the previous declaration we find might be a tag type
6607 // (class or enum). In this case, the new declaration will hide the
6608 // tag type. Note that this applies to functions, function templates, and
6609 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6610 if (Previous.isSingleTagDecl() &&
6612 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6613 Previous.clear();
6614
6615 // Check that there are no default arguments other than in the parameters
6616 // of a function declaration (C++ only).
6617 if (getLangOpts().CPlusPlus)
6619
6620 /// Get the innermost enclosing declaration scope.
6621 S = S->getDeclParent();
6622
6623 NamedDecl *New;
6624
6625 bool AddToScope = true;
6627 if (TemplateParamLists.size()) {
6628 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6629 return nullptr;
6630 }
6631
6632 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6633 } else if (R->isFunctionType()) {
6634 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6635 TemplateParamLists,
6636 AddToScope);
6637 } else {
6638 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6639 AddToScope);
6640 }
6641
6642 if (!New)
6643 return nullptr;
6644
6646
6647 // If this has an identifier and is not a function template specialization,
6648 // add it to the scope stack.
6649 if (New->getDeclName() && AddToScope)
6651
6652 if (OpenMP().isInOpenMPDeclareTargetContext())
6654
6655 return New;
6656}
6657
6658/// Helper method to turn variable array types into constant array
6659/// types in certain situations which would otherwise be errors (for
6660/// GCC compatibility).
6662 ASTContext &Context,
6663 bool &SizeIsNegative,
6664 llvm::APSInt &Oversized) {
6665 // This method tries to turn a variable array into a constant
6666 // array even when the size isn't an ICE. This is necessary
6667 // for compatibility with code that depends on gcc's buggy
6668 // constant expression folding, like struct {char x[(int)(char*)2];}
6669 SizeIsNegative = false;
6670 Oversized = 0;
6671
6672 if (T->isDependentType())
6673 return QualType();
6674
6676 const Type *Ty = Qs.strip(T);
6677
6678 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6679 QualType Pointee = PTy->getPointeeType();
6680 QualType FixedType =
6681 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6682 Oversized);
6683 if (FixedType.isNull()) return FixedType;
6684 FixedType = Context.getPointerType(FixedType);
6685 return Qs.apply(Context, FixedType);
6686 }
6687 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6688 QualType Inner = PTy->getInnerType();
6689 QualType FixedType =
6690 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6691 Oversized);
6692 if (FixedType.isNull()) return FixedType;
6693 FixedType = Context.getParenType(FixedType);
6694 return Qs.apply(Context, FixedType);
6695 }
6696
6697 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6698 if (!VLATy)
6699 return QualType();
6700
6701 QualType ElemTy = VLATy->getElementType();
6702 if (ElemTy->isVariablyModifiedType()) {
6703 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6704 SizeIsNegative, Oversized);
6705 if (ElemTy.isNull())
6706 return QualType();
6707 }
6708
6709 Expr::EvalResult Result;
6710 if (!VLATy->getSizeExpr() ||
6711 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6712 return QualType();
6713
6714 llvm::APSInt Res = Result.Val.getInt();
6715
6716 // Check whether the array size is negative.
6717 if (Res.isSigned() && Res.isNegative()) {
6718 SizeIsNegative = true;
6719 return QualType();
6720 }
6721
6722 // Check whether the array is too large to be addressed.
6723 unsigned ActiveSizeBits =
6724 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6725 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6726 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6727 : Res.getActiveBits();
6728 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6729 Oversized = Res;
6730 return QualType();
6731 }
6732
6733 QualType FoldedArrayType = Context.getConstantArrayType(
6734 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6735 return Qs.apply(Context, FoldedArrayType);
6736}
6737
6738static void
6740 SrcTL = SrcTL.getUnqualifiedLoc();
6741 DstTL = DstTL.getUnqualifiedLoc();
6742 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6743 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6744 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6745 DstPTL.getPointeeLoc());
6746 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6747 return;
6748 }
6749 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6750 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6751 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6752 DstPTL.getInnerLoc());
6753 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6754 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6755 return;
6756 }
6757 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6758 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6759 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6760 TypeLoc DstElemTL = DstATL.getElementLoc();
6761 if (VariableArrayTypeLoc SrcElemATL =
6762 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6763 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6764 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6765 } else {
6766 DstElemTL.initializeFullCopy(SrcElemTL);
6767 }
6768 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6769 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6770 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6771}
6772
6773/// Helper method to turn variable array types into constant array
6774/// types in certain situations which would otherwise be errors (for
6775/// GCC compatibility).
6776static TypeSourceInfo*
6778 ASTContext &Context,
6779 bool &SizeIsNegative,
6780 llvm::APSInt &Oversized) {
6781 QualType FixedTy
6782 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6783 SizeIsNegative, Oversized);
6784 if (FixedTy.isNull())
6785 return nullptr;
6786 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6788 FixedTInfo->getTypeLoc());
6789 return FixedTInfo;
6790}
6791
6794 unsigned FailedFoldDiagID) {
6795 bool SizeIsNegative;
6796 llvm::APSInt Oversized;
6798 TInfo, Context, SizeIsNegative, Oversized);
6799 if (FixedTInfo) {
6800 Diag(Loc, diag::ext_vla_folded_to_constant);
6801 TInfo = FixedTInfo;
6802 T = FixedTInfo->getType();
6803 return true;
6804 }
6805
6806 if (SizeIsNegative)
6807 Diag(Loc, diag::err_typecheck_negative_array_size);
6808 else if (Oversized.getBoolValue())
6809 Diag(Loc, diag::err_array_too_large) << toString(
6810 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6811 /*UpperCase=*/false, /*InsertSeparators=*/true);
6812 else if (FailedFoldDiagID)
6813 Diag(Loc, FailedFoldDiagID);
6814 return false;
6815}
6816
6817void
6819 if (!getLangOpts().CPlusPlus &&
6821 // Don't need to track declarations in the TU in C.
6822 return;
6823
6824 // Note that we have a locally-scoped external with this name.
6825 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6826}
6827
6829 // FIXME: We can have multiple results via __attribute__((overloadable)).
6830 auto Result = Context.getExternCContextDecl()->lookup(Name);
6831 return Result.empty() ? nullptr : *Result.begin();
6832}
6833
6835 // FIXME: We should probably indicate the identifier in question to avoid
6836 // confusion for constructs like "virtual int a(), b;"
6837 if (DS.isVirtualSpecified())
6839 diag::err_virtual_non_function);
6840
6841 if (DS.hasExplicitSpecifier())
6843 diag::err_explicit_non_function);
6844
6845 if (DS.isNoreturnSpecified())
6847 diag::err_noreturn_non_function);
6848}
6849
6850NamedDecl*
6853 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6854 if (D.getCXXScopeSpec().isSet()) {
6855 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6856 << D.getCXXScopeSpec().getRange();
6857 D.setInvalidType();
6858 // Pretend we didn't see the scope specifier.
6859 DC = CurContext;
6860 Previous.clear();
6861 }
6862
6864
6867 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6868 ? diag::warn_ms_inline_non_function
6869 : diag::err_inline_non_function)
6870 << getLangOpts().CPlusPlus17;
6872 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6873 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6874
6878 diag::err_deduction_guide_invalid_specifier)
6879 << "typedef";
6880 else
6881 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6882 << D.getName().getSourceRange();
6883 return nullptr;
6884 }
6885
6886 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6887 if (!NewTD) return nullptr;
6888
6889 // Handle attributes prior to checking for duplicates in MergeVarDecl
6890 ProcessDeclAttributes(S, NewTD, D);
6891
6893
6894 bool Redeclaration = D.isRedeclaration();
6897 return ND;
6898}
6899
6900void
6902 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6903 // then it shall have block scope.
6904 // Note that variably modified types must be fixed before merging the decl so
6905 // that redeclarations will match.
6906 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6907 QualType T = TInfo->getType();
6908 if (T->isVariablyModifiedType()) {
6910
6911 if (S->getFnParent() == nullptr) {
6912 bool SizeIsNegative;
6913 llvm::APSInt Oversized;
6914 TypeSourceInfo *FixedTInfo =
6916 SizeIsNegative,
6917 Oversized);
6918 if (FixedTInfo) {
6919 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6920 NewTD->setTypeSourceInfo(FixedTInfo);
6921 } else {
6922 if (SizeIsNegative)
6923 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6924 else if (T->isVariableArrayType())
6925 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6926 else if (Oversized.getBoolValue())
6927 Diag(NewTD->getLocation(), diag::err_array_too_large)
6928 << toString(Oversized, 10);
6929 else
6930 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6931 NewTD->setInvalidDecl();
6932 }
6933 }
6934 }
6935}
6936
6937NamedDecl*
6940
6941 // Find the shadowed declaration before filtering for scope.
6942 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6943
6944 // Merge the decl with the existing one if appropriate. If the decl is
6945 // in an outer scope, it isn't the same thing.
6946 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6947 /*AllowInlineNamespace*/false);
6949 if (!Previous.empty()) {
6950 Redeclaration = true;
6951 MergeTypedefNameDecl(S, NewTD, Previous);
6952 } else {
6954 }
6955
6956 if (ShadowedDecl && !Redeclaration)
6957 CheckShadow(NewTD, ShadowedDecl, Previous);
6958
6959 // If this is the C FILE type, notify the AST context.
6960 if (IdentifierInfo *II = NewTD->getIdentifier())
6961 if (!NewTD->isInvalidDecl() &&
6963 switch (II->getNotableIdentifierID()) {
6964 case tok::NotableIdentifierKind::FILE:
6965 Context.setFILEDecl(NewTD);
6966 break;
6967 case tok::NotableIdentifierKind::jmp_buf:
6968 Context.setjmp_bufDecl(NewTD);
6969 break;
6970 case tok::NotableIdentifierKind::sigjmp_buf:
6971 Context.setsigjmp_bufDecl(NewTD);
6972 break;
6973 case tok::NotableIdentifierKind::ucontext_t:
6974 Context.setucontext_tDecl(NewTD);
6975 break;
6976 case tok::NotableIdentifierKind::float_t:
6977 case tok::NotableIdentifierKind::double_t:
6978 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6979 break;
6980 default:
6981 break;
6982 }
6983 }
6984
6985 return NewTD;
6986}
6987
6988/// Determines whether the given declaration is an out-of-scope
6989/// previous declaration.
6990///
6991/// This routine should be invoked when name lookup has found a
6992/// previous declaration (PrevDecl) that is not in the scope where a
6993/// new declaration by the same name is being introduced. If the new
6994/// declaration occurs in a local scope, previous declarations with
6995/// linkage may still be considered previous declarations (C99
6996/// 6.2.2p4-5, C++ [basic.link]p6).
6997///
6998/// \param PrevDecl the previous declaration found by name
6999/// lookup
7000///
7001/// \param DC the context in which the new declaration is being
7002/// declared.
7003///
7004/// \returns true if PrevDecl is an out-of-scope previous declaration
7005/// for a new delcaration with the same name.
7006static bool
7008 ASTContext &Context) {
7009 if (!PrevDecl)
7010 return false;
7011
7012 if (!PrevDecl->hasLinkage())
7013 return false;
7014
7015 if (Context.getLangOpts().CPlusPlus) {
7016 // C++ [basic.link]p6:
7017 // If there is a visible declaration of an entity with linkage
7018 // having the same name and type, ignoring entities declared
7019 // outside the innermost enclosing namespace scope, the block
7020 // scope declaration declares that same entity and receives the
7021 // linkage of the previous declaration.
7022 DeclContext *OuterContext = DC->getRedeclContext();
7023 if (!OuterContext->isFunctionOrMethod())
7024 // This rule only applies to block-scope declarations.
7025 return false;
7026
7027 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7028 if (PrevOuterContext->isRecord())
7029 // We found a member function: ignore it.
7030 return false;
7031
7032 // Find the innermost enclosing namespace for the new and
7033 // previous declarations.
7034 OuterContext = OuterContext->getEnclosingNamespaceContext();
7035 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7036
7037 // The previous declaration is in a different namespace, so it
7038 // isn't the same function.
7039 if (!OuterContext->Equals(PrevOuterContext))
7040 return false;
7041 }
7042
7043 return true;
7044}
7045
7047 CXXScopeSpec &SS = D.getCXXScopeSpec();
7048 if (!SS.isSet()) return;
7050}
7051
7053 if (Decl->getType().hasAddressSpace())
7054 return;
7055 if (Decl->getType()->isDependentType())
7056 return;
7057 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7058 QualType Type = Var->getType();
7059 if (Type->isSamplerT() || Type->isVoidType())
7060 return;
7062 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7063 // __opencl_c_program_scope_global_variables feature, the address space
7064 // for a variable at program scope or a static or extern variable inside
7065 // a function are inferred to be __global.
7066 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7067 Var->hasGlobalStorage())
7068 ImplAS = LangAS::opencl_global;
7069 // If the original type from a decayed type is an array type and that array
7070 // type has no address space yet, deduce it now.
7071 if (auto DT = dyn_cast<DecayedType>(Type)) {
7072 auto OrigTy = DT->getOriginalType();
7073 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7074 // Add the address space to the original array type and then propagate
7075 // that to the element type through `getAsArrayType`.
7076 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7077 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7078 // Re-generate the decayed type.
7079 Type = Context.getDecayedType(OrigTy);
7080 }
7081 }
7082 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7083 // Apply any qualifiers (including address space) from the array type to
7084 // the element type. This implements C99 6.7.3p8: "If the specification of
7085 // an array type includes any type qualifiers, the element type is so
7086 // qualified, not the array type."
7087 if (Type->isArrayType())
7088 Type = QualType(Context.getAsArrayType(Type), 0);
7089 Decl->setType(Type);
7090 }
7091}
7092
7093static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7094 // 'weak' only applies to declarations with external linkage.
7095 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7096 if (!ND.isExternallyVisible()) {
7097 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7098 ND.dropAttr<WeakAttr>();
7099 }
7100 }
7101}
7102
7103static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7104 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7105 if (ND.isExternallyVisible()) {
7106 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7107 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7108 }
7109 }
7110}
7111
7112static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7113 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7114 if (VD->hasInit()) {
7115 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7116 assert(VD->isThisDeclarationADefinition() &&
7117 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7118 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7119 VD->dropAttr<AliasAttr>();
7120 }
7121 }
7122 }
7123}
7124
7125static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7126 // 'selectany' only applies to externally visible variable declarations.
7127 // It does not apply to functions.
7128 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7129 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7130 S.Diag(Attr->getLocation(),
7131 diag::err_attribute_selectany_non_extern_data);
7132 ND.dropAttr<SelectAnyAttr>();
7133 }
7134 }
7135}
7136
7138 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7139 if (!ND.isExternallyVisible())
7140 S.Diag(Attr->getLocation(),
7141 diag::warn_attribute_hybrid_patchable_non_extern);
7142 }
7143}
7144
7146 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7147 auto *VD = dyn_cast<VarDecl>(&ND);
7148 bool IsAnonymousNS = false;
7149 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7150 if (VD) {
7151 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7152 while (NS && !IsAnonymousNS) {
7153 IsAnonymousNS = NS->isAnonymousNamespace();
7154 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7155 }
7156 }
7157 // dll attributes require external linkage. Static locals may have external
7158 // linkage but still cannot be explicitly imported or exported.
7159 // In Microsoft mode, a variable defined in anonymous namespace must have
7160 // external linkage in order to be exported.
7161 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7162 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7163 (!AnonNSInMicrosoftMode &&
7164 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7165 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7166 << &ND << Attr;
7167 ND.setInvalidDecl();
7168 }
7169 }
7170}
7171
7173 // Check the attributes on the function type and function params, if any.
7174 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7175 FD = FD->getMostRecentDecl();
7176 // Don't declare this variable in the second operand of the for-statement;
7177 // GCC miscompiles that by ending its lifetime before evaluating the
7178 // third operand. See gcc.gnu.org/PR86769.
7180 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7181 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7182 TL = ATL.getModifiedLoc()) {
7183 // The [[lifetimebound]] attribute can be applied to the implicit object
7184 // parameter of a non-static member function (other than a ctor or dtor)
7185 // by applying it to the function type.
7186 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7187 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7188 int NoImplicitObjectError = -1;
7189 if (!MD)
7190 NoImplicitObjectError = 0;
7191 else if (MD->isStatic())
7192 NoImplicitObjectError = 1;
7193 else if (MD->isExplicitObjectMemberFunction())
7194 NoImplicitObjectError = 2;
7195 if (NoImplicitObjectError != -1) {
7196 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7197 << NoImplicitObjectError << A->getRange();
7198 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7199 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7200 << isa<CXXDestructorDecl>(MD) << A->getRange();
7201 } else if (MD->getReturnType()->isVoidType()) {
7202 S.Diag(
7203 MD->getLocation(),
7204 diag::
7205 err_lifetimebound_implicit_object_parameter_void_return_type);
7206 }
7207 }
7208 }
7209
7210 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7211 const ParmVarDecl *P = FD->getParamDecl(I);
7212
7213 // The [[lifetimebound]] attribute can be applied to a function parameter
7214 // only if the function returns a value.
7215 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7216 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7217 S.Diag(A->getLocation(),
7218 diag::err_lifetimebound_parameter_void_return_type);
7219 }
7220 }
7221 }
7222 }
7223}
7224
7226 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7227 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7228}
7229
7231 // Ensure that an auto decl is deduced otherwise the checks below might cache
7232 // the wrong linkage.
7233 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7234
7235 checkWeakAttr(S, ND);
7236 checkWeakRefAttr(S, ND);
7237 checkAliasAttr(S, ND);
7238 checkSelectAnyAttr(S, ND);
7240 checkInheritableAttr(S, ND);
7243}
7244
7246 NamedDecl *NewDecl,
7247 bool IsSpecialization,
7248 bool IsDefinition) {
7249 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7250 return;
7251
7252 bool IsTemplate = false;
7253 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7254 OldDecl = OldTD->getTemplatedDecl();
7255 IsTemplate = true;
7256 if (!IsSpecialization)
7257 IsDefinition = false;
7258 }
7259 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7260 NewDecl = NewTD->getTemplatedDecl();
7261 IsTemplate = true;
7262 }
7263
7264 if (!OldDecl || !NewDecl)
7265 return;
7266
7267 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7268 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7269 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7270 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7271
7272 // dllimport and dllexport are inheritable attributes so we have to exclude
7273 // inherited attribute instances.
7274 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7275 (NewExportAttr && !NewExportAttr->isInherited());
7276
7277 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7278 // the only exception being explicit specializations.
7279 // Implicitly generated declarations are also excluded for now because there
7280 // is no other way to switch these to use dllimport or dllexport.
7281 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7282
7283 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7284 // Allow with a warning for free functions and global variables.
7285 bool JustWarn = false;
7286 if (!OldDecl->isCXXClassMember()) {
7287 auto *VD = dyn_cast<VarDecl>(OldDecl);
7288 if (VD && !VD->getDescribedVarTemplate())
7289 JustWarn = true;
7290 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7291 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7292 JustWarn = true;
7293 }
7294
7295 // We cannot change a declaration that's been used because IR has already
7296 // been emitted. Dllimported functions will still work though (modulo
7297 // address equality) as they can use the thunk.
7298 if (OldDecl->isUsed())
7299 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7300 JustWarn = false;
7301
7302 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7303 : diag::err_attribute_dll_redeclaration;
7304 S.Diag(NewDecl->getLocation(), DiagID)
7305 << NewDecl
7306 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7307 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7308 if (!JustWarn) {
7309 NewDecl->setInvalidDecl();
7310 return;
7311 }
7312 }
7313
7314 // A redeclaration is not allowed to drop a dllimport attribute, the only
7315 // exceptions being inline function definitions (except for function
7316 // templates), local extern declarations, qualified friend declarations or
7317 // special MSVC extension: in the last case, the declaration is treated as if
7318 // it were marked dllexport.
7319 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7320 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7321 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7322 // Ignore static data because out-of-line definitions are diagnosed
7323 // separately.
7324 IsStaticDataMember = VD->isStaticDataMember();
7325 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7327 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7328 IsInline = FD->isInlined();
7329 IsQualifiedFriend = FD->getQualifier() &&
7330 FD->getFriendObjectKind() == Decl::FOK_Declared;
7331 }
7332
7333 if (OldImportAttr && !HasNewAttr &&
7334 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7335 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7336 if (IsMicrosoftABI && IsDefinition) {
7337 if (IsSpecialization) {
7338 S.Diag(
7339 NewDecl->getLocation(),
7340 diag::err_attribute_dllimport_function_specialization_definition);
7341 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7342 NewDecl->dropAttr<DLLImportAttr>();
7343 } else {
7344 S.Diag(NewDecl->getLocation(),
7345 diag::warn_redeclaration_without_import_attribute)
7346 << NewDecl;
7347 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7348 NewDecl->dropAttr<DLLImportAttr>();
7349 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7350 S.Context, NewImportAttr->getRange()));
7351 }
7352 } else if (IsMicrosoftABI && IsSpecialization) {
7353 assert(!IsDefinition);
7354 // MSVC allows this. Keep the inherited attribute.
7355 } else {
7356 S.Diag(NewDecl->getLocation(),
7357 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7358 << NewDecl << OldImportAttr;
7359 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7360 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7361 OldDecl->dropAttr<DLLImportAttr>();
7362 NewDecl->dropAttr<DLLImportAttr>();
7363 }
7364 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7365 // In MinGW, seeing a function declared inline drops the dllimport
7366 // attribute.
7367 OldDecl->dropAttr<DLLImportAttr>();
7368 NewDecl->dropAttr<DLLImportAttr>();
7369 S.Diag(NewDecl->getLocation(),
7370 diag::warn_dllimport_dropped_from_inline_function)
7371 << NewDecl << OldImportAttr;
7372 }
7373
7374 // A specialization of a class template member function is processed here
7375 // since it's a redeclaration. If the parent class is dllexport, the
7376 // specialization inherits that attribute. This doesn't happen automatically
7377 // since the parent class isn't instantiated until later.
7378 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7379 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7380 !NewImportAttr && !NewExportAttr) {
7381 if (const DLLExportAttr *ParentExportAttr =
7382 MD->getParent()->getAttr<DLLExportAttr>()) {
7383 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7384 NewAttr->setInherited(true);
7385 NewDecl->addAttr(NewAttr);
7386 }
7387 }
7388 }
7389}
7390
7391/// Given that we are within the definition of the given function,
7392/// will that definition behave like C99's 'inline', where the
7393/// definition is discarded except for optimization purposes?
7395 // Try to avoid calling GetGVALinkageForFunction.
7396
7397 // All cases of this require the 'inline' keyword.
7398 if (!FD->isInlined()) return false;
7399
7400 // This is only possible in C++ with the gnu_inline attribute.
7401 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7402 return false;
7403
7404 // Okay, go ahead and call the relatively-more-expensive function.
7406}
7407
7408/// Determine whether a variable is extern "C" prior to attaching
7409/// an initializer. We can't just call isExternC() here, because that
7410/// will also compute and cache whether the declaration is externally
7411/// visible, which might change when we attach the initializer.
7412///
7413/// This can only be used if the declaration is known to not be a
7414/// redeclaration of an internal linkage declaration.
7415///
7416/// For instance:
7417///
7418/// auto x = []{};
7419///
7420/// Attaching the initializer here makes this declaration not externally
7421/// visible, because its type has internal linkage.
7422///
7423/// FIXME: This is a hack.
7424template<typename T>
7425static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7426 if (S.getLangOpts().CPlusPlus) {
7427 // In C++, the overloadable attribute negates the effects of extern "C".
7428 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7429 return false;
7430
7431 // So do CUDA's host/device attributes.
7432 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7433 D->template hasAttr<CUDAHostAttr>()))
7434 return false;
7435 }
7436 return D->isExternC();
7437}
7438
7439static bool shouldConsiderLinkage(const VarDecl *VD) {
7440 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7443 return VD->hasExternalStorage();
7444 if (DC->isFileContext())
7445 return true;
7446 if (DC->isRecord())
7447 return false;
7448 if (DC->getDeclKind() == Decl::HLSLBuffer)
7449 return false;
7450
7452 return false;
7453 llvm_unreachable("Unexpected context");
7454}
7455
7456static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7457 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7458 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7460 return true;
7461 if (DC->isRecord())
7462 return false;
7463 llvm_unreachable("Unexpected context");
7464}
7465
7466static bool hasParsedAttr(Scope *S, const Declarator &PD,
7467 ParsedAttr::Kind Kind) {
7468 // Check decl attributes on the DeclSpec.
7469 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7470 return true;
7471
7472 // Walk the declarator structure, checking decl attributes that were in a type
7473 // position to the decl itself.
7474 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7475 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7476 return true;
7477 }
7478
7479 // Finally, check attributes on the decl itself.
7480 return PD.getAttributes().hasAttribute(Kind) ||
7482}
7483
7485 if (!DC->isFunctionOrMethod())
7486 return false;
7487
7488 // If this is a local extern function or variable declared within a function
7489 // template, don't add it into the enclosing namespace scope until it is
7490 // instantiated; it might have a dependent type right now.
7491 if (DC->isDependentContext())
7492 return true;
7493
7494 // C++11 [basic.link]p7:
7495 // When a block scope declaration of an entity with linkage is not found to
7496 // refer to some other declaration, then that entity is a member of the
7497 // innermost enclosing namespace.
7498 //
7499 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7500 // semantically-enclosing namespace, not a lexically-enclosing one.
7501 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7502 DC = DC->getParent();
7503 return true;
7504}
7505
7506/// Returns true if given declaration has external C language linkage.
7507static bool isDeclExternC(const Decl *D) {
7508 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7509 return FD->isExternC();
7510 if (const auto *VD = dyn_cast<VarDecl>(D))
7511 return VD->isExternC();
7512
7513 llvm_unreachable("Unknown type of decl!");
7514}
7515
7516/// Returns true if there hasn't been any invalid type diagnosed.
7517static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7518 DeclContext *DC = NewVD->getDeclContext();
7519 QualType R = NewVD->getType();
7520
7521 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7522 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7523 // argument.
7524 if (R->isImageType() || R->isPipeType()) {
7525 Se.Diag(NewVD->getLocation(),
7526 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7527 << R;
7528 NewVD->setInvalidDecl();
7529 return false;
7530 }
7531
7532 // OpenCL v1.2 s6.9.r:
7533 // The event type cannot be used to declare a program scope variable.
7534 // OpenCL v2.0 s6.9.q:
7535 // The clk_event_t and reserve_id_t types cannot be declared in program
7536 // scope.
7537 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7538 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7539 Se.Diag(NewVD->getLocation(),
7540 diag::err_invalid_type_for_program_scope_var)
7541 << R;
7542 NewVD->setInvalidDecl();
7543 return false;
7544 }
7545 }
7546
7547 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7548 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7549 Se.getLangOpts())) {
7550 QualType NR = R.getCanonicalType();
7551 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7552 NR->isReferenceType()) {
7555 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7556 << NR->isReferenceType();
7557 NewVD->setInvalidDecl();
7558 return false;
7559 }
7560 NR = NR->getPointeeType();
7561 }
7562 }
7563
7564 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7565 Se.getLangOpts())) {
7566 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7567 // half array type (unless the cl_khr_fp16 extension is enabled).
7568 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7569 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7570 NewVD->setInvalidDecl();
7571 return false;
7572 }
7573 }
7574
7575 // OpenCL v1.2 s6.9.r:
7576 // The event type cannot be used with the __local, __constant and __global
7577 // address space qualifiers.
7578 if (R->isEventT()) {
7580 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7581 NewVD->setInvalidDecl();
7582 return false;
7583 }
7584 }
7585
7586 if (R->isSamplerT()) {
7587 // OpenCL v1.2 s6.9.b p4:
7588 // The sampler type cannot be used with the __local and __global address
7589 // space qualifiers.
7592 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7593 NewVD->setInvalidDecl();
7594 }
7595
7596 // OpenCL v1.2 s6.12.14.1:
7597 // A global sampler must be declared with either the constant address
7598 // space qualifier or with the const qualifier.
7599 if (DC->isTranslationUnit() &&
7601 R.isConstQualified())) {
7602 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7603 NewVD->setInvalidDecl();
7604 }
7605 if (NewVD->isInvalidDecl())
7606 return false;
7607 }
7608
7609 return true;
7610}
7611
7612template <typename AttrTy>
7613static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7614 const TypedefNameDecl *TND = TT->getDecl();
7615 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7616 AttrTy *Clone = Attribute->clone(S.Context);
7617 Clone->setInherited(true);
7618 D->addAttr(Clone);
7619 }
7620}
7621
7622// This function emits warning and a corresponding note based on the
7623// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7624// declarations of an annotated type must be const qualified.
7626 QualType VarType = VD->getType().getCanonicalType();
7627
7628 // Ignore local declarations (for now) and those with const qualification.
7629 // TODO: Local variables should not be allowed if their type declaration has
7630 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7631 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7632 return;
7633
7634 if (VarType->isArrayType()) {
7635 // Retrieve element type for array declarations.
7636 VarType = S.getASTContext().getBaseElementType(VarType);
7637 }
7638
7639 const RecordDecl *RD = VarType->getAsRecordDecl();
7640
7641 // Check if the record declaration is present and if it has any attributes.
7642 if (RD == nullptr)
7643 return;
7644
7645 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7646 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7647 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7648 return;
7649 }
7650}
7651
7652// Checks if VD is declared at global scope or with C language linkage.
7653static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7654 return Name.getAsIdentifierInfo() &&
7655 Name.getAsIdentifierInfo()->isStr("main") &&
7656 !VD->getDescribedVarTemplate() &&
7657 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7658 VD->isExternC());
7659}
7660
7661void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7662 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7663
7664 // Quickly return if the function does not have an `asm` attribute.
7665 if (E == nullptr)
7666 return;
7667
7668 // The parser guarantees this is a string.
7669 StringLiteral *SE = cast<StringLiteral>(E);
7670 StringRef Label = SE->getString();
7671 QualType R = TInfo->getType();
7672 if (S->getFnParent() != nullptr) {
7673 switch (SC) {
7674 case SC_None:
7675 case SC_Auto:
7676 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7677 break;
7678 case SC_Register:
7679 // Local Named register
7680 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7682 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7683 break;
7684 case SC_Static:
7685 case SC_Extern:
7686 case SC_PrivateExtern:
7687 break;
7688 }
7689 } else if (SC == SC_Register) {
7690 // Global Named register
7691 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7692 const auto &TI = Context.getTargetInfo();
7693 bool HasSizeMismatch;
7694
7695 if (!TI.isValidGCCRegisterName(Label))
7696 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7697 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7698 HasSizeMismatch))
7699 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7700 else if (HasSizeMismatch)
7701 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7702 }
7703
7704 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7705 Diag(TInfo->getTypeLoc().getBeginLoc(),
7706 diag::err_asm_unsupported_register_type)
7707 << TInfo->getTypeLoc().getSourceRange();
7708 NewVD->setInvalidDecl(true);
7709 }
7710 }
7711}
7712
7714 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7715 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7716 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7717 QualType R = TInfo->getType();
7719
7721 bool IsPlaceholderVariable = false;
7722
7723 if (D.isDecompositionDeclarator()) {
7724 // Take the name of the first declarator as our name for diagnostic
7725 // purposes.
7726 auto &Decomp = D.getDecompositionDeclarator();
7727 if (!Decomp.bindings().empty()) {
7728 II = Decomp.bindings()[0].Name;
7729 Name = II;
7730 }
7731 } else if (!II) {
7732 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7733 return nullptr;
7734 }
7735
7736
7739 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7740 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7741
7742 IsPlaceholderVariable = true;
7743
7744 if (!Previous.empty()) {
7745 NamedDecl *PrevDecl = *Previous.begin();
7746 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7747 DC->getRedeclContext());
7748 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7749 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7750 if (IsPlaceholderVariable)
7752 }
7753 }
7754 }
7755
7756 // dllimport globals without explicit storage class are treated as extern. We
7757 // have to change the storage class this early to get the right DeclContext.
7758 if (SC == SC_None && !DC->isRecord() &&
7759 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7760 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7761 SC = SC_Extern;
7762
7763 DeclContext *OriginalDC = DC;
7764 bool IsLocalExternDecl = SC == SC_Extern &&
7766
7767 if (SCSpec == DeclSpec::SCS_mutable) {
7768 // mutable can only appear on non-static class members, so it's always
7769 // an error here
7770 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7771 D.setInvalidType();
7772 SC = SC_None;
7773 }
7774
7775 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7776 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7778 // In C++11, the 'register' storage class specifier is deprecated.
7779 // Suppress the warning in system macros, it's used in macros in some
7780 // popular C system headers, such as in glibc's htonl() macro.
7782 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7783 : diag::warn_deprecated_register)
7785 }
7786
7788
7789 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7790 // C99 6.9p2: The storage-class specifiers auto and register shall not
7791 // appear in the declaration specifiers in an external declaration.
7792 // Global Register+Asm is a GNU extension we support.
7793 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7794 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7795 D.setInvalidType();
7796 }
7797 }
7798
7799 // If this variable has a VLA type and an initializer, try to
7800 // fold to a constant-sized type. This is otherwise invalid.
7801 if (D.hasInitializer() && R->isVariableArrayType())
7803 /*DiagID=*/0);
7804
7805 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7806 const AutoType *AT = TL.getTypePtr();
7807 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7808 }
7809
7810 bool IsMemberSpecialization = false;
7811 bool IsVariableTemplateSpecialization = false;
7812 bool IsPartialSpecialization = false;
7813 bool IsVariableTemplate = false;
7814 VarDecl *NewVD = nullptr;
7815 VarTemplateDecl *NewTemplate = nullptr;
7816 TemplateParameterList *TemplateParams = nullptr;
7817 if (!getLangOpts().CPlusPlus) {
7819 II, R, TInfo, SC);
7820
7821 if (R->getContainedDeducedType())
7822 ParsingInitForAutoVars.insert(NewVD);
7823
7824 if (D.isInvalidType())
7825 NewVD->setInvalidDecl();
7826
7828 NewVD->hasLocalStorage())
7829 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7831 } else {
7832 bool Invalid = false;
7833 // Match up the template parameter lists with the scope specifier, then
7834 // determine whether we have a template or a template specialization.
7837 D.getCXXScopeSpec(),
7839 ? D.getName().TemplateId
7840 : nullptr,
7841 TemplateParamLists,
7842 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7843
7844 if (TemplateParams) {
7845 if (DC->isDependentContext()) {
7846 ContextRAII SavedContext(*this, DC);
7848 Invalid = true;
7849 }
7850
7851 if (!TemplateParams->size() &&
7853 // There is an extraneous 'template<>' for this variable. Complain
7854 // about it, but allow the declaration of the variable.
7855 Diag(TemplateParams->getTemplateLoc(),
7856 diag::err_template_variable_noparams)
7857 << II
7858 << SourceRange(TemplateParams->getTemplateLoc(),
7859 TemplateParams->getRAngleLoc());
7860 TemplateParams = nullptr;
7861 } else {
7862 // Check that we can declare a template here.
7863 if (CheckTemplateDeclScope(S, TemplateParams))
7864 return nullptr;
7865
7867 // This is an explicit specialization or a partial specialization.
7868 IsVariableTemplateSpecialization = true;
7869 IsPartialSpecialization = TemplateParams->size() > 0;
7870 } else { // if (TemplateParams->size() > 0)
7871 // This is a template declaration.
7872 IsVariableTemplate = true;
7873
7874 // Only C++1y supports variable templates (N3651).
7875 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7876 }
7877 }
7878 } else {
7879 // Check that we can declare a member specialization here.
7880 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7881 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7882 return nullptr;
7883 assert((Invalid ||
7885 "should have a 'template<>' for this decl");
7886 }
7887
7888 bool IsExplicitSpecialization =
7889 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7890
7891 // C++ [temp.expl.spec]p2:
7892 // The declaration in an explicit-specialization shall not be an
7893 // export-declaration. An explicit specialization shall not use a
7894 // storage-class-specifier other than thread_local.
7895 //
7896 // We use the storage-class-specifier from DeclSpec because we may have
7897 // added implicit 'extern' for declarations with __declspec(dllimport)!
7898 if (SCSpec != DeclSpec::SCS_unspecified &&
7899 (IsExplicitSpecialization || IsMemberSpecialization)) {
7901 diag::ext_explicit_specialization_storage_class)
7903 }
7904
7905 if (CurContext->isRecord()) {
7906 if (SC == SC_Static) {
7907 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7908 // Walk up the enclosing DeclContexts to check for any that are
7909 // incompatible with static data members.
7910 const DeclContext *FunctionOrMethod = nullptr;
7911 const CXXRecordDecl *AnonStruct = nullptr;
7912 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7913 if (Ctxt->isFunctionOrMethod()) {
7914 FunctionOrMethod = Ctxt;
7915 break;
7916 }
7917 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7918 if (ParentDecl && !ParentDecl->getDeclName()) {
7919 AnonStruct = ParentDecl;
7920 break;
7921 }
7922 }
7923 if (FunctionOrMethod) {
7924 // C++ [class.static.data]p5: A local class shall not have static
7925 // data members.
7927 diag::err_static_data_member_not_allowed_in_local_class)
7928 << Name << RD->getDeclName() << RD->getTagKind();
7929 } else if (AnonStruct) {
7930 // C++ [class.static.data]p4: Unnamed classes and classes contained
7931 // directly or indirectly within unnamed classes shall not contain
7932 // static data members.
7934 diag::err_static_data_member_not_allowed_in_anon_struct)
7935 << Name << AnonStruct->getTagKind();
7936 Invalid = true;
7937 } else if (RD->isUnion()) {
7938 // C++98 [class.union]p1: If a union contains a static data member,
7939 // the program is ill-formed. C++11 drops this restriction.
7941 diag_compat::static_data_member_in_union)
7942 << Name;
7943 }
7944 }
7945 } else if (IsVariableTemplate || IsPartialSpecialization) {
7946 // There is no such thing as a member field template.
7947 Diag(D.getIdentifierLoc(), diag::err_template_member)
7948 << II << TemplateParams->getSourceRange();
7949 // Recover by pretending this is a static data member template.
7950 SC = SC_Static;
7951 }
7952 } else if (DC->isRecord()) {
7953 // This is an out-of-line definition of a static data member.
7954 switch (SC) {
7955 case SC_None:
7956 break;
7957 case SC_Static:
7959 diag::err_static_out_of_line)
7962 break;
7963 case SC_Auto:
7964 case SC_Register:
7965 case SC_Extern:
7966 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7967 // to names of variables declared in a block or to function parameters.
7968 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7969 // of class members
7970
7972 diag::err_storage_class_for_static_member)
7975 break;
7976 case SC_PrivateExtern:
7977 llvm_unreachable("C storage class in c++!");
7978 }
7979 }
7980
7981 if (IsVariableTemplateSpecialization) {
7982 SourceLocation TemplateKWLoc =
7983 TemplateParamLists.size() > 0
7984 ? TemplateParamLists[0]->getTemplateLoc()
7985 : SourceLocation();
7987 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7989 if (Res.isInvalid())
7990 return nullptr;
7991 NewVD = cast<VarDecl>(Res.get());
7992 AddToScope = false;
7993 } else if (D.isDecompositionDeclarator()) {
7995 D.getIdentifierLoc(), R, TInfo, SC,
7996 Bindings);
7997 } else
7998 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7999 D.getIdentifierLoc(), II, R, TInfo, SC);
8000
8001 // If this is supposed to be a variable template, create it as such.
8002 if (IsVariableTemplate) {
8003 NewTemplate =
8005 TemplateParams, NewVD);
8006 NewVD->setDescribedVarTemplate(NewTemplate);
8007 }
8008
8009 // If this decl has an auto type in need of deduction, make a note of the
8010 // Decl so we can diagnose uses of it in its own initializer.
8011 if (R->getContainedDeducedType())
8012 ParsingInitForAutoVars.insert(NewVD);
8013
8014 if (D.isInvalidType() || Invalid) {
8015 NewVD->setInvalidDecl();
8016 if (NewTemplate)
8017 NewTemplate->setInvalidDecl();
8018 }
8019
8020 SetNestedNameSpecifier(*this, NewVD, D);
8021
8022 // If we have any template parameter lists that don't directly belong to
8023 // the variable (matching the scope specifier), store them.
8024 // An explicit variable template specialization does not own any template
8025 // parameter lists.
8026 unsigned VDTemplateParamLists =
8027 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8028 if (TemplateParamLists.size() > VDTemplateParamLists)
8030 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8031 }
8032
8033 if (D.getDeclSpec().isInlineSpecified()) {
8034 if (!getLangOpts().CPlusPlus) {
8035 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8036 << 0;
8037 } else if (CurContext->isFunctionOrMethod()) {
8038 // 'inline' is not allowed on block scope variable declaration.
8040 diag::err_inline_declaration_block_scope) << Name
8042 } else {
8044 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8045 : diag::compat_pre_cxx17_inline_variable);
8046 NewVD->setInlineSpecified();
8047 }
8048 }
8049
8050 // Set the lexical context. If the declarator has a C++ scope specifier, the
8051 // lexical context will be different from the semantic context.
8053 if (NewTemplate)
8054 NewTemplate->setLexicalDeclContext(CurContext);
8055
8056 if (IsLocalExternDecl) {
8058 for (auto *B : Bindings)
8059 B->setLocalExternDecl();
8060 else
8061 NewVD->setLocalExternDecl();
8062 }
8063
8064 bool EmitTLSUnsupportedError = false;
8066 // C++11 [dcl.stc]p4:
8067 // When thread_local is applied to a variable of block scope the
8068 // storage-class-specifier static is implied if it does not appear
8069 // explicitly.
8070 // Core issue: 'static' is not implied if the variable is declared
8071 // 'extern'.
8072 if (NewVD->hasLocalStorage() &&
8073 (SCSpec != DeclSpec::SCS_unspecified ||
8075 !DC->isFunctionOrMethod()))
8077 diag::err_thread_non_global)
8079 else if (!Context.getTargetInfo().isTLSSupported()) {
8080 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8081 // Postpone error emission until we've collected attributes required to
8082 // figure out whether it's a host or device variable and whether the
8083 // error should be ignored.
8084 EmitTLSUnsupportedError = true;
8085 // We still need to mark the variable as TLS so it shows up in AST with
8086 // proper storage class for other tools to use even if we're not going
8087 // to emit any code for it.
8088 NewVD->setTSCSpec(TSCS);
8089 } else
8091 diag::err_thread_unsupported);
8092 } else
8093 NewVD->setTSCSpec(TSCS);
8094 }
8095
8096 switch (D.getDeclSpec().getConstexprSpecifier()) {
8098 break;
8099
8102 diag::err_constexpr_wrong_decl_kind)
8103 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8104 [[fallthrough]];
8105
8107 NewVD->setConstexpr(true);
8108 // C++1z [dcl.spec.constexpr]p1:
8109 // A static data member declared with the constexpr specifier is
8110 // implicitly an inline variable.
8111 if (NewVD->isStaticDataMember() &&
8113 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8114 NewVD->setImplicitlyInline();
8115 break;
8116
8118 if (!NewVD->hasGlobalStorage())
8120 diag::err_constinit_local_variable);
8121 else
8122 NewVD->addAttr(
8123 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8124 ConstInitAttr::Keyword_constinit));
8125 break;
8126 }
8127
8128 // C99 6.7.4p3
8129 // An inline definition of a function with external linkage shall
8130 // not contain a definition of a modifiable object with static or
8131 // thread storage duration...
8132 // We only apply this when the function is required to be defined
8133 // elsewhere, i.e. when the function is not 'extern inline'. Note
8134 // that a local variable with thread storage duration still has to
8135 // be marked 'static'. Also note that it's possible to get these
8136 // semantics in C++ using __attribute__((gnu_inline)).
8137 if (SC == SC_Static && S->getFnParent() != nullptr &&
8138 !NewVD->getType().isConstQualified()) {
8140 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8142 diag::warn_static_local_in_extern_inline);
8144 }
8145 }
8146
8148 if (IsVariableTemplateSpecialization)
8149 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8150 << (IsPartialSpecialization ? 1 : 0)
8153 else if (IsMemberSpecialization)
8154 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8155 << 2
8157 else if (NewVD->hasLocalStorage())
8158 Diag(NewVD->getLocation(), diag::err_module_private_local)
8159 << 0 << NewVD
8163 else {
8164 NewVD->setModulePrivate();
8165 if (NewTemplate)
8166 NewTemplate->setModulePrivate();
8167 for (auto *B : Bindings)
8168 B->setModulePrivate();
8169 }
8170 }
8171
8172 if (getLangOpts().OpenCL) {
8174
8176 if (TSC != TSCS_unspecified) {
8178 diag::err_opencl_unknown_type_specifier)
8180 << DeclSpec::getSpecifierName(TSC) << 1;
8181 NewVD->setInvalidDecl();
8182 }
8183 }
8184
8185 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8186 // address space if the table has local storage (semantic checks elsewhere
8187 // will produce an error anyway).
8188 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8189 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8190 !NewVD->hasLocalStorage()) {
8191 QualType Type = Context.getAddrSpaceQualType(
8192 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8193 NewVD->setType(Type);
8194 }
8195 }
8196
8197 if (Expr *E = D.getAsmLabel()) {
8198 // The parser guarantees this is a string.
8200 StringRef Label = SE->getString();
8201
8202 // Insert the asm attribute.
8203 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8204 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8205 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8207 if (I != ExtnameUndeclaredIdentifiers.end()) {
8208 if (isDeclExternC(NewVD)) {
8209 NewVD->addAttr(I->second);
8211 } else
8212 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8213 << /*Variable*/ 1 << NewVD;
8214 }
8215 }
8216
8217 // Handle attributes prior to checking for duplicates in MergeVarDecl
8218 ProcessDeclAttributes(S, NewVD, D);
8219
8220 if (getLangOpts().HLSL)
8222
8223 if (getLangOpts().OpenACC)
8225
8226 // FIXME: This is probably the wrong location to be doing this and we should
8227 // probably be doing this for more attributes (especially for function
8228 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8229 // the code to copy attributes would be generated by TableGen.
8230 if (R->isFunctionPointerType())
8231 if (const auto *TT = R->getAs<TypedefType>())
8233
8234 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8235 if (EmitTLSUnsupportedError &&
8237 (getLangOpts().OpenMPIsTargetDevice &&
8238 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8240 diag::err_thread_unsupported);
8241
8242 if (EmitTLSUnsupportedError &&
8243 (LangOpts.SYCLIsDevice ||
8244 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8245 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8246 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8247 // storage [duration]."
8248 if (SC == SC_None && S->getFnParent() != nullptr &&
8249 (NewVD->hasAttr<CUDASharedAttr>() ||
8250 NewVD->hasAttr<CUDAConstantAttr>())) {
8251 NewVD->setStorageClass(SC_Static);
8252 }
8253 }
8254
8255 // Ensure that dllimport globals without explicit storage class are treated as
8256 // extern. The storage class is set above using parsed attributes. Now we can
8257 // check the VarDecl itself.
8258 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8259 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8260 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8261
8262 // In auto-retain/release, infer strong retension for variables of
8263 // retainable type.
8264 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8265 NewVD->setInvalidDecl();
8266
8267 // Check the ASM label here, as we need to know all other attributes of the
8268 // Decl first. Otherwise, we can't know if the asm label refers to the
8269 // host or device in a CUDA context. The device has other registers than
8270 // host and we must know where the function will be placed.
8271 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8272
8273 // Find the shadowed declaration before filtering for scope.
8274 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8276 : nullptr;
8277
8278 // Don't consider existing declarations that are in a different
8279 // scope and are out-of-semantic-context declarations (if the new
8280 // declaration has linkage).
8283 IsMemberSpecialization ||
8284 IsVariableTemplateSpecialization);
8285
8286 // Check whether the previous declaration is in the same block scope. This
8287 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8288 if (getLangOpts().CPlusPlus &&
8289 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8291 Previous.isSingleResult() && !Previous.isShadowed() &&
8292 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8293
8294 if (!getLangOpts().CPlusPlus) {
8296 } else {
8297 // If this is an explicit specialization of a static data member, check it.
8298 if (IsMemberSpecialization && !IsVariableTemplate &&
8299 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8301 NewVD->setInvalidDecl();
8302
8303 // Merge the decl with the existing one if appropriate.
8304 if (!Previous.empty()) {
8305 if (Previous.isSingleResult() &&
8306 isa<FieldDecl>(Previous.getFoundDecl()) &&
8307 D.getCXXScopeSpec().isSet()) {
8308 // The user tried to define a non-static data member
8309 // out-of-line (C++ [dcl.meaning]p1).
8310 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8311 << D.getCXXScopeSpec().getRange();
8312 Previous.clear();
8313 NewVD->setInvalidDecl();
8314 }
8315 } else if (D.getCXXScopeSpec().isSet() &&
8316 !IsVariableTemplateSpecialization) {
8317 // No previous declaration in the qualifying scope.
8318 Diag(D.getIdentifierLoc(), diag::err_no_member)
8319 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8320 << D.getCXXScopeSpec().getRange();
8321 NewVD->setInvalidDecl();
8322 }
8323
8324 if (!IsPlaceholderVariable)
8326
8327 // CheckVariableDeclaration will set NewVD as invalid if something is in
8328 // error like WebAssembly tables being declared as arrays with a non-zero
8329 // size, but then parsing continues and emits further errors on that line.
8330 // To avoid that we check here if it happened and return nullptr.
8331 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8332 return nullptr;
8333
8334 if (NewTemplate) {
8335 VarTemplateDecl *PrevVarTemplate =
8336 NewVD->getPreviousDecl()
8338 : nullptr;
8339
8340 // Check the template parameter list of this declaration, possibly
8341 // merging in the template parameter list from the previous variable
8342 // template declaration.
8344 TemplateParams,
8345 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8346 : nullptr,
8347 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8348 DC->isDependentContext())
8350 : TPC_Other))
8351 NewVD->setInvalidDecl();
8352
8353 // If we are providing an explicit specialization of a static variable
8354 // template, make a note of that.
8355 if (PrevVarTemplate &&
8356 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8357 PrevVarTemplate->setMemberSpecialization();
8358 }
8359 }
8360
8361 // Diagnose shadowed variables iff this isn't a redeclaration.
8362 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8363 CheckShadow(NewVD, ShadowedDecl, Previous);
8364
8365 ProcessPragmaWeak(S, NewVD);
8366
8367 // If this is the first declaration of an extern C variable, update
8368 // the map of such variables.
8369 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8370 isIncompleteDeclExternC(*this, NewVD))
8372
8373 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8375 Decl *ManglingContextDecl;
8376 std::tie(MCtx, ManglingContextDecl) =
8378 if (MCtx) {
8379 Context.setManglingNumber(
8380 NewVD, MCtx->getManglingNumber(
8381 NewVD, getMSManglingNumber(getLangOpts(), S)));
8382 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8383 }
8384 }
8385
8386 // Special handling of variable named 'main'.
8387 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8388 // C++ [basic.start.main]p3:
8389 // A program that declares
8390 // - a variable main at global scope, or
8391 // - an entity named main with C language linkage (in any namespace)
8392 // is ill-formed
8393 if (getLangOpts().CPlusPlus)
8394 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8395 << NewVD->isExternC();
8396
8397 // In C, and external-linkage variable named main results in undefined
8398 // behavior.
8399 else if (NewVD->hasExternalFormalLinkage())
8400 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8401 }
8402
8403 if (D.isRedeclaration() && !Previous.empty()) {
8404 NamedDecl *Prev = Previous.getRepresentativeDecl();
8405 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8407 }
8408
8409 if (NewTemplate) {
8410 if (NewVD->isInvalidDecl())
8411 NewTemplate->setInvalidDecl();
8412 ActOnDocumentableDecl(NewTemplate);
8413 return NewTemplate;
8414 }
8415
8416 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8418
8420
8421 return NewVD;
8422}
8423
8424/// Enum describing the %select options in diag::warn_decl_shadow.
8434
8435/// Determine what kind of declaration we're shadowing.
8437 const DeclContext *OldDC) {
8438 if (isa<TypeAliasDecl>(ShadowedDecl))
8439 return SDK_Using;
8440 else if (isa<TypedefDecl>(ShadowedDecl))
8441 return SDK_Typedef;
8442 else if (isa<BindingDecl>(ShadowedDecl))
8443 return SDK_StructuredBinding;
8444 else if (isa<RecordDecl>(OldDC))
8445 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8446
8447 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8448}
8449
8450/// Return the location of the capture if the given lambda captures the given
8451/// variable \p VD, or an invalid source location otherwise.
8453 const ValueDecl *VD) {
8454 for (const Capture &Capture : LSI->Captures) {
8456 return Capture.getLocation();
8457 }
8458 return SourceLocation();
8459}
8460
8462 const LookupResult &R) {
8463 // Only diagnose if we're shadowing an unambiguous field or variable.
8465 return false;
8466
8467 // Return false if warning is ignored.
8468 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8469}
8470
8472 const LookupResult &R) {
8474 return nullptr;
8475
8476 // Don't diagnose declarations at file scope.
8477 if (D->hasGlobalStorage() && !D->isStaticLocal())
8478 return nullptr;
8479
8480 NamedDecl *ShadowedDecl = R.getFoundDecl();
8481 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8482 : nullptr;
8483}
8484
8486 const LookupResult &R) {
8487 // Don't warn if typedef declaration is part of a class
8488 if (D->getDeclContext()->isRecord())
8489 return nullptr;
8490
8492 return nullptr;
8493
8494 NamedDecl *ShadowedDecl = R.getFoundDecl();
8495 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8496}
8497
8499 const LookupResult &R) {
8501 return nullptr;
8502
8503 NamedDecl *ShadowedDecl = R.getFoundDecl();
8504 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8505 : nullptr;
8506}
8507
8509 const LookupResult &R) {
8510 DeclContext *NewDC = D->getDeclContext();
8511
8512 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8513 if (const auto *MD =
8514 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8515 // Fields aren't shadowed in C++ static members or in member functions
8516 // with an explicit object parameter.
8517 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8518 return;
8519 }
8520 // Fields shadowed by constructor parameters are a special case. Usually
8521 // the constructor initializes the field with the parameter.
8522 if (isa<CXXConstructorDecl>(NewDC))
8523 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8524 // Remember that this was shadowed so we can either warn about its
8525 // modification or its existence depending on warning settings.
8526 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8527 return;
8528 }
8529 }
8530
8531 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8532 if (shadowedVar->isExternC()) {
8533 // For shadowing external vars, make sure that we point to the global
8534 // declaration, not a locally scoped extern declaration.
8535 for (auto *I : shadowedVar->redecls())
8536 if (I->isFileVarDecl()) {
8537 ShadowedDecl = I;
8538 break;
8539 }
8540 }
8541
8542 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8543
8544 unsigned WarningDiag = diag::warn_decl_shadow;
8545 SourceLocation CaptureLoc;
8546 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8547 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8548 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8549 // Handle both VarDecl and BindingDecl in lambda contexts
8550 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8551 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8552 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8553 if (RD->getLambdaCaptureDefault() == LCD_None) {
8554 // Try to avoid warnings for lambdas with an explicit capture
8555 // list. Warn only when the lambda captures the shadowed decl
8556 // explicitly.
8557 CaptureLoc = getCaptureLocation(LSI, VD);
8558 if (CaptureLoc.isInvalid())
8559 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8560 } else {
8561 // Remember that this was shadowed so we can avoid the warning if
8562 // the shadowed decl isn't captured and the warning settings allow
8563 // it.
8565 ->ShadowingDecls.push_back({D, VD});
8566 return;
8567 }
8568 }
8569 if (isa<FieldDecl>(ShadowedDecl)) {
8570 // If lambda can capture this, then emit default shadowing warning,
8571 // Otherwise it is not really a shadowing case since field is not
8572 // available in lambda's body.
8573 // At this point we don't know that lambda can capture this, so
8574 // remember that this was shadowed and delay until we know.
8576 ->ShadowingDecls.push_back({D, ShadowedDecl});
8577 return;
8578 }
8579 }
8580 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8581 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8582 bool HasLocalStorage = false;
8583 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8584 HasLocalStorage = VD->hasLocalStorage();
8585 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8586 HasLocalStorage =
8587 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8588
8589 if (HasLocalStorage) {
8590 // A variable can't shadow a local variable or binding in an enclosing
8591 // scope, if they are separated by a non-capturing declaration
8592 // context.
8593 for (DeclContext *ParentDC = NewDC;
8594 ParentDC && !ParentDC->Equals(OldDC);
8595 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8596 // Only block literals, captured statements, and lambda expressions
8597 // can capture; other scopes don't.
8598 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8599 !isLambdaCallOperator(ParentDC))
8600 return;
8601 }
8602 }
8603 }
8604 }
8605 }
8606
8607 // Never warn about shadowing a placeholder variable.
8608 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8609 return;
8610
8611 // Only warn about certain kinds of shadowing for class members.
8612 if (NewDC) {
8613 // In particular, don't warn about shadowing non-class members.
8614 if (NewDC->isRecord() && !OldDC->isRecord())
8615 return;
8616
8617 // Skip shadowing check if we're in a class scope, dealing with an enum
8618 // constant in a different context.
8619 DeclContext *ReDC = NewDC->getRedeclContext();
8620 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8621 return;
8622
8623 // TODO: should we warn about static data members shadowing
8624 // static data members from base classes?
8625
8626 // TODO: don't diagnose for inaccessible shadowed members.
8627 // This is hard to do perfectly because we might friend the
8628 // shadowing context, but that's just a false negative.
8629 }
8630
8631 DeclarationName Name = R.getLookupName();
8632
8633 // Emit warning and note.
8634 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8635 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8636 if (!CaptureLoc.isInvalid())
8637 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8638 << Name << /*explicitly*/ 1;
8639 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8640}
8641
8643 for (const auto &Shadow : LSI->ShadowingDecls) {
8644 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8645 // Try to avoid the warning when the shadowed decl isn't captured.
8646 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8647 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8648 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8649 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8650 Diag(Shadow.VD->getLocation(),
8651 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8652 : diag::warn_decl_shadow)
8653 << Shadow.VD->getDeclName()
8654 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8655 if (CaptureLoc.isValid())
8656 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8657 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8658 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8659 } else if (isa<FieldDecl>(ShadowedDecl)) {
8660 Diag(Shadow.VD->getLocation(),
8661 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8662 : diag::warn_decl_shadow_uncaptured_local)
8663 << Shadow.VD->getDeclName()
8664 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8665 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8666 }
8667 }
8668}
8669
8671 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8672 return;
8673
8674 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8677 LookupName(R, S);
8678 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8679 CheckShadow(D, ShadowedDecl, R);
8680}
8681
8682/// Check if 'E', which is an expression that is about to be modified, refers
8683/// to a constructor parameter that shadows a field.
8685 // Quickly ignore expressions that can't be shadowing ctor parameters.
8686 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8687 return;
8688 E = E->IgnoreParenImpCasts();
8689 auto *DRE = dyn_cast<DeclRefExpr>(E);
8690 if (!DRE)
8691 return;
8692 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8693 auto I = ShadowingDecls.find(D);
8694 if (I == ShadowingDecls.end())
8695 return;
8696 const NamedDecl *ShadowedDecl = I->second;
8697 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8698 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8699 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8700 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8701
8702 // Avoid issuing multiple warnings about the same decl.
8703 ShadowingDecls.erase(I);
8704}
8705
8706/// Check for conflict between this global or extern "C" declaration and
8707/// previous global or extern "C" declarations. This is only used in C++.
8708template<typename T>
8710 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8711 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8712 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8713
8714 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8715 // The common case: this global doesn't conflict with any extern "C"
8716 // declaration.
8717 return false;
8718 }
8719
8720 if (Prev) {
8721 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8722 // Both the old and new declarations have C language linkage. This is a
8723 // redeclaration.
8724 Previous.clear();
8725 Previous.addDecl(Prev);
8726 return true;
8727 }
8728
8729 // This is a global, non-extern "C" declaration, and there is a previous
8730 // non-global extern "C" declaration. Diagnose if this is a variable
8731 // declaration.
8732 if (!isa<VarDecl>(ND))
8733 return false;
8734 } else {
8735 // The declaration is extern "C". Check for any declaration in the
8736 // translation unit which might conflict.
8737 if (IsGlobal) {
8738 // We have already performed the lookup into the translation unit.
8739 IsGlobal = false;
8740 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8741 I != E; ++I) {
8742 if (isa<VarDecl>(*I)) {
8743 Prev = *I;
8744 break;
8745 }
8746 }
8747 } else {
8749 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8750 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8751 I != E; ++I) {
8752 if (isa<VarDecl>(*I)) {
8753 Prev = *I;
8754 break;
8755 }
8756 // FIXME: If we have any other entity with this name in global scope,
8757 // the declaration is ill-formed, but that is a defect: it breaks the
8758 // 'stat' hack, for instance. Only variables can have mangled name
8759 // clashes with extern "C" declarations, so only they deserve a
8760 // diagnostic.
8761 }
8762 }
8763
8764 if (!Prev)
8765 return false;
8766 }
8767
8768 // Use the first declaration's location to ensure we point at something which
8769 // is lexically inside an extern "C" linkage-spec.
8770 assert(Prev && "should have found a previous declaration to diagnose");
8771 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8772 Prev = FD->getFirstDecl();
8773 else
8774 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8775
8776 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8777 << IsGlobal << ND;
8778 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8779 << IsGlobal;
8780 return false;
8781}
8782
8783/// Apply special rules for handling extern "C" declarations. Returns \c true
8784/// if we have found that this is a redeclaration of some prior entity.
8785///
8786/// Per C++ [dcl.link]p6:
8787/// Two declarations [for a function or variable] with C language linkage
8788/// with the same name that appear in different scopes refer to the same
8789/// [entity]. An entity with C language linkage shall not be declared with
8790/// the same name as an entity in global scope.
8791template<typename T>
8794 if (!S.getLangOpts().CPlusPlus) {
8795 // In C, when declaring a global variable, look for a corresponding 'extern'
8796 // variable declared in function scope. We don't need this in C++, because
8797 // we find local extern decls in the surrounding file-scope DeclContext.
8798 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8799 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8800 Previous.clear();
8801 Previous.addDecl(Prev);
8802 return true;
8803 }
8804 }
8805 return false;
8806 }
8807
8808 // A declaration in the translation unit can conflict with an extern "C"
8809 // declaration.
8810 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8811 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8812
8813 // An extern "C" declaration can conflict with a declaration in the
8814 // translation unit or can be a redeclaration of an extern "C" declaration
8815 // in another scope.
8816 if (isIncompleteDeclExternC(S,ND))
8817 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8818
8819 // Neither global nor extern "C": nothing to do.
8820 return false;
8821}
8822
8823static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8824 QualType T) {
8825 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8826 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8827 // any of its members, even recursively, shall not have an atomic type, or a
8828 // variably modified type, or a type that is volatile or restrict qualified.
8829 if (CanonT->isVariablyModifiedType()) {
8830 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8831 return true;
8832 }
8833
8834 // Arrays are qualified by their element type, so get the base type (this
8835 // works on non-arrays as well).
8836 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8837
8838 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8839 CanonT.isRestrictQualified()) {
8840 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8841 return true;
8842 }
8843
8844 if (CanonT->isRecordType()) {
8845 const RecordDecl *RD = CanonT->getAsRecordDecl();
8846 if (!RD->isInvalidDecl() &&
8847 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8848 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8849 }))
8850 return true;
8851 }
8852
8853 return false;
8854}
8855
8857 // If the decl is already known invalid, don't check it.
8858 if (NewVD->isInvalidDecl())
8859 return;
8860
8861 QualType T = NewVD->getType();
8862
8863 // Defer checking an 'auto' type until its initializer is attached.
8864 if (T->isUndeducedType())
8865 return;
8866
8867 if (NewVD->hasAttrs())
8869
8870 if (T->isObjCObjectType()) {
8871 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8872 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8873 T = Context.getObjCObjectPointerType(T);
8874 NewVD->setType(T);
8875 }
8876
8877 // Emit an error if an address space was applied to decl with local storage.
8878 // This includes arrays of objects with address space qualifiers, but not
8879 // automatic variables that point to other address spaces.
8880 // ISO/IEC TR 18037 S5.1.2
8881 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8882 T.getAddressSpace() != LangAS::Default) {
8883 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8884 NewVD->setInvalidDecl();
8885 return;
8886 }
8887
8888 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8889 // scope.
8890 if (getLangOpts().OpenCLVersion == 120 &&
8891 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8892 getLangOpts()) &&
8893 NewVD->isStaticLocal()) {
8894 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8895 NewVD->setInvalidDecl();
8896 return;
8897 }
8898
8899 if (getLangOpts().OpenCL) {
8900 if (!diagnoseOpenCLTypes(*this, NewVD))
8901 return;
8902
8903 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8904 if (NewVD->hasAttr<BlocksAttr>()) {
8905 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8906 return;
8907 }
8908
8909 if (T->isBlockPointerType()) {
8910 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8911 // can't use 'extern' storage class.
8912 if (!T.isConstQualified()) {
8913 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8914 << 0 /*const*/;
8915 NewVD->setInvalidDecl();
8916 return;
8917 }
8918 if (NewVD->hasExternalStorage()) {
8919 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8920 NewVD->setInvalidDecl();
8921 return;
8922 }
8923 }
8924
8925 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8926 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8927 NewVD->hasExternalStorage()) {
8928 if (!T->isSamplerT() && !T->isDependentType() &&
8929 !(T.getAddressSpace() == LangAS::opencl_constant ||
8930 (T.getAddressSpace() == LangAS::opencl_global &&
8931 getOpenCLOptions().areProgramScopeVariablesSupported(
8932 getLangOpts())))) {
8933 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8934 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8935 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8936 << Scope << "global or constant";
8937 else
8938 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8939 << Scope << "constant";
8940 NewVD->setInvalidDecl();
8941 return;
8942 }
8943 } else {
8944 if (T.getAddressSpace() == LangAS::opencl_global) {
8945 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8946 << 1 /*is any function*/ << "global";
8947 NewVD->setInvalidDecl();
8948 return;
8949 }
8950 if (T.getAddressSpace() == LangAS::opencl_constant ||
8951 T.getAddressSpace() == LangAS::opencl_local) {
8953 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8954 // in functions.
8955 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8956 if (T.getAddressSpace() == LangAS::opencl_constant)
8957 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8958 << 0 /*non-kernel only*/ << "constant";
8959 else
8960 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8961 << 0 /*non-kernel only*/ << "local";
8962 NewVD->setInvalidDecl();
8963 return;
8964 }
8965 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8966 // in the outermost scope of a kernel function.
8967 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8968 if (!getCurScope()->isFunctionScope()) {
8969 if (T.getAddressSpace() == LangAS::opencl_constant)
8970 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8971 << "constant";
8972 else
8973 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8974 << "local";
8975 NewVD->setInvalidDecl();
8976 return;
8977 }
8978 }
8979 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8980 // If we are parsing a template we didn't deduce an addr
8981 // space yet.
8982 T.getAddressSpace() != LangAS::Default) {
8983 // Do not allow other address spaces on automatic variable.
8984 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8985 NewVD->setInvalidDecl();
8986 return;
8987 }
8988 }
8989 }
8990
8991 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8992 && !NewVD->hasAttr<BlocksAttr>()) {
8993 if (getLangOpts().getGC() != LangOptions::NonGC)
8994 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8995 else {
8996 assert(!getLangOpts().ObjCAutoRefCount);
8997 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8998 }
8999 }
9000
9001 // WebAssembly tables must be static with a zero length and can't be
9002 // declared within functions.
9003 if (T->isWebAssemblyTableType()) {
9004 if (getCurScope()->getParent()) { // Parent is null at top-level
9005 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9006 NewVD->setInvalidDecl();
9007 return;
9008 }
9009 if (NewVD->getStorageClass() != SC_Static) {
9010 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9011 NewVD->setInvalidDecl();
9012 return;
9013 }
9014 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9015 if (!ATy || ATy->getZExtSize() != 0) {
9016 Diag(NewVD->getLocation(),
9017 diag::err_typecheck_wasm_table_must_have_zero_length);
9018 NewVD->setInvalidDecl();
9019 return;
9020 }
9021 }
9022
9023 // zero sized static arrays are not allowed in HIP device functions
9024 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9025 if (FunctionDecl *FD = getCurFunctionDecl();
9026 FD &&
9027 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9028 if (const ConstantArrayType *ArrayT =
9029 getASTContext().getAsConstantArrayType(T);
9030 ArrayT && ArrayT->isZeroSize()) {
9031 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9032 }
9033 }
9034 }
9035
9036 bool isVM = T->isVariablyModifiedType();
9037 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9038 NewVD->hasAttr<BlocksAttr>())
9040
9041 if ((isVM && NewVD->hasLinkage()) ||
9042 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9043 bool SizeIsNegative;
9044 llvm::APSInt Oversized;
9046 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9047 QualType FixedT;
9048 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9049 FixedT = FixedTInfo->getType();
9050 else if (FixedTInfo) {
9051 // Type and type-as-written are canonically different. We need to fix up
9052 // both types separately.
9053 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9054 Oversized);
9055 }
9056 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9057 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9058 // FIXME: This won't give the correct result for
9059 // int a[10][n];
9060 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9061
9062 if (NewVD->isFileVarDecl())
9063 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9064 << SizeRange;
9065 else if (NewVD->isStaticLocal())
9066 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9067 << SizeRange;
9068 else
9069 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9070 << SizeRange;
9071 NewVD->setInvalidDecl();
9072 return;
9073 }
9074
9075 if (!FixedTInfo) {
9076 if (NewVD->isFileVarDecl())
9077 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9078 else
9079 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9080 NewVD->setInvalidDecl();
9081 return;
9082 }
9083
9084 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9085 NewVD->setType(FixedT);
9086 NewVD->setTypeSourceInfo(FixedTInfo);
9087 }
9088
9089 if (T->isVoidType()) {
9090 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9091 // of objects and functions.
9093 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9094 << T;
9095 NewVD->setInvalidDecl();
9096 return;
9097 }
9098 }
9099
9100 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9101 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9102 NewVD->setInvalidDecl();
9103 return;
9104 }
9105
9106 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9107 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9108 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9109 NewVD->setInvalidDecl();
9110 return;
9111 }
9112
9113 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9114 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9115 NewVD->setInvalidDecl();
9116 return;
9117 }
9118
9119 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9120 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9121 NewVD->setInvalidDecl();
9122 return;
9123 }
9124
9125 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9126 !T->isDependentType() &&
9128 diag::err_constexpr_var_non_literal)) {
9129 NewVD->setInvalidDecl();
9130 return;
9131 }
9132
9133 // PPC MMA non-pointer types are not allowed as non-local variable types.
9134 if (Context.getTargetInfo().getTriple().isPPC64() &&
9135 !NewVD->isLocalVarDecl() &&
9136 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9137 NewVD->setInvalidDecl();
9138 return;
9139 }
9140
9141 // Check that SVE types are only used in functions with SVE available.
9142 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9144 llvm::StringMap<bool> CallerFeatureMap;
9145 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9146 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9147 CallerFeatureMap)) {
9148 NewVD->setInvalidDecl();
9149 return;
9150 }
9151 }
9152
9153 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9155 llvm::StringMap<bool> CallerFeatureMap;
9156 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9158 CallerFeatureMap);
9159 }
9160}
9161
9164
9165 // If the decl is already known invalid, don't check it.
9166 if (NewVD->isInvalidDecl())
9167 return false;
9168
9169 // If we did not find anything by this name, look for a non-visible
9170 // extern "C" declaration with the same name.
9171 if (Previous.empty() &&
9173 Previous.setShadowed();
9174
9175 if (!Previous.empty()) {
9176 MergeVarDecl(NewVD, Previous);
9177 return true;
9178 }
9179 return false;
9180}
9181
9184
9185 // Look for methods in base classes that this method might override.
9186 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9187 /*DetectVirtual=*/false);
9188 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9189 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9190 DeclarationName Name = MD->getDeclName();
9191
9193 // We really want to find the base class destructor here.
9194 Name = Context.DeclarationNames.getCXXDestructorName(
9195 Context.getCanonicalTagType(BaseRecord));
9196 }
9197
9198 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9199 CXXMethodDecl *BaseMD =
9200 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9201 if (!BaseMD || !BaseMD->isVirtual() ||
9202 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9203 /*ConsiderCudaAttrs=*/true))
9204 continue;
9205 if (!CheckExplicitObjectOverride(MD, BaseMD))
9206 continue;
9207 if (Overridden.insert(BaseMD).second) {
9208 MD->addOverriddenMethod(BaseMD);
9213 }
9214
9215 // A method can only override one function from each base class. We
9216 // don't track indirectly overridden methods from bases of bases.
9217 return true;
9218 }
9219
9220 return false;
9221 };
9222
9223 DC->lookupInBases(VisitBase, Paths);
9224 return !Overridden.empty();
9225}
9226
9227namespace {
9228 // Struct for holding all of the extra arguments needed by
9229 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9230 struct ActOnFDArgs {
9231 Scope *S;
9232 Declarator &D;
9233 MultiTemplateParamsArg TemplateParamLists;
9234 bool AddToScope;
9235 };
9236} // end anonymous namespace
9237
9238namespace {
9239
9240// Callback to only accept typo corrections that have a non-zero edit distance.
9241// Also only accept corrections that have the same parent decl.
9242class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9243 public:
9244 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9245 CXXRecordDecl *Parent)
9246 : Context(Context), OriginalFD(TypoFD),
9247 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9248
9249 bool ValidateCandidate(const TypoCorrection &candidate) override {
9250 if (candidate.getEditDistance() == 0)
9251 return false;
9252
9253 SmallVector<unsigned, 1> MismatchedParams;
9254 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9255 CDeclEnd = candidate.end();
9256 CDecl != CDeclEnd; ++CDecl) {
9257 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9258
9259 if (FD && !FD->hasBody() &&
9260 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9261 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9262 CXXRecordDecl *Parent = MD->getParent();
9263 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9264 return true;
9265 } else if (!ExpectedParent) {
9266 return true;
9267 }
9268 }
9269 }
9270
9271 return false;
9272 }
9273
9274 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9275 return std::make_unique<DifferentNameValidatorCCC>(*this);
9276 }
9277
9278 private:
9279 ASTContext &Context;
9280 FunctionDecl *OriginalFD;
9281 CXXRecordDecl *ExpectedParent;
9282};
9283
9284} // end anonymous namespace
9285
9289
9290/// Generate diagnostics for an invalid function redeclaration.
9291///
9292/// This routine handles generating the diagnostic messages for an invalid
9293/// function redeclaration, including finding possible similar declarations
9294/// or performing typo correction if there are no previous declarations with
9295/// the same name.
9296///
9297/// Returns a NamedDecl iff typo correction was performed and substituting in
9298/// the new declaration name does not cause new errors.
9300 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9301 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9302 DeclarationName Name = NewFD->getDeclName();
9303 DeclContext *NewDC = NewFD->getDeclContext();
9304 SmallVector<unsigned, 1> MismatchedParams;
9306 TypoCorrection Correction;
9307 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9308 unsigned DiagMsg =
9309 IsLocalFriend ? diag::err_no_matching_local_friend :
9310 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9311 diag::err_member_decl_does_not_match;
9312 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9313 IsLocalFriend ? Sema::LookupLocalFriendName
9316
9317 NewFD->setInvalidDecl();
9318 if (IsLocalFriend)
9319 SemaRef.LookupName(Prev, S);
9320 else
9321 SemaRef.LookupQualifiedName(Prev, NewDC);
9322 assert(!Prev.isAmbiguous() &&
9323 "Cannot have an ambiguity in previous-declaration lookup");
9324 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9325 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9326 MD ? MD->getParent() : nullptr);
9327 if (!Prev.empty()) {
9328 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9329 Func != FuncEnd; ++Func) {
9330 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9331 if (FD &&
9332 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9333 // Add 1 to the index so that 0 can mean the mismatch didn't
9334 // involve a parameter
9335 unsigned ParamNum =
9336 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9337 NearMatches.push_back(std::make_pair(FD, ParamNum));
9338 }
9339 }
9340 // If the qualified name lookup yielded nothing, try typo correction
9341 } else if ((Correction = SemaRef.CorrectTypo(
9342 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9343 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9345 IsLocalFriend ? nullptr : NewDC))) {
9346 // Set up everything for the call to ActOnFunctionDeclarator
9347 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9348 ExtraArgs.D.getIdentifierLoc());
9349 Previous.clear();
9350 Previous.setLookupName(Correction.getCorrection());
9351 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9352 CDeclEnd = Correction.end();
9353 CDecl != CDeclEnd; ++CDecl) {
9354 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9355 if (FD && !FD->hasBody() &&
9356 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9357 Previous.addDecl(FD);
9358 }
9359 }
9360 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9361
9362 NamedDecl *Result;
9363 // Retry building the function declaration with the new previous
9364 // declarations, and with errors suppressed.
9365 {
9366 // Trap errors.
9367 Sema::SFINAETrap Trap(SemaRef);
9368
9369 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9370 // pieces need to verify the typo-corrected C++ declaration and hopefully
9371 // eliminate the need for the parameter pack ExtraArgs.
9372 Result = SemaRef.ActOnFunctionDeclarator(
9373 ExtraArgs.S, ExtraArgs.D,
9374 Correction.getCorrectionDecl()->getDeclContext(),
9375 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9376 ExtraArgs.AddToScope);
9377
9378 if (Trap.hasErrorOccurred())
9379 Result = nullptr;
9380 }
9381
9382 if (Result) {
9383 // Determine which correction we picked.
9384 Decl *Canonical = Result->getCanonicalDecl();
9385 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9386 I != E; ++I)
9387 if ((*I)->getCanonicalDecl() == Canonical)
9388 Correction.setCorrectionDecl(*I);
9389
9390 // Let Sema know about the correction.
9392 SemaRef.diagnoseTypo(
9393 Correction,
9394 SemaRef.PDiag(IsLocalFriend
9395 ? diag::err_no_matching_local_friend_suggest
9396 : diag::err_member_decl_does_not_match_suggest)
9397 << Name << NewDC << IsDefinition);
9398 return Result;
9399 }
9400
9401 // Pretend the typo correction never occurred
9402 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9403 ExtraArgs.D.getIdentifierLoc());
9404 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9405 Previous.clear();
9406 Previous.setLookupName(Name);
9407 }
9408
9409 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9410 << Name << NewDC << IsDefinition << NewFD->getLocation();
9411
9412 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9413 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9414 CXXRecordDecl *RD = NewMD->getParent();
9415 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9416 << RD->getName() << RD->getLocation();
9417 }
9418
9419 bool NewFDisConst = NewMD && NewMD->isConst();
9420
9421 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9422 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9423 NearMatch != NearMatchEnd; ++NearMatch) {
9424 FunctionDecl *FD = NearMatch->first;
9425 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9426 bool FDisConst = MD && MD->isConst();
9427 bool IsMember = MD || !IsLocalFriend;
9428
9429 // FIXME: These notes are poorly worded for the local friend case.
9430 if (unsigned Idx = NearMatch->second) {
9431 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9432 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9433 if (Loc.isInvalid()) Loc = FD->getLocation();
9434 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9435 : diag::note_local_decl_close_param_match)
9436 << Idx << FDParam->getType()
9437 << NewFD->getParamDecl(Idx - 1)->getType();
9438 } else if (FDisConst != NewFDisConst) {
9439 auto DB = SemaRef.Diag(FD->getLocation(),
9440 diag::note_member_def_close_const_match)
9441 << NewFDisConst << FD->getSourceRange().getEnd();
9442 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9443 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9444 " const");
9445 else if (FTI.hasMethodTypeQualifiers() &&
9446 FTI.getConstQualifierLoc().isValid())
9447 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9448 } else {
9449 SemaRef.Diag(FD->getLocation(),
9450 IsMember ? diag::note_member_def_close_match
9451 : diag::note_local_decl_close_match);
9452 }
9453 }
9454 return nullptr;
9455}
9456
9458 switch (D.getDeclSpec().getStorageClassSpec()) {
9459 default: llvm_unreachable("Unknown storage class!");
9460 case DeclSpec::SCS_auto:
9464 diag::err_typecheck_sclass_func);
9466 D.setInvalidType();
9467 break;
9468 case DeclSpec::SCS_unspecified: break;
9471 return SC_None;
9472 return SC_Extern;
9473 case DeclSpec::SCS_static: {
9475 // C99 6.7.1p5:
9476 // The declaration of an identifier for a function that has
9477 // block scope shall have no explicit storage-class specifier
9478 // other than extern
9479 // See also (C++ [dcl.stc]p4).
9481 diag::err_static_block_func);
9482 break;
9483 } else
9484 return SC_Static;
9485 }
9487 }
9488
9489 // No explicit storage class has already been returned
9490 return SC_None;
9491}
9492
9494 DeclContext *DC, QualType &R,
9495 TypeSourceInfo *TInfo,
9496 StorageClass SC,
9497 bool &IsVirtualOkay) {
9498 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9499 DeclarationName Name = NameInfo.getName();
9500
9501 FunctionDecl *NewFD = nullptr;
9502 bool isInline = D.getDeclSpec().isInlineSpecified();
9503
9505 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9506 (SemaRef.getLangOpts().C23 &&
9507 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9508
9509 if (SemaRef.getLangOpts().C23)
9510 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9511 diag::err_c23_constexpr_not_variable);
9512 else
9513 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9514 diag::err_constexpr_wrong_decl_kind)
9515 << static_cast<int>(ConstexprKind);
9516 ConstexprKind = ConstexprSpecKind::Unspecified;
9518 }
9519
9520 if (!SemaRef.getLangOpts().CPlusPlus) {
9521 // Determine whether the function was written with a prototype. This is
9522 // true when:
9523 // - there is a prototype in the declarator, or
9524 // - the type R of the function is some kind of typedef or other non-
9525 // attributed reference to a type name (which eventually refers to a
9526 // function type). Note, we can't always look at the adjusted type to
9527 // check this case because attributes may cause a non-function
9528 // declarator to still have a function type. e.g.,
9529 // typedef void func(int a);
9530 // __attribute__((noreturn)) func other_func; // This has a prototype
9531 bool HasPrototype =
9533 (D.getDeclSpec().isTypeRep() &&
9534 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9535 ->isFunctionProtoType()) ||
9537 assert(
9538 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9539 "Strict prototypes are required");
9540
9541 NewFD = FunctionDecl::Create(
9542 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9543 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9545 /*TrailingRequiresClause=*/{});
9546 if (D.isInvalidType())
9547 NewFD->setInvalidDecl();
9548
9549 return NewFD;
9550 }
9551
9553 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9554
9555 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9556
9558 // This is a C++ constructor declaration.
9559 assert(DC->isRecord() &&
9560 "Constructors can only be declared in a member context");
9561
9562 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9564 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9566 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9567 InheritedConstructor(), TrailingRequiresClause);
9568
9569 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9570 // This is a C++ destructor declaration.
9571 if (DC->isRecord()) {
9572 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9575 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9576 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9577 /*isImplicitlyDeclared=*/false, ConstexprKind,
9578 TrailingRequiresClause);
9579 // User defined destructors start as not selected if the class definition is still
9580 // not done.
9581 if (Record->isBeingDefined())
9582 NewDD->setIneligibleOrNotSelected(true);
9583
9584 // If the destructor needs an implicit exception specification, set it
9585 // now. FIXME: It'd be nice to be able to create the right type to start
9586 // with, but the type needs to reference the destructor declaration.
9587 if (SemaRef.getLangOpts().CPlusPlus11)
9588 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9589
9590 IsVirtualOkay = true;
9591 return NewDD;
9592
9593 } else {
9594 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9595 D.setInvalidType();
9596
9597 // Create a FunctionDecl to satisfy the function definition parsing
9598 // code path.
9599 return FunctionDecl::Create(
9600 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9601 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9602 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9603 }
9604
9606 if (!DC->isRecord()) {
9607 SemaRef.Diag(D.getIdentifierLoc(),
9608 diag::err_conv_function_not_member);
9609 return nullptr;
9610 }
9611
9612 SemaRef.CheckConversionDeclarator(D, R, SC);
9613 if (D.isInvalidType())
9614 return nullptr;
9615
9616 IsVirtualOkay = true;
9618 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9619 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9620 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9621 TrailingRequiresClause);
9622
9624 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9625 return nullptr;
9627 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9628 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9629 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9630 } else if (DC->isRecord()) {
9631 // If the name of the function is the same as the name of the record,
9632 // then this must be an invalid constructor that has a return type.
9633 // (The parser checks for a return type and makes the declarator a
9634 // constructor if it has no return type).
9635 if (Name.getAsIdentifierInfo() &&
9636 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9637 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9640 return nullptr;
9641 }
9642
9643 // This is a C++ method declaration.
9645 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9646 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9647 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9648 IsVirtualOkay = !Ret->isStatic();
9649 return Ret;
9650 } else {
9651 bool isFriend =
9652 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9653 if (!isFriend && SemaRef.CurContext->isRecord())
9654 return nullptr;
9655
9656 // Determine whether the function was written with a
9657 // prototype. This true when:
9658 // - we're in C++ (where every function has a prototype),
9659 return FunctionDecl::Create(
9660 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9661 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9662 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9663 }
9664}
9665
9674
9676 // Size dependent types are just typedefs to normal integer types
9677 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9678 // integers other than by their names.
9679 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9680
9681 // Remove typedefs one by one until we reach a typedef
9682 // for a size dependent type.
9683 QualType DesugaredTy = Ty;
9684 do {
9685 ArrayRef<StringRef> Names(SizeTypeNames);
9686 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9687 if (Names.end() != Match)
9688 return true;
9689
9690 Ty = DesugaredTy;
9691 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9692 } while (DesugaredTy != Ty);
9693
9694 return false;
9695}
9696
9698 if (PT->isDependentType())
9699 return InvalidKernelParam;
9700
9701 if (PT->isPointerOrReferenceType()) {
9702 QualType PointeeType = PT->getPointeeType();
9703 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9704 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9705 PointeeType.getAddressSpace() == LangAS::Default)
9707
9708 if (PointeeType->isPointerType()) {
9709 // This is a pointer to pointer parameter.
9710 // Recursively check inner type.
9711 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9712 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9713 ParamKind == InvalidKernelParam)
9714 return ParamKind;
9715
9716 // OpenCL v3.0 s6.11.a:
9717 // A restriction to pass pointers to pointers only applies to OpenCL C
9718 // v1.2 or below.
9720 return ValidKernelParam;
9721
9722 return PtrPtrKernelParam;
9723 }
9724
9725 // C++ for OpenCL v1.0 s2.4:
9726 // Moreover the types used in parameters of the kernel functions must be:
9727 // Standard layout types for pointer parameters. The same applies to
9728 // reference if an implementation supports them in kernel parameters.
9729 if (S.getLangOpts().OpenCLCPlusPlus &&
9731 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9732 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9733 bool IsStandardLayoutType = true;
9734 if (CXXRec) {
9735 // If template type is not ODR-used its definition is only available
9736 // in the template definition not its instantiation.
9737 // FIXME: This logic doesn't work for types that depend on template
9738 // parameter (PR58590).
9739 if (!CXXRec->hasDefinition())
9740 CXXRec = CXXRec->getTemplateInstantiationPattern();
9741 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9742 IsStandardLayoutType = false;
9743 }
9744 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9745 !IsStandardLayoutType)
9746 return InvalidKernelParam;
9747 }
9748
9749 // OpenCL v1.2 s6.9.p:
9750 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9752 return ValidKernelParam;
9753
9754 return PtrKernelParam;
9755 }
9756
9757 // OpenCL v1.2 s6.9.k:
9758 // Arguments to kernel functions in a program cannot be declared with the
9759 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9760 // uintptr_t or a struct and/or union that contain fields declared to be one
9761 // of these built-in scalar types.
9763 return InvalidKernelParam;
9764
9765 if (PT->isImageType())
9766 return PtrKernelParam;
9767
9768 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9769 return InvalidKernelParam;
9770
9771 // OpenCL extension spec v1.2 s9.5:
9772 // This extension adds support for half scalar and vector types as built-in
9773 // types that can be used for arithmetic operations, conversions etc.
9774 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9775 PT->isHalfType())
9776 return InvalidKernelParam;
9777
9778 // Look into an array argument to check if it has a forbidden type.
9779 if (PT->isArrayType()) {
9780 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9781 // Call ourself to check an underlying type of an array. Since the
9782 // getPointeeOrArrayElementType returns an innermost type which is not an
9783 // array, this recursive call only happens once.
9784 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9785 }
9786
9787 // C++ for OpenCL v1.0 s2.4:
9788 // Moreover the types used in parameters of the kernel functions must be:
9789 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9790 // types) for parameters passed by value;
9791 if (S.getLangOpts().OpenCLCPlusPlus &&
9793 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9794 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9795 return InvalidKernelParam;
9796
9797 if (PT->isRecordType())
9798 return RecordKernelParam;
9799
9800 return ValidKernelParam;
9801}
9802
9804 Sema &S,
9805 Declarator &D,
9806 ParmVarDecl *Param,
9807 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9808 QualType PT = Param->getType();
9809
9810 // Cache the valid types we encounter to avoid rechecking structs that are
9811 // used again
9812 if (ValidTypes.count(PT.getTypePtr()))
9813 return;
9814
9815 switch (getOpenCLKernelParameterType(S, PT)) {
9816 case PtrPtrKernelParam:
9817 // OpenCL v3.0 s6.11.a:
9818 // A kernel function argument cannot be declared as a pointer to a pointer
9819 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9820 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9821 D.setInvalidType();
9822 return;
9823
9825 // OpenCL v1.0 s6.5:
9826 // __kernel function arguments declared to be a pointer of a type can point
9827 // to one of the following address spaces only : __global, __local or
9828 // __constant.
9829 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9830 D.setInvalidType();
9831 return;
9832
9833 // OpenCL v1.2 s6.9.k:
9834 // Arguments to kernel functions in a program cannot be declared with the
9835 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9836 // uintptr_t or a struct and/or union that contain fields declared to be
9837 // one of these built-in scalar types.
9838
9839 case InvalidKernelParam:
9840 // OpenCL v1.2 s6.8 n:
9841 // A kernel function argument cannot be declared
9842 // of event_t type.
9843 // Do not diagnose half type since it is diagnosed as invalid argument
9844 // type for any function elsewhere.
9845 if (!PT->isHalfType()) {
9846 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9847
9848 // Explain what typedefs are involved.
9849 const TypedefType *Typedef = nullptr;
9850 while ((Typedef = PT->getAs<TypedefType>())) {
9851 SourceLocation Loc = Typedef->getDecl()->getLocation();
9852 // SourceLocation may be invalid for a built-in type.
9853 if (Loc.isValid())
9854 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9855 PT = Typedef->desugar();
9856 }
9857 }
9858
9859 D.setInvalidType();
9860 return;
9861
9862 case PtrKernelParam:
9863 case ValidKernelParam:
9864 ValidTypes.insert(PT.getTypePtr());
9865 return;
9866
9867 case RecordKernelParam:
9868 break;
9869 }
9870
9871 // Track nested structs we will inspect
9873
9874 // Track where we are in the nested structs. Items will migrate from
9875 // VisitStack to HistoryStack as we do the DFS for bad field.
9877 HistoryStack.push_back(nullptr);
9878
9879 // At this point we already handled everything except of a RecordType.
9880 assert(PT->isRecordType() && "Unexpected type.");
9881 const auto *PD = PT->castAsRecordDecl();
9882 VisitStack.push_back(PD);
9883 assert(VisitStack.back() && "First decl null?");
9884
9885 do {
9886 const Decl *Next = VisitStack.pop_back_val();
9887 if (!Next) {
9888 assert(!HistoryStack.empty());
9889 // Found a marker, we have gone up a level
9890 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9891 ValidTypes.insert(Hist->getType().getTypePtr());
9892
9893 continue;
9894 }
9895
9896 // Adds everything except the original parameter declaration (which is not a
9897 // field itself) to the history stack.
9898 const RecordDecl *RD;
9899 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9900 HistoryStack.push_back(Field);
9901
9902 QualType FieldTy = Field->getType();
9903 // Other field types (known to be valid or invalid) are handled while we
9904 // walk around RecordDecl::fields().
9905 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9906 "Unexpected type.");
9907 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9908
9909 RD = FieldRecTy->castAsRecordDecl();
9910 } else {
9911 RD = cast<RecordDecl>(Next);
9912 }
9913
9914 // Add a null marker so we know when we've gone back up a level
9915 VisitStack.push_back(nullptr);
9916
9917 for (const auto *FD : RD->fields()) {
9918 QualType QT = FD->getType();
9919
9920 if (ValidTypes.count(QT.getTypePtr()))
9921 continue;
9922
9924 if (ParamType == ValidKernelParam)
9925 continue;
9926
9927 if (ParamType == RecordKernelParam) {
9928 VisitStack.push_back(FD);
9929 continue;
9930 }
9931
9932 // OpenCL v1.2 s6.9.p:
9933 // Arguments to kernel functions that are declared to be a struct or union
9934 // do not allow OpenCL objects to be passed as elements of the struct or
9935 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9936 // of SVM.
9937 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9938 ParamType == InvalidAddrSpacePtrKernelParam) {
9939 S.Diag(Param->getLocation(),
9940 diag::err_record_with_pointers_kernel_param)
9941 << PT->isUnionType()
9942 << PT;
9943 } else {
9944 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9945 }
9946
9947 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9948 << PD->getDeclName();
9949
9950 // We have an error, now let's go back up through history and show where
9951 // the offending field came from
9953 I = HistoryStack.begin() + 1,
9954 E = HistoryStack.end();
9955 I != E; ++I) {
9956 const FieldDecl *OuterField = *I;
9957 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9958 << OuterField->getType();
9959 }
9960
9961 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9962 << QT->isPointerType()
9963 << QT;
9964 D.setInvalidType();
9965 return;
9966 }
9967 } while (!VisitStack.empty());
9968}
9969
9970/// Find the DeclContext in which a tag is implicitly declared if we see an
9971/// elaborated type specifier in the specified context, and lookup finds
9972/// nothing.
9974 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9975 DC = DC->getParent();
9976 return DC;
9977}
9978
9979/// Find the Scope in which a tag is implicitly declared if we see an
9980/// elaborated type specifier in the specified context, and lookup finds
9981/// nothing.
9982static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9983 while (S->isClassScope() ||
9984 (LangOpts.CPlusPlus &&
9986 ((S->getFlags() & Scope::DeclScope) == 0) ||
9987 (S->getEntity() && S->getEntity()->isTransparentContext()))
9988 S = S->getParent();
9989 return S;
9990}
9991
9992/// Determine whether a declaration matches a known function in namespace std.
9994 unsigned BuiltinID) {
9995 switch (BuiltinID) {
9996 case Builtin::BI__GetExceptionInfo:
9997 // No type checking whatsoever.
9998 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9999
10000 case Builtin::BIaddressof:
10001 case Builtin::BI__addressof:
10002 case Builtin::BIforward:
10003 case Builtin::BIforward_like:
10004 case Builtin::BImove:
10005 case Builtin::BImove_if_noexcept:
10006 case Builtin::BIas_const: {
10007 // Ensure that we don't treat the algorithm
10008 // OutputIt std::move(InputIt, InputIt, OutputIt)
10009 // as the builtin std::move.
10010 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10011 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10012 }
10013
10014 default:
10015 return false;
10016 }
10017}
10018
10019NamedDecl*
10022 MultiTemplateParamsArg TemplateParamListsRef,
10023 bool &AddToScope) {
10024 QualType R = TInfo->getType();
10025
10026 assert(R->isFunctionType());
10028 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10029
10030 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10031 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10033 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10034 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10035 TemplateParamLists.back() = Invented;
10036 else
10037 TemplateParamLists.push_back(Invented);
10038 }
10039
10040 // TODO: consider using NameInfo for diagnostic.
10042 DeclarationName Name = NameInfo.getName();
10044
10047 diag::err_invalid_thread)
10049
10054
10055 bool isFriend = false;
10057 bool isMemberSpecialization = false;
10058 bool isFunctionTemplateSpecialization = false;
10059
10060 bool HasExplicitTemplateArgs = false;
10061 TemplateArgumentListInfo TemplateArgs;
10062
10063 bool isVirtualOkay = false;
10064
10065 DeclContext *OriginalDC = DC;
10066 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10067
10068 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10069 isVirtualOkay);
10070 if (!NewFD) return nullptr;
10071
10072 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10074
10075 // Set the lexical context. If this is a function-scope declaration, or has a
10076 // C++ scope specifier, or is the object of a friend declaration, the lexical
10077 // context will be different from the semantic context.
10079
10080 if (IsLocalExternDecl)
10081 NewFD->setLocalExternDecl();
10082
10083 if (getLangOpts().CPlusPlus) {
10084 // The rules for implicit inlines changed in C++20 for methods and friends
10085 // with an in-class definition (when such a definition is not attached to
10086 // the global module). This does not affect declarations that are already
10087 // inline (whether explicitly or implicitly by being declared constexpr,
10088 // consteval, etc).
10089 // FIXME: We need a better way to separate C++ standard and clang modules.
10090 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10091 !NewFD->getOwningModule() ||
10092 NewFD->isFromGlobalModule() ||
10094 bool isInline = D.getDeclSpec().isInlineSpecified();
10095 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10096 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10097 isFriend = D.getDeclSpec().isFriendSpecified();
10098 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10099 // Pre-C++20 [class.friend]p5
10100 // A function can be defined in a friend declaration of a
10101 // class . . . . Such a function is implicitly inline.
10102 // Post C++20 [class.friend]p7
10103 // Such a function is implicitly an inline function if it is attached
10104 // to the global module.
10105 NewFD->setImplicitlyInline();
10106 }
10107
10108 // If this is a method defined in an __interface, and is not a constructor
10109 // or an overloaded operator, then set the pure flag (isVirtual will already
10110 // return true).
10111 if (const CXXRecordDecl *Parent =
10112 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10113 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10114 NewFD->setIsPureVirtual(true);
10115
10116 // C++ [class.union]p2
10117 // A union can have member functions, but not virtual functions.
10118 if (isVirtual && Parent->isUnion()) {
10119 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10120 NewFD->setInvalidDecl();
10121 }
10122 if ((Parent->isClass() || Parent->isStruct()) &&
10123 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10124 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10125 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10126 if (auto *Def = Parent->getDefinition())
10127 Def->setInitMethod(true);
10128 }
10129 }
10130
10131 SetNestedNameSpecifier(*this, NewFD, D);
10132 isMemberSpecialization = false;
10133 isFunctionTemplateSpecialization = false;
10134 if (D.isInvalidType())
10135 NewFD->setInvalidDecl();
10136
10137 // Match up the template parameter lists with the scope specifier, then
10138 // determine whether we have a template or a template specialization.
10139 bool Invalid = false;
10140 TemplateIdAnnotation *TemplateId =
10142 ? D.getName().TemplateId
10143 : nullptr;
10144 TemplateParameterList *TemplateParams =
10147 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10148 isMemberSpecialization, Invalid);
10149 if (TemplateParams) {
10150 // Check that we can declare a template here.
10151 if (CheckTemplateDeclScope(S, TemplateParams))
10152 NewFD->setInvalidDecl();
10153
10154 if (TemplateParams->size() > 0) {
10155 // This is a function template
10156
10157 // A destructor cannot be a template.
10159 Diag(NewFD->getLocation(), diag::err_destructor_template);
10160 NewFD->setInvalidDecl();
10161 // Function template with explicit template arguments.
10162 } else if (TemplateId) {
10163 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10164 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10165 NewFD->setInvalidDecl();
10166 }
10167
10168 // If we're adding a template to a dependent context, we may need to
10169 // rebuilding some of the types used within the template parameter list,
10170 // now that we know what the current instantiation is.
10171 if (DC->isDependentContext()) {
10172 ContextRAII SavedContext(*this, DC);
10174 Invalid = true;
10175 }
10176
10178 NewFD->getLocation(),
10179 Name, TemplateParams,
10180 NewFD);
10181 FunctionTemplate->setLexicalDeclContext(CurContext);
10183
10184 // For source fidelity, store the other template param lists.
10185 if (TemplateParamLists.size() > 1) {
10187 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10188 .drop_back(1));
10189 }
10190 } else {
10191 // This is a function template specialization.
10192 isFunctionTemplateSpecialization = true;
10193 // For source fidelity, store all the template param lists.
10194 if (TemplateParamLists.size() > 0)
10195 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10196
10197 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10198 if (isFriend) {
10199 // We want to remove the "template<>", found here.
10200 SourceRange RemoveRange = TemplateParams->getSourceRange();
10201
10202 // If we remove the template<> and the name is not a
10203 // template-id, we're actually silently creating a problem:
10204 // the friend declaration will refer to an untemplated decl,
10205 // and clearly the user wants a template specialization. So
10206 // we need to insert '<>' after the name.
10207 SourceLocation InsertLoc;
10209 InsertLoc = D.getName().getSourceRange().getEnd();
10210 InsertLoc = getLocForEndOfToken(InsertLoc);
10211 }
10212
10213 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10214 << Name << RemoveRange
10215 << FixItHint::CreateRemoval(RemoveRange)
10216 << FixItHint::CreateInsertion(InsertLoc, "<>");
10217 Invalid = true;
10218
10219 // Recover by faking up an empty template argument list.
10220 HasExplicitTemplateArgs = true;
10221 TemplateArgs.setLAngleLoc(InsertLoc);
10222 TemplateArgs.setRAngleLoc(InsertLoc);
10223 }
10224 }
10225 } else {
10226 // Check that we can declare a template here.
10227 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10228 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10229 NewFD->setInvalidDecl();
10230
10231 // All template param lists were matched against the scope specifier:
10232 // this is NOT (an explicit specialization of) a template.
10233 if (TemplateParamLists.size() > 0)
10234 // For source fidelity, store all the template param lists.
10235 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10236
10237 // "friend void foo<>(int);" is an implicit specialization decl.
10238 if (isFriend && TemplateId)
10239 isFunctionTemplateSpecialization = true;
10240 }
10241
10242 // If this is a function template specialization and the unqualified-id of
10243 // the declarator-id is a template-id, convert the template argument list
10244 // into our AST format and check for unexpanded packs.
10245 if (isFunctionTemplateSpecialization && TemplateId) {
10246 HasExplicitTemplateArgs = true;
10247
10248 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10249 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10250 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10251 TemplateId->NumArgs);
10252 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10253
10254 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10255 // declaration of a function template partial specialization? Should we
10256 // consider the unexpanded pack context to be a partial specialization?
10257 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10259 ArgLoc, isFriend ? UPPC_FriendDeclaration
10261 NewFD->setInvalidDecl();
10262 }
10263 }
10264
10265 if (Invalid) {
10266 NewFD->setInvalidDecl();
10267 if (FunctionTemplate)
10268 FunctionTemplate->setInvalidDecl();
10269 }
10270
10271 // C++ [dcl.fct.spec]p5:
10272 // The virtual specifier shall only be used in declarations of
10273 // nonstatic class member functions that appear within a
10274 // member-specification of a class declaration; see 10.3.
10275 //
10276 if (isVirtual && !NewFD->isInvalidDecl()) {
10277 if (!isVirtualOkay) {
10279 diag::err_virtual_non_function);
10280 } else if (!CurContext->isRecord()) {
10281 // 'virtual' was specified outside of the class.
10283 diag::err_virtual_out_of_class)
10285 } else if (NewFD->getDescribedFunctionTemplate()) {
10286 // C++ [temp.mem]p3:
10287 // A member function template shall not be virtual.
10289 diag::err_virtual_member_function_template)
10291 } else {
10292 // Okay: Add virtual to the method.
10293 NewFD->setVirtualAsWritten(true);
10294 }
10295
10296 if (getLangOpts().CPlusPlus14 &&
10297 NewFD->getReturnType()->isUndeducedType())
10298 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10299 }
10300
10301 // C++ [dcl.fct.spec]p3:
10302 // The inline specifier shall not appear on a block scope function
10303 // declaration.
10304 if (isInline && !NewFD->isInvalidDecl()) {
10305 if (CurContext->isFunctionOrMethod()) {
10306 // 'inline' is not allowed on block scope function declaration.
10308 diag::err_inline_declaration_block_scope) << Name
10310 }
10311 }
10312
10313 // C++ [dcl.fct.spec]p6:
10314 // The explicit specifier shall be used only in the declaration of a
10315 // constructor or conversion function within its class definition;
10316 // see 12.3.1 and 12.3.2.
10317 if (hasExplicit && !NewFD->isInvalidDecl() &&
10319 if (!CurContext->isRecord()) {
10320 // 'explicit' was specified outside of the class.
10322 diag::err_explicit_out_of_class)
10324 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10325 !isa<CXXConversionDecl>(NewFD)) {
10326 // 'explicit' was specified on a function that wasn't a constructor
10327 // or conversion function.
10329 diag::err_explicit_non_ctor_or_conv_function)
10331 }
10332 }
10333
10335 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10336 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10337 // are implicitly inline.
10338 NewFD->setImplicitlyInline();
10339
10340 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10341 // be either constructors or to return a literal type. Therefore,
10342 // destructors cannot be declared constexpr.
10343 if (isa<CXXDestructorDecl>(NewFD) &&
10345 ConstexprKind == ConstexprSpecKind::Consteval)) {
10346 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10347 << static_cast<int>(ConstexprKind);
10351 }
10352 // C++20 [dcl.constexpr]p2: An allocation function, or a
10353 // deallocation function shall not be declared with the consteval
10354 // specifier.
10355 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10358 diag::err_invalid_consteval_decl_kind)
10359 << NewFD;
10361 }
10362 }
10363
10364 // If __module_private__ was specified, mark the function accordingly.
10366 if (isFunctionTemplateSpecialization) {
10367 SourceLocation ModulePrivateLoc
10369 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10370 << 0
10371 << FixItHint::CreateRemoval(ModulePrivateLoc);
10372 } else {
10373 NewFD->setModulePrivate();
10374 if (FunctionTemplate)
10375 FunctionTemplate->setModulePrivate();
10376 }
10377 }
10378
10379 if (isFriend) {
10380 if (FunctionTemplate) {
10381 FunctionTemplate->setObjectOfFriendDecl();
10382 FunctionTemplate->setAccess(AS_public);
10383 }
10384 NewFD->setObjectOfFriendDecl();
10385 NewFD->setAccess(AS_public);
10386 }
10387
10388 // If a function is defined as defaulted or deleted, mark it as such now.
10389 // We'll do the relevant checks on defaulted / deleted functions later.
10390 switch (D.getFunctionDefinitionKind()) {
10393 break;
10394
10396 NewFD->setDefaulted();
10397 break;
10398
10400 NewFD->setDeletedAsWritten();
10401 break;
10402 }
10403
10404 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10406 // Pre C++20 [class.mfct]p2:
10407 // A member function may be defined (8.4) in its class definition, in
10408 // which case it is an inline member function (7.1.2)
10409 // Post C++20 [class.mfct]p1:
10410 // If a member function is attached to the global module and is defined
10411 // in its class definition, it is inline.
10412 NewFD->setImplicitlyInline();
10413 }
10414
10415 if (!isFriend && SC != SC_None) {
10416 // C++ [temp.expl.spec]p2:
10417 // The declaration in an explicit-specialization shall not be an
10418 // export-declaration. An explicit specialization shall not use a
10419 // storage-class-specifier other than thread_local.
10420 //
10421 // We diagnose friend declarations with storage-class-specifiers
10422 // elsewhere.
10423 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10425 diag::ext_explicit_specialization_storage_class)
10428 }
10429
10430 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10431 assert(isa<CXXMethodDecl>(NewFD) &&
10432 "Out-of-line member function should be a CXXMethodDecl");
10433 // C++ [class.static]p1:
10434 // A data or function member of a class may be declared static
10435 // in a class definition, in which case it is a static member of
10436 // the class.
10437
10438 // Complain about the 'static' specifier if it's on an out-of-line
10439 // member function definition.
10440
10441 // MSVC permits the use of a 'static' storage specifier on an
10442 // out-of-line member function template declaration and class member
10443 // template declaration (MSVC versions before 2015), warn about this.
10445 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10446 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10447 (getLangOpts().MSVCCompat &&
10449 ? diag::ext_static_out_of_line
10450 : diag::err_static_out_of_line)
10453 }
10454 }
10455
10456 // C++11 [except.spec]p15:
10457 // A deallocation function with no exception-specification is treated
10458 // as if it were specified with noexcept(true).
10459 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10460 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10461 !FPT->hasExceptionSpec())
10462 NewFD->setType(Context.getFunctionType(
10463 FPT->getReturnType(), FPT->getParamTypes(),
10465
10466 // C++20 [dcl.inline]/7
10467 // If an inline function or variable that is attached to a named module
10468 // is declared in a definition domain, it shall be defined in that
10469 // domain.
10470 // So, if the current declaration does not have a definition, we must
10471 // check at the end of the TU (or when the PMF starts) to see that we
10472 // have a definition at that point.
10473 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10474 NewFD->isInNamedModule()) {
10475 PendingInlineFuncDecls.insert(NewFD);
10476 }
10477 }
10478
10479 // Filter out previous declarations that don't match the scope.
10482 isMemberSpecialization ||
10483 isFunctionTemplateSpecialization);
10484
10485 // Handle GNU asm-label extension (encoded as an attribute).
10486 if (Expr *E = D.getAsmLabel()) {
10487 // The parser guarantees this is a string.
10489 NewFD->addAttr(
10490 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10491 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10492 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10494 if (I != ExtnameUndeclaredIdentifiers.end()) {
10495 if (isDeclExternC(NewFD)) {
10496 NewFD->addAttr(I->second);
10498 } else
10499 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10500 << /*Variable*/0 << NewFD;
10501 }
10502 }
10503
10504 // Copy the parameter declarations from the declarator D to the function
10505 // declaration NewFD, if they are available. First scavenge them into Params.
10507 unsigned FTIIdx;
10508 if (D.isFunctionDeclarator(FTIIdx)) {
10510
10511 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10512 // function that takes no arguments, not a function that takes a
10513 // single void argument.
10514 // We let through "const void" here because Sema::GetTypeForDeclarator
10515 // already checks for that case.
10516 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10517 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10518 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10519 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10520 Param->setDeclContext(NewFD);
10521 Params.push_back(Param);
10522
10523 if (Param->isInvalidDecl())
10524 NewFD->setInvalidDecl();
10525 }
10526 }
10527
10528 if (!getLangOpts().CPlusPlus) {
10529 // In C, find all the tag declarations from the prototype and move them
10530 // into the function DeclContext. Remove them from the surrounding tag
10531 // injection context of the function, which is typically but not always
10532 // the TU.
10533 DeclContext *PrototypeTagContext =
10535 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10536 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10537
10538 // We don't want to reparent enumerators. Look at their parent enum
10539 // instead.
10540 if (!TD) {
10541 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10542 TD = cast<EnumDecl>(ECD->getDeclContext());
10543 }
10544 if (!TD)
10545 continue;
10546 DeclContext *TagDC = TD->getLexicalDeclContext();
10547 if (!TagDC->containsDecl(TD))
10548 continue;
10549 TagDC->removeDecl(TD);
10550 TD->setDeclContext(NewFD);
10551 NewFD->addDecl(TD);
10552
10553 // Preserve the lexical DeclContext if it is not the surrounding tag
10554 // injection context of the FD. In this example, the semantic context of
10555 // E will be f and the lexical context will be S, while both the
10556 // semantic and lexical contexts of S will be f:
10557 // void f(struct S { enum E { a } f; } s);
10558 if (TagDC != PrototypeTagContext)
10559 TD->setLexicalDeclContext(TagDC);
10560 }
10561 }
10562 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10563 // When we're declaring a function with a typedef, typeof, etc as in the
10564 // following example, we'll need to synthesize (unnamed)
10565 // parameters for use in the declaration.
10566 //
10567 // @code
10568 // typedef void fn(int);
10569 // fn f;
10570 // @endcode
10571
10572 // Synthesize a parameter for each argument type.
10573 for (const auto &AI : FT->param_types()) {
10574 ParmVarDecl *Param =
10576 Param->setScopeInfo(0, Params.size());
10577 Params.push_back(Param);
10578 }
10579 } else {
10580 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10581 "Should not need args for typedef of non-prototype fn");
10582 }
10583
10584 // Finally, we know we have the right number of parameters, install them.
10585 NewFD->setParams(Params);
10586
10587 // If this declarator is a declaration and not a definition, its parameters
10588 // will not be pushed onto a scope chain. That means we will not issue any
10589 // reserved identifier warnings for the declaration, but we will for the
10590 // definition. Handle those here.
10591 if (!D.isFunctionDefinition()) {
10592 for (const ParmVarDecl *PVD : Params)
10594 }
10595
10597 NewFD->addAttr(
10598 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10599
10600 // Functions returning a variably modified type violate C99 6.7.5.2p2
10601 // because all functions have linkage.
10602 if (!NewFD->isInvalidDecl() &&
10604 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10605 NewFD->setInvalidDecl();
10606 }
10607
10608 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10610 !NewFD->hasAttr<SectionAttr>())
10611 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10612 Context, PragmaClangTextSection.SectionName,
10613 PragmaClangTextSection.PragmaLocation));
10614
10615 // Apply an implicit SectionAttr if #pragma code_seg is active.
10616 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10617 !NewFD->hasAttr<SectionAttr>()) {
10618 NewFD->addAttr(SectionAttr::CreateImplicit(
10619 Context, CodeSegStack.CurrentValue->getString(),
10620 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10621 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10624 NewFD))
10625 NewFD->dropAttr<SectionAttr>();
10626 }
10627
10628 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10629 // active.
10630 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10631 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10632 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10633 Context, PragmaClangTextSection.PragmaLocation));
10634
10635 // Apply an implicit CodeSegAttr from class declspec or
10636 // apply an implicit SectionAttr from #pragma code_seg if active.
10637 if (!NewFD->hasAttr<CodeSegAttr>()) {
10639 D.isFunctionDefinition())) {
10640 NewFD->addAttr(SAttr);
10641 }
10642 }
10643
10644 // Handle attributes.
10645 ProcessDeclAttributes(S, NewFD, D);
10646 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10647 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10648 !NewTVA->isDefaultVersion() &&
10649 !Context.getTargetInfo().hasFeature("fmv")) {
10650 // Don't add to scope fmv functions declarations if fmv disabled
10651 AddToScope = false;
10652 return NewFD;
10653 }
10654
10655 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10656 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10657 // type.
10658 //
10659 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10660 // type declaration will generate a compilation error.
10661 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10662 if (AddressSpace != LangAS::Default) {
10663 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10664 NewFD->setInvalidDecl();
10665 }
10666 }
10667
10668 if (!getLangOpts().CPlusPlus) {
10669 // Perform semantic checking on the function declaration.
10670 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10671 CheckMain(NewFD, D.getDeclSpec());
10672
10673 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10674 CheckMSVCRTEntryPoint(NewFD);
10675
10676 if (!NewFD->isInvalidDecl())
10678 isMemberSpecialization,
10680 else if (!Previous.empty())
10681 // Recover gracefully from an invalid redeclaration.
10682 D.setRedeclaration(true);
10683 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10684 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10685 "previous declaration set still overloaded");
10686
10687 // Diagnose no-prototype function declarations with calling conventions that
10688 // don't support variadic calls. Only do this in C and do it after merging
10689 // possibly prototyped redeclarations.
10690 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10692 CallingConv CC = FT->getExtInfo().getCC();
10693 if (!supportsVariadicCall(CC)) {
10694 // Windows system headers sometimes accidentally use stdcall without
10695 // (void) parameters, so we relax this to a warning.
10696 int DiagID =
10697 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10698 Diag(NewFD->getLocation(), DiagID)
10700 }
10701 }
10702
10706 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10708 } else {
10709 // C++11 [replacement.functions]p3:
10710 // The program's definitions shall not be specified as inline.
10711 //
10712 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10713 //
10714 // Suppress the diagnostic if the function is __attribute__((used)), since
10715 // that forces an external definition to be emitted.
10716 if (D.getDeclSpec().isInlineSpecified() &&
10718 !NewFD->hasAttr<UsedAttr>())
10720 diag::ext_operator_new_delete_declared_inline)
10721 << NewFD->getDeclName();
10722
10723 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10724 // C++20 [dcl.decl.general]p4:
10725 // The optional requires-clause in an init-declarator or
10726 // member-declarator shall be present only if the declarator declares a
10727 // templated function.
10728 //
10729 // C++20 [temp.pre]p8:
10730 // An entity is templated if it is
10731 // - a template,
10732 // - an entity defined or created in a templated entity,
10733 // - a member of a templated entity,
10734 // - an enumerator for an enumeration that is a templated entity, or
10735 // - the closure type of a lambda-expression appearing in the
10736 // declaration of a templated entity.
10737 //
10738 // [Note 6: A local class, a local or block variable, or a friend
10739 // function defined in a templated entity is a templated entity.
10740 // — end note]
10741 //
10742 // A templated function is a function template or a function that is
10743 // templated. A templated class is a class template or a class that is
10744 // templated. A templated variable is a variable template or a variable
10745 // that is templated.
10746 if (!FunctionTemplate) {
10747 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10748 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10749 // An explicit specialization shall not have a trailing
10750 // requires-clause unless it declares a function template.
10751 //
10752 // Since a friend function template specialization cannot be
10753 // definition, and since a non-template friend declaration with a
10754 // trailing requires-clause must be a definition, we diagnose
10755 // friend function template specializations with trailing
10756 // requires-clauses on the same path as explicit specializations
10757 // even though they aren't necessarily prohibited by the same
10758 // language rule.
10759 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10760 << isFriend;
10761 } else if (isFriend && NewFD->isTemplated() &&
10762 !D.isFunctionDefinition()) {
10763 // C++ [temp.friend]p9:
10764 // A non-template friend declaration with a requires-clause shall be
10765 // a definition.
10766 Diag(NewFD->getBeginLoc(),
10767 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10768 NewFD->setInvalidDecl();
10769 } else if (!NewFD->isTemplated() ||
10770 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10771 Diag(TRC->getBeginLoc(),
10772 diag::err_constrained_non_templated_function);
10773 }
10774 }
10775 }
10776
10777 // We do not add HD attributes to specializations here because
10778 // they may have different constexpr-ness compared to their
10779 // templates and, after maybeAddHostDeviceAttrs() is applied,
10780 // may end up with different effective targets. Instead, a
10781 // specialization inherits its target attributes from its template
10782 // in the CheckFunctionTemplateSpecialization() call below.
10783 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10785
10786 // Handle explicit specializations of function templates
10787 // and friend function declarations with an explicit
10788 // template argument list.
10789 if (isFunctionTemplateSpecialization) {
10790 bool isDependentSpecialization = false;
10791 if (isFriend) {
10792 // For friend function specializations, this is a dependent
10793 // specialization if its semantic context is dependent, its
10794 // type is dependent, or if its template-id is dependent.
10795 isDependentSpecialization =
10796 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10797 (HasExplicitTemplateArgs &&
10798 TemplateSpecializationType::
10799 anyInstantiationDependentTemplateArguments(
10800 TemplateArgs.arguments()));
10801 assert((!isDependentSpecialization ||
10802 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10803 "dependent friend function specialization without template "
10804 "args");
10805 } else {
10806 // For class-scope explicit specializations of function templates,
10807 // if the lexical context is dependent, then the specialization
10808 // is dependent.
10809 isDependentSpecialization =
10810 CurContext->isRecord() && CurContext->isDependentContext();
10811 }
10812
10813 TemplateArgumentListInfo *ExplicitTemplateArgs =
10814 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10815 if (isDependentSpecialization) {
10816 // If it's a dependent specialization, it may not be possible
10817 // to determine the primary template (for explicit specializations)
10818 // or befriended declaration (for friends) until the enclosing
10819 // template is instantiated. In such cases, we store the declarations
10820 // found by name lookup and defer resolution until instantiation.
10822 NewFD, ExplicitTemplateArgs, Previous))
10823 NewFD->setInvalidDecl();
10824 } else if (!NewFD->isInvalidDecl()) {
10825 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10826 Previous))
10827 NewFD->setInvalidDecl();
10828 }
10829 } else if (isMemberSpecialization && !FunctionTemplate) {
10831 NewFD->setInvalidDecl();
10832 }
10833
10834 // Perform semantic checking on the function declaration.
10835 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10836 CheckMain(NewFD, D.getDeclSpec());
10837
10838 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10839 CheckMSVCRTEntryPoint(NewFD);
10840
10841 if (!NewFD->isInvalidDecl())
10843 isMemberSpecialization,
10845 else if (!Previous.empty())
10846 // Recover gracefully from an invalid redeclaration.
10847 D.setRedeclaration(true);
10848
10849 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10850 !D.isRedeclaration() ||
10851 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10852 "previous declaration set still overloaded");
10853
10854 NamedDecl *PrincipalDecl = (FunctionTemplate
10856 : NewFD);
10857
10858 if (isFriend && NewFD->getPreviousDecl()) {
10859 AccessSpecifier Access = AS_public;
10860 if (!NewFD->isInvalidDecl())
10861 Access = NewFD->getPreviousDecl()->getAccess();
10862
10863 NewFD->setAccess(Access);
10864 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10865 }
10866
10867 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10869 PrincipalDecl->setNonMemberOperator();
10870
10871 // If we have a function template, check the template parameter
10872 // list. This will check and merge default template arguments.
10873 if (FunctionTemplate) {
10874 FunctionTemplateDecl *PrevTemplate =
10875 FunctionTemplate->getPreviousDecl();
10876 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10877 PrevTemplate ? PrevTemplate->getTemplateParameters()
10878 : nullptr,
10883 : (D.getCXXScopeSpec().isSet() &&
10884 DC && DC->isRecord() &&
10885 DC->isDependentContext())
10888 }
10889
10890 if (NewFD->isInvalidDecl()) {
10891 // Ignore all the rest of this.
10892 } else if (!D.isRedeclaration()) {
10893 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10894 AddToScope };
10895 // Fake up an access specifier if it's supposed to be a class member.
10896 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10897 NewFD->setAccess(AS_public);
10898
10899 // Qualified decls generally require a previous declaration.
10900 if (D.getCXXScopeSpec().isSet()) {
10901 // ...with the major exception of templated-scope or
10902 // dependent-scope friend declarations.
10903
10904 // TODO: we currently also suppress this check in dependent
10905 // contexts because (1) the parameter depth will be off when
10906 // matching friend templates and (2) we might actually be
10907 // selecting a friend based on a dependent factor. But there
10908 // are situations where these conditions don't apply and we
10909 // can actually do this check immediately.
10910 //
10911 // Unless the scope is dependent, it's always an error if qualified
10912 // redeclaration lookup found nothing at all. Diagnose that now;
10913 // nothing will diagnose that error later.
10914 if (isFriend &&
10916 (!Previous.empty() && CurContext->isDependentContext()))) {
10917 // ignore these
10918 } else if (NewFD->isCPUDispatchMultiVersion() ||
10919 NewFD->isCPUSpecificMultiVersion()) {
10920 // ignore this, we allow the redeclaration behavior here to create new
10921 // versions of the function.
10922 } else {
10923 // The user tried to provide an out-of-line definition for a
10924 // function that is a member of a class or namespace, but there
10925 // was no such member function declared (C++ [class.mfct]p2,
10926 // C++ [namespace.memdef]p2). For example:
10927 //
10928 // class X {
10929 // void f() const;
10930 // };
10931 //
10932 // void X::f() { } // ill-formed
10933 //
10934 // Complain about this problem, and attempt to suggest close
10935 // matches (e.g., those that differ only in cv-qualifiers and
10936 // whether the parameter types are references).
10937
10939 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10940 AddToScope = ExtraArgs.AddToScope;
10941 return Result;
10942 }
10943 }
10944
10945 // Unqualified local friend declarations are required to resolve
10946 // to something.
10947 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10949 *this, Previous, NewFD, ExtraArgs, true, S)) {
10950 AddToScope = ExtraArgs.AddToScope;
10951 return Result;
10952 }
10953 }
10954 } else if (!D.isFunctionDefinition() &&
10955 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10956 !isFriend && !isFunctionTemplateSpecialization &&
10957 !isMemberSpecialization) {
10958 // An out-of-line member function declaration must also be a
10959 // definition (C++ [class.mfct]p2).
10960 // Note that this is not the case for explicit specializations of
10961 // function templates or member functions of class templates, per
10962 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10963 // extension for compatibility with old SWIG code which likes to
10964 // generate them.
10965 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10966 << D.getCXXScopeSpec().getRange();
10967 }
10968 }
10969
10970 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10971 // Any top level function could potentially be specified as an entry.
10972 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10973 HLSL().ActOnTopLevelFunction(NewFD);
10974
10975 if (NewFD->hasAttr<HLSLShaderAttr>())
10976 HLSL().CheckEntryPoint(NewFD);
10977 }
10978
10979 // If this is the first declaration of a library builtin function, add
10980 // attributes as appropriate.
10981 if (!D.isRedeclaration()) {
10982 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10983 if (unsigned BuiltinID = II->getBuiltinID()) {
10984 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10985 if (!InStdNamespace &&
10987 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10988 // Validate the type matches unless this builtin is specified as
10989 // matching regardless of its declared type.
10990 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10991 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10992 } else {
10994 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10995 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10996
10997 if (!Error && !BuiltinType.isNull() &&
10998 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10999 NewFD->getType(), BuiltinType))
11000 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11001 }
11002 }
11003 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11004 isStdBuiltin(Context, NewFD, BuiltinID)) {
11005 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11006 }
11007 }
11008 }
11009 }
11010
11011 ProcessPragmaWeak(S, NewFD);
11012 checkAttributesAfterMerging(*this, *NewFD);
11013
11015
11016 if (NewFD->hasAttr<OverloadableAttr>() &&
11017 !NewFD->getType()->getAs<FunctionProtoType>()) {
11018 Diag(NewFD->getLocation(),
11019 diag::err_attribute_overloadable_no_prototype)
11020 << NewFD;
11021 NewFD->dropAttr<OverloadableAttr>();
11022 }
11023
11024 // If there's a #pragma GCC visibility in scope, and this isn't a class
11025 // member, set the visibility of this function.
11026 if (!DC->isRecord() && NewFD->isExternallyVisible())
11028
11029 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11030 // marking the function.
11031 ObjC().AddCFAuditedAttribute(NewFD);
11032
11033 // If this is a function definition, check if we have to apply any
11034 // attributes (i.e. optnone and no_builtin) due to a pragma.
11035 if (D.isFunctionDefinition()) {
11036 AddRangeBasedOptnone(NewFD);
11038 AddSectionMSAllocText(NewFD);
11040 }
11041
11042 // If this is the first declaration of an extern C variable, update
11043 // the map of such variables.
11044 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11045 isIncompleteDeclExternC(*this, NewFD))
11047
11048 // Set this FunctionDecl's range up to the right paren.
11049 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11050
11051 if (D.isRedeclaration() && !Previous.empty()) {
11052 NamedDecl *Prev = Previous.getRepresentativeDecl();
11053 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11054 isMemberSpecialization ||
11055 isFunctionTemplateSpecialization,
11057 }
11058
11059 if (getLangOpts().CUDA) {
11060 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11061 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11064 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11066 Context.setcudaConfigureCallDecl(NewFD);
11067 }
11068 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11069 !NewFD->isInvalidDecl() &&
11072 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11074 Context.setcudaGetParameterBufferDecl(NewFD);
11075 }
11076 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11077 !NewFD->isInvalidDecl() &&
11080 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11082 Context.setcudaLaunchDeviceDecl(NewFD);
11083 }
11084 }
11085 }
11086
11088
11089 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11090 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11091 if (SC == SC_Static) {
11092 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11093 D.setInvalidType();
11094 }
11095
11096 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11097 if (!NewFD->getReturnType()->isVoidType()) {
11098 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11099 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11100 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11101 : FixItHint());
11102 D.setInvalidType();
11103 }
11104
11106 for (auto *Param : NewFD->parameters())
11107 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11108
11109 if (getLangOpts().OpenCLCPlusPlus) {
11110 if (DC->isRecord()) {
11111 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11112 D.setInvalidType();
11113 }
11114 if (FunctionTemplate) {
11115 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11116 D.setInvalidType();
11117 }
11118 }
11119 }
11120
11121 if (getLangOpts().CPlusPlus) {
11122 // Precalculate whether this is a friend function template with a constraint
11123 // that depends on an enclosing template, per [temp.friend]p9.
11124 if (isFriend && FunctionTemplate &&
11127
11128 // C++ [temp.friend]p9:
11129 // A friend function template with a constraint that depends on a
11130 // template parameter from an enclosing template shall be a definition.
11131 if (!D.isFunctionDefinition()) {
11132 Diag(NewFD->getBeginLoc(),
11133 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11134 NewFD->setInvalidDecl();
11135 }
11136 }
11137
11138 if (FunctionTemplate) {
11139 if (NewFD->isInvalidDecl())
11140 FunctionTemplate->setInvalidDecl();
11141 return FunctionTemplate;
11142 }
11143
11144 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11146 }
11147
11148 for (const ParmVarDecl *Param : NewFD->parameters()) {
11149 QualType PT = Param->getType();
11150
11151 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11152 // types.
11153 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11154 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11155 QualType ElemTy = PipeTy->getElementType();
11156 if (ElemTy->isPointerOrReferenceType()) {
11157 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11158 D.setInvalidType();
11159 }
11160 }
11161 }
11162 // WebAssembly tables can't be used as function parameters.
11163 if (Context.getTargetInfo().getTriple().isWasm()) {
11165 Diag(Param->getTypeSpecStartLoc(),
11166 diag::err_wasm_table_as_function_parameter);
11167 D.setInvalidType();
11168 }
11169 }
11170 }
11171
11172 // Diagnose availability attributes. Availability cannot be used on functions
11173 // that are run during load/unload.
11174 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11175 if (NewFD->hasAttr<ConstructorAttr>()) {
11176 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11177 << 1;
11178 NewFD->dropAttr<AvailabilityAttr>();
11179 }
11180 if (NewFD->hasAttr<DestructorAttr>()) {
11181 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11182 << 2;
11183 NewFD->dropAttr<AvailabilityAttr>();
11184 }
11185 }
11186
11187 // Diagnose no_builtin attribute on function declaration that are not a
11188 // definition.
11189 // FIXME: We should really be doing this in
11190 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11191 // the FunctionDecl and at this point of the code
11192 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11193 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11194 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11195 switch (D.getFunctionDefinitionKind()) {
11198 Diag(NBA->getLocation(),
11199 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11200 << NBA->getSpelling();
11201 break;
11203 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11204 << NBA->getSpelling();
11205 break;
11207 break;
11208 }
11209
11210 // Similar to no_builtin logic above, at this point of the code
11211 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11212 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11213 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11214 !NewFD->isInvalidDecl() &&
11216 ExternalDeclarations.push_back(NewFD);
11217
11218 // Used for a warning on the 'next' declaration when used with a
11219 // `routine(name)`.
11220 if (getLangOpts().OpenACC)
11222
11223 return NewFD;
11224}
11225
11226/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11227/// when __declspec(code_seg) "is applied to a class, all member functions of
11228/// the class and nested classes -- this includes compiler-generated special
11229/// member functions -- are put in the specified segment."
11230/// The actual behavior is a little more complicated. The Microsoft compiler
11231/// won't check outer classes if there is an active value from #pragma code_seg.
11232/// The CodeSeg is always applied from the direct parent but only from outer
11233/// classes when the #pragma code_seg stack is empty. See:
11234/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11235/// available since MS has removed the page.
11237 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11238 if (!Method)
11239 return nullptr;
11240 const CXXRecordDecl *Parent = Method->getParent();
11241 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11242 Attr *NewAttr = SAttr->clone(S.getASTContext());
11243 NewAttr->setImplicit(true);
11244 return NewAttr;
11245 }
11246
11247 // The Microsoft compiler won't check outer classes for the CodeSeg
11248 // when the #pragma code_seg stack is active.
11249 if (S.CodeSegStack.CurrentValue)
11250 return nullptr;
11251
11252 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11253 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11254 Attr *NewAttr = SAttr->clone(S.getASTContext());
11255 NewAttr->setImplicit(true);
11256 return NewAttr;
11257 }
11258 }
11259 return nullptr;
11260}
11261
11263 bool IsDefinition) {
11264 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11265 return A;
11266 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11267 CodeSegStack.CurrentValue)
11268 return SectionAttr::CreateImplicit(
11269 getASTContext(), CodeSegStack.CurrentValue->getString(),
11270 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11271 return nullptr;
11272}
11273
11275 QualType NewT, QualType OldT) {
11277 return true;
11278
11279 // For dependently-typed local extern declarations and friends, we can't
11280 // perform a correct type check in general until instantiation:
11281 //
11282 // int f();
11283 // template<typename T> void g() { T f(); }
11284 //
11285 // (valid if g() is only instantiated with T = int).
11286 if (NewT->isDependentType() &&
11287 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11288 return false;
11289
11290 // Similarly, if the previous declaration was a dependent local extern
11291 // declaration, we don't really know its type yet.
11292 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11293 return false;
11294
11295 return true;
11296}
11297
11300 return true;
11301
11302 // Don't chain dependent friend function definitions until instantiation, to
11303 // permit cases like
11304 //
11305 // void func();
11306 // template<typename T> class C1 { friend void func() {} };
11307 // template<typename T> class C2 { friend void func() {} };
11308 //
11309 // ... which is valid if only one of C1 and C2 is ever instantiated.
11310 //
11311 // FIXME: This need only apply to function definitions. For now, we proxy
11312 // this by checking for a file-scope function. We do not want this to apply
11313 // to friend declarations nominating member functions, because that gets in
11314 // the way of access checks.
11316 return false;
11317
11318 auto *VD = dyn_cast<ValueDecl>(D);
11319 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11320 return !VD || !PrevVD ||
11321 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11322 PrevVD->getType());
11323}
11324
11325/// Check the target or target_version attribute of the function for
11326/// MultiVersion validity.
11327///
11328/// Returns true if there was an error, false otherwise.
11329static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11330 const auto *TA = FD->getAttr<TargetAttr>();
11331 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11332
11333 assert((TA || TVA) && "Expecting target or target_version attribute");
11334
11336 enum ErrType { Feature = 0, Architecture = 1 };
11337
11338 if (TA) {
11339 ParsedTargetAttr ParseInfo =
11340 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11341 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11342 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11343 << Architecture << ParseInfo.CPU;
11344 return true;
11345 }
11346 for (const auto &Feat : ParseInfo.Features) {
11347 auto BareFeat = StringRef{Feat}.substr(1);
11348 if (Feat[0] == '-') {
11349 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11350 << Feature << ("no-" + BareFeat).str();
11351 return true;
11352 }
11353
11354 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11355 !TargetInfo.isValidFeatureName(BareFeat) ||
11356 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11357 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11358 << Feature << BareFeat;
11359 return true;
11360 }
11361 }
11362 }
11363
11364 if (TVA) {
11366 ParsedTargetAttr ParseInfo;
11367 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11368 ParseInfo =
11369 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11370 for (auto &Feat : ParseInfo.Features)
11371 Feats.push_back(StringRef{Feat}.substr(1));
11372 } else {
11373 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11374 TVA->getFeatures(Feats);
11375 }
11376 for (const auto &Feat : Feats) {
11377 if (!TargetInfo.validateCpuSupports(Feat)) {
11378 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11379 << Feature << Feat;
11380 return true;
11381 }
11382 }
11383 }
11384 return false;
11385}
11386
11387// Provide a white-list of attributes that are allowed to be combined with
11388// multiversion functions.
11390 MultiVersionKind MVKind) {
11391 // Note: this list/diagnosis must match the list in
11392 // checkMultiversionAttributesAllSame.
11393 switch (Kind) {
11394 default:
11395 return false;
11396 case attr::ArmLocallyStreaming:
11397 return MVKind == MultiVersionKind::TargetVersion ||
11399 case attr::Used:
11400 return MVKind == MultiVersionKind::Target;
11401 case attr::NonNull:
11402 case attr::NoThrow:
11403 return true;
11404 }
11405}
11406
11408 const FunctionDecl *FD,
11409 const FunctionDecl *CausedFD,
11410 MultiVersionKind MVKind) {
11411 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11412 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11413 << static_cast<unsigned>(MVKind) << A;
11414 if (CausedFD)
11415 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11416 return true;
11417 };
11418
11419 for (const Attr *A : FD->attrs()) {
11420 switch (A->getKind()) {
11421 case attr::CPUDispatch:
11422 case attr::CPUSpecific:
11423 if (MVKind != MultiVersionKind::CPUDispatch &&
11425 return Diagnose(S, A);
11426 break;
11427 case attr::Target:
11428 if (MVKind != MultiVersionKind::Target)
11429 return Diagnose(S, A);
11430 break;
11431 case attr::TargetVersion:
11432 if (MVKind != MultiVersionKind::TargetVersion &&
11434 return Diagnose(S, A);
11435 break;
11436 case attr::TargetClones:
11437 if (MVKind != MultiVersionKind::TargetClones &&
11439 return Diagnose(S, A);
11440 break;
11441 default:
11442 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11443 return Diagnose(S, A);
11444 break;
11445 }
11446 }
11447 return false;
11448}
11449
11451 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11452 const PartialDiagnostic &NoProtoDiagID,
11453 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11454 const PartialDiagnosticAt &NoSupportDiagIDAt,
11455 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11456 bool ConstexprSupported, bool CLinkageMayDiffer) {
11457 enum DoesntSupport {
11458 FuncTemplates = 0,
11459 VirtFuncs = 1,
11460 DeducedReturn = 2,
11461 Constructors = 3,
11462 Destructors = 4,
11463 DeletedFuncs = 5,
11464 DefaultedFuncs = 6,
11465 ConstexprFuncs = 7,
11466 ConstevalFuncs = 8,
11467 Lambda = 9,
11468 };
11469 enum Different {
11470 CallingConv = 0,
11471 ReturnType = 1,
11472 ConstexprSpec = 2,
11473 InlineSpec = 3,
11474 Linkage = 4,
11475 LanguageLinkage = 5,
11476 };
11477
11478 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11479 !OldFD->getType()->getAs<FunctionProtoType>()) {
11480 Diag(OldFD->getLocation(), NoProtoDiagID);
11481 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11482 return true;
11483 }
11484
11485 if (NoProtoDiagID.getDiagID() != 0 &&
11486 !NewFD->getType()->getAs<FunctionProtoType>())
11487 return Diag(NewFD->getLocation(), NoProtoDiagID);
11488
11489 if (!TemplatesSupported &&
11491 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11492 << FuncTemplates;
11493
11494 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11495 if (NewCXXFD->isVirtual())
11496 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11497 << VirtFuncs;
11498
11499 if (isa<CXXConstructorDecl>(NewCXXFD))
11500 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11501 << Constructors;
11502
11503 if (isa<CXXDestructorDecl>(NewCXXFD))
11504 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11505 << Destructors;
11506 }
11507
11508 if (NewFD->isDeleted())
11509 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11510 << DeletedFuncs;
11511
11512 if (NewFD->isDefaulted())
11513 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11514 << DefaultedFuncs;
11515
11516 if (!ConstexprSupported && NewFD->isConstexpr())
11517 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11518 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11519
11520 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11521 const auto *NewType = cast<FunctionType>(NewQType);
11522 QualType NewReturnType = NewType->getReturnType();
11523
11524 if (NewReturnType->isUndeducedType())
11525 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11526 << DeducedReturn;
11527
11528 // Ensure the return type is identical.
11529 if (OldFD) {
11530 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11531 const auto *OldType = cast<FunctionType>(OldQType);
11532 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11533 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11534
11535 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11536 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11537
11538 bool ArmStreamingCCMismatched = false;
11539 if (OldFPT && NewFPT) {
11540 unsigned Diff =
11541 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11542 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11543 // cannot be mixed.
11546 ArmStreamingCCMismatched = true;
11547 }
11548
11549 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11550 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11551
11552 QualType OldReturnType = OldType->getReturnType();
11553
11554 if (OldReturnType != NewReturnType)
11555 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11556
11557 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11558 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11559
11560 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11561 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11562
11563 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11564 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11565
11566 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11567 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11568
11569 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11570 NewFD->getLocation()))
11571 return true;
11572 }
11573 return false;
11574}
11575
11577 const FunctionDecl *NewFD,
11578 bool CausesMV,
11579 MultiVersionKind MVKind) {
11581 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11582 if (OldFD)
11583 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11584 return true;
11585 }
11586
11587 bool IsCPUSpecificCPUDispatchMVKind =
11590
11591 if (CausesMV && OldFD &&
11592 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11593 return true;
11594
11595 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11596 return true;
11597
11598 // Only allow transition to MultiVersion if it hasn't been used.
11599 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11600 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11601 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11602 return true;
11603 }
11604
11606 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11608 S.PDiag(diag::note_multiversioning_caused_here)),
11610 S.PDiag(diag::err_multiversion_doesnt_support)
11611 << static_cast<unsigned>(MVKind)),
11613 S.PDiag(diag::err_multiversion_diff)),
11614 /*TemplatesSupported=*/false,
11615 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11616 /*CLinkageMayDiffer=*/false);
11617}
11618
11619/// Check the validity of a multiversion function declaration that is the
11620/// first of its kind. Also sets the multiversion'ness' of the function itself.
11621///
11622/// This sets NewFD->isInvalidDecl() to true if there was an error.
11623///
11624/// Returns true if there was an error, false otherwise.
11627 assert(MVKind != MultiVersionKind::None &&
11628 "Function lacks multiversion attribute");
11629 const auto *TA = FD->getAttr<TargetAttr>();
11630 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11631 // The target attribute only causes MV if this declaration is the default,
11632 // otherwise it is treated as a normal function.
11633 if (TA && !TA->isDefaultVersion())
11634 return false;
11635
11636 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11637 FD->setInvalidDecl();
11638 return true;
11639 }
11640
11641 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11642 FD->setInvalidDecl();
11643 return true;
11644 }
11645
11646 FD->setIsMultiVersion();
11647 return false;
11648}
11649
11651 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11653 return true;
11654 }
11655
11656 return false;
11657}
11658
11660 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11661 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11662 return;
11663
11664 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11665 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11666
11667 if (MVKindTo == MultiVersionKind::None &&
11668 (MVKindFrom == MultiVersionKind::TargetVersion ||
11669 MVKindFrom == MultiVersionKind::TargetClones))
11670 To->addAttr(TargetVersionAttr::CreateImplicit(
11671 To->getASTContext(), "default", To->getSourceRange()));
11672}
11673
11675 FunctionDecl *NewFD,
11676 bool &Redeclaration,
11677 NamedDecl *&OldDecl,
11679 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11680
11681 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11682 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11683 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11684 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11685
11686 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11687
11688 // The definitions should be allowed in any order. If we have discovered
11689 // a new target version and the preceeding was the default, then add the
11690 // corresponding attribute to it.
11691 patchDefaultTargetVersion(NewFD, OldFD);
11692
11693 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11694 // to change, this is a simple redeclaration.
11695 if (NewTA && !NewTA->isDefaultVersion() &&
11696 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11697 return false;
11698
11699 // Otherwise, this decl causes MultiVersioning.
11700 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11703 NewFD->setInvalidDecl();
11704 return true;
11705 }
11706
11707 if (CheckMultiVersionValue(S, NewFD)) {
11708 NewFD->setInvalidDecl();
11709 return true;
11710 }
11711
11712 // If this is 'default', permit the forward declaration.
11713 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11714 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11715 Redeclaration = true;
11716 OldDecl = OldFD;
11717 OldFD->setIsMultiVersion();
11718 NewFD->setIsMultiVersion();
11719 return false;
11720 }
11721
11722 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11723 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11724 NewFD->setInvalidDecl();
11725 return true;
11726 }
11727
11728 if (NewTA) {
11729 ParsedTargetAttr OldParsed =
11731 OldTA->getFeaturesStr());
11732 llvm::sort(OldParsed.Features);
11733 ParsedTargetAttr NewParsed =
11735 NewTA->getFeaturesStr());
11736 // Sort order doesn't matter, it just needs to be consistent.
11737 llvm::sort(NewParsed.Features);
11738 if (OldParsed == NewParsed) {
11739 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11740 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11741 NewFD->setInvalidDecl();
11742 return true;
11743 }
11744 }
11745
11746 for (const auto *FD : OldFD->redecls()) {
11747 const auto *CurTA = FD->getAttr<TargetAttr>();
11748 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11749 // We allow forward declarations before ANY multiversioning attributes, but
11750 // nothing after the fact.
11752 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11753 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11754 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11755 << (NewTA ? 0 : 2);
11756 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11757 NewFD->setInvalidDecl();
11758 return true;
11759 }
11760 }
11761
11762 OldFD->setIsMultiVersion();
11763 NewFD->setIsMultiVersion();
11764 Redeclaration = false;
11765 OldDecl = nullptr;
11766 Previous.clear();
11767 return false;
11768}
11769
11771 MultiVersionKind OldKind = Old->getMultiVersionKind();
11772 MultiVersionKind NewKind = New->getMultiVersionKind();
11773
11774 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11775 NewKind == MultiVersionKind::None)
11776 return true;
11777
11778 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11779 switch (OldKind) {
11781 return NewKind == MultiVersionKind::TargetClones;
11783 return NewKind == MultiVersionKind::TargetVersion;
11784 default:
11785 return false;
11786 }
11787 } else {
11788 switch (OldKind) {
11790 return NewKind == MultiVersionKind::CPUSpecific;
11792 return NewKind == MultiVersionKind::CPUDispatch;
11793 default:
11794 return false;
11795 }
11796 }
11797}
11798
11799/// Check the validity of a new function declaration being added to an existing
11800/// multiversioned declaration collection.
11802 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11803 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11804 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11806
11807 // Disallow mixing of multiversioning types.
11808 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11809 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11810 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11811 NewFD->setInvalidDecl();
11812 return true;
11813 }
11814
11815 // Add the default target_version attribute if it's missing.
11816 patchDefaultTargetVersion(OldFD, NewFD);
11817 patchDefaultTargetVersion(NewFD, OldFD);
11818
11819 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11820 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11821 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11822 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11823
11824 ParsedTargetAttr NewParsed;
11825 if (NewTA) {
11827 NewTA->getFeaturesStr());
11828 llvm::sort(NewParsed.Features);
11829 }
11831 if (NewTVA) {
11832 NewTVA->getFeatures(NewFeats);
11833 llvm::sort(NewFeats);
11834 }
11835
11836 bool UseMemberUsingDeclRules =
11837 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11838
11839 bool MayNeedOverloadableChecks =
11841
11842 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11843 // of a previous member of the MultiVersion set.
11844 for (NamedDecl *ND : Previous) {
11845 FunctionDecl *CurFD = ND->getAsFunction();
11846 if (!CurFD || CurFD->isInvalidDecl())
11847 continue;
11848 if (MayNeedOverloadableChecks &&
11849 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11850 continue;
11851
11852 switch (NewMVKind) {
11854 assert(OldMVKind == MultiVersionKind::TargetClones &&
11855 "Only target_clones can be omitted in subsequent declarations");
11856 break;
11858 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11859 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11860 NewFD->setIsMultiVersion();
11861 Redeclaration = true;
11862 OldDecl = ND;
11863 return false;
11864 }
11865
11866 ParsedTargetAttr CurParsed =
11868 CurTA->getFeaturesStr());
11869 llvm::sort(CurParsed.Features);
11870 if (CurParsed == NewParsed) {
11871 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11872 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11873 NewFD->setInvalidDecl();
11874 return true;
11875 }
11876 break;
11877 }
11879 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11880 if (CurTVA->getName() == NewTVA->getName()) {
11881 NewFD->setIsMultiVersion();
11882 Redeclaration = true;
11883 OldDecl = ND;
11884 return false;
11885 }
11887 CurTVA->getFeatures(CurFeats);
11888 llvm::sort(CurFeats);
11889
11890 if (CurFeats == NewFeats) {
11891 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11892 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11893 NewFD->setInvalidDecl();
11894 return true;
11895 }
11896 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11897 // Default
11898 if (NewFeats.empty())
11899 break;
11900
11901 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11903 CurClones->getFeatures(CurFeats, I);
11904 llvm::sort(CurFeats);
11905
11906 if (CurFeats == NewFeats) {
11907 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11908 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11909 NewFD->setInvalidDecl();
11910 return true;
11911 }
11912 }
11913 }
11914 break;
11915 }
11917 assert(NewClones && "MultiVersionKind does not match attribute type");
11918 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11919 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11920 !std::equal(CurClones->featuresStrs_begin(),
11921 CurClones->featuresStrs_end(),
11922 NewClones->featuresStrs_begin())) {
11923 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11924 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11925 NewFD->setInvalidDecl();
11926 return true;
11927 }
11928 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11930 CurTVA->getFeatures(CurFeats);
11931 llvm::sort(CurFeats);
11932
11933 // Default
11934 if (CurFeats.empty())
11935 break;
11936
11937 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11938 NewFeats.clear();
11939 NewClones->getFeatures(NewFeats, I);
11940 llvm::sort(NewFeats);
11941
11942 if (CurFeats == NewFeats) {
11943 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11944 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11945 NewFD->setInvalidDecl();
11946 return true;
11947 }
11948 }
11949 break;
11950 }
11951 Redeclaration = true;
11952 OldDecl = CurFD;
11953 NewFD->setIsMultiVersion();
11954 return false;
11955 }
11958 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11959 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11960 // Handle CPUDispatch/CPUSpecific versions.
11961 // Only 1 CPUDispatch function is allowed, this will make it go through
11962 // the redeclaration errors.
11963 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11964 CurFD->hasAttr<CPUDispatchAttr>()) {
11965 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11966 std::equal(
11967 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11968 NewCPUDisp->cpus_begin(),
11969 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11970 return Cur->getName() == New->getName();
11971 })) {
11972 NewFD->setIsMultiVersion();
11973 Redeclaration = true;
11974 OldDecl = ND;
11975 return false;
11976 }
11977
11978 // If the declarations don't match, this is an error condition.
11979 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11980 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11981 NewFD->setInvalidDecl();
11982 return true;
11983 }
11984 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11985 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11986 std::equal(
11987 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11988 NewCPUSpec->cpus_begin(),
11989 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11990 return Cur->getName() == New->getName();
11991 })) {
11992 NewFD->setIsMultiVersion();
11993 Redeclaration = true;
11994 OldDecl = ND;
11995 return false;
11996 }
11997
11998 // Only 1 version of CPUSpecific is allowed for each CPU.
11999 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12000 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12001 if (CurII == NewII) {
12002 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12003 << NewII;
12004 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12005 NewFD->setInvalidDecl();
12006 return true;
12007 }
12008 }
12009 }
12010 }
12011 break;
12012 }
12013 }
12014 }
12015
12016 // Redeclarations of a target_clones function may omit the attribute, in which
12017 // case it will be inherited during declaration merging.
12018 if (NewMVKind == MultiVersionKind::None &&
12019 OldMVKind == MultiVersionKind::TargetClones) {
12020 NewFD->setIsMultiVersion();
12021 Redeclaration = true;
12022 OldDecl = OldFD;
12023 return false;
12024 }
12025
12026 // Else, this is simply a non-redecl case. Checking the 'value' is only
12027 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12028 // handled in the attribute adding step.
12029 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12030 NewFD->setInvalidDecl();
12031 return true;
12032 }
12033
12034 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12035 !OldFD->isMultiVersion(), NewMVKind)) {
12036 NewFD->setInvalidDecl();
12037 return true;
12038 }
12039
12040 // Permit forward declarations in the case where these two are compatible.
12041 if (!OldFD->isMultiVersion()) {
12042 OldFD->setIsMultiVersion();
12043 NewFD->setIsMultiVersion();
12044 Redeclaration = true;
12045 OldDecl = OldFD;
12046 return false;
12047 }
12048
12049 NewFD->setIsMultiVersion();
12050 Redeclaration = false;
12051 OldDecl = nullptr;
12052 Previous.clear();
12053 return false;
12054}
12055
12056/// Check the validity of a mulitversion function declaration.
12057/// Also sets the multiversion'ness' of the function itself.
12058///
12059/// This sets NewFD->isInvalidDecl() to true if there was an error.
12060///
12061/// Returns true if there was an error, false otherwise.
12063 bool &Redeclaration, NamedDecl *&OldDecl,
12065 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12066
12067 // Check if FMV is disabled.
12068 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12069 return false;
12070
12071 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12072 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12073 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12074 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12075 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12076 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12077
12078 // Main isn't allowed to become a multiversion function, however it IS
12079 // permitted to have 'main' be marked with the 'target' optimization hint,
12080 // for 'target_version' only default is allowed.
12081 if (NewFD->isMain()) {
12082 if (MVKind != MultiVersionKind::None &&
12083 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12084 !(MVKind == MultiVersionKind::TargetVersion &&
12085 NewTVA->isDefaultVersion())) {
12086 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12087 NewFD->setInvalidDecl();
12088 return true;
12089 }
12090 return false;
12091 }
12092
12093 // Target attribute on AArch64 is not used for multiversioning
12094 if (NewTA && TI.getTriple().isAArch64())
12095 return false;
12096
12097 // Target attribute on RISCV is not used for multiversioning
12098 if (NewTA && TI.getTriple().isRISCV())
12099 return false;
12100
12101 if (!OldDecl || !OldDecl->getAsFunction() ||
12102 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12103 NewFD->getDeclContext()->getRedeclContext())) {
12104 // If there's no previous declaration, AND this isn't attempting to cause
12105 // multiversioning, this isn't an error condition.
12106 if (MVKind == MultiVersionKind::None)
12107 return false;
12108 return CheckMultiVersionFirstFunction(S, NewFD);
12109 }
12110
12111 FunctionDecl *OldFD = OldDecl->getAsFunction();
12112
12113 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12114 return false;
12115
12116 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12117 // for target_clones and target_version.
12118 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12121 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12123 NewFD->setInvalidDecl();
12124 return true;
12125 }
12126
12127 if (!OldFD->isMultiVersion()) {
12128 switch (MVKind) {
12132 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12134 if (OldFD->isUsed(false)) {
12135 NewFD->setInvalidDecl();
12136 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12137 }
12138 OldFD->setIsMultiVersion();
12139 break;
12140
12144 break;
12145 }
12146 }
12147
12148 // At this point, we have a multiversion function decl (in OldFD) AND an
12149 // appropriate attribute in the current function decl (unless it's allowed to
12150 // omit the attribute). Resolve that these are still compatible with previous
12151 // declarations.
12152 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12153 NewCPUSpec, NewClones, Redeclaration,
12154 OldDecl, Previous);
12155}
12156
12158 bool IsPure = NewFD->hasAttr<PureAttr>();
12159 bool IsConst = NewFD->hasAttr<ConstAttr>();
12160
12161 // If there are no pure or const attributes, there's nothing to check.
12162 if (!IsPure && !IsConst)
12163 return;
12164
12165 // If the function is marked both pure and const, we retain the const
12166 // attribute because it makes stronger guarantees than the pure attribute, and
12167 // we drop the pure attribute explicitly to prevent later confusion about
12168 // semantics.
12169 if (IsPure && IsConst) {
12170 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12171 NewFD->dropAttrs<PureAttr>();
12172 }
12173
12174 // Constructors and destructors are functions which return void, so are
12175 // handled here as well.
12176 if (NewFD->getReturnType()->isVoidType()) {
12177 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12178 << IsConst;
12179 NewFD->dropAttrs<PureAttr, ConstAttr>();
12180 }
12181}
12182
12185 bool IsMemberSpecialization,
12186 bool DeclIsDefn) {
12187 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12188 "Variably modified return types are not handled here");
12189
12190 // Determine whether the type of this function should be merged with
12191 // a previous visible declaration. This never happens for functions in C++,
12192 // and always happens in C if the previous declaration was visible.
12193 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12194 !Previous.isShadowed();
12195
12196 bool Redeclaration = false;
12197 NamedDecl *OldDecl = nullptr;
12198 bool MayNeedOverloadableChecks = false;
12199
12201 // Merge or overload the declaration with an existing declaration of
12202 // the same name, if appropriate.
12203 if (!Previous.empty()) {
12204 // Determine whether NewFD is an overload of PrevDecl or
12205 // a declaration that requires merging. If it's an overload,
12206 // there's no more work to do here; we'll just add the new
12207 // function to the scope.
12209 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12210 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12211 Redeclaration = true;
12212 OldDecl = Candidate;
12213 }
12214 } else {
12215 MayNeedOverloadableChecks = true;
12216 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12217 /*NewIsUsingDecl*/ false)) {
12219 Redeclaration = true;
12220 break;
12221
12223 Redeclaration = true;
12224 break;
12225
12227 Redeclaration = false;
12228 break;
12229 }
12230 }
12231 }
12232
12233 // Check for a previous extern "C" declaration with this name.
12234 if (!Redeclaration &&
12236 if (!Previous.empty()) {
12237 // This is an extern "C" declaration with the same name as a previous
12238 // declaration, and thus redeclares that entity...
12239 Redeclaration = true;
12240 OldDecl = Previous.getFoundDecl();
12241 MergeTypeWithPrevious = false;
12242
12243 // ... except in the presence of __attribute__((overloadable)).
12244 if (OldDecl->hasAttr<OverloadableAttr>() ||
12245 NewFD->hasAttr<OverloadableAttr>()) {
12246 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12247 MayNeedOverloadableChecks = true;
12248 Redeclaration = false;
12249 OldDecl = nullptr;
12250 }
12251 }
12252 }
12253 }
12254
12255 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12256 return Redeclaration;
12257
12258 // PPC MMA non-pointer types are not allowed as function return types.
12259 if (Context.getTargetInfo().getTriple().isPPC64() &&
12260 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12261 NewFD->setInvalidDecl();
12262 }
12263
12264 CheckConstPureAttributesUsage(*this, NewFD);
12265
12266 // C++ [dcl.spec.auto.general]p12:
12267 // Return type deduction for a templated function with a placeholder in its
12268 // declared type occurs when the definition is instantiated even if the
12269 // function body contains a return statement with a non-type-dependent
12270 // operand.
12271 //
12272 // C++ [temp.dep.expr]p3:
12273 // An id-expression is type-dependent if it is a template-id that is not a
12274 // concept-id and is dependent; or if its terminal name is:
12275 // - [...]
12276 // - associated by name lookup with one or more declarations of member
12277 // functions of a class that is the current instantiation declared with a
12278 // return type that contains a placeholder type,
12279 // - [...]
12280 //
12281 // If this is a templated function with a placeholder in its return type,
12282 // make the placeholder type dependent since it won't be deduced until the
12283 // definition is instantiated. We do this here because it needs to happen
12284 // for implicitly instantiated member functions/member function templates.
12285 if (getLangOpts().CPlusPlus14 &&
12286 (NewFD->isDependentContext() &&
12287 NewFD->getReturnType()->isUndeducedType())) {
12288 const FunctionProtoType *FPT =
12289 NewFD->getType()->castAs<FunctionProtoType>();
12290 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12291 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12292 FPT->getExtProtoInfo()));
12293 }
12294
12295 // C++11 [dcl.constexpr]p8:
12296 // A constexpr specifier for a non-static member function that is not
12297 // a constructor declares that member function to be const.
12298 //
12299 // This needs to be delayed until we know whether this is an out-of-line
12300 // definition of a static member function.
12301 //
12302 // This rule is not present in C++1y, so we produce a backwards
12303 // compatibility warning whenever it happens in C++11.
12304 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12305 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12306 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12308 CXXMethodDecl *OldMD = nullptr;
12309 if (OldDecl)
12310 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12311 if (!OldMD || !OldMD->isStatic()) {
12312 const FunctionProtoType *FPT =
12315 EPI.TypeQuals.addConst();
12316 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12317 FPT->getParamTypes(), EPI));
12318
12319 // Warn that we did this, if we're not performing template instantiation.
12320 // In that case, we'll have warned already when the template was defined.
12321 if (!inTemplateInstantiation()) {
12322 SourceLocation AddConstLoc;
12325 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12326
12327 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12328 << FixItHint::CreateInsertion(AddConstLoc, " const");
12329 }
12330 }
12331 }
12332
12333 if (Redeclaration) {
12334 // NewFD and OldDecl represent declarations that need to be
12335 // merged.
12336 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12337 DeclIsDefn)) {
12338 NewFD->setInvalidDecl();
12339 return Redeclaration;
12340 }
12341
12342 Previous.clear();
12343 Previous.addDecl(OldDecl);
12344
12345 if (FunctionTemplateDecl *OldTemplateDecl =
12346 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12347 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12348 FunctionTemplateDecl *NewTemplateDecl
12350 assert(NewTemplateDecl && "Template/non-template mismatch");
12351
12352 // The call to MergeFunctionDecl above may have created some state in
12353 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12354 // can add it as a redeclaration.
12355 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12356
12357 NewFD->setPreviousDeclaration(OldFD);
12358 if (NewFD->isCXXClassMember()) {
12359 NewFD->setAccess(OldTemplateDecl->getAccess());
12360 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12361 }
12362
12363 // If this is an explicit specialization of a member that is a function
12364 // template, mark it as a member specialization.
12365 if (IsMemberSpecialization &&
12366 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12367 NewTemplateDecl->setMemberSpecialization();
12368 assert(OldTemplateDecl->isMemberSpecialization());
12369 // Explicit specializations of a member template do not inherit deleted
12370 // status from the parent member template that they are specializing.
12371 if (OldFD->isDeleted()) {
12372 // FIXME: This assert will not hold in the presence of modules.
12373 assert(OldFD->getCanonicalDecl() == OldFD);
12374 // FIXME: We need an update record for this AST mutation.
12375 OldFD->setDeletedAsWritten(false);
12376 }
12377 }
12378
12379 } else {
12380 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12381 auto *OldFD = cast<FunctionDecl>(OldDecl);
12382 // This needs to happen first so that 'inline' propagates.
12383 NewFD->setPreviousDeclaration(OldFD);
12384 if (NewFD->isCXXClassMember())
12385 NewFD->setAccess(OldFD->getAccess());
12386 }
12387 }
12388 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12389 !NewFD->getAttr<OverloadableAttr>()) {
12390 assert((Previous.empty() ||
12391 llvm::any_of(Previous,
12392 [](const NamedDecl *ND) {
12393 return ND->hasAttr<OverloadableAttr>();
12394 })) &&
12395 "Non-redecls shouldn't happen without overloadable present");
12396
12397 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12398 const auto *FD = dyn_cast<FunctionDecl>(ND);
12399 return FD && !FD->hasAttr<OverloadableAttr>();
12400 });
12401
12402 if (OtherUnmarkedIter != Previous.end()) {
12403 Diag(NewFD->getLocation(),
12404 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12405 Diag((*OtherUnmarkedIter)->getLocation(),
12406 diag::note_attribute_overloadable_prev_overload)
12407 << false;
12408
12409 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12410 }
12411 }
12412
12413 if (LangOpts.OpenMP)
12415
12416 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12418
12419 if (NewFD->hasAttr<SYCLExternalAttr>())
12421
12422 // Semantic checking for this function declaration (in isolation).
12423
12424 if (getLangOpts().CPlusPlus) {
12425 // C++-specific checks.
12426 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12428 } else if (CXXDestructorDecl *Destructor =
12429 dyn_cast<CXXDestructorDecl>(NewFD)) {
12430 // We check here for invalid destructor names.
12431 // If we have a friend destructor declaration that is dependent, we can't
12432 // diagnose right away because cases like this are still valid:
12433 // template <class T> struct A { friend T::X::~Y(); };
12434 // struct B { struct Y { ~Y(); }; using X = Y; };
12435 // template struct A<B>;
12437 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12438 CanQualType ClassType =
12439 Context.getCanonicalTagType(Destructor->getParent());
12440
12441 DeclarationName Name =
12442 Context.DeclarationNames.getCXXDestructorName(ClassType);
12443 if (NewFD->getDeclName() != Name) {
12444 Diag(NewFD->getLocation(), diag::err_destructor_name);
12445 NewFD->setInvalidDecl();
12446 return Redeclaration;
12447 }
12448 }
12449 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12450 if (auto *TD = Guide->getDescribedFunctionTemplate())
12452
12453 // A deduction guide is not on the list of entities that can be
12454 // explicitly specialized.
12455 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12456 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12457 << /*explicit specialization*/ 1;
12458 }
12459
12460 // Find any virtual functions that this function overrides.
12461 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12462 if (!Method->isFunctionTemplateSpecialization() &&
12463 !Method->getDescribedFunctionTemplate() &&
12464 Method->isCanonicalDecl()) {
12465 AddOverriddenMethods(Method->getParent(), Method);
12466 }
12467 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12468 // C++2a [class.virtual]p6
12469 // A virtual method shall not have a requires-clause.
12471 diag::err_constrained_virtual_method);
12472
12473 if (Method->isStatic())
12475 }
12476
12477 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12478 ActOnConversionDeclarator(Conversion);
12479
12480 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12481 if (NewFD->isOverloadedOperator() &&
12483 NewFD->setInvalidDecl();
12484 return Redeclaration;
12485 }
12486
12487 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12488 if (NewFD->getLiteralIdentifier() &&
12490 NewFD->setInvalidDecl();
12491 return Redeclaration;
12492 }
12493
12494 // In C++, check default arguments now that we have merged decls. Unless
12495 // the lexical context is the class, because in this case this is done
12496 // during delayed parsing anyway.
12497 if (!CurContext->isRecord())
12499
12500 // If this function is declared as being extern "C", then check to see if
12501 // the function returns a UDT (class, struct, or union type) that is not C
12502 // compatible, and if it does, warn the user.
12503 // But, issue any diagnostic on the first declaration only.
12504 if (Previous.empty() && NewFD->isExternC()) {
12505 QualType R = NewFD->getReturnType();
12506 if (R->isIncompleteType() && !R->isVoidType())
12507 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12508 << NewFD << R;
12509 else if (!R.isPODType(Context) && !R->isVoidType() &&
12511 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12512 }
12513
12514 // C++1z [dcl.fct]p6:
12515 // [...] whether the function has a non-throwing exception-specification
12516 // [is] part of the function type
12517 //
12518 // This results in an ABI break between C++14 and C++17 for functions whose
12519 // declared type includes an exception-specification in a parameter or
12520 // return type. (Exception specifications on the function itself are OK in
12521 // most cases, and exception specifications are not permitted in most other
12522 // contexts where they could make it into a mangling.)
12523 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12524 auto HasNoexcept = [&](QualType T) -> bool {
12525 // Strip off declarator chunks that could be between us and a function
12526 // type. We don't need to look far, exception specifications are very
12527 // restricted prior to C++17.
12528 if (auto *RT = T->getAs<ReferenceType>())
12529 T = RT->getPointeeType();
12530 else if (T->isAnyPointerType())
12531 T = T->getPointeeType();
12532 else if (auto *MPT = T->getAs<MemberPointerType>())
12533 T = MPT->getPointeeType();
12534 if (auto *FPT = T->getAs<FunctionProtoType>())
12535 if (FPT->isNothrow())
12536 return true;
12537 return false;
12538 };
12539
12540 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12541 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12542 for (QualType T : FPT->param_types())
12543 AnyNoexcept |= HasNoexcept(T);
12544 if (AnyNoexcept)
12545 Diag(NewFD->getLocation(),
12546 diag::warn_cxx17_compat_exception_spec_in_signature)
12547 << NewFD;
12548 }
12549
12550 if (!Redeclaration && LangOpts.CUDA) {
12551 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12552 for (auto *Parm : NewFD->parameters()) {
12553 if (!Parm->getType()->isDependentType() &&
12554 Parm->hasAttr<CUDAGridConstantAttr>() &&
12555 !(IsKernel && Parm->getType().isConstQualified()))
12556 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12557 diag::err_cuda_grid_constant_not_allowed);
12558 }
12560 }
12561 }
12562
12563 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12565
12566 return Redeclaration;
12567}
12568
12570 // [basic.start.main]p3
12571 // The main function shall not be declared with C linkage-specification.
12572 if (FD->isExternCContext())
12573 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12574
12575 // C++11 [basic.start.main]p3:
12576 // A program that [...] declares main to be inline, static or
12577 // constexpr is ill-formed.
12578 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12579 // appear in a declaration of main.
12580 // static main is not an error under C99, but we should warn about it.
12581 // We accept _Noreturn main as an extension.
12582 if (FD->getStorageClass() == SC_Static)
12584 ? diag::err_static_main : diag::warn_static_main)
12586 if (FD->isInlineSpecified())
12587 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12589 if (DS.isNoreturnSpecified()) {
12590 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12591 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12592 Diag(NoreturnLoc, diag::ext_noreturn_main);
12593 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12594 << FixItHint::CreateRemoval(NoreturnRange);
12595 }
12596 if (FD->isConstexpr()) {
12597 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12598 << FD->isConsteval()
12601 }
12602
12603 if (getLangOpts().OpenCL) {
12604 Diag(FD->getLocation(), diag::err_opencl_no_main)
12605 << FD->hasAttr<DeviceKernelAttr>();
12606 FD->setInvalidDecl();
12607 return;
12608 }
12609
12610 if (FD->hasAttr<SYCLExternalAttr>()) {
12611 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12612 << FD->getAttr<SYCLExternalAttr>();
12613 FD->setInvalidDecl();
12614 return;
12615 }
12616
12617 // Functions named main in hlsl are default entries, but don't have specific
12618 // signatures they are required to conform to.
12619 if (getLangOpts().HLSL)
12620 return;
12621
12622 QualType T = FD->getType();
12623 assert(T->isFunctionType() && "function decl is not of function type");
12624 const FunctionType* FT = T->castAs<FunctionType>();
12625
12626 // Set default calling convention for main()
12627 if (FT->getCallConv() != CC_C) {
12628 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12629 FD->setType(QualType(FT, 0));
12630 T = Context.getCanonicalType(FD->getType());
12631 }
12632
12634 // In C with GNU extensions we allow main() to have non-integer return
12635 // type, but we should warn about the extension, and we disable the
12636 // implicit-return-zero rule.
12637
12638 // GCC in C mode accepts qualified 'int'.
12639 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12640 FD->setHasImplicitReturnZero(true);
12641 else {
12642 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12643 SourceRange RTRange = FD->getReturnTypeSourceRange();
12644 if (RTRange.isValid())
12645 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12646 << FixItHint::CreateReplacement(RTRange, "int");
12647 }
12648 } else {
12649 // In C and C++, main magically returns 0 if you fall off the end;
12650 // set the flag which tells us that.
12651 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12652
12653 // All the standards say that main() should return 'int'.
12654 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12655 FD->setHasImplicitReturnZero(true);
12656 else {
12657 // Otherwise, this is just a flat-out error.
12658 SourceRange RTRange = FD->getReturnTypeSourceRange();
12659 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12660 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12661 : FixItHint());
12662 FD->setInvalidDecl(true);
12663 }
12664
12665 // [basic.start.main]p3:
12666 // A program that declares a function main that belongs to the global scope
12667 // and is attached to a named module is ill-formed.
12668 if (FD->isInNamedModule()) {
12669 const SourceLocation start = FD->getTypeSpecStartLoc();
12670 Diag(start, diag::warn_main_in_named_module)
12671 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12672 }
12673 }
12674
12675 // Treat protoless main() as nullary.
12676 if (isa<FunctionNoProtoType>(FT)) return;
12677
12679 unsigned nparams = FTP->getNumParams();
12680 assert(FD->getNumParams() == nparams);
12681
12682 bool HasExtraParameters = (nparams > 3);
12683
12684 if (FTP->isVariadic()) {
12685 Diag(FD->getLocation(), diag::ext_variadic_main);
12686 // FIXME: if we had information about the location of the ellipsis, we
12687 // could add a FixIt hint to remove it as a parameter.
12688 }
12689
12690 // Darwin passes an undocumented fourth argument of type char**. If
12691 // other platforms start sprouting these, the logic below will start
12692 // getting shifty.
12693 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12694 HasExtraParameters = false;
12695
12696 if (HasExtraParameters) {
12697 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12698 FD->setInvalidDecl(true);
12699 nparams = 3;
12700 }
12701
12702 // FIXME: a lot of the following diagnostics would be improved
12703 // if we had some location information about types.
12704
12705 QualType CharPP =
12706 Context.getPointerType(Context.getPointerType(Context.CharTy));
12707 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12708
12709 for (unsigned i = 0; i < nparams; ++i) {
12710 QualType AT = FTP->getParamType(i);
12711
12712 bool mismatch = true;
12713
12714 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12715 mismatch = false;
12716 else if (Expected[i] == CharPP) {
12717 // As an extension, the following forms are okay:
12718 // char const **
12719 // char const * const *
12720 // char * const *
12721
12723 const PointerType* PT;
12724 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12725 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12726 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12727 Context.CharTy)) {
12728 qs.removeConst();
12729 mismatch = !qs.empty();
12730 }
12731 }
12732
12733 if (mismatch) {
12734 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12735 // TODO: suggest replacing given type with expected type
12736 FD->setInvalidDecl(true);
12737 }
12738 }
12739
12740 if (nparams == 1 && !FD->isInvalidDecl()) {
12741 Diag(FD->getLocation(), diag::warn_main_one_arg);
12742 }
12743
12744 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12745 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12746 FD->setInvalidDecl();
12747 }
12748}
12749
12750static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12751
12752 // Default calling convention for main and wmain is __cdecl
12753 if (FD->getName() == "main" || FD->getName() == "wmain")
12754 return false;
12755
12756 // Default calling convention for MinGW and Cygwin is __cdecl
12757 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12758 if (T.isOSCygMing())
12759 return false;
12760
12761 // Default calling convention for WinMain, wWinMain and DllMain
12762 // is __stdcall on 32 bit Windows
12763 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12764 return true;
12765
12766 return false;
12767}
12768
12770 QualType T = FD->getType();
12771 assert(T->isFunctionType() && "function decl is not of function type");
12772 const FunctionType *FT = T->castAs<FunctionType>();
12773
12774 // Set an implicit return of 'zero' if the function can return some integral,
12775 // enumeration, pointer or nullptr type.
12779 // DllMain is exempt because a return value of zero means it failed.
12780 if (FD->getName() != "DllMain")
12781 FD->setHasImplicitReturnZero(true);
12782
12783 // Explicitly specified calling conventions are applied to MSVC entry points
12784 if (!hasExplicitCallingConv(T)) {
12785 if (isDefaultStdCall(FD, *this)) {
12786 if (FT->getCallConv() != CC_X86StdCall) {
12787 FT = Context.adjustFunctionType(
12789 FD->setType(QualType(FT, 0));
12790 }
12791 } else if (FT->getCallConv() != CC_C) {
12792 FT = Context.adjustFunctionType(FT,
12794 FD->setType(QualType(FT, 0));
12795 }
12796 }
12797
12798 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12799 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12800 FD->setInvalidDecl();
12801 }
12802}
12803
12805 // FIXME: Need strict checking. In C89, we need to check for
12806 // any assignment, increment, decrement, function-calls, or
12807 // commas outside of a sizeof. In C99, it's the same list,
12808 // except that the aforementioned are allowed in unevaluated
12809 // expressions. Everything else falls under the
12810 // "may accept other forms of constant expressions" exception.
12811 //
12812 // Regular C++ code will not end up here (exceptions: language extensions,
12813 // OpenCL C++ etc), so the constant expression rules there don't matter.
12814 if (Init->isValueDependent()) {
12815 assert(Init->containsErrors() &&
12816 "Dependent code should only occur in error-recovery path.");
12817 return true;
12818 }
12819 const Expr *Culprit;
12820 if (Init->isConstantInitializer(Context, false, &Culprit))
12821 return false;
12822 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12823 return true;
12824}
12825
12826namespace {
12827 // Visits an initialization expression to see if OrigDecl is evaluated in
12828 // its own initialization and throws a warning if it does.
12829 class SelfReferenceChecker
12830 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12831 Sema &S;
12832 Decl *OrigDecl;
12833 bool isRecordType;
12834 bool isPODType;
12835 bool isReferenceType;
12836 bool isInCXXOperatorCall;
12837
12838 bool isInitList;
12839 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12840
12841 public:
12843
12844 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12845 S(S), OrigDecl(OrigDecl) {
12846 isPODType = false;
12847 isRecordType = false;
12848 isReferenceType = false;
12849 isInCXXOperatorCall = false;
12850 isInitList = false;
12851 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12852 isPODType = VD->getType().isPODType(S.Context);
12853 isRecordType = VD->getType()->isRecordType();
12854 isReferenceType = VD->getType()->isReferenceType();
12855 }
12856 }
12857
12858 // For most expressions, just call the visitor. For initializer lists,
12859 // track the index of the field being initialized since fields are
12860 // initialized in order allowing use of previously initialized fields.
12861 void CheckExpr(Expr *E) {
12862 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12863 if (!InitList) {
12864 Visit(E);
12865 return;
12866 }
12867
12868 // Track and increment the index here.
12869 isInitList = true;
12870 InitFieldIndex.push_back(0);
12871 for (auto *Child : InitList->children()) {
12872 CheckExpr(cast<Expr>(Child));
12873 ++InitFieldIndex.back();
12874 }
12875 InitFieldIndex.pop_back();
12876 }
12877
12878 // Returns true if MemberExpr is checked and no further checking is needed.
12879 // Returns false if additional checking is required.
12880 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12881 llvm::SmallVector<FieldDecl*, 4> Fields;
12882 Expr *Base = E;
12883 bool ReferenceField = false;
12884
12885 // Get the field members used.
12886 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12887 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12888 if (!FD)
12889 return false;
12890 Fields.push_back(FD);
12891 if (FD->getType()->isReferenceType())
12892 ReferenceField = true;
12893 Base = ME->getBase()->IgnoreParenImpCasts();
12894 }
12895
12896 // Keep checking only if the base Decl is the same.
12897 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12898 if (!DRE || DRE->getDecl() != OrigDecl)
12899 return false;
12900
12901 // A reference field can be bound to an unininitialized field.
12902 if (CheckReference && !ReferenceField)
12903 return true;
12904
12905 // Convert FieldDecls to their index number.
12906 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12907 for (const FieldDecl *I : llvm::reverse(Fields))
12908 UsedFieldIndex.push_back(I->getFieldIndex());
12909
12910 // See if a warning is needed by checking the first difference in index
12911 // numbers. If field being used has index less than the field being
12912 // initialized, then the use is safe.
12913 for (auto UsedIter = UsedFieldIndex.begin(),
12914 UsedEnd = UsedFieldIndex.end(),
12915 OrigIter = InitFieldIndex.begin(),
12916 OrigEnd = InitFieldIndex.end();
12917 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12918 if (*UsedIter < *OrigIter)
12919 return true;
12920 if (*UsedIter > *OrigIter)
12921 break;
12922 }
12923
12924 // TODO: Add a different warning which will print the field names.
12925 HandleDeclRefExpr(DRE);
12926 return true;
12927 }
12928
12929 // For most expressions, the cast is directly above the DeclRefExpr.
12930 // For conditional operators, the cast can be outside the conditional
12931 // operator if both expressions are DeclRefExpr's.
12932 void HandleValue(Expr *E) {
12933 E = E->IgnoreParens();
12934 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12935 HandleDeclRefExpr(DRE);
12936 return;
12937 }
12938
12939 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12940 Visit(CO->getCond());
12941 HandleValue(CO->getTrueExpr());
12942 HandleValue(CO->getFalseExpr());
12943 return;
12944 }
12945
12946 if (BinaryConditionalOperator *BCO =
12947 dyn_cast<BinaryConditionalOperator>(E)) {
12948 Visit(BCO->getCond());
12949 HandleValue(BCO->getFalseExpr());
12950 return;
12951 }
12952
12953 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12954 if (Expr *SE = OVE->getSourceExpr())
12955 HandleValue(SE);
12956 return;
12957 }
12958
12959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12960 if (BO->getOpcode() == BO_Comma) {
12961 Visit(BO->getLHS());
12962 HandleValue(BO->getRHS());
12963 return;
12964 }
12965 }
12966
12967 if (isa<MemberExpr>(E)) {
12968 if (isInitList) {
12969 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12970 false /*CheckReference*/))
12971 return;
12972 }
12973
12974 Expr *Base = E->IgnoreParenImpCasts();
12975 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12976 // Check for static member variables and don't warn on them.
12977 if (!isa<FieldDecl>(ME->getMemberDecl()))
12978 return;
12979 Base = ME->getBase()->IgnoreParenImpCasts();
12980 }
12981 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12982 HandleDeclRefExpr(DRE);
12983 return;
12984 }
12985
12986 Visit(E);
12987 }
12988
12989 // Reference types not handled in HandleValue are handled here since all
12990 // uses of references are bad, not just r-value uses.
12991 void VisitDeclRefExpr(DeclRefExpr *E) {
12992 if (isReferenceType)
12993 HandleDeclRefExpr(E);
12994 }
12995
12996 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12997 if (E->getCastKind() == CK_LValueToRValue) {
12998 HandleValue(E->getSubExpr());
12999 return;
13000 }
13001
13002 Inherited::VisitImplicitCastExpr(E);
13003 }
13004
13005 void VisitMemberExpr(MemberExpr *E) {
13006 if (isInitList) {
13007 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13008 return;
13009 }
13010
13011 // Don't warn on arrays since they can be treated as pointers.
13012 if (E->getType()->canDecayToPointerType()) return;
13013
13014 // Warn when a non-static method call is followed by non-static member
13015 // field accesses, which is followed by a DeclRefExpr.
13016 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13017 bool Warn = (MD && !MD->isStatic());
13018 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13019 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13020 if (!isa<FieldDecl>(ME->getMemberDecl()))
13021 Warn = false;
13022 Base = ME->getBase()->IgnoreParenImpCasts();
13023 }
13024
13025 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13026 if (Warn)
13027 HandleDeclRefExpr(DRE);
13028 return;
13029 }
13030
13031 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13032 // Visit that expression.
13033 Visit(Base);
13034 }
13035
13036 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13037 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13038 Expr *Callee = E->getCallee();
13039
13040 if (isa<UnresolvedLookupExpr>(Callee))
13041 return Inherited::VisitCXXOperatorCallExpr(E);
13042
13043 Visit(Callee);
13044 for (auto Arg: E->arguments())
13045 HandleValue(Arg->IgnoreParenImpCasts());
13046 }
13047
13048 void VisitLambdaExpr(LambdaExpr *E) {
13049 if (!isInCXXOperatorCall) {
13050 Inherited::VisitLambdaExpr(E);
13051 return;
13052 }
13053
13054 for (Expr *Init : E->capture_inits())
13055 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13056 HandleDeclRefExpr(DRE);
13057 else if (Init)
13058 Visit(Init);
13059 }
13060
13061 void VisitUnaryOperator(UnaryOperator *E) {
13062 // For POD record types, addresses of its own members are well-defined.
13063 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13065 if (!isPODType)
13066 HandleValue(E->getSubExpr());
13067 return;
13068 }
13069
13070 if (E->isIncrementDecrementOp()) {
13071 HandleValue(E->getSubExpr());
13072 return;
13073 }
13074
13075 Inherited::VisitUnaryOperator(E);
13076 }
13077
13078 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13079
13080 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13081 if (E->getConstructor()->isCopyConstructor()) {
13082 Expr *ArgExpr = E->getArg(0);
13083 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13084 if (ILE->getNumInits() == 1)
13085 ArgExpr = ILE->getInit(0);
13086 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13087 if (ICE->getCastKind() == CK_NoOp)
13088 ArgExpr = ICE->getSubExpr();
13089 HandleValue(ArgExpr);
13090 return;
13091 }
13092 Inherited::VisitCXXConstructExpr(E);
13093 }
13094
13095 void VisitCallExpr(CallExpr *E) {
13096 // Treat std::move as a use.
13097 if (E->isCallToStdMove()) {
13098 HandleValue(E->getArg(0));
13099 return;
13100 }
13101
13102 Inherited::VisitCallExpr(E);
13103 }
13104
13105 void VisitBinaryOperator(BinaryOperator *E) {
13106 if (E->isCompoundAssignmentOp()) {
13107 HandleValue(E->getLHS());
13108 Visit(E->getRHS());
13109 return;
13110 }
13111
13112 Inherited::VisitBinaryOperator(E);
13113 }
13114
13115 // A custom visitor for BinaryConditionalOperator is needed because the
13116 // regular visitor would check the condition and true expression separately
13117 // but both point to the same place giving duplicate diagnostics.
13118 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13119 Visit(E->getCond());
13120 Visit(E->getFalseExpr());
13121 }
13122
13123 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13124 Decl* ReferenceDecl = DRE->getDecl();
13125 if (OrigDecl != ReferenceDecl) return;
13126 unsigned diag;
13127 if (isReferenceType) {
13128 diag = diag::warn_uninit_self_reference_in_reference_init;
13129 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13130 diag = diag::warn_static_self_reference_in_init;
13131 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13132 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13133 DRE->getDecl()->getType()->isRecordType()) {
13134 diag = diag::warn_uninit_self_reference_in_init;
13135 } else {
13136 // Local variables will be handled by the CFG analysis.
13137 return;
13138 }
13139
13140 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13141 S.PDiag(diag)
13142 << DRE->getDecl() << OrigDecl->getLocation()
13143 << DRE->getSourceRange());
13144 }
13145 };
13146
13147 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13148 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13149 bool DirectInit) {
13150 // Parameters arguments are occassionially constructed with itself,
13151 // for instance, in recursive functions. Skip them.
13152 if (isa<ParmVarDecl>(OrigDecl))
13153 return;
13154
13155 // Skip checking for file-scope constexpr variables - constant evaluation
13156 // will produce appropriate errors without needing runtime diagnostics.
13157 // Local constexpr should still emit runtime warnings.
13158 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13159 VD && VD->isConstexpr() && VD->isFileVarDecl())
13160 return;
13161
13162 E = E->IgnoreParens();
13163
13164 // Skip checking T a = a where T is not a record or reference type.
13165 // Doing so is a way to silence uninitialized warnings.
13166 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13167 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13168 if (ICE->getCastKind() == CK_LValueToRValue)
13169 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13170 if (DRE->getDecl() == OrigDecl)
13171 return;
13172
13173 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13174 }
13175} // end anonymous namespace
13176
13177namespace {
13178 // Simple wrapper to add the name of a variable or (if no variable is
13179 // available) a DeclarationName into a diagnostic.
13180 struct VarDeclOrName {
13181 VarDecl *VDecl;
13182 DeclarationName Name;
13183
13184 friend const Sema::SemaDiagnosticBuilder &
13185 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13186 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13187 }
13188 };
13189} // end anonymous namespace
13190
13193 TypeSourceInfo *TSI,
13194 SourceRange Range, bool DirectInit,
13195 Expr *Init) {
13196 bool IsInitCapture = !VDecl;
13197 assert((!VDecl || !VDecl->isInitCapture()) &&
13198 "init captures are expected to be deduced prior to initialization");
13199
13200 VarDeclOrName VN{VDecl, Name};
13201
13202 DeducedType *Deduced = Type->getContainedDeducedType();
13203 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13204
13205 // Diagnose auto array declarations in C23, unless it's a supported extension.
13206 if (getLangOpts().C23 && Type->isArrayType() &&
13207 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13208 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13209 << (int)Deduced->getContainedAutoType()->getKeyword()
13210 << /*in array decl*/ 23 << Range;
13211 return QualType();
13212 }
13213
13214 // C++11 [dcl.spec.auto]p3
13215 if (!Init) {
13216 assert(VDecl && "no init for init capture deduction?");
13217
13218 // Except for class argument deduction, and then for an initializing
13219 // declaration only, i.e. no static at class scope or extern.
13221 VDecl->hasExternalStorage() ||
13222 VDecl->isStaticDataMember()) {
13223 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13224 << VDecl->getDeclName() << Type;
13225 return QualType();
13226 }
13227 }
13228
13229 ArrayRef<Expr*> DeduceInits;
13230 if (Init)
13231 DeduceInits = Init;
13232
13233 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13234 if (DirectInit && PL)
13235 DeduceInits = PL->exprs();
13236
13238 assert(VDecl && "non-auto type for init capture deduction?");
13241 VDecl->getLocation(), DirectInit, Init);
13242 // FIXME: Initialization should not be taking a mutable list of inits.
13243 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13244 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13245 InitsCopy);
13246 }
13247
13248 if (DirectInit) {
13249 if (auto *IL = dyn_cast<InitListExpr>(Init))
13250 DeduceInits = IL->inits();
13251 }
13252
13253 // Deduction only works if we have exactly one source expression.
13254 if (DeduceInits.empty()) {
13255 // It isn't possible to write this directly, but it is possible to
13256 // end up in this situation with "auto x(some_pack...);"
13257 Diag(Init->getBeginLoc(), IsInitCapture
13258 ? diag::err_init_capture_no_expression
13259 : diag::err_auto_var_init_no_expression)
13260 << VN << Type << Range;
13261 return QualType();
13262 }
13263
13264 if (DeduceInits.size() > 1) {
13265 Diag(DeduceInits[1]->getBeginLoc(),
13266 IsInitCapture ? diag::err_init_capture_multiple_expressions
13267 : diag::err_auto_var_init_multiple_expressions)
13268 << VN << Type << Range;
13269 return QualType();
13270 }
13271
13272 Expr *DeduceInit = DeduceInits[0];
13273 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13274 Diag(Init->getBeginLoc(), IsInitCapture
13275 ? diag::err_init_capture_paren_braces
13276 : diag::err_auto_var_init_paren_braces)
13277 << isa<InitListExpr>(Init) << VN << Type << Range;
13278 return QualType();
13279 }
13280
13281 // Expressions default to 'id' when we're in a debugger.
13282 bool DefaultedAnyToId = false;
13283 if (getLangOpts().DebuggerCastResultToId &&
13284 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13286 if (Result.isInvalid()) {
13287 return QualType();
13288 }
13289 Init = Result.get();
13290 DefaultedAnyToId = true;
13291 }
13292
13293 // C++ [dcl.decomp]p1:
13294 // If the assignment-expression [...] has array type A and no ref-qualifier
13295 // is present, e has type cv A
13296 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13297 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13298 DeduceInit->getType()->isConstantArrayType())
13299 return Context.getQualifiedType(DeduceInit->getType(),
13300 Type.getQualifiers());
13301
13302 QualType DeducedType;
13303 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13305 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13308 if (!IsInitCapture)
13309 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13310 else if (isa<InitListExpr>(Init))
13311 Diag(Range.getBegin(),
13312 diag::err_init_capture_deduction_failure_from_init_list)
13313 << VN
13314 << (DeduceInit->getType().isNull() ? TSI->getType()
13315 : DeduceInit->getType())
13316 << DeduceInit->getSourceRange();
13317 else
13318 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13319 << VN << TSI->getType()
13320 << (DeduceInit->getType().isNull() ? TSI->getType()
13321 : DeduceInit->getType())
13322 << DeduceInit->getSourceRange();
13323 }
13324
13325 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13326 // 'id' instead of a specific object type prevents most of our usual
13327 // checks.
13328 // We only want to warn outside of template instantiations, though:
13329 // inside a template, the 'id' could have come from a parameter.
13330 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13331 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13332 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13333 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13334 }
13335
13336 return DeducedType;
13337}
13338
13340 Expr *Init) {
13341 assert(!Init || !Init->containsErrors());
13343 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13344 VDecl->getSourceRange(), DirectInit, Init);
13345 if (DeducedType.isNull()) {
13346 VDecl->setInvalidDecl();
13347 return true;
13348 }
13349
13350 VDecl->setType(DeducedType);
13351 assert(VDecl->isLinkageValid());
13352
13353 // In ARC, infer lifetime.
13354 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13355 VDecl->setInvalidDecl();
13356
13357 if (getLangOpts().OpenCL)
13359
13360 if (getLangOpts().HLSL)
13361 HLSL().deduceAddressSpace(VDecl);
13362
13363 // If this is a redeclaration, check that the type we just deduced matches
13364 // the previously declared type.
13365 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13366 // We never need to merge the type, because we cannot form an incomplete
13367 // array of auto, nor deduce such a type.
13368 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13369 }
13370
13371 // Check the deduced type is valid for a variable declaration.
13373 return VDecl->isInvalidDecl();
13374}
13375
13377 SourceLocation Loc) {
13378 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13379 Init = EWC->getSubExpr();
13380
13381 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13382 Init = CE->getSubExpr();
13383
13384 QualType InitType = Init->getType();
13387 "shouldn't be called if type doesn't have a non-trivial C struct");
13388 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13389 for (auto *I : ILE->inits()) {
13390 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13391 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13392 continue;
13393 SourceLocation SL = I->getExprLoc();
13394 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13395 }
13396 return;
13397 }
13398
13401 checkNonTrivialCUnion(InitType, Loc,
13403 NTCUK_Init);
13404 } else {
13405 // Assume all other explicit initializers involving copying some existing
13406 // object.
13407 // TODO: ignore any explicit initializers where we can guarantee
13408 // copy-elision.
13411 NTCUK_Copy);
13412 }
13413}
13414
13415namespace {
13416
13417bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13418 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13419 // in the source code or implicitly by the compiler if it is in a union
13420 // defined in a system header and has non-trivial ObjC ownership
13421 // qualifications. We don't want those fields to participate in determining
13422 // whether the containing union is non-trivial.
13423 return FD->hasAttr<UnavailableAttr>();
13424}
13425
13426struct DiagNonTrivalCUnionDefaultInitializeVisitor
13427 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13428 void> {
13429 using Super =
13430 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13431 void>;
13432
13433 DiagNonTrivalCUnionDefaultInitializeVisitor(
13434 QualType OrigTy, SourceLocation OrigLoc,
13435 NonTrivialCUnionContext UseContext, Sema &S)
13436 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13437
13438 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13439 const FieldDecl *FD, bool InNonTrivialUnion) {
13440 if (const auto *AT = S.Context.getAsArrayType(QT))
13441 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13442 InNonTrivialUnion);
13443 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13444 }
13445
13446 void visitARCStrong(QualType QT, const FieldDecl *FD,
13447 bool InNonTrivialUnion) {
13448 if (InNonTrivialUnion)
13449 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13450 << 1 << 0 << QT << FD->getName();
13451 }
13452
13453 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13454 if (InNonTrivialUnion)
13455 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13456 << 1 << 0 << QT << FD->getName();
13457 }
13458
13459 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13460 const auto *RD = QT->castAsRecordDecl();
13461 if (RD->isUnion()) {
13462 if (OrigLoc.isValid()) {
13463 bool IsUnion = false;
13464 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13465 IsUnion = OrigRD->isUnion();
13466 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13467 << 0 << OrigTy << IsUnion << UseContext;
13468 // Reset OrigLoc so that this diagnostic is emitted only once.
13469 OrigLoc = SourceLocation();
13470 }
13471 InNonTrivialUnion = true;
13472 }
13473
13474 if (InNonTrivialUnion)
13475 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13476 << 0 << 0 << QT.getUnqualifiedType() << "";
13477
13478 for (const FieldDecl *FD : RD->fields())
13479 if (!shouldIgnoreForRecordTriviality(FD))
13480 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13481 }
13482
13483 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13484
13485 // The non-trivial C union type or the struct/union type that contains a
13486 // non-trivial C union.
13487 QualType OrigTy;
13488 SourceLocation OrigLoc;
13489 NonTrivialCUnionContext UseContext;
13490 Sema &S;
13491};
13492
13493struct DiagNonTrivalCUnionDestructedTypeVisitor
13494 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13495 using Super =
13496 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13497
13498 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13499 SourceLocation OrigLoc,
13500 NonTrivialCUnionContext UseContext,
13501 Sema &S)
13502 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13503
13504 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13505 const FieldDecl *FD, bool InNonTrivialUnion) {
13506 if (const auto *AT = S.Context.getAsArrayType(QT))
13507 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13508 InNonTrivialUnion);
13509 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13510 }
13511
13512 void visitARCStrong(QualType QT, const FieldDecl *FD,
13513 bool InNonTrivialUnion) {
13514 if (InNonTrivialUnion)
13515 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13516 << 1 << 1 << QT << FD->getName();
13517 }
13518
13519 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13520 if (InNonTrivialUnion)
13521 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13522 << 1 << 1 << QT << FD->getName();
13523 }
13524
13525 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13526 const auto *RD = QT->castAsRecordDecl();
13527 if (RD->isUnion()) {
13528 if (OrigLoc.isValid()) {
13529 bool IsUnion = false;
13530 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13531 IsUnion = OrigRD->isUnion();
13532 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13533 << 1 << OrigTy << IsUnion << UseContext;
13534 // Reset OrigLoc so that this diagnostic is emitted only once.
13535 OrigLoc = SourceLocation();
13536 }
13537 InNonTrivialUnion = true;
13538 }
13539
13540 if (InNonTrivialUnion)
13541 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13542 << 0 << 1 << QT.getUnqualifiedType() << "";
13543
13544 for (const FieldDecl *FD : RD->fields())
13545 if (!shouldIgnoreForRecordTriviality(FD))
13546 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13547 }
13548
13549 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13550 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13551 bool InNonTrivialUnion) {}
13552
13553 // The non-trivial C union type or the struct/union type that contains a
13554 // non-trivial C union.
13555 QualType OrigTy;
13556 SourceLocation OrigLoc;
13557 NonTrivialCUnionContext UseContext;
13558 Sema &S;
13559};
13560
13561struct DiagNonTrivalCUnionCopyVisitor
13562 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13563 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13564
13565 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13566 NonTrivialCUnionContext UseContext, Sema &S)
13567 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13568
13569 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13570 const FieldDecl *FD, bool InNonTrivialUnion) {
13571 if (const auto *AT = S.Context.getAsArrayType(QT))
13572 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13573 InNonTrivialUnion);
13574 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13575 }
13576
13577 void visitARCStrong(QualType QT, const FieldDecl *FD,
13578 bool InNonTrivialUnion) {
13579 if (InNonTrivialUnion)
13580 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13581 << 1 << 2 << QT << FD->getName();
13582 }
13583
13584 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13585 if (InNonTrivialUnion)
13586 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13587 << 1 << 2 << QT << FD->getName();
13588 }
13589
13590 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13591 const auto *RD = QT->castAsRecordDecl();
13592 if (RD->isUnion()) {
13593 if (OrigLoc.isValid()) {
13594 bool IsUnion = false;
13595 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13596 IsUnion = OrigRD->isUnion();
13597 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13598 << 2 << OrigTy << IsUnion << UseContext;
13599 // Reset OrigLoc so that this diagnostic is emitted only once.
13600 OrigLoc = SourceLocation();
13601 }
13602 InNonTrivialUnion = true;
13603 }
13604
13605 if (InNonTrivialUnion)
13606 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13607 << 0 << 2 << QT.getUnqualifiedType() << "";
13608
13609 for (const FieldDecl *FD : RD->fields())
13610 if (!shouldIgnoreForRecordTriviality(FD))
13611 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13612 }
13613
13614 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13615 if (InNonTrivialUnion)
13616 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13617 << 1 << 2 << QT << FD->getName();
13618 }
13619
13620 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13621 const FieldDecl *FD, bool InNonTrivialUnion) {}
13622 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13623 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13624 bool InNonTrivialUnion) {}
13625
13626 // The non-trivial C union type or the struct/union type that contains a
13627 // non-trivial C union.
13628 QualType OrigTy;
13629 SourceLocation OrigLoc;
13630 NonTrivialCUnionContext UseContext;
13631 Sema &S;
13632};
13633
13634} // namespace
13635
13637 NonTrivialCUnionContext UseContext,
13638 unsigned NonTrivialKind) {
13642 "shouldn't be called if type doesn't have a non-trivial C union");
13643
13644 if ((NonTrivialKind & NTCUK_Init) &&
13646 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13647 .visit(QT, nullptr, false);
13648 if ((NonTrivialKind & NTCUK_Destruct) &&
13650 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13651 .visit(QT, nullptr, false);
13652 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13653 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13654 .visit(QT, nullptr, false);
13655}
13656
13658 const VarDecl *Dcl) {
13659 if (!getLangOpts().CPlusPlus)
13660 return false;
13661
13662 // We only need to warn if the definition is in a header file, so wait to
13663 // diagnose until we've seen the definition.
13664 if (!Dcl->isThisDeclarationADefinition())
13665 return false;
13666
13667 // If an object is defined in a source file, its definition can't get
13668 // duplicated since it will never appear in more than one TU.
13670 return false;
13671
13672 // If the variable we're looking at is a static local, then we actually care
13673 // about the properties of the function containing it.
13674 const ValueDecl *Target = Dcl;
13675 // VarDecls and FunctionDecls have different functions for checking
13676 // inline-ness, and whether they were originally templated, so we have to
13677 // call the appropriate functions manually.
13678 bool TargetIsInline = Dcl->isInline();
13679 bool TargetWasTemplated =
13681
13682 // Update the Target and TargetIsInline property if necessary
13683 if (Dcl->isStaticLocal()) {
13684 const DeclContext *Ctx = Dcl->getDeclContext();
13685 if (!Ctx)
13686 return false;
13687
13688 const FunctionDecl *FunDcl =
13689 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13690 if (!FunDcl)
13691 return false;
13692
13693 Target = FunDcl;
13694 // IsInlined() checks for the C++ inline property
13695 TargetIsInline = FunDcl->isInlined();
13696 TargetWasTemplated =
13698 }
13699
13700 // Non-inline functions/variables can only legally appear in one TU
13701 // unless they were part of a template. Unfortunately, making complex
13702 // template instantiations visible is infeasible in practice, since
13703 // everything the template depends on also has to be visible. To avoid
13704 // giving impractical-to-fix warnings, don't warn if we're inside
13705 // something that was templated, even on inline stuff.
13706 if (!TargetIsInline || TargetWasTemplated)
13707 return false;
13708
13709 // If the object isn't hidden, the dynamic linker will prevent duplication.
13710 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13711
13712 // The target is "hidden" (from the dynamic linker) if:
13713 // 1. On posix, it has hidden visibility, or
13714 // 2. On windows, it has no import/export annotation, and neither does the
13715 // class which directly contains it.
13716 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13717 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13718 return false;
13719
13720 // If the variable isn't directly annotated, check to see if it's a member
13721 // of an annotated class.
13722 const CXXRecordDecl *Ctx =
13723 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13724 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13725 return false;
13726
13727 } else if (Lnk.getVisibility() != HiddenVisibility) {
13728 // Posix case
13729 return false;
13730 }
13731
13732 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13734 return false;
13735
13736 return true;
13737}
13738
13739// Determine whether the object seems mutable for the purpose of diagnosing
13740// possible unique object duplication, i.e. non-const-qualified, and
13741// not an always-constant type like a function.
13742// Not perfect: doesn't account for mutable members, for example, or
13743// elements of container types.
13744// For nested pointers, any individual level being non-const is sufficient.
13745static bool looksMutable(QualType T, const ASTContext &Ctx) {
13746 T = T.getNonReferenceType();
13747 if (T->isFunctionType())
13748 return false;
13749 if (!T.isConstant(Ctx))
13750 return true;
13751 if (T->isPointerType())
13752 return looksMutable(T->getPointeeType(), Ctx);
13753 return false;
13754}
13755
13757 // If this object has external linkage and hidden visibility, it might be
13758 // duplicated when built into a shared library, which causes problems if it's
13759 // mutable (since the copies won't be in sync) or its initialization has side
13760 // effects (since it will run once per copy instead of once globally).
13761
13762 // Don't diagnose if we're inside a template, because it's not practical to
13763 // fix the warning in most cases.
13764 if (!VD->isTemplated() &&
13766
13767 QualType Type = VD->getType();
13768 if (looksMutable(Type, VD->getASTContext())) {
13769 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13770 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13771 }
13772
13773 // To keep false positives low, only warn if we're certain that the
13774 // initializer has side effects. Don't warn on operator new, since a mutable
13775 // pointer will trigger the previous warning, and an immutable pointer
13776 // getting duplicated just results in a little extra memory usage.
13777 const Expr *Init = VD->getAnyInitializer();
13778 if (Init &&
13779 Init->HasSideEffects(VD->getASTContext(),
13780 /*IncludePossibleEffects=*/false) &&
13781 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13782 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13783 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13784 }
13785 }
13786}
13787
13789 auto ResetDeclForInitializer = llvm::make_scope_exit([this]() {
13790 if (this->ExprEvalContexts.empty())
13791 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13792 });
13793
13794 // If there is no declaration, there was an error parsing it. Just ignore
13795 // the initializer.
13796 if (!RealDecl) {
13797 return;
13798 }
13799
13800 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13801 if (!Method->isInvalidDecl()) {
13802 // Pure-specifiers are handled in ActOnPureSpecifier.
13803 Diag(Method->getLocation(), diag::err_member_function_initialization)
13804 << Method->getDeclName() << Init->getSourceRange();
13805 Method->setInvalidDecl();
13806 }
13807 return;
13808 }
13809
13810 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13811 if (!VDecl) {
13812 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13813 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13814 RealDecl->setInvalidDecl();
13815 return;
13816 }
13817
13818 if (VDecl->isInvalidDecl()) {
13819 ExprResult Recovery =
13820 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13821 if (Expr *E = Recovery.get())
13822 VDecl->setInit(E);
13823 return;
13824 }
13825
13826 // WebAssembly tables can't be used to initialise a variable.
13827 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13828 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13829 VDecl->setInvalidDecl();
13830 return;
13831 }
13832
13833 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13834 if (VDecl->getType()->isUndeducedType()) {
13835 if (Init->containsErrors()) {
13836 // Invalidate the decl as we don't know the type for recovery-expr yet.
13837 RealDecl->setInvalidDecl();
13838 VDecl->setInit(Init);
13839 return;
13840 }
13841
13843 return;
13844 }
13845
13846 this->CheckAttributesOnDeducedType(RealDecl);
13847
13848 // dllimport cannot be used on variable definitions.
13849 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13850 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13851 VDecl->setInvalidDecl();
13852 return;
13853 }
13854
13855 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13856 // the identifier has external or internal linkage, the declaration shall
13857 // have no initializer for the identifier.
13858 // C++14 [dcl.init]p5 is the same restriction for C++.
13859 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13860 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13861 VDecl->setInvalidDecl();
13862 return;
13863 }
13864
13865 if (!VDecl->getType()->isDependentType()) {
13866 // A definition must end up with a complete type, which means it must be
13867 // complete with the restriction that an array type might be completed by
13868 // the initializer; note that later code assumes this restriction.
13869 QualType BaseDeclType = VDecl->getType();
13870 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13871 BaseDeclType = Array->getElementType();
13872 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13873 diag::err_typecheck_decl_incomplete_type)) {
13874 RealDecl->setInvalidDecl();
13875 return;
13876 }
13877
13878 // The variable can not have an abstract class type.
13879 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13880 diag::err_abstract_type_in_decl,
13882 VDecl->setInvalidDecl();
13883 }
13884
13885 // C++ [module.import/6]
13886 // ...
13887 // A header unit shall not contain a definition of a non-inline function or
13888 // variable whose name has external linkage.
13889 //
13890 // We choose to allow weak & selectany definitions, as they are common in
13891 // headers, and have semantics similar to inline definitions which are allowed
13892 // in header units.
13893 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13894 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13895 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13896 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13898 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13899 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13900 VDecl->setInvalidDecl();
13901 }
13902
13903 // If adding the initializer will turn this declaration into a definition,
13904 // and we already have a definition for this variable, diagnose or otherwise
13905 // handle the situation.
13906 if (VarDecl *Def = VDecl->getDefinition())
13907 if (Def != VDecl &&
13908 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13910 checkVarDeclRedefinition(Def, VDecl))
13911 return;
13912
13913 if (getLangOpts().CPlusPlus) {
13914 // C++ [class.static.data]p4
13915 // If a static data member is of const integral or const
13916 // enumeration type, its declaration in the class definition can
13917 // specify a constant-initializer which shall be an integral
13918 // constant expression (5.19). In that case, the member can appear
13919 // in integral constant expressions. The member shall still be
13920 // defined in a namespace scope if it is used in the program and the
13921 // namespace scope definition shall not contain an initializer.
13922 //
13923 // We already performed a redefinition check above, but for static
13924 // data members we also need to check whether there was an in-class
13925 // declaration with an initializer.
13926 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13927 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13928 << VDecl->getDeclName();
13929 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13930 diag::note_previous_initializer)
13931 << 0;
13932 return;
13933 }
13934
13936 VDecl->setInvalidDecl();
13937 return;
13938 }
13939 }
13940
13941 // If the variable has an initializer and local storage, check whether
13942 // anything jumps over the initialization.
13943 if (VDecl->hasLocalStorage())
13945
13946 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13947 // a kernel function cannot be initialized."
13948 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13949 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13950 VDecl->setInvalidDecl();
13951 return;
13952 }
13953
13954 // The LoaderUninitialized attribute acts as a definition (of undef).
13955 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13956 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13957 VDecl->setInvalidDecl();
13958 return;
13959 }
13960
13961 if (getLangOpts().HLSL)
13962 if (!HLSL().handleInitialization(VDecl, Init))
13963 return;
13964
13965 // Get the decls type and save a reference for later, since
13966 // CheckInitializerTypes may change it.
13967 QualType DclT = VDecl->getType(), SavT = DclT;
13968
13969 // Expressions default to 'id' when we're in a debugger
13970 // and we are assigning it to a variable of Objective-C pointer type.
13971 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13972 Init->getType() == Context.UnknownAnyTy) {
13974 if (!Result.isUsable()) {
13975 VDecl->setInvalidDecl();
13976 return;
13977 }
13978 Init = Result.get();
13979 }
13980
13981 // Perform the initialization.
13982 bool InitializedFromParenListExpr = false;
13983 bool IsParenListInit = false;
13984 if (!VDecl->isInvalidDecl()) {
13987 VDecl->getLocation(), DirectInit, Init);
13988
13989 MultiExprArg Args = Init;
13990 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
13991 Args =
13992 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13993 InitializedFromParenListExpr = true;
13994 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
13995 Args = CXXDirectInit->getInitExprs();
13996 InitializedFromParenListExpr = true;
13997 }
13998
13999 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14000 /*TopLevelOfInitList=*/false,
14001 /*TreatUnavailableAsInvalid=*/false);
14002 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14003 if (!Result.isUsable()) {
14004 // If the provided initializer fails to initialize the var decl,
14005 // we attach a recovery expr for better recovery.
14006 auto RecoveryExpr =
14007 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14008 if (RecoveryExpr.get())
14009 VDecl->setInit(RecoveryExpr.get());
14010 // In general, for error recovery purposes, the initializer doesn't play
14011 // part in the valid bit of the declaration. There are a few exceptions:
14012 // 1) if the var decl has a deduced auto type, and the type cannot be
14013 // deduced by an invalid initializer;
14014 // 2) if the var decl is a decomposition decl with a non-deduced type,
14015 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14016 // Case 1) was already handled elsewhere.
14017 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14018 VDecl->setInvalidDecl();
14019 return;
14020 }
14021
14022 Init = Result.getAs<Expr>();
14023 IsParenListInit = !InitSeq.steps().empty() &&
14024 InitSeq.step_begin()->Kind ==
14026 QualType VDeclType = VDecl->getType();
14027 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14028 !VDeclType->isDependentType() &&
14029 Context.getAsIncompleteArrayType(VDeclType) &&
14030 Context.getAsIncompleteArrayType(Init->getType())) {
14031 // Bail out if it is not possible to deduce array size from the
14032 // initializer.
14033 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14034 << VDeclType;
14035 VDecl->setInvalidDecl();
14036 return;
14037 }
14038 }
14039
14040 // Check for self-references within variable initializers.
14041 // Variables declared within a function/method body (except for references)
14042 // are handled by a dataflow analysis.
14043 // This is undefined behavior in C++, but valid in C.
14044 if (getLangOpts().CPlusPlus)
14045 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14046 VDecl->getType()->isReferenceType())
14047 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14048
14049 // If the type changed, it means we had an incomplete type that was
14050 // completed by the initializer. For example:
14051 // int ary[] = { 1, 3, 5 };
14052 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14053 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14054 VDecl->setType(DclT);
14055
14056 if (!VDecl->isInvalidDecl()) {
14057 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14058
14059 if (VDecl->hasAttr<BlocksAttr>())
14060 ObjC().checkRetainCycles(VDecl, Init);
14061
14062 // It is safe to assign a weak reference into a strong variable.
14063 // Although this code can still have problems:
14064 // id x = self.weakProp;
14065 // id y = self.weakProp;
14066 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14067 // paths through the function. This should be revisited if
14068 // -Wrepeated-use-of-weak is made flow-sensitive.
14069 if (FunctionScopeInfo *FSI = getCurFunction())
14070 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14072 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14073 Init->getBeginLoc()))
14074 FSI->markSafeWeakUse(Init);
14075 }
14076
14077 // The initialization is usually a full-expression.
14078 //
14079 // FIXME: If this is a braced initialization of an aggregate, it is not
14080 // an expression, and each individual field initializer is a separate
14081 // full-expression. For instance, in:
14082 //
14083 // struct Temp { ~Temp(); };
14084 // struct S { S(Temp); };
14085 // struct T { S a, b; } t = { Temp(), Temp() }
14086 //
14087 // we should destroy the first Temp before constructing the second.
14090 /*DiscardedValue*/ false, VDecl->isConstexpr());
14091 if (!Result.isUsable()) {
14092 VDecl->setInvalidDecl();
14093 return;
14094 }
14095 Init = Result.get();
14096
14097 // Attach the initializer to the decl.
14098 VDecl->setInit(Init);
14099
14100 if (VDecl->isLocalVarDecl()) {
14101 // Don't check the initializer if the declaration is malformed.
14102 if (VDecl->isInvalidDecl()) {
14103 // do nothing
14104
14105 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14106 // This is true even in C++ for OpenCL.
14107 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14109
14110 // Otherwise, C++ does not restrict the initializer.
14111 } else if (getLangOpts().CPlusPlus) {
14112 // do nothing
14113
14114 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14115 // static storage duration shall be constant expressions or string literals.
14116 } else if (VDecl->getStorageClass() == SC_Static) {
14118
14119 // C89 is stricter than C99 for aggregate initializers.
14120 // C89 6.5.7p3: All the expressions [...] in an initializer list
14121 // for an object that has aggregate or union type shall be
14122 // constant expressions.
14123 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14125 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14126 }
14127
14128 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14129 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14130 if (VDecl->hasLocalStorage())
14131 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14132 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14133 VDecl->getLexicalDeclContext()->isRecord()) {
14134 // This is an in-class initialization for a static data member, e.g.,
14135 //
14136 // struct S {
14137 // static const int value = 17;
14138 // };
14139
14140 // C++ [class.mem]p4:
14141 // A member-declarator can contain a constant-initializer only
14142 // if it declares a static member (9.4) of const integral or
14143 // const enumeration type, see 9.4.2.
14144 //
14145 // C++11 [class.static.data]p3:
14146 // If a non-volatile non-inline const static data member is of integral
14147 // or enumeration type, its declaration in the class definition can
14148 // specify a brace-or-equal-initializer in which every initializer-clause
14149 // that is an assignment-expression is a constant expression. A static
14150 // data member of literal type can be declared in the class definition
14151 // with the constexpr specifier; if so, its declaration shall specify a
14152 // brace-or-equal-initializer in which every initializer-clause that is
14153 // an assignment-expression is a constant expression.
14154
14155 // Do nothing on dependent types.
14156 if (DclT->isDependentType()) {
14157
14158 // Allow any 'static constexpr' members, whether or not they are of literal
14159 // type. We separately check that every constexpr variable is of literal
14160 // type.
14161 } else if (VDecl->isConstexpr()) {
14162
14163 // Require constness.
14164 } else if (!DclT.isConstQualified()) {
14165 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14166 << Init->getSourceRange();
14167 VDecl->setInvalidDecl();
14168
14169 // We allow integer constant expressions in all cases.
14170 } else if (DclT->isIntegralOrEnumerationType()) {
14172 // In C++11, a non-constexpr const static data member with an
14173 // in-class initializer cannot be volatile.
14174 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14175
14176 // We allow foldable floating-point constants as an extension.
14177 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14178 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14179 // it anyway and provide a fixit to add the 'constexpr'.
14180 if (getLangOpts().CPlusPlus11) {
14181 Diag(VDecl->getLocation(),
14182 diag::ext_in_class_initializer_float_type_cxx11)
14183 << DclT << Init->getSourceRange();
14184 Diag(VDecl->getBeginLoc(),
14185 diag::note_in_class_initializer_float_type_cxx11)
14186 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14187 } else {
14188 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14189 << DclT << Init->getSourceRange();
14190
14191 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14192 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14193 << Init->getSourceRange();
14194 VDecl->setInvalidDecl();
14195 }
14196 }
14197
14198 // Suggest adding 'constexpr' in C++11 for literal types.
14199 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14200 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14201 << DclT << Init->getSourceRange()
14202 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14203 VDecl->setConstexpr(true);
14204
14205 } else {
14206 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14207 << DclT << Init->getSourceRange();
14208 VDecl->setInvalidDecl();
14209 }
14210 } else if (VDecl->isFileVarDecl()) {
14211 // In C, extern is typically used to avoid tentative definitions when
14212 // declaring variables in headers, but adding an initializer makes it a
14213 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14214 // In C++, extern is often used to give implicitly static const variables
14215 // external linkage, so don't warn in that case. If selectany is present,
14216 // this might be header code intended for C and C++ inclusion, so apply the
14217 // C++ rules.
14218 if (VDecl->getStorageClass() == SC_Extern &&
14219 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14220 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14221 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14223 Diag(VDecl->getLocation(), diag::warn_extern_init);
14224
14225 // In Microsoft C++ mode, a const variable defined in namespace scope has
14226 // external linkage by default if the variable is declared with
14227 // __declspec(dllexport).
14228 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14230 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14231 VDecl->setStorageClass(SC_Extern);
14232
14233 // C99 6.7.8p4. All file scoped initializers need to be constant.
14234 // Avoid duplicate diagnostics for constexpr variables.
14235 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14236 !VDecl->isConstexpr())
14238 }
14239
14240 QualType InitType = Init->getType();
14241 if (!InitType.isNull() &&
14245
14246 // We will represent direct-initialization similarly to copy-initialization:
14247 // int x(1); -as-> int x = 1;
14248 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14249 //
14250 // Clients that want to distinguish between the two forms, can check for
14251 // direct initializer using VarDecl::getInitStyle().
14252 // A major benefit is that clients that don't particularly care about which
14253 // exactly form was it (like the CodeGen) can handle both cases without
14254 // special case code.
14255
14256 // C++ 8.5p11:
14257 // The form of initialization (using parentheses or '=') matters
14258 // when the entity being initialized has class type.
14259 if (InitializedFromParenListExpr) {
14260 assert(DirectInit && "Call-style initializer must be direct init.");
14261 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14263 } else if (DirectInit) {
14264 // This must be list-initialization. No other way is direct-initialization.
14266 }
14267
14268 if (LangOpts.OpenMP &&
14269 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14270 VDecl->isFileVarDecl())
14271 DeclsToCheckForDeferredDiags.insert(VDecl);
14273
14274 if (LangOpts.OpenACC && !InitType.isNull())
14275 OpenACC().ActOnVariableInit(VDecl, InitType);
14276}
14277
14279 // Our main concern here is re-establishing invariants like "a
14280 // variable's type is either dependent or complete".
14281 if (!D || D->isInvalidDecl()) return;
14282
14283 VarDecl *VD = dyn_cast<VarDecl>(D);
14284 if (!VD) return;
14285
14286 // Bindings are not usable if we can't make sense of the initializer.
14287 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14288 for (auto *BD : DD->bindings())
14289 BD->setInvalidDecl();
14290
14291 // Auto types are meaningless if we can't make sense of the initializer.
14292 if (VD->getType()->isUndeducedType()) {
14293 D->setInvalidDecl();
14294 return;
14295 }
14296
14297 QualType Ty = VD->getType();
14298 if (Ty->isDependentType()) return;
14299
14300 // Require a complete type.
14302 Context.getBaseElementType(Ty),
14303 diag::err_typecheck_decl_incomplete_type)) {
14304 VD->setInvalidDecl();
14305 return;
14306 }
14307
14308 // Require a non-abstract type.
14309 if (RequireNonAbstractType(VD->getLocation(), Ty,
14310 diag::err_abstract_type_in_decl,
14312 VD->setInvalidDecl();
14313 return;
14314 }
14315
14316 // Don't bother complaining about constructors or destructors,
14317 // though.
14318}
14319
14321 // If there is no declaration, there was an error parsing it. Just ignore it.
14322 if (!RealDecl)
14323 return;
14324
14325 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14326 QualType Type = Var->getType();
14327
14328 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14329 if (isa<DecompositionDecl>(RealDecl)) {
14330 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14331 Var->setInvalidDecl();
14332 return;
14333 }
14334
14335 if (Type->isUndeducedType() &&
14336 DeduceVariableDeclarationType(Var, false, nullptr))
14337 return;
14338
14339 this->CheckAttributesOnDeducedType(RealDecl);
14340
14341 // C++11 [class.static.data]p3: A static data member can be declared with
14342 // the constexpr specifier; if so, its declaration shall specify
14343 // a brace-or-equal-initializer.
14344 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14345 // the definition of a variable [...] or the declaration of a static data
14346 // member.
14347 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14348 !Var->isThisDeclarationADemotedDefinition()) {
14349 if (Var->isStaticDataMember()) {
14350 // C++1z removes the relevant rule; the in-class declaration is always
14351 // a definition there.
14352 if (!getLangOpts().CPlusPlus17 &&
14353 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14354 Diag(Var->getLocation(),
14355 diag::err_constexpr_static_mem_var_requires_init)
14356 << Var;
14357 Var->setInvalidDecl();
14358 return;
14359 }
14360 } else {
14361 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14362 Var->setInvalidDecl();
14363 return;
14364 }
14365 }
14366
14367 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14368 // be initialized.
14369 if (!Var->isInvalidDecl() &&
14370 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14371 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14372 bool HasConstExprDefaultConstructor = false;
14373 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14374 for (auto *Ctor : RD->ctors()) {
14375 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14376 Ctor->getMethodQualifiers().getAddressSpace() ==
14378 HasConstExprDefaultConstructor = true;
14379 }
14380 }
14381 }
14382 if (!HasConstExprDefaultConstructor) {
14383 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14384 Var->setInvalidDecl();
14385 return;
14386 }
14387 }
14388
14389 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14390 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14391 Diag(Var->getLocation(), diag::err_specialization_const);
14392 Var->setInvalidDecl();
14393 return;
14394 }
14395
14396 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14397 if (Var->getStorageClass() == SC_Extern) {
14398 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14399 << Var;
14400 Var->setInvalidDecl();
14401 return;
14402 }
14403 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14404 diag::err_typecheck_decl_incomplete_type)) {
14405 Var->setInvalidDecl();
14406 return;
14407 }
14408 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14409 if (!RD->hasTrivialDefaultConstructor()) {
14410 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14411 Var->setInvalidDecl();
14412 return;
14413 }
14414 }
14415 // The declaration is uninitialized, no need for further checks.
14416 return;
14417 }
14418
14419 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14420 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14421 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14422 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14424 NTCUK_Init);
14425
14426 switch (DefKind) {
14428 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14429 break;
14430
14431 // We have an out-of-line definition of a static data member
14432 // that has an in-class initializer, so we type-check this like
14433 // a declaration.
14434 //
14435 [[fallthrough]];
14436
14438 // It's only a declaration.
14439
14440 // Block scope. C99 6.7p7: If an identifier for an object is
14441 // declared with no linkage (C99 6.2.2p6), the type for the
14442 // object shall be complete.
14443 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14444 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14445 RequireCompleteType(Var->getLocation(), Type,
14446 diag::err_typecheck_decl_incomplete_type))
14447 Var->setInvalidDecl();
14448
14449 // Make sure that the type is not abstract.
14450 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14451 RequireNonAbstractType(Var->getLocation(), Type,
14452 diag::err_abstract_type_in_decl,
14454 Var->setInvalidDecl();
14455 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14456 Var->getStorageClass() == SC_PrivateExtern) {
14457 Diag(Var->getLocation(), diag::warn_private_extern);
14458 Diag(Var->getLocation(), diag::note_private_extern);
14459 }
14460
14461 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14462 !Var->isInvalidDecl())
14463 ExternalDeclarations.push_back(Var);
14464
14465 return;
14466
14468 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14469 // object that has file scope without an initializer, and without a
14470 // storage-class specifier or with the storage-class specifier "static",
14471 // constitutes a tentative definition. Note: A tentative definition with
14472 // external linkage is valid (C99 6.2.2p5).
14473 if (!Var->isInvalidDecl()) {
14474 if (const IncompleteArrayType *ArrayT
14475 = Context.getAsIncompleteArrayType(Type)) {
14477 Var->getLocation(), ArrayT->getElementType(),
14478 diag::err_array_incomplete_or_sizeless_type))
14479 Var->setInvalidDecl();
14480 }
14481 if (Var->getStorageClass() == SC_Static) {
14482 // C99 6.9.2p3: If the declaration of an identifier for an object is
14483 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14484 // declared type shall not be an incomplete type.
14485 // NOTE: code such as the following
14486 // static struct s;
14487 // struct s { int a; };
14488 // is accepted by gcc. Hence here we issue a warning instead of
14489 // an error and we do not invalidate the static declaration.
14490 // NOTE: to avoid multiple warnings, only check the first declaration.
14491 if (Var->isFirstDecl())
14492 RequireCompleteType(Var->getLocation(), Type,
14493 diag::ext_typecheck_decl_incomplete_type,
14494 Type->isArrayType());
14495 }
14496 }
14497
14498 // Record the tentative definition; we're done.
14499 if (!Var->isInvalidDecl())
14500 TentativeDefinitions.push_back(Var);
14501 return;
14502 }
14503
14504 // Provide a specific diagnostic for uninitialized variable definitions
14505 // with incomplete array type, unless it is a global unbounded HLSL resource
14506 // array.
14507 if (Type->isIncompleteArrayType() &&
14508 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14510 if (Var->isConstexpr())
14511 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14512 << Var;
14513 else
14514 Diag(Var->getLocation(),
14515 diag::err_typecheck_incomplete_array_needs_initializer);
14516 Var->setInvalidDecl();
14517 return;
14518 }
14519
14520 // Provide a specific diagnostic for uninitialized variable
14521 // definitions with reference type.
14522 if (Type->isReferenceType()) {
14523 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14524 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14525 return;
14526 }
14527
14528 // Do not attempt to type-check the default initializer for a
14529 // variable with dependent type.
14530 if (Type->isDependentType())
14531 return;
14532
14533 if (Var->isInvalidDecl())
14534 return;
14535
14536 if (!Var->hasAttr<AliasAttr>()) {
14537 if (RequireCompleteType(Var->getLocation(),
14538 Context.getBaseElementType(Type),
14539 diag::err_typecheck_decl_incomplete_type)) {
14540 Var->setInvalidDecl();
14541 return;
14542 }
14543 } else {
14544 return;
14545 }
14546
14547 // The variable can not have an abstract class type.
14548 if (RequireNonAbstractType(Var->getLocation(), Type,
14549 diag::err_abstract_type_in_decl,
14551 Var->setInvalidDecl();
14552 return;
14553 }
14554
14555 // In C, if the definition is const-qualified and has no initializer, it
14556 // is left uninitialized unless it has static or thread storage duration.
14557 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14558 unsigned DiagID = diag::warn_default_init_const_unsafe;
14559 if (Var->getStorageDuration() == SD_Static ||
14560 Var->getStorageDuration() == SD_Thread)
14561 DiagID = diag::warn_default_init_const;
14562
14563 bool EmitCppCompat = !Diags.isIgnored(
14564 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14565 Var->getLocation());
14566
14567 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14568 }
14569
14570 // Check for jumps past the implicit initializer. C++0x
14571 // clarifies that this applies to a "variable with automatic
14572 // storage duration", not a "local variable".
14573 // C++11 [stmt.dcl]p3
14574 // A program that jumps from a point where a variable with automatic
14575 // storage duration is not in scope to a point where it is in scope is
14576 // ill-formed unless the variable has scalar type, class type with a
14577 // trivial default constructor and a trivial destructor, a cv-qualified
14578 // version of one of these types, or an array of one of the preceding
14579 // types and is declared without an initializer.
14580 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14581 if (const auto *CXXRecord =
14582 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14583 // Mark the function (if we're in one) for further checking even if the
14584 // looser rules of C++11 do not require such checks, so that we can
14585 // diagnose incompatibilities with C++98.
14586 if (!CXXRecord->isPOD())
14588 }
14589 }
14590 // In OpenCL, we can't initialize objects in the __local address space,
14591 // even implicitly, so don't synthesize an implicit initializer.
14592 if (getLangOpts().OpenCL &&
14593 Var->getType().getAddressSpace() == LangAS::opencl_local)
14594 return;
14595
14596 // Handle HLSL uninitialized decls
14597 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14598 return;
14599
14600 // HLSL input variables are expected to be externally initialized, even
14601 // when marked `static`.
14602 if (getLangOpts().HLSL &&
14603 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14604 return;
14605
14606 // C++03 [dcl.init]p9:
14607 // If no initializer is specified for an object, and the
14608 // object is of (possibly cv-qualified) non-POD class type (or
14609 // array thereof), the object shall be default-initialized; if
14610 // the object is of const-qualified type, the underlying class
14611 // type shall have a user-declared default
14612 // constructor. Otherwise, if no initializer is specified for
14613 // a non- static object, the object and its subobjects, if
14614 // any, have an indeterminate initial value); if the object
14615 // or any of its subobjects are of const-qualified type, the
14616 // program is ill-formed.
14617 // C++0x [dcl.init]p11:
14618 // If no initializer is specified for an object, the object is
14619 // default-initialized; [...].
14622 = InitializationKind::CreateDefault(Var->getLocation());
14623
14624 InitializationSequence InitSeq(*this, Entity, Kind, {});
14625 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14626
14627 if (Init.get()) {
14628 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14629 // This is important for template substitution.
14630 Var->setInitStyle(VarDecl::CallInit);
14631 } else if (Init.isInvalid()) {
14632 // If default-init fails, attach a recovery-expr initializer to track
14633 // that initialization was attempted and failed.
14634 auto RecoveryExpr =
14635 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14636 if (RecoveryExpr.get())
14637 Var->setInit(RecoveryExpr.get());
14638 }
14639
14641 }
14642}
14643
14645 // If there is no declaration, there was an error parsing it. Ignore it.
14646 if (!D)
14647 return;
14648
14649 VarDecl *VD = dyn_cast<VarDecl>(D);
14650 if (!VD) {
14651 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14652 D->setInvalidDecl();
14653 return;
14654 }
14655
14656 VD->setCXXForRangeDecl(true);
14657
14658 // for-range-declaration cannot be given a storage class specifier.
14659 int Error = -1;
14660 switch (VD->getStorageClass()) {
14661 case SC_None:
14662 break;
14663 case SC_Extern:
14664 Error = 0;
14665 break;
14666 case SC_Static:
14667 Error = 1;
14668 break;
14669 case SC_PrivateExtern:
14670 Error = 2;
14671 break;
14672 case SC_Auto:
14673 Error = 3;
14674 break;
14675 case SC_Register:
14676 Error = 4;
14677 break;
14678 }
14679
14680 // for-range-declaration cannot be given a storage class specifier con't.
14681 switch (VD->getTSCSpec()) {
14682 case TSCS_thread_local:
14683 Error = 6;
14684 break;
14685 case TSCS___thread:
14686 case TSCS__Thread_local:
14687 case TSCS_unspecified:
14688 break;
14689 }
14690
14691 if (Error != -1) {
14692 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14693 << VD << Error;
14694 D->setInvalidDecl();
14695 }
14696}
14697
14699 IdentifierInfo *Ident,
14700 ParsedAttributes &Attrs) {
14701 // C++1y [stmt.iter]p1:
14702 // A range-based for statement of the form
14703 // for ( for-range-identifier : for-range-initializer ) statement
14704 // is equivalent to
14705 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14706 DeclSpec DS(Attrs.getPool().getFactory());
14707
14708 const char *PrevSpec;
14709 unsigned DiagID;
14710 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14712
14714 D.SetIdentifier(Ident, IdentLoc);
14715 D.takeAttributesAppending(Attrs);
14716
14717 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14718 IdentLoc);
14719 Decl *Var = ActOnDeclarator(S, D);
14720 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14722 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14723 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14724 : IdentLoc);
14725}
14726
14728 if (var->isInvalidDecl()) return;
14729
14731
14732 if (getLangOpts().OpenCL) {
14733 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14734 // initialiser
14735 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14736 !var->hasInit()) {
14737 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14738 << 1 /*Init*/;
14739 var->setInvalidDecl();
14740 return;
14741 }
14742 }
14743
14744 // In Objective-C, don't allow jumps past the implicit initialization of a
14745 // local retaining variable.
14746 if (getLangOpts().ObjC &&
14747 var->hasLocalStorage()) {
14748 switch (var->getType().getObjCLifetime()) {
14752 break;
14753
14757 break;
14758 }
14759 }
14760
14761 if (var->hasLocalStorage() &&
14762 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14764
14765 // Warn about externally-visible variables being defined without a
14766 // prior declaration. We only want to do this for global
14767 // declarations, but we also specifically need to avoid doing it for
14768 // class members because the linkage of an anonymous class can
14769 // change if it's later given a typedef name.
14770 if (var->isThisDeclarationADefinition() &&
14771 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14772 var->isExternallyVisible() && var->hasLinkage() &&
14773 !var->isInline() && !var->getDescribedVarTemplate() &&
14774 var->getStorageClass() != SC_Register &&
14776 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14777 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14778 var->getLocation())) {
14779 // Find a previous declaration that's not a definition.
14780 VarDecl *prev = var->getPreviousDecl();
14781 while (prev && prev->isThisDeclarationADefinition())
14782 prev = prev->getPreviousDecl();
14783
14784 if (!prev) {
14785 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14786 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14787 << /* variable */ 0;
14788 }
14789 }
14790
14791 // Cache the result of checking for constant initialization.
14792 std::optional<bool> CacheHasConstInit;
14793 const Expr *CacheCulprit = nullptr;
14794 auto checkConstInit = [&]() mutable {
14795 const Expr *Init = var->getInit();
14796 if (Init->isInstantiationDependent())
14797 return true;
14798
14799 if (!CacheHasConstInit)
14800 CacheHasConstInit = var->getInit()->isConstantInitializer(
14801 Context, var->getType()->isReferenceType(), &CacheCulprit);
14802 return *CacheHasConstInit;
14803 };
14804
14805 if (var->getTLSKind() == VarDecl::TLS_Static) {
14806 if (var->getType().isDestructedType()) {
14807 // GNU C++98 edits for __thread, [basic.start.term]p3:
14808 // The type of an object with thread storage duration shall not
14809 // have a non-trivial destructor.
14810 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14812 Diag(var->getLocation(), diag::note_use_thread_local);
14813 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14814 if (!checkConstInit()) {
14815 // GNU C++98 edits for __thread, [basic.start.init]p4:
14816 // An object of thread storage duration shall not require dynamic
14817 // initialization.
14818 // FIXME: Need strict checking here.
14819 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14820 << CacheCulprit->getSourceRange();
14822 Diag(var->getLocation(), diag::note_use_thread_local);
14823 }
14824 }
14825 }
14826
14827
14828 if (!var->getType()->isStructureType() && var->hasInit() &&
14829 isa<InitListExpr>(var->getInit())) {
14830 const auto *ILE = cast<InitListExpr>(var->getInit());
14831 unsigned NumInits = ILE->getNumInits();
14832 if (NumInits > 2)
14833 for (unsigned I = 0; I < NumInits; ++I) {
14834 const auto *Init = ILE->getInit(I);
14835 if (!Init)
14836 break;
14837 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14838 if (!SL)
14839 break;
14840
14841 unsigned NumConcat = SL->getNumConcatenated();
14842 // Diagnose missing comma in string array initialization.
14843 // Do not warn when all the elements in the initializer are concatenated
14844 // together. Do not warn for macros too.
14845 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14846 bool OnlyOneMissingComma = true;
14847 for (unsigned J = I + 1; J < NumInits; ++J) {
14848 const auto *Init = ILE->getInit(J);
14849 if (!Init)
14850 break;
14851 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14852 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14853 OnlyOneMissingComma = false;
14854 break;
14855 }
14856 }
14857
14858 if (OnlyOneMissingComma) {
14860 for (unsigned i = 0; i < NumConcat - 1; ++i)
14861 Hints.push_back(FixItHint::CreateInsertion(
14862 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14863
14864 Diag(SL->getStrTokenLoc(1),
14865 diag::warn_concatenated_literal_array_init)
14866 << Hints;
14867 Diag(SL->getBeginLoc(),
14868 diag::note_concatenated_string_literal_silence);
14869 }
14870 // In any case, stop now.
14871 break;
14872 }
14873 }
14874 }
14875
14876
14877 QualType type = var->getType();
14878
14879 if (var->hasAttr<BlocksAttr>())
14881
14882 Expr *Init = var->getInit();
14883 bool GlobalStorage = var->hasGlobalStorage();
14884 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14885 QualType baseType = Context.getBaseElementType(type);
14886 bool HasConstInit = true;
14887
14888 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14889 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14890 << var;
14891
14892 // Check whether the initializer is sufficiently constant.
14893 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14894 !type->isDependentType() && Init && !Init->isValueDependent() &&
14895 (GlobalStorage || var->isConstexpr() ||
14896 var->mightBeUsableInConstantExpressions(Context))) {
14897 // If this variable might have a constant initializer or might be usable in
14898 // constant expressions, check whether or not it actually is now. We can't
14899 // do this lazily, because the result might depend on things that change
14900 // later, such as which constexpr functions happen to be defined.
14902 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14903 // Prior to C++11, in contexts where a constant initializer is required,
14904 // the set of valid constant initializers is described by syntactic rules
14905 // in [expr.const]p2-6.
14906 // FIXME: Stricter checking for these rules would be useful for constinit /
14907 // -Wglobal-constructors.
14908 HasConstInit = checkConstInit();
14909
14910 // Compute and cache the constant value, and remember that we have a
14911 // constant initializer.
14912 if (HasConstInit) {
14913 if (var->isStaticDataMember() && !var->isInline() &&
14914 var->getLexicalDeclContext()->isRecord() &&
14915 type->isIntegralOrEnumerationType()) {
14916 // In C++98, in-class initialization for a static data member must
14917 // be an integer constant expression.
14918 if (!Init->isIntegerConstantExpr(Context)) {
14919 Diag(Init->getExprLoc(),
14920 diag::ext_in_class_initializer_non_constant)
14921 << Init->getSourceRange();
14922 }
14923 }
14924 (void)var->checkForConstantInitialization(Notes);
14925 Notes.clear();
14926 } else if (CacheCulprit) {
14927 Notes.emplace_back(CacheCulprit->getExprLoc(),
14928 PDiag(diag::note_invalid_subexpr_in_const_expr));
14929 Notes.back().second << CacheCulprit->getSourceRange();
14930 }
14931 } else {
14932 // Evaluate the initializer to see if it's a constant initializer.
14933 HasConstInit = var->checkForConstantInitialization(Notes);
14934 }
14935
14936 if (HasConstInit) {
14937 // FIXME: Consider replacing the initializer with a ConstantExpr.
14938 } else if (var->isConstexpr()) {
14939 SourceLocation DiagLoc = var->getLocation();
14940 // If the note doesn't add any useful information other than a source
14941 // location, fold it into the primary diagnostic.
14942 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14943 diag::note_invalid_subexpr_in_const_expr) {
14944 DiagLoc = Notes[0].first;
14945 Notes.clear();
14946 }
14947 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14948 << var << Init->getSourceRange();
14949 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14950 Diag(Notes[I].first, Notes[I].second);
14951 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14952 auto *Attr = var->getAttr<ConstInitAttr>();
14953 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14954 << Init->getSourceRange();
14955 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14956 << Attr->getRange() << Attr->isConstinit();
14957 for (auto &it : Notes)
14958 Diag(it.first, it.second);
14959 } else if (var->isStaticDataMember() && !var->isInline() &&
14960 var->getLexicalDeclContext()->isRecord()) {
14961 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
14962 << Init->getSourceRange();
14963 for (auto &it : Notes)
14964 Diag(it.first, it.second);
14965 var->setInvalidDecl();
14966 } else if (IsGlobal &&
14967 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14968 var->getLocation())) {
14969 // Warn about globals which don't have a constant initializer. Don't
14970 // warn about globals with a non-trivial destructor because we already
14971 // warned about them.
14972 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14973 if (!(RD && !RD->hasTrivialDestructor())) {
14974 // checkConstInit() here permits trivial default initialization even in
14975 // C++11 onwards, where such an initializer is not a constant initializer
14976 // but nonetheless doesn't require a global constructor.
14977 if (!checkConstInit())
14978 Diag(var->getLocation(), diag::warn_global_constructor)
14979 << Init->getSourceRange();
14980 }
14981 }
14982 }
14983
14984 // Apply section attributes and pragmas to global variables.
14985 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14987 PragmaStack<StringLiteral *> *Stack = nullptr;
14988 int SectionFlags = ASTContext::PSF_Read;
14989 bool MSVCEnv =
14990 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14991 std::optional<QualType::NonConstantStorageReason> Reason;
14992 if (HasConstInit &&
14993 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14994 Stack = &ConstSegStack;
14995 } else {
14996 SectionFlags |= ASTContext::PSF_Write;
14997 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14998 }
14999 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15000 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15001 SectionFlags |= ASTContext::PSF_Implicit;
15002 UnifySection(SA->getName(), SectionFlags, var);
15003 } else if (Stack->CurrentValue) {
15004 if (Stack != &ConstSegStack && MSVCEnv &&
15005 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15006 var->getType().isConstQualified()) {
15007 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15008 NonConstNonReferenceType) &&
15009 "This case should've already been handled elsewhere");
15010 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15011 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15013 : *Reason);
15014 }
15015 SectionFlags |= ASTContext::PSF_Implicit;
15016 auto SectionName = Stack->CurrentValue->getString();
15017 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15018 Stack->CurrentPragmaLocation,
15019 SectionAttr::Declspec_allocate));
15020 if (UnifySection(SectionName, SectionFlags, var))
15021 var->dropAttr<SectionAttr>();
15022 }
15023
15024 // Apply the init_seg attribute if this has an initializer. If the
15025 // initializer turns out to not be dynamic, we'll end up ignoring this
15026 // attribute.
15027 if (CurInitSeg && var->getInit())
15028 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15029 CurInitSegLoc));
15030 }
15031
15032 // All the following checks are C++ only.
15033 if (!getLangOpts().CPlusPlus) {
15034 // If this variable must be emitted, add it as an initializer for the
15035 // current module.
15036 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15037 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15038 return;
15039 }
15040
15042
15043 // Require the destructor.
15044 if (!type->isDependentType())
15045 if (auto *RD = baseType->getAsCXXRecordDecl())
15047
15048 // If this variable must be emitted, add it as an initializer for the current
15049 // module.
15050 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15051 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15052
15053 // Build the bindings if this is a structured binding declaration.
15054 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15056}
15057
15059 assert(VD->isStaticLocal());
15060
15061 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15062
15063 // Find outermost function when VD is in lambda function.
15064 while (FD && !getDLLAttr(FD) &&
15065 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15066 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15067 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15068 }
15069
15070 if (!FD)
15071 return;
15072
15073 // Static locals inherit dll attributes from their function.
15074 if (Attr *A = getDLLAttr(FD)) {
15075 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15076 NewAttr->setInherited(true);
15077 VD->addAttr(NewAttr);
15078 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15079 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15080 NewAttr->setInherited(true);
15081 VD->addAttr(NewAttr);
15082
15083 // Export this function to enforce exporting this static variable even
15084 // if it is not used in this compilation unit.
15085 if (!FD->hasAttr<DLLExportAttr>())
15086 FD->addAttr(NewAttr);
15087
15088 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15089 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15090 NewAttr->setInherited(true);
15091 VD->addAttr(NewAttr);
15092 }
15093}
15094
15096 assert(VD->getTLSKind());
15097
15098 // Perform TLS alignment check here after attributes attached to the variable
15099 // which may affect the alignment have been processed. Only perform the check
15100 // if the target has a maximum TLS alignment (zero means no constraints).
15101 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15102 // Protect the check so that it's not performed on dependent types and
15103 // dependent alignments (we can't determine the alignment in that case).
15104 if (!VD->hasDependentAlignment()) {
15105 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15106 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15107 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15108 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15109 << (unsigned)MaxAlignChars.getQuantity();
15110 }
15111 }
15112 }
15113}
15114
15116 // Note that we are no longer parsing the initializer for this declaration.
15117 ParsingInitForAutoVars.erase(ThisDecl);
15118
15119 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15120 if (!VD)
15121 return;
15122
15123 // Emit any deferred warnings for the variable's initializer, even if the
15124 // variable is invalid
15125 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15126
15127 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15129 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15130 if (PragmaClangBSSSection.Valid)
15131 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15132 Context, PragmaClangBSSSection.SectionName,
15133 PragmaClangBSSSection.PragmaLocation));
15134 if (PragmaClangDataSection.Valid)
15135 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15136 Context, PragmaClangDataSection.SectionName,
15137 PragmaClangDataSection.PragmaLocation));
15138 if (PragmaClangRodataSection.Valid)
15139 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15140 Context, PragmaClangRodataSection.SectionName,
15141 PragmaClangRodataSection.PragmaLocation));
15142 if (PragmaClangRelroSection.Valid)
15143 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15144 Context, PragmaClangRelroSection.SectionName,
15145 PragmaClangRelroSection.PragmaLocation));
15146 }
15147
15148 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15149 for (auto *BD : DD->bindings()) {
15151 }
15152 }
15153
15154 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15156
15157 checkAttributesAfterMerging(*this, *VD);
15158
15159 if (VD->isStaticLocal())
15161
15162 if (VD->getTLSKind())
15164
15165 // Perform check for initializers of device-side global variables.
15166 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15167 // 7.5). We must also apply the same checks to all __shared__
15168 // variables whether they are local or not. CUDA also allows
15169 // constant initializers for __constant__ and __device__ variables.
15170 if (getLangOpts().CUDA)
15172
15173 // Grab the dllimport or dllexport attribute off of the VarDecl.
15174 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15175
15176 // Imported static data members cannot be defined out-of-line.
15177 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15178 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15180 // We allow definitions of dllimport class template static data members
15181 // with a warning.
15184 bool IsClassTemplateMember =
15186 Context->getDescribedClassTemplate();
15187
15188 Diag(VD->getLocation(),
15189 IsClassTemplateMember
15190 ? diag::warn_attribute_dllimport_static_field_definition
15191 : diag::err_attribute_dllimport_static_field_definition);
15192 Diag(IA->getLocation(), diag::note_attribute);
15193 if (!IsClassTemplateMember)
15194 VD->setInvalidDecl();
15195 }
15196 }
15197
15198 // dllimport/dllexport variables cannot be thread local, their TLS index
15199 // isn't exported with the variable.
15200 if (DLLAttr && VD->getTLSKind()) {
15201 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15202 if (F && getDLLAttr(F)) {
15203 assert(VD->isStaticLocal());
15204 // But if this is a static local in a dlimport/dllexport function, the
15205 // function will never be inlined, which means the var would never be
15206 // imported, so having it marked import/export is safe.
15207 } else {
15208 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15209 << DLLAttr;
15210 VD->setInvalidDecl();
15211 }
15212 }
15213
15214 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15215 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15216 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15217 << Attr;
15218 VD->dropAttr<UsedAttr>();
15219 }
15220 }
15221 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15222 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15223 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15224 << Attr;
15225 VD->dropAttr<RetainAttr>();
15226 }
15227 }
15228
15229 const DeclContext *DC = VD->getDeclContext();
15230 // If there's a #pragma GCC visibility in scope, and this isn't a class
15231 // member, set the visibility of this variable.
15234
15235 // FIXME: Warn on unused var template partial specializations.
15238
15239 // Now we have parsed the initializer and can update the table of magic
15240 // tag values.
15241 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15243 return;
15244
15245 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15246 const Expr *MagicValueExpr = VD->getInit();
15247 if (!MagicValueExpr) {
15248 continue;
15249 }
15250 std::optional<llvm::APSInt> MagicValueInt;
15251 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15252 Diag(I->getRange().getBegin(),
15253 diag::err_type_tag_for_datatype_not_ice)
15254 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15255 continue;
15256 }
15257 if (MagicValueInt->getActiveBits() > 64) {
15258 Diag(I->getRange().getBegin(),
15259 diag::err_type_tag_for_datatype_too_large)
15260 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15261 continue;
15262 }
15263 uint64_t MagicValue = MagicValueInt->getZExtValue();
15264 RegisterTypeTagForDatatype(I->getArgumentKind(),
15265 MagicValue,
15266 I->getMatchingCType(),
15267 I->getLayoutCompatible(),
15268 I->getMustBeNull());
15269 }
15270}
15271
15273 auto *VD = dyn_cast<VarDecl>(DD);
15274 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15275}
15276
15278 ArrayRef<Decl *> Group) {
15280
15281 if (DS.isTypeSpecOwned())
15282 Decls.push_back(DS.getRepAsDecl());
15283
15284 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15285 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15286 bool DiagnosedMultipleDecomps = false;
15287 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15288 bool DiagnosedNonDeducedAuto = false;
15289
15290 for (Decl *D : Group) {
15291 if (!D)
15292 continue;
15293 // Check if the Decl has been declared in '#pragma omp declare target'
15294 // directive and has static storage duration.
15295 if (auto *VD = dyn_cast<VarDecl>(D);
15296 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15297 VD->hasGlobalStorage())
15299 // For declarators, there are some additional syntactic-ish checks we need
15300 // to perform.
15301 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15302 if (!FirstDeclaratorInGroup)
15303 FirstDeclaratorInGroup = DD;
15304 if (!FirstDecompDeclaratorInGroup)
15305 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15306 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15307 !hasDeducedAuto(DD))
15308 FirstNonDeducedAutoInGroup = DD;
15309
15310 if (FirstDeclaratorInGroup != DD) {
15311 // A decomposition declaration cannot be combined with any other
15312 // declaration in the same group.
15313 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15314 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15315 diag::err_decomp_decl_not_alone)
15316 << FirstDeclaratorInGroup->getSourceRange()
15317 << DD->getSourceRange();
15318 DiagnosedMultipleDecomps = true;
15319 }
15320
15321 // A declarator that uses 'auto' in any way other than to declare a
15322 // variable with a deduced type cannot be combined with any other
15323 // declarator in the same group.
15324 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15325 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15326 diag::err_auto_non_deduced_not_alone)
15327 << FirstNonDeducedAutoInGroup->getType()
15329 << FirstDeclaratorInGroup->getSourceRange()
15330 << DD->getSourceRange();
15331 DiagnosedNonDeducedAuto = true;
15332 }
15333 }
15334 }
15335
15336 Decls.push_back(D);
15337 }
15338
15340 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15341 handleTagNumbering(Tag, S);
15342 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15344 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15345 }
15346 }
15347
15348 return BuildDeclaratorGroup(Decls);
15349}
15350
15353 // C++14 [dcl.spec.auto]p7: (DR1347)
15354 // If the type that replaces the placeholder type is not the same in each
15355 // deduction, the program is ill-formed.
15356 if (Group.size() > 1) {
15357 QualType Deduced;
15358 VarDecl *DeducedDecl = nullptr;
15359 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15360 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15361 if (!D || D->isInvalidDecl())
15362 break;
15363 DeducedType *DT = D->getType()->getContainedDeducedType();
15364 if (!DT || DT->getDeducedType().isNull())
15365 continue;
15366 if (Deduced.isNull()) {
15367 Deduced = DT->getDeducedType();
15368 DeducedDecl = D;
15369 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15370 auto *AT = dyn_cast<AutoType>(DT);
15371 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15372 diag::err_auto_different_deductions)
15373 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15374 << DeducedDecl->getDeclName() << DT->getDeducedType()
15375 << D->getDeclName();
15376 if (DeducedDecl->hasInit())
15377 Dia << DeducedDecl->getInit()->getSourceRange();
15378 if (D->getInit())
15379 Dia << D->getInit()->getSourceRange();
15380 D->setInvalidDecl();
15381 break;
15382 }
15383 }
15384 }
15385
15387
15388 return DeclGroupPtrTy::make(
15389 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15390}
15391
15395
15397 // Don't parse the comment if Doxygen diagnostics are ignored.
15398 if (Group.empty() || !Group[0])
15399 return;
15400
15401 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15402 Group[0]->getLocation()) &&
15403 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15404 Group[0]->getLocation()))
15405 return;
15406
15407 if (Group.size() >= 2) {
15408 // This is a decl group. Normally it will contain only declarations
15409 // produced from declarator list. But in case we have any definitions or
15410 // additional declaration references:
15411 // 'typedef struct S {} S;'
15412 // 'typedef struct S *S;'
15413 // 'struct S *pS;'
15414 // FinalizeDeclaratorGroup adds these as separate declarations.
15415 Decl *MaybeTagDecl = Group[0];
15416 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15417 Group = Group.slice(1);
15418 }
15419 }
15420
15421 // FIMXE: We assume every Decl in the group is in the same file.
15422 // This is false when preprocessor constructs the group from decls in
15423 // different files (e. g. macros or #include).
15424 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15425}
15426
15428 // Check that there are no default arguments inside the type of this
15429 // parameter.
15430 if (getLangOpts().CPlusPlus)
15432
15433 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15434 if (D.getCXXScopeSpec().isSet()) {
15435 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15436 << D.getCXXScopeSpec().getRange();
15437 }
15438
15439 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15440 // simple identifier except [...irrelevant cases...].
15441 switch (D.getName().getKind()) {
15443 break;
15444
15452 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15454 break;
15455
15458 // GetNameForDeclarator would not produce a useful name in this case.
15459 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15460 break;
15461 }
15462}
15463
15465 // This only matters in C.
15466 if (getLangOpts().CPlusPlus)
15467 return;
15468
15469 // This only matters if the declaration has a type.
15470 const auto *VD = dyn_cast<ValueDecl>(D);
15471 if (!VD)
15472 return;
15473
15474 // Get the type, this only matters for tag types.
15475 QualType QT = VD->getType();
15476 const auto *TD = QT->getAsTagDecl();
15477 if (!TD)
15478 return;
15479
15480 // Check if the tag declaration is lexically declared somewhere different
15481 // from the lexical declaration of the given object, then it will be hidden
15482 // in C++ and we should warn on it.
15483 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15484 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15485 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15486 Diag(TD->getLocation(), diag::note_declared_at);
15487 }
15488}
15489
15491 SourceLocation ExplicitThisLoc) {
15492 if (!ExplicitThisLoc.isValid())
15493 return;
15494 assert(S.getLangOpts().CPlusPlus &&
15495 "explicit parameter in non-cplusplus mode");
15496 if (!S.getLangOpts().CPlusPlus23)
15497 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15498 << P->getSourceRange();
15499
15500 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15501 // parameter pack.
15502 if (P->isParameterPack()) {
15503 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15504 << P->getSourceRange();
15505 return;
15506 }
15507 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15508 if (LambdaScopeInfo *LSI = S.getCurLambda())
15509 LSI->ExplicitObjectParameter = P;
15510}
15511
15513 SourceLocation ExplicitThisLoc) {
15514 const DeclSpec &DS = D.getDeclSpec();
15515
15516 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15517 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15518 // except for the special case of a single unnamed parameter of type void
15519 // with no storage class specifier, no type qualifier, and no following
15520 // ellipsis terminator.
15521 // Clang applies the C2y rules for 'register void' in all C language modes,
15522 // same as GCC, because it's questionable what that could possibly mean.
15523
15524 // C++03 [dcl.stc]p2 also permits 'auto'.
15525 StorageClass SC = SC_None;
15527 SC = SC_Register;
15528 // In C++11, the 'register' storage class specifier is deprecated.
15529 // In C++17, it is not allowed, but we tolerate it as an extension.
15530 if (getLangOpts().CPlusPlus11) {
15532 ? diag::ext_register_storage_class
15533 : diag::warn_deprecated_register)
15535 } else if (!getLangOpts().CPlusPlus &&
15537 D.getNumTypeObjects() == 0) {
15539 diag::err_invalid_storage_class_in_func_decl)
15542 }
15543 } else if (getLangOpts().CPlusPlus &&
15545 SC = SC_Auto;
15548 diag::err_invalid_storage_class_in_func_decl);
15550 }
15551
15553 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15555 if (DS.isInlineSpecified())
15556 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15557 << getLangOpts().CPlusPlus17;
15558 if (DS.hasConstexprSpecifier())
15559 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15560 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15561
15563
15565
15567 QualType parmDeclType = TInfo->getType();
15568
15569 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15570 const IdentifierInfo *II = D.getIdentifier();
15571 if (II) {
15574 LookupName(R, S);
15575 if (!R.empty()) {
15576 NamedDecl *PrevDecl = *R.begin();
15577 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15578 // Maybe we will complain about the shadowed template parameter.
15580 // Just pretend that we didn't see the previous declaration.
15581 PrevDecl = nullptr;
15582 }
15583 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15584 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15585 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15586 // Recover by removing the name
15587 II = nullptr;
15588 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15589 D.setInvalidType(true);
15590 }
15591 }
15592 }
15593
15594 // Incomplete resource arrays are not allowed as function parameters in HLSL
15595 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15596 parmDeclType->isHLSLResourceRecordArray()) {
15598 diag::err_hlsl_incomplete_resource_array_in_function_param);
15599 D.setInvalidType(true);
15600 }
15601
15602 // Temporarily put parameter variables in the translation unit, not
15603 // the enclosing context. This prevents them from accidentally
15604 // looking like class members in C++.
15605 ParmVarDecl *New =
15606 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15607 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15608
15609 if (D.isInvalidType())
15610 New->setInvalidDecl();
15611
15612 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15613
15614 assert(S->isFunctionPrototypeScope());
15615 assert(S->getFunctionPrototypeDepth() >= 1);
15616 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15618
15620
15621 // Add the parameter declaration into this scope.
15622 S->AddDecl(New);
15623 if (II)
15624 IdResolver.AddDecl(New);
15625
15627
15629 Diag(New->getLocation(), diag::err_module_private_local)
15632
15633 if (New->hasAttr<BlocksAttr>()) {
15634 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15635 }
15636
15637 if (getLangOpts().OpenCL)
15639
15640 return New;
15641}
15642
15644 SourceLocation Loc,
15645 QualType T) {
15646 /* FIXME: setting StartLoc == Loc.
15647 Would it be worth to modify callers so as to provide proper source
15648 location for the unnamed parameters, embedding the parameter's type? */
15649 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15650 T, Context.getTrivialTypeSourceInfo(T, Loc),
15651 SC_None, nullptr);
15652 Param->setImplicit();
15653 return Param;
15654}
15655
15657 // Don't diagnose unused-parameter errors in template instantiations; we
15658 // will already have done so in the template itself.
15660 return;
15661
15662 for (const ParmVarDecl *Parameter : Parameters) {
15663 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15664 !Parameter->hasAttr<UnusedAttr>() &&
15665 !Parameter->getIdentifier()->isPlaceholder()) {
15666 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15667 << Parameter->getDeclName();
15668 }
15669 }
15670}
15671
15673 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15674 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15675 return;
15676
15677 // Warn if the return value is pass-by-value and larger than the specified
15678 // threshold.
15679 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15680 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15681 if (Size > LangOpts.NumLargeByValueCopy)
15682 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15683 }
15684
15685 // Warn if any parameter is pass-by-value and larger than the specified
15686 // threshold.
15687 for (const ParmVarDecl *Parameter : Parameters) {
15688 QualType T = Parameter->getType();
15689 if (T->isDependentType() || !T.isPODType(Context))
15690 continue;
15691 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15692 if (Size > LangOpts.NumLargeByValueCopy)
15693 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15694 << Parameter << Size;
15695 }
15696}
15697
15699 SourceLocation NameLoc,
15700 const IdentifierInfo *Name, QualType T,
15701 TypeSourceInfo *TSInfo, StorageClass SC) {
15702 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15703 if (getLangOpts().ObjCAutoRefCount &&
15704 T.getObjCLifetime() == Qualifiers::OCL_None &&
15705 T->isObjCLifetimeType()) {
15706
15707 Qualifiers::ObjCLifetime lifetime;
15708
15709 // Special cases for arrays:
15710 // - if it's const, use __unsafe_unretained
15711 // - otherwise, it's an error
15712 if (T->isArrayType()) {
15713 if (!T.isConstQualified()) {
15717 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15718 else
15719 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15720 << TSInfo->getTypeLoc().getSourceRange();
15721 }
15723 } else {
15724 lifetime = T->getObjCARCImplicitLifetime();
15725 }
15726 T = Context.getLifetimeQualifiedType(T, lifetime);
15727 }
15728
15729 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15730 Context.getAdjustedParameterType(T),
15731 TSInfo, SC, nullptr);
15732
15733 // Make a note if we created a new pack in the scope of a lambda, so that
15734 // we know that references to that pack must also be expanded within the
15735 // lambda scope.
15736 if (New->isParameterPack())
15737 if (auto *CSI = getEnclosingLambdaOrBlock())
15738 CSI->LocalPacks.push_back(New);
15739
15740 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15741 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15742 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15745
15746 // Parameter declarators cannot be interface types. All ObjC objects are
15747 // passed by reference.
15748 if (T->isObjCObjectType()) {
15749 SourceLocation TypeEndLoc =
15751 Diag(NameLoc,
15752 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15753 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15754 T = Context.getObjCObjectPointerType(T);
15755 New->setType(T);
15756 }
15757
15758 // __ptrauth is forbidden on parameters.
15759 if (T.getPointerAuth()) {
15760 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15761 New->setInvalidDecl();
15762 }
15763
15764 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15765 // duration shall not be qualified by an address-space qualifier."
15766 // Since all parameters have automatic store duration, they can not have
15767 // an address space.
15768 if (T.getAddressSpace() != LangAS::Default &&
15769 // OpenCL allows function arguments declared to be an array of a type
15770 // to be qualified with an address space.
15771 !(getLangOpts().OpenCL &&
15772 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15773 // WebAssembly allows reference types as parameters. Funcref in particular
15774 // lives in a different address space.
15775 !(T->isFunctionPointerType() &&
15776 T.getAddressSpace() == LangAS::wasm_funcref)) {
15777 Diag(NameLoc, diag::err_arg_with_address_space);
15778 New->setInvalidDecl();
15779 }
15780
15781 // PPC MMA non-pointer types are not allowed as function argument types.
15782 if (Context.getTargetInfo().getTriple().isPPC64() &&
15783 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15784 New->setInvalidDecl();
15785 }
15786
15787 return New;
15788}
15789
15791 SourceLocation LocAfterDecls) {
15793
15794 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15795 // in the declaration list shall have at least one declarator, those
15796 // declarators shall only declare identifiers from the identifier list, and
15797 // every identifier in the identifier list shall be declared.
15798 //
15799 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15800 // identifiers it names shall be declared in the declaration list."
15801 //
15802 // This is why we only diagnose in C99 and later. Note, the other conditions
15803 // listed are checked elsewhere.
15804 if (!FTI.hasPrototype) {
15805 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15806 --i;
15807 if (FTI.Params[i].Param == nullptr) {
15808 if (getLangOpts().C99) {
15809 SmallString<256> Code;
15810 llvm::raw_svector_ostream(Code)
15811 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15812 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15813 << FTI.Params[i].Ident
15814 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15815 }
15816
15817 // Implicitly declare the argument as type 'int' for lack of a better
15818 // type.
15819 AttributeFactory attrs;
15820 DeclSpec DS(attrs);
15821 const char* PrevSpec; // unused
15822 unsigned DiagID; // unused
15823 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15824 DiagID, Context.getPrintingPolicy());
15825 // Use the identifier location for the type source range.
15826 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15827 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15830 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15831 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15832 }
15833 }
15834 }
15835}
15836
15837Decl *
15839 MultiTemplateParamsArg TemplateParameterLists,
15840 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15841 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15842 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15843 Scope *ParentScope = FnBodyScope->getParent();
15844
15845 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15846 // we define a non-templated function definition, we will create a declaration
15847 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15848 // The base function declaration will have the equivalent of an `omp declare
15849 // variant` annotation which specifies the mangled definition as a
15850 // specialization function under the OpenMP context defined as part of the
15851 // `omp begin declare variant`.
15853 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15855 ParentScope, D, TemplateParameterLists, Bases);
15856
15858 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15859 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15860
15861 if (!Bases.empty())
15863 Bases);
15864
15865 return Dcl;
15866}
15867
15869 Consumer.HandleInlineFunctionDefinition(D);
15870}
15871
15873 const FunctionDecl *&PossiblePrototype) {
15874 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15875 Prev = Prev->getPreviousDecl()) {
15876 // Ignore any declarations that occur in function or method
15877 // scope, because they aren't visible from the header.
15878 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15879 continue;
15880
15881 PossiblePrototype = Prev;
15882 return Prev->getType()->isFunctionProtoType();
15883 }
15884 return false;
15885}
15886
15887static bool
15889 const FunctionDecl *&PossiblePrototype) {
15890 // Don't warn about invalid declarations.
15891 if (FD->isInvalidDecl())
15892 return false;
15893
15894 // Or declarations that aren't global.
15895 if (!FD->isGlobal())
15896 return false;
15897
15898 // Don't warn about C++ member functions.
15899 if (isa<CXXMethodDecl>(FD))
15900 return false;
15901
15902 // Don't warn about 'main'.
15904 if (IdentifierInfo *II = FD->getIdentifier())
15905 if (II->isStr("main") || II->isStr("efi_main"))
15906 return false;
15907
15908 if (FD->isMSVCRTEntryPoint())
15909 return false;
15910
15911 // Don't warn about inline functions.
15912 if (FD->isInlined())
15913 return false;
15914
15915 // Don't warn about function templates.
15917 return false;
15918
15919 // Don't warn about function template specializations.
15921 return false;
15922
15923 // Don't warn for OpenCL kernels.
15924 if (FD->hasAttr<DeviceKernelAttr>())
15925 return false;
15926
15927 // Don't warn on explicitly deleted functions.
15928 if (FD->isDeleted())
15929 return false;
15930
15931 // Don't warn on implicitly local functions (such as having local-typed
15932 // parameters).
15933 if (!FD->isExternallyVisible())
15934 return false;
15935
15936 // If we were able to find a potential prototype, don't warn.
15937 if (FindPossiblePrototype(FD, PossiblePrototype))
15938 return false;
15939
15940 return true;
15941}
15942
15943void
15945 const FunctionDecl *EffectiveDefinition,
15946 SkipBodyInfo *SkipBody) {
15947 const FunctionDecl *Definition = EffectiveDefinition;
15948 if (!Definition &&
15949 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15950 return;
15951
15952 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15953 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15954 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15955 // A merged copy of the same function, instantiated as a member of
15956 // the same class, is OK.
15957 if (declaresSameEntity(OrigFD, OrigDef) &&
15958 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15960 return;
15961 }
15962 }
15963 }
15964
15966 return;
15967
15968 // Don't emit an error when this is redefinition of a typo-corrected
15969 // definition.
15971 return;
15972
15973 bool DefinitionVisible = false;
15974 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
15975 (Definition->getFormalLinkage() == Linkage::Internal ||
15976 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15977 Definition->getNumTemplateParameterLists())) {
15978 SkipBody->ShouldSkip = true;
15979 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15980 if (!DefinitionVisible) {
15981 if (auto *TD = Definition->getDescribedFunctionTemplate())
15984 }
15985 return;
15986 }
15987
15988 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15989 Definition->getStorageClass() == SC_Extern)
15990 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15991 << FD << getLangOpts().CPlusPlus;
15992 else
15993 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15994
15995 Diag(Definition->getLocation(), diag::note_previous_definition);
15996 FD->setInvalidDecl();
15997}
15998
16000 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16001
16003 LSI->CallOperator = CallOperator;
16004 LSI->Lambda = LambdaClass;
16005 LSI->ReturnType = CallOperator->getReturnType();
16006 // When this function is called in situation where the context of the call
16007 // operator is not entered, we set AfterParameterList to false, so that
16008 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16009 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16010 // where we would set the CurContext to the lambda operator before
16011 // substituting into it. In this case the flag needs to be true such that
16012 // tryCaptureVariable can correctly handle potential captures thereof.
16013 LSI->AfterParameterList = CurContext == CallOperator;
16014
16015 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16016 // used at the point of dealing with potential captures.
16017 //
16018 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16019 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16020 // associated. (Technically, we could recover that list from their
16021 // instantiation patterns, but for now, the GLTemplateParameterList seems
16022 // unnecessary in these cases.)
16023 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16024 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16025 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16026
16027 if (LCD == LCD_None)
16029 else if (LCD == LCD_ByCopy)
16031 else if (LCD == LCD_ByRef)
16033 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16034
16036 LSI->Mutable = !CallOperator->isConst();
16037 if (CallOperator->isExplicitObjectMemberFunction())
16038 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16039
16040 // Add the captures to the LSI so they can be noted as already
16041 // captured within tryCaptureVar.
16042 auto I = LambdaClass->field_begin();
16043 for (const auto &C : LambdaClass->captures()) {
16044 if (C.capturesVariable()) {
16045 ValueDecl *VD = C.getCapturedVar();
16046 if (VD->isInitCapture())
16047 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16048 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16049 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16050 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16051 /*EllipsisLoc*/C.isPackExpansion()
16052 ? C.getEllipsisLoc() : SourceLocation(),
16053 I->getType(), /*Invalid*/false);
16054
16055 } else if (C.capturesThis()) {
16056 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16057 C.getCaptureKind() == LCK_StarThis);
16058 } else {
16059 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16060 I->getType());
16061 }
16062 ++I;
16063 }
16064 return LSI;
16065}
16066
16068 SkipBodyInfo *SkipBody,
16069 FnBodyKind BodyKind) {
16070 if (!D) {
16071 // Parsing the function declaration failed in some way. Push on a fake scope
16072 // anyway so we can try to parse the function body.
16075 return D;
16076 }
16077
16078 FunctionDecl *FD = nullptr;
16079
16080 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16081 FD = FunTmpl->getTemplatedDecl();
16082 else
16083 FD = cast<FunctionDecl>(D);
16084
16085 // Do not push if it is a lambda because one is already pushed when building
16086 // the lambda in ActOnStartOfLambdaDefinition().
16087 if (!isLambdaCallOperator(FD))
16089 FD);
16090
16091 // Check for defining attributes before the check for redefinition.
16092 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16093 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16094 FD->dropAttr<AliasAttr>();
16095 FD->setInvalidDecl();
16096 }
16097 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16098 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16099 FD->dropAttr<IFuncAttr>();
16100 FD->setInvalidDecl();
16101 }
16102 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16103 if (Context.getTargetInfo().getTriple().isAArch64() &&
16104 !Context.getTargetInfo().hasFeature("fmv") &&
16105 !Attr->isDefaultVersion()) {
16106 // If function multi versioning disabled skip parsing function body
16107 // defined with non-default target_version attribute
16108 if (SkipBody)
16109 SkipBody->ShouldSkip = true;
16110 return nullptr;
16111 }
16112 }
16113
16114 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16115 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16116 Ctor->isDefaultConstructor() &&
16117 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16118 // If this is an MS ABI dllexport default constructor, instantiate any
16119 // default arguments.
16121 }
16122 }
16123
16124 // See if this is a redefinition. If 'will have body' (or similar) is already
16125 // set, then these checks were already performed when it was set.
16126 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16128 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16129
16130 // If we're skipping the body, we're done. Don't enter the scope.
16131 if (SkipBody && SkipBody->ShouldSkip)
16132 return D;
16133 }
16134
16135 // Mark this function as "will have a body eventually". This lets users to
16136 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16137 // this function.
16138 FD->setWillHaveBody();
16139
16140 // If we are instantiating a generic lambda call operator, push
16141 // a LambdaScopeInfo onto the function stack. But use the information
16142 // that's already been calculated (ActOnLambdaExpr) to prime the current
16143 // LambdaScopeInfo.
16144 // When the template operator is being specialized, the LambdaScopeInfo,
16145 // has to be properly restored so that tryCaptureVariable doesn't try
16146 // and capture any new variables. In addition when calculating potential
16147 // captures during transformation of nested lambdas, it is necessary to
16148 // have the LSI properly restored.
16150 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16151 // instantiated, explicitly specialized.
16154 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16155 FD->setInvalidDecl();
16157 } else {
16158 assert(inTemplateInstantiation() &&
16159 "There should be an active template instantiation on the stack "
16160 "when instantiating a generic lambda!");
16162 }
16163 } else {
16164 // Enter a new function scope
16166 }
16167
16168 // Builtin functions cannot be defined.
16169 if (unsigned BuiltinID = FD->getBuiltinID()) {
16170 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16171 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16172 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16173 FD->setInvalidDecl();
16174 }
16175 }
16176
16177 // The return type of a function definition must be complete (C99 6.9.1p3).
16178 // C++23 [dcl.fct.def.general]/p2
16179 // The type of [...] the return for a function definition
16180 // shall not be a (possibly cv-qualified) class type that is incomplete
16181 // or abstract within the function body unless the function is deleted.
16182 QualType ResultType = FD->getReturnType();
16183 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16184 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16185 (RequireCompleteType(FD->getLocation(), ResultType,
16186 diag::err_func_def_incomplete_result) ||
16188 diag::err_abstract_type_in_decl,
16190 FD->setInvalidDecl();
16191
16192 if (FnBodyScope)
16193 PushDeclContext(FnBodyScope, FD);
16194
16195 // Check the validity of our function parameters
16196 if (BodyKind != FnBodyKind::Delete)
16198 /*CheckParameterNames=*/true);
16199
16200 // Add non-parameter declarations already in the function to the current
16201 // scope.
16202 if (FnBodyScope) {
16203 for (Decl *NPD : FD->decls()) {
16204 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16205 if (!NonParmDecl)
16206 continue;
16207 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16208 "parameters should not be in newly created FD yet");
16209
16210 // If the decl has a name, make it accessible in the current scope.
16211 if (NonParmDecl->getDeclName())
16212 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16213
16214 // Similarly, dive into enums and fish their constants out, making them
16215 // accessible in this scope.
16216 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16217 for (auto *EI : ED->enumerators())
16218 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16219 }
16220 }
16221 }
16222
16223 // Introduce our parameters into the function scope
16224 for (auto *Param : FD->parameters()) {
16225 Param->setOwningFunction(FD);
16226
16227 // If this has an identifier, add it to the scope stack.
16228 if (Param->getIdentifier() && FnBodyScope) {
16229 CheckShadow(FnBodyScope, Param);
16230
16231 PushOnScopeChains(Param, FnBodyScope);
16232 }
16233 }
16234
16235 // C++ [module.import/6]
16236 // ...
16237 // A header unit shall not contain a definition of a non-inline function or
16238 // variable whose name has external linkage.
16239 //
16240 // Deleted and Defaulted functions are implicitly inline (but the
16241 // inline state is not set at this point, so check the BodyKind explicitly).
16242 // We choose to allow weak & selectany definitions, as they are common in
16243 // headers, and have semantics similar to inline definitions which are allowed
16244 // in header units.
16245 // FIXME: Consider an alternate location for the test where the inlined()
16246 // state is complete.
16247 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16248 !FD->isInvalidDecl() && !FD->isInlined() &&
16249 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16250 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16251 !FD->isTemplateInstantiation() &&
16252 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16253 assert(FD->isThisDeclarationADefinition());
16254 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16255 FD->setInvalidDecl();
16256 }
16257
16258 // Ensure that the function's exception specification is instantiated.
16259 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16261
16262 // dllimport cannot be applied to non-inline function definitions.
16263 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16264 !FD->isTemplateInstantiation()) {
16265 assert(!FD->hasAttr<DLLExportAttr>());
16266 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16267 FD->setInvalidDecl();
16268 return D;
16269 }
16270
16271 // Some function attributes (like OptimizeNoneAttr) need actions before
16272 // parsing body started.
16274
16275 // We want to attach documentation to original Decl (which might be
16276 // a function template).
16278 if (getCurLexicalContext()->isObjCContainer() &&
16279 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16280 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16281 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16282
16284
16285 return D;
16286}
16287
16289 if (!FD || FD->isInvalidDecl())
16290 return;
16291 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16292 FD = TD->getTemplatedDecl();
16293 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16296 CurFPFeatures.applyChanges(FPO);
16297 FpPragmaStack.CurrentValue =
16298 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16299 }
16300}
16301
16303 ReturnStmt **Returns = Scope->Returns.data();
16304
16305 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16306 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16307 if (!NRVOCandidate->isNRVOVariable()) {
16308 Diag(Returns[I]->getRetValue()->getExprLoc(),
16309 diag::warn_not_eliding_copy_on_return);
16310 Returns[I]->setNRVOCandidate(nullptr);
16311 }
16312 }
16313 }
16314}
16315
16317 // We can't delay parsing the body of a constexpr function template (yet).
16319 return false;
16320
16321 // We can't delay parsing the body of a function template with a deduced
16322 // return type (yet).
16323 if (D.getDeclSpec().hasAutoTypeSpec()) {
16324 // If the placeholder introduces a non-deduced trailing return type,
16325 // we can still delay parsing it.
16326 if (D.getNumTypeObjects()) {
16327 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16328 if (Outer.Kind == DeclaratorChunk::Function &&
16329 Outer.Fun.hasTrailingReturnType()) {
16330 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16331 return Ty.isNull() || !Ty->isUndeducedType();
16332 }
16333 }
16334 return false;
16335 }
16336
16337 return true;
16338}
16339
16341 // We cannot skip the body of a function (or function template) which is
16342 // constexpr, since we may need to evaluate its body in order to parse the
16343 // rest of the file.
16344 // We cannot skip the body of a function with an undeduced return type,
16345 // because any callers of that function need to know the type.
16346 if (const FunctionDecl *FD = D->getAsFunction()) {
16347 if (FD->isConstexpr())
16348 return false;
16349 // We can't simply call Type::isUndeducedType here, because inside template
16350 // auto can be deduced to a dependent type, which is not considered
16351 // "undeduced".
16352 if (FD->getReturnType()->getContainedDeducedType())
16353 return false;
16354 }
16355 return Consumer.shouldSkipFunctionBody(D);
16356}
16357
16359 if (!Decl)
16360 return nullptr;
16361 if (FunctionDecl *FD = Decl->getAsFunction())
16362 FD->setHasSkippedBody();
16363 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16364 MD->setHasSkippedBody();
16365 return Decl;
16366}
16367
16368/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16369/// body.
16371public:
16372 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16374 if (!IsLambda)
16375 S.PopExpressionEvaluationContext();
16376 }
16377
16378private:
16379 Sema &S;
16380 bool IsLambda = false;
16381};
16382
16384 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16385
16386 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16387 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16388 if (!Inserted)
16389 return It->second;
16390
16391 bool R = false;
16392 const BlockDecl *CurBD = BD;
16393
16394 do {
16395 R = !CurBD->doesNotEscape();
16396 if (R)
16397 break;
16398 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16399 } while (CurBD);
16400
16401 return It->second = R;
16402 };
16403
16404 // If the location where 'self' is implicitly retained is inside a escaping
16405 // block, emit a diagnostic.
16406 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16408 if (IsOrNestedInEscapingBlock(P.second))
16409 S.Diag(P.first, diag::warn_implicitly_retains_self)
16410 << FixItHint::CreateInsertion(P.first, "self->");
16411}
16412
16413static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16414 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16415 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16416}
16417
16419 return methodHasName(FD, "get_return_object");
16420}
16421
16423 return FD->isStatic() &&
16424 methodHasName(FD, "get_return_object_on_allocation_failure");
16425}
16426
16429 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16430 return;
16431 // Allow some_promise_type::get_return_object().
16433 return;
16434 if (!FD->hasAttr<CoroWrapperAttr>())
16435 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16436}
16437
16438Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16439 bool RetainFunctionScopeInfo) {
16441 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16442
16443 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16444 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16445
16446 SourceLocation AnalysisLoc;
16447 if (Body)
16448 AnalysisLoc = Body->getEndLoc();
16449 else if (FD)
16450 AnalysisLoc = FD->getEndLoc();
16452 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16453 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16454
16455 // If we skip function body, we can't tell if a function is a coroutine.
16456 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16457 if (FSI->isCoroutine())
16459 else
16461 }
16462
16463 // Diagnose invalid SYCL kernel entry point function declarations
16464 // and build SYCLKernelCallStmts for valid ones.
16465 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16466 SYCLKernelEntryPointAttr *SKEPAttr =
16467 FD->getAttr<SYCLKernelEntryPointAttr>();
16468 if (FD->isDefaulted()) {
16469 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16470 << SKEPAttr << /*defaulted function*/ 3;
16471 SKEPAttr->setInvalidAttr();
16472 } else if (FD->isDeleted()) {
16473 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16474 << SKEPAttr << /*deleted function*/ 2;
16475 SKEPAttr->setInvalidAttr();
16476 } else if (FSI->isCoroutine()) {
16477 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16478 << SKEPAttr << /*coroutine*/ 7;
16479 SKEPAttr->setInvalidAttr();
16480 } else if (Body && isa<CXXTryStmt>(Body)) {
16481 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16482 << SKEPAttr << /*function defined with a function try block*/ 8;
16483 SKEPAttr->setInvalidAttr();
16484 }
16485
16486 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16487 StmtResult SR =
16489 if (SR.isInvalid())
16490 return nullptr;
16491 Body = SR.get();
16492 }
16493 }
16494
16495 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16496 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16497 if (FD->isDeletedAsWritten())
16498 Diag(SEAttr->getLocation(),
16499 diag::err_sycl_external_invalid_deleted_function)
16500 << SEAttr;
16501 }
16502
16503 {
16504 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16505 // one is already popped when finishing the lambda in BuildLambdaExpr().
16506 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16507 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16508 if (FD) {
16509 // The function body and the DefaultedOrDeletedInfo, if present, use
16510 // the same storage; don't overwrite the latter if the former is null
16511 // (the body is initialised to null anyway, so even if the latter isn't
16512 // present, this would still be a no-op).
16513 if (Body)
16514 FD->setBody(Body);
16515 FD->setWillHaveBody(false);
16516
16517 if (getLangOpts().CPlusPlus14) {
16518 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16519 FD->getReturnType()->isUndeducedType()) {
16520 // For a function with a deduced result type to return void,
16521 // the result type as written must be 'auto' or 'decltype(auto)',
16522 // possibly cv-qualified or constrained, but not ref-qualified.
16523 if (!FD->getReturnType()->getAs<AutoType>()) {
16524 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16525 << FD->getReturnType();
16526 FD->setInvalidDecl();
16527 } else {
16528 // Falling off the end of the function is the same as 'return;'.
16529 Expr *Dummy = nullptr;
16531 FD, dcl->getLocation(), Dummy,
16532 FD->getReturnType()->getAs<AutoType>()))
16533 FD->setInvalidDecl();
16534 }
16535 }
16536 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16537 // In C++11, we don't use 'auto' deduction rules for lambda call
16538 // operators because we don't support return type deduction.
16539 auto *LSI = getCurLambda();
16540 if (LSI->HasImplicitReturnType) {
16542
16543 // C++11 [expr.prim.lambda]p4:
16544 // [...] if there are no return statements in the compound-statement
16545 // [the deduced type is] the type void
16546 QualType RetType =
16547 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16548
16549 // Update the return type to the deduced type.
16550 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16551 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16552 Proto->getExtProtoInfo()));
16553 }
16554 }
16555
16556 // If the function implicitly returns zero (like 'main') or is naked,
16557 // don't complain about missing return statements.
16558 // Clang implicitly returns 0 in C89 mode, but that's considered an
16559 // extension. The check is necessary to ensure the expected extension
16560 // warning is emitted in C89 mode.
16561 if ((FD->hasImplicitReturnZero() &&
16562 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16563 FD->hasAttr<NakedAttr>())
16565
16566 // MSVC permits the use of pure specifier (=0) on function definition,
16567 // defined at class scope, warn about this non-standard construct.
16568 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16569 !FD->isOutOfLine())
16570 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16571
16572 if (!FD->isInvalidDecl()) {
16573 // Don't diagnose unused parameters of defaulted, deleted or naked
16574 // functions.
16575 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16576 !FD->hasAttr<NakedAttr>())
16579 FD->getReturnType(), FD);
16580
16581 // If this is a structor, we need a vtable.
16582 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16583 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16584 else if (CXXDestructorDecl *Destructor =
16585 dyn_cast<CXXDestructorDecl>(FD))
16586 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16587
16588 // Try to apply the named return value optimization. We have to check
16589 // if we can do this here because lambdas keep return statements around
16590 // to deduce an implicit return type.
16591 if (FD->getReturnType()->isRecordType() &&
16593 computeNRVO(Body, FSI);
16594 }
16595
16596 // GNU warning -Wmissing-prototypes:
16597 // Warn if a global function is defined without a previous
16598 // prototype declaration. This warning is issued even if the
16599 // definition itself provides a prototype. The aim is to detect
16600 // global functions that fail to be declared in header files.
16601 const FunctionDecl *PossiblePrototype = nullptr;
16602 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16603 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16604
16605 if (PossiblePrototype) {
16606 // We found a declaration that is not a prototype,
16607 // but that could be a zero-parameter prototype
16608 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16609 TypeLoc TL = TI->getTypeLoc();
16611 Diag(PossiblePrototype->getLocation(),
16612 diag::note_declaration_not_a_prototype)
16613 << (FD->getNumParams() != 0)
16615 FTL.getRParenLoc(), "void")
16616 : FixItHint{});
16617 }
16618 } else {
16619 // Returns true if the token beginning at this Loc is `const`.
16620 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16621 const LangOptions &LangOpts) {
16622 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16623 if (LocInfo.first.isInvalid())
16624 return false;
16625
16626 bool Invalid = false;
16627 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16628 if (Invalid)
16629 return false;
16630
16631 if (LocInfo.second > Buffer.size())
16632 return false;
16633
16634 const char *LexStart = Buffer.data() + LocInfo.second;
16635 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16636
16637 return StartTok.consume_front("const") &&
16638 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16639 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16640 };
16641
16642 auto findBeginLoc = [&]() {
16643 // If the return type has `const` qualifier, we want to insert
16644 // `static` before `const` (and not before the typename).
16645 if ((FD->getReturnType()->isAnyPointerType() &&
16648 // But only do this if we can determine where the `const` is.
16649
16650 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16651 getLangOpts()))
16652
16653 return FD->getBeginLoc();
16654 }
16655 return FD->getTypeSpecStartLoc();
16656 };
16658 diag::note_static_for_internal_linkage)
16659 << /* function */ 1
16660 << (FD->getStorageClass() == SC_None
16661 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16662 : FixItHint{});
16663 }
16664 }
16665
16666 // We might not have found a prototype because we didn't wish to warn on
16667 // the lack of a missing prototype. Try again without the checks for
16668 // whether we want to warn on the missing prototype.
16669 if (!PossiblePrototype)
16670 (void)FindPossiblePrototype(FD, PossiblePrototype);
16671
16672 // If the function being defined does not have a prototype, then we may
16673 // need to diagnose it as changing behavior in C23 because we now know
16674 // whether the function accepts arguments or not. This only handles the
16675 // case where the definition has no prototype but does have parameters
16676 // and either there is no previous potential prototype, or the previous
16677 // potential prototype also has no actual prototype. This handles cases
16678 // like:
16679 // void f(); void f(a) int a; {}
16680 // void g(a) int a; {}
16681 // See MergeFunctionDecl() for other cases of the behavior change
16682 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16683 // type without a prototype.
16684 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16685 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16686 !PossiblePrototype->isImplicit()))) {
16687 // The function definition has parameters, so this will change behavior
16688 // in C23. If there is a possible prototype, it comes before the
16689 // function definition.
16690 // FIXME: The declaration may have already been diagnosed as being
16691 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16692 // there's no way to test for the "changes behavior" condition in
16693 // SemaType.cpp when forming the declaration's function type. So, we do
16694 // this awkward dance instead.
16695 //
16696 // If we have a possible prototype and it declares a function with a
16697 // prototype, we don't want to diagnose it; if we have a possible
16698 // prototype and it has no prototype, it may have already been
16699 // diagnosed in SemaType.cpp as deprecated depending on whether
16700 // -Wstrict-prototypes is enabled. If we already warned about it being
16701 // deprecated, add a note that it also changes behavior. If we didn't
16702 // warn about it being deprecated (because the diagnostic is not
16703 // enabled), warn now that it is deprecated and changes behavior.
16704
16705 // This K&R C function definition definitely changes behavior in C23,
16706 // so diagnose it.
16707 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16708 << /*definition*/ 1 << /* not supported in C23 */ 0;
16709
16710 // If we have a possible prototype for the function which is a user-
16711 // visible declaration, we already tested that it has no prototype.
16712 // This will change behavior in C23. This gets a warning rather than a
16713 // note because it's the same behavior-changing problem as with the
16714 // definition.
16715 if (PossiblePrototype)
16716 Diag(PossiblePrototype->getLocation(),
16717 diag::warn_non_prototype_changes_behavior)
16718 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16719 << /*definition*/ 1;
16720 }
16721
16722 // Warn on CPUDispatch with an actual body.
16723 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16724 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16725 if (!CmpndBody->body_empty())
16726 Diag(CmpndBody->body_front()->getBeginLoc(),
16727 diag::warn_dispatch_body_ignored);
16728
16729 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16730 const CXXMethodDecl *KeyFunction;
16731 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16732 MD->isVirtual() &&
16733 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16734 MD == KeyFunction->getCanonicalDecl()) {
16735 // Update the key-function state if necessary for this ABI.
16736 if (FD->isInlined() &&
16737 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16738 Context.setNonKeyFunction(MD);
16739
16740 // If the newly-chosen key function is already defined, then we
16741 // need to mark the vtable as used retroactively.
16742 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16743 const FunctionDecl *Definition;
16744 if (KeyFunction && KeyFunction->isDefined(Definition))
16745 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16746 } else {
16747 // We just defined they key function; mark the vtable as used.
16748 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16749 }
16750 }
16751 }
16752
16753 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16754 "Function parsing confused");
16755 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16756 assert(MD == getCurMethodDecl() && "Method parsing confused");
16757 MD->setBody(Body);
16758 if (!MD->isInvalidDecl()) {
16760 MD->getReturnType(), MD);
16761
16762 if (Body)
16763 computeNRVO(Body, FSI);
16764 }
16765 if (FSI->ObjCShouldCallSuper) {
16766 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16767 << MD->getSelector().getAsString();
16768 FSI->ObjCShouldCallSuper = false;
16769 }
16771 const ObjCMethodDecl *InitMethod = nullptr;
16772 bool isDesignated =
16773 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16774 assert(isDesignated && InitMethod);
16775 (void)isDesignated;
16776
16777 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16778 auto IFace = MD->getClassInterface();
16779 if (!IFace)
16780 return false;
16781 auto SuperD = IFace->getSuperClass();
16782 if (!SuperD)
16783 return false;
16784 return SuperD->getIdentifier() ==
16785 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16786 };
16787 // Don't issue this warning for unavailable inits or direct subclasses
16788 // of NSObject.
16789 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16790 Diag(MD->getLocation(),
16791 diag::warn_objc_designated_init_missing_super_call);
16792 Diag(InitMethod->getLocation(),
16793 diag::note_objc_designated_init_marked_here);
16794 }
16796 }
16797 if (FSI->ObjCWarnForNoInitDelegation) {
16798 // Don't issue this warning for unavailable inits.
16799 if (!MD->isUnavailable())
16800 Diag(MD->getLocation(),
16801 diag::warn_objc_secondary_init_missing_init_call);
16802 FSI->ObjCWarnForNoInitDelegation = false;
16803 }
16804
16806 } else {
16807 // Parsing the function declaration failed in some way. Pop the fake scope
16808 // we pushed on.
16809 PopFunctionScopeInfo(ActivePolicy, dcl);
16810 return nullptr;
16811 }
16812
16813 if (Body && FSI->HasPotentialAvailabilityViolations)
16815
16816 assert(!FSI->ObjCShouldCallSuper &&
16817 "This should only be set for ObjC methods, which should have been "
16818 "handled in the block above.");
16819
16820 // Verify and clean out per-function state.
16821 if (Body && (!FD || !FD->isDefaulted())) {
16822 // C++ constructors that have function-try-blocks can't have return
16823 // statements in the handlers of that block. (C++ [except.handle]p14)
16824 // Verify this.
16825 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16827
16828 // Verify that gotos and switch cases don't jump into scopes illegally.
16829 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16831
16832 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16833 if (!Destructor->getParent()->isDependentType())
16835
16837 Destructor->getParent());
16838 }
16839
16840 // If any errors have occurred, clear out any temporaries that may have
16841 // been leftover. This ensures that these temporaries won't be picked up
16842 // for deletion in some later function.
16845 getDiagnostics().getSuppressAllDiagnostics()) {
16847 }
16849 // Since the body is valid, issue any analysis-based warnings that are
16850 // enabled.
16851 ActivePolicy = &WP;
16852 }
16853
16854 if (!IsInstantiation && FD &&
16855 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16856 !FD->isInvalidDecl() &&
16858 FD->setInvalidDecl();
16859
16860 if (FD && FD->hasAttr<NakedAttr>()) {
16861 for (const Stmt *S : Body->children()) {
16862 // Allow local register variables without initializer as they don't
16863 // require prologue.
16864 bool RegisterVariables = false;
16865 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16866 for (const auto *Decl : DS->decls()) {
16867 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16868 RegisterVariables =
16869 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16870 if (!RegisterVariables)
16871 break;
16872 }
16873 }
16874 }
16875 if (RegisterVariables)
16876 continue;
16877 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16878 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16879 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16880 FD->setInvalidDecl();
16881 break;
16882 }
16883 }
16884 }
16885
16886 assert(ExprCleanupObjects.size() ==
16887 ExprEvalContexts.back().NumCleanupObjects &&
16888 "Leftover temporaries in function");
16889 assert(!Cleanup.exprNeedsCleanups() &&
16890 "Unaccounted cleanups in function");
16891 assert(MaybeODRUseExprs.empty() &&
16892 "Leftover expressions for odr-use checking");
16893 }
16894 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16895 // the declaration context below. Otherwise, we're unable to transform
16896 // 'this' expressions when transforming immediate context functions.
16897
16898 if (FD)
16900
16901 if (!IsInstantiation)
16903
16904 if (!RetainFunctionScopeInfo)
16905 PopFunctionScopeInfo(ActivePolicy, dcl);
16906 // If any errors have occurred, clear out any temporaries that may have
16907 // been leftover. This ensures that these temporaries won't be picked up for
16908 // deletion in some later function.
16911 }
16912
16913 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16914 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16915 auto ES = getEmissionStatus(FD);
16919 }
16920
16921 if (FD && !FD->isDeleted())
16922 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16923
16924 return dcl;
16925}
16926
16927/// When we finish delayed parsing of an attribute, we must attach it to the
16928/// relevant Decl.
16930 ParsedAttributes &Attrs) {
16931 // Always attach attributes to the underlying decl.
16932 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16933 D = TD->getTemplatedDecl();
16934 ProcessDeclAttributeList(S, D, Attrs);
16935 ProcessAPINotes(D);
16936
16937 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16938 if (Method->isStatic())
16940}
16941
16943 IdentifierInfo &II, Scope *S) {
16944 // It is not valid to implicitly define a function in C23.
16945 assert(LangOpts.implicitFunctionsAllowed() &&
16946 "Implicit function declarations aren't allowed in this language mode");
16947
16948 // Find the scope in which the identifier is injected and the corresponding
16949 // DeclContext.
16950 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16951 // In that case, we inject the declaration into the translation unit scope
16952 // instead.
16953 Scope *BlockScope = S;
16954 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16955 BlockScope = BlockScope->getParent();
16956
16957 // Loop until we find a DeclContext that is either a function/method or the
16958 // translation unit, which are the only two valid places to implicitly define
16959 // a function. This avoids accidentally defining the function within a tag
16960 // declaration, for example.
16961 Scope *ContextScope = BlockScope;
16962 while (!ContextScope->getEntity() ||
16963 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16964 !ContextScope->getEntity()->isTranslationUnit()))
16965 ContextScope = ContextScope->getParent();
16966 ContextRAII SavedContext(*this, ContextScope->getEntity());
16967
16968 // Before we produce a declaration for an implicitly defined
16969 // function, see whether there was a locally-scoped declaration of
16970 // this name as a function or variable. If so, use that
16971 // (non-visible) declaration, and complain about it.
16972 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16973 if (ExternCPrev) {
16974 // We still need to inject the function into the enclosing block scope so
16975 // that later (non-call) uses can see it.
16976 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16977
16978 // C89 footnote 38:
16979 // If in fact it is not defined as having type "function returning int",
16980 // the behavior is undefined.
16981 if (!isa<FunctionDecl>(ExternCPrev) ||
16982 !Context.typesAreCompatible(
16983 cast<FunctionDecl>(ExternCPrev)->getType(),
16984 Context.getFunctionNoProtoType(Context.IntTy))) {
16985 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16986 << ExternCPrev << !getLangOpts().C99;
16987 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16988 return ExternCPrev;
16989 }
16990 }
16991
16992 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16993 unsigned diag_id;
16994 if (II.getName().starts_with("__builtin_"))
16995 diag_id = diag::warn_builtin_unknown;
16996 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16997 else if (getLangOpts().C99)
16998 diag_id = diag::ext_implicit_function_decl_c99;
16999 else
17000 diag_id = diag::warn_implicit_function_decl;
17001
17002 TypoCorrection Corrected;
17003 // Because typo correction is expensive, only do it if the implicit
17004 // function declaration is going to be treated as an error.
17005 //
17006 // Perform the correction before issuing the main diagnostic, as some
17007 // consumers use typo-correction callbacks to enhance the main diagnostic.
17008 if (S && !ExternCPrev &&
17009 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17011 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17012 S, nullptr, CCC, CorrectTypoKind::NonError);
17013 }
17014
17015 Diag(Loc, diag_id) << &II;
17016 if (Corrected) {
17017 // If the correction is going to suggest an implicitly defined function,
17018 // skip the correction as not being a particularly good idea.
17019 bool Diagnose = true;
17020 if (const auto *D = Corrected.getCorrectionDecl())
17021 Diagnose = !D->isImplicit();
17022 if (Diagnose)
17023 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17024 /*ErrorRecovery*/ false);
17025 }
17026
17027 // If we found a prior declaration of this function, don't bother building
17028 // another one. We've already pushed that one into scope, so there's nothing
17029 // more to do.
17030 if (ExternCPrev)
17031 return ExternCPrev;
17032
17033 // Set a Declarator for the implicit definition: int foo();
17034 const char *Dummy;
17035 AttributeFactory attrFactory;
17036 DeclSpec DS(attrFactory);
17037 unsigned DiagID;
17038 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17039 Context.getPrintingPolicy());
17040 (void)Error; // Silence warning.
17041 assert(!Error && "Error setting up implicit decl!");
17042 SourceLocation NoLoc;
17044 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17045 /*IsAmbiguous=*/false,
17046 /*LParenLoc=*/NoLoc,
17047 /*Params=*/nullptr,
17048 /*NumParams=*/0,
17049 /*EllipsisLoc=*/NoLoc,
17050 /*RParenLoc=*/NoLoc,
17051 /*RefQualifierIsLvalueRef=*/true,
17052 /*RefQualifierLoc=*/NoLoc,
17053 /*MutableLoc=*/NoLoc, EST_None,
17054 /*ESpecRange=*/SourceRange(),
17055 /*Exceptions=*/nullptr,
17056 /*ExceptionRanges=*/nullptr,
17057 /*NumExceptions=*/0,
17058 /*NoexceptExpr=*/nullptr,
17059 /*ExceptionSpecTokens=*/nullptr,
17060 /*DeclsInPrototype=*/{}, Loc, Loc,
17061 D),
17062 std::move(DS.getAttributes()), SourceLocation());
17063 D.SetIdentifier(&II, Loc);
17064
17065 // Insert this function into the enclosing block scope.
17066 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17067 FD->setImplicit();
17068
17070
17071 return FD;
17072}
17073
17075 FunctionDecl *FD) {
17076 if (FD->isInvalidDecl())
17077 return;
17078
17079 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17080 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17081 return;
17082
17083 UnsignedOrNone AlignmentParam = std::nullopt;
17084 bool IsNothrow = false;
17085 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17086 return;
17087
17088 // C++2a [basic.stc.dynamic.allocation]p4:
17089 // An allocation function that has a non-throwing exception specification
17090 // indicates failure by returning a null pointer value. Any other allocation
17091 // function never returns a null pointer value and indicates failure only by
17092 // throwing an exception [...]
17093 //
17094 // However, -fcheck-new invalidates this possible assumption, so don't add
17095 // NonNull when that is enabled.
17096 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17097 !getLangOpts().CheckNew)
17098 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17099
17100 // C++2a [basic.stc.dynamic.allocation]p2:
17101 // An allocation function attempts to allocate the requested amount of
17102 // storage. [...] If the request succeeds, the value returned by a
17103 // replaceable allocation function is a [...] pointer value p0 different
17104 // from any previously returned value p1 [...]
17105 //
17106 // However, this particular information is being added in codegen,
17107 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17108
17109 // C++2a [basic.stc.dynamic.allocation]p2:
17110 // An allocation function attempts to allocate the requested amount of
17111 // storage. If it is successful, it returns the address of the start of a
17112 // block of storage whose length in bytes is at least as large as the
17113 // requested size.
17114 if (!FD->hasAttr<AllocSizeAttr>()) {
17115 FD->addAttr(AllocSizeAttr::CreateImplicit(
17116 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17117 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17118 }
17119
17120 // C++2a [basic.stc.dynamic.allocation]p3:
17121 // For an allocation function [...], the pointer returned on a successful
17122 // call shall represent the address of storage that is aligned as follows:
17123 // (3.1) If the allocation function takes an argument of type
17124 // std​::​align_­val_­t, the storage will have the alignment
17125 // specified by the value of this argument.
17126 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17127 FD->addAttr(AllocAlignAttr::CreateImplicit(
17128 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17129 }
17130
17131 // FIXME:
17132 // C++2a [basic.stc.dynamic.allocation]p3:
17133 // For an allocation function [...], the pointer returned on a successful
17134 // call shall represent the address of storage that is aligned as follows:
17135 // (3.2) Otherwise, if the allocation function is named operator new[],
17136 // the storage is aligned for any object that does not have
17137 // new-extended alignment ([basic.align]) and is no larger than the
17138 // requested size.
17139 // (3.3) Otherwise, the storage is aligned for any object that does not
17140 // have new-extended alignment and is of the requested size.
17141}
17142
17144 if (FD->isInvalidDecl())
17145 return;
17146
17147 // If this is a built-in function, map its builtin attributes to
17148 // actual attributes.
17149 if (unsigned BuiltinID = FD->getBuiltinID()) {
17150 // Handle printf-formatting attributes.
17151 unsigned FormatIdx;
17152 bool HasVAListArg;
17153 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17154 if (!FD->hasAttr<FormatAttr>()) {
17155 const char *fmt = "printf";
17156 unsigned int NumParams = FD->getNumParams();
17157 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17158 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17159 fmt = "NSString";
17160 FD->addAttr(FormatAttr::CreateImplicit(Context,
17161 &Context.Idents.get(fmt),
17162 FormatIdx+1,
17163 HasVAListArg ? 0 : FormatIdx+2,
17164 FD->getLocation()));
17165 }
17166 }
17167 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17168 HasVAListArg)) {
17169 if (!FD->hasAttr<FormatAttr>())
17170 FD->addAttr(FormatAttr::CreateImplicit(Context,
17171 &Context.Idents.get("scanf"),
17172 FormatIdx+1,
17173 HasVAListArg ? 0 : FormatIdx+2,
17174 FD->getLocation()));
17175 }
17176
17177 // Handle automatically recognized callbacks.
17178 SmallVector<int, 4> Encoding;
17179 if (!FD->hasAttr<CallbackAttr>() &&
17180 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17181 FD->addAttr(CallbackAttr::CreateImplicit(
17182 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17183
17184 // Mark const if we don't care about errno and/or floating point exceptions
17185 // that are the only thing preventing the function from being const. This
17186 // allows IRgen to use LLVM intrinsics for such functions.
17187 bool NoExceptions =
17189 bool ConstWithoutErrnoAndExceptions =
17190 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17191 bool ConstWithoutExceptions =
17192 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17193 if (!FD->hasAttr<ConstAttr>() &&
17194 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17195 (!ConstWithoutErrnoAndExceptions ||
17196 (!getLangOpts().MathErrno && NoExceptions)) &&
17197 (!ConstWithoutExceptions || NoExceptions))
17198 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17199
17200 // We make "fma" on GNU or Windows const because we know it does not set
17201 // errno in those environments even though it could set errno based on the
17202 // C standard.
17203 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17204 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17205 !FD->hasAttr<ConstAttr>()) {
17206 switch (BuiltinID) {
17207 case Builtin::BI__builtin_fma:
17208 case Builtin::BI__builtin_fmaf:
17209 case Builtin::BI__builtin_fmal:
17210 case Builtin::BIfma:
17211 case Builtin::BIfmaf:
17212 case Builtin::BIfmal:
17213 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17214 break;
17215 default:
17216 break;
17217 }
17218 }
17219
17220 SmallVector<int, 4> Indxs;
17222 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17223 !FD->hasAttr<NonNullAttr>()) {
17225 for (int I : Indxs) {
17226 ParmVarDecl *PVD = FD->getParamDecl(I);
17227 QualType T = PVD->getType();
17228 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17229 PVD->setType(T);
17230 }
17231 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17233 for (int I : Indxs)
17234 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17235 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17236 ParamIndxs.size()));
17237 }
17238 }
17239 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17240 !FD->hasAttr<ReturnsTwiceAttr>())
17241 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17242 FD->getLocation()));
17243 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17244 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17245 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17246 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17247 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17248 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17249 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17250 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17251 // Add the appropriate attribute, depending on the CUDA compilation mode
17252 // and which target the builtin belongs to. For example, during host
17253 // compilation, aux builtins are __device__, while the rest are __host__.
17254 if (getLangOpts().CUDAIsDevice !=
17255 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17256 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17257 else
17258 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17259 }
17260
17261 // Add known guaranteed alignment for allocation functions.
17262 switch (BuiltinID) {
17263 case Builtin::BImemalign:
17264 case Builtin::BIaligned_alloc:
17265 if (!FD->hasAttr<AllocAlignAttr>())
17266 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17267 FD->getLocation()));
17268 break;
17269 default:
17270 break;
17271 }
17272
17273 // Add allocsize attribute for allocation functions.
17274 switch (BuiltinID) {
17275 case Builtin::BIcalloc:
17276 FD->addAttr(AllocSizeAttr::CreateImplicit(
17277 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17278 break;
17279 case Builtin::BImemalign:
17280 case Builtin::BIaligned_alloc:
17281 case Builtin::BIrealloc:
17282 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17283 ParamIdx(), FD->getLocation()));
17284 break;
17285 case Builtin::BImalloc:
17286 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17287 ParamIdx(), FD->getLocation()));
17288 break;
17289 default:
17290 break;
17291 }
17292 }
17293
17298
17299 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17300 // throw, add an implicit nothrow attribute to any extern "C" function we come
17301 // across.
17302 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17303 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17304 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17305 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17306 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17307 }
17308
17309 IdentifierInfo *Name = FD->getIdentifier();
17310 if (!Name)
17311 return;
17314 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17316 // Okay: this could be a libc/libm/Objective-C function we know
17317 // about.
17318 } else
17319 return;
17320
17321 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17322 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17323 // target-specific builtins, perhaps?
17324 if (!FD->hasAttr<FormatAttr>())
17325 FD->addAttr(FormatAttr::CreateImplicit(Context,
17326 &Context.Idents.get("printf"), 2,
17327 Name->isStr("vasprintf") ? 0 : 3,
17328 FD->getLocation()));
17329 }
17330
17331 if (Name->isStr("__CFStringMakeConstantString")) {
17332 // We already have a __builtin___CFStringMakeConstantString,
17333 // but builds that use -fno-constant-cfstrings don't go through that.
17334 if (!FD->hasAttr<FormatArgAttr>())
17335 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17336 FD->getLocation()));
17337 }
17338}
17339
17341 TypeSourceInfo *TInfo) {
17342 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17343 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17344
17345 if (!TInfo) {
17346 assert(D.isInvalidType() && "no declarator info for valid type");
17347 TInfo = Context.getTrivialTypeSourceInfo(T);
17348 }
17349
17350 // Scope manipulation handled by caller.
17351 TypedefDecl *NewTD =
17353 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17354
17355 // Bail out immediately if we have an invalid declaration.
17356 if (D.isInvalidType()) {
17357 NewTD->setInvalidDecl();
17358 return NewTD;
17359 }
17360
17362 if (CurContext->isFunctionOrMethod())
17363 Diag(NewTD->getLocation(), diag::err_module_private_local)
17364 << 2 << NewTD
17368 else
17369 NewTD->setModulePrivate();
17370 }
17371
17372 // C++ [dcl.typedef]p8:
17373 // If the typedef declaration defines an unnamed class (or
17374 // enum), the first typedef-name declared by the declaration
17375 // to be that class type (or enum type) is used to denote the
17376 // class type (or enum type) for linkage purposes only.
17377 // We need to check whether the type was declared in the declaration.
17378 switch (D.getDeclSpec().getTypeSpecType()) {
17379 case TST_enum:
17380 case TST_struct:
17381 case TST_interface:
17382 case TST_union:
17383 case TST_class: {
17384 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17385 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17386 break;
17387 }
17388
17389 default:
17390 break;
17391 }
17392
17393 return NewTD;
17394}
17395
17397 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17398 QualType T = TI->getType();
17399
17400 if (T->isDependentType())
17401 return false;
17402
17403 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17404 // integral type; any cv-qualification is ignored.
17405 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17406 // non-atomic version of the type specified by the type specifiers in the
17407 // specifier qualifier list.
17408 // Because of how odd C's rule is, we'll let the user know that operations
17409 // involving the enumeration type will be non-atomic.
17410 if (T->isAtomicType())
17411 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17412
17413 Qualifiers Q = T.getQualifiers();
17414 std::optional<unsigned> QualSelect;
17415 if (Q.hasConst() && Q.hasVolatile())
17416 QualSelect = diag::CVQualList::Both;
17417 else if (Q.hasConst())
17418 QualSelect = diag::CVQualList::Const;
17419 else if (Q.hasVolatile())
17420 QualSelect = diag::CVQualList::Volatile;
17421
17422 if (QualSelect)
17423 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17424
17425 T = T.getAtomicUnqualifiedType();
17426
17427 // This doesn't use 'isIntegralType' despite the error message mentioning
17428 // integral type because isIntegralType would also allow enum types in C.
17429 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17430 if (BT->isInteger())
17431 return false;
17432
17433 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17434 << T << T->isBitIntType();
17435}
17436
17438 QualType EnumUnderlyingTy, bool IsFixed,
17439 const EnumDecl *Prev) {
17440 if (IsScoped != Prev->isScoped()) {
17441 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17442 << Prev->isScoped();
17443 Diag(Prev->getLocation(), diag::note_previous_declaration);
17444 return true;
17445 }
17446
17447 if (IsFixed && Prev->isFixed()) {
17448 if (!EnumUnderlyingTy->isDependentType() &&
17449 !Prev->getIntegerType()->isDependentType() &&
17450 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17451 Prev->getIntegerType())) {
17452 // TODO: Highlight the underlying type of the redeclaration.
17453 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17454 << EnumUnderlyingTy << Prev->getIntegerType();
17455 Diag(Prev->getLocation(), diag::note_previous_declaration)
17456 << Prev->getIntegerTypeRange();
17457 return true;
17458 }
17459 } else if (IsFixed != Prev->isFixed()) {
17460 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17461 << Prev->isFixed();
17462 Diag(Prev->getLocation(), diag::note_previous_declaration);
17463 return true;
17464 }
17465
17466 return false;
17467}
17468
17469/// Get diagnostic %select index for tag kind for
17470/// redeclaration diagnostic message.
17471/// WARNING: Indexes apply to particular diagnostics only!
17472///
17473/// \returns diagnostic %select index.
17475 switch (Tag) {
17477 return 0;
17479 return 1;
17480 case TagTypeKind::Class:
17481 return 2;
17482 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17483 }
17484}
17485
17486/// Determine if tag kind is a class-key compatible with
17487/// class for redeclaration (class, struct, or __interface).
17488///
17489/// \returns true iff the tag kind is compatible.
17491{
17492 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17494}
17495
17497 if (isa<TypedefDecl>(PrevDecl))
17498 return NonTagKind::Typedef;
17499 else if (isa<TypeAliasDecl>(PrevDecl))
17500 return NonTagKind::TypeAlias;
17501 else if (isa<ClassTemplateDecl>(PrevDecl))
17502 return NonTagKind::Template;
17503 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17505 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17507 switch (TTK) {
17510 case TagTypeKind::Class:
17511 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17513 case TagTypeKind::Union:
17514 return NonTagKind::NonUnion;
17515 case TagTypeKind::Enum:
17516 return NonTagKind::NonEnum;
17517 }
17518 llvm_unreachable("invalid TTK");
17519}
17520
17522 TagTypeKind NewTag, bool isDefinition,
17523 SourceLocation NewTagLoc,
17524 const IdentifierInfo *Name) {
17525 // C++ [dcl.type.elab]p3:
17526 // The class-key or enum keyword present in the
17527 // elaborated-type-specifier shall agree in kind with the
17528 // declaration to which the name in the elaborated-type-specifier
17529 // refers. This rule also applies to the form of
17530 // elaborated-type-specifier that declares a class-name or
17531 // friend class since it can be construed as referring to the
17532 // definition of the class. Thus, in any
17533 // elaborated-type-specifier, the enum keyword shall be used to
17534 // refer to an enumeration (7.2), the union class-key shall be
17535 // used to refer to a union (clause 9), and either the class or
17536 // struct class-key shall be used to refer to a class (clause 9)
17537 // declared using the class or struct class-key.
17538 TagTypeKind OldTag = Previous->getTagKind();
17539 if (OldTag != NewTag &&
17541 return false;
17542
17543 // Tags are compatible, but we might still want to warn on mismatched tags.
17544 // Non-class tags can't be mismatched at this point.
17546 return true;
17547
17548 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17549 // by our warning analysis. We don't want to warn about mismatches with (eg)
17550 // declarations in system headers that are designed to be specialized, but if
17551 // a user asks us to warn, we should warn if their code contains mismatched
17552 // declarations.
17553 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17554 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17555 Loc);
17556 };
17557 if (IsIgnoredLoc(NewTagLoc))
17558 return true;
17559
17560 auto IsIgnored = [&](const TagDecl *Tag) {
17561 return IsIgnoredLoc(Tag->getLocation());
17562 };
17563 while (IsIgnored(Previous)) {
17564 Previous = Previous->getPreviousDecl();
17565 if (!Previous)
17566 return true;
17567 OldTag = Previous->getTagKind();
17568 }
17569
17570 bool isTemplate = false;
17571 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17572 isTemplate = Record->getDescribedClassTemplate();
17573
17575 if (OldTag != NewTag) {
17576 // In a template instantiation, do not offer fix-its for tag mismatches
17577 // since they usually mess up the template instead of fixing the problem.
17578 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17580 << getRedeclDiagFromTagKind(OldTag);
17581 // FIXME: Note previous location?
17582 }
17583 return true;
17584 }
17585
17586 if (isDefinition) {
17587 // On definitions, check all previous tags and issue a fix-it for each
17588 // one that doesn't match the current tag.
17589 if (Previous->getDefinition()) {
17590 // Don't suggest fix-its for redefinitions.
17591 return true;
17592 }
17593
17594 bool previousMismatch = false;
17595 for (const TagDecl *I : Previous->redecls()) {
17596 if (I->getTagKind() != NewTag) {
17597 // Ignore previous declarations for which the warning was disabled.
17598 if (IsIgnored(I))
17599 continue;
17600
17601 if (!previousMismatch) {
17602 previousMismatch = true;
17603 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17605 << getRedeclDiagFromTagKind(I->getTagKind());
17606 }
17607 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17609 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17611 }
17612 }
17613 return true;
17614 }
17615
17616 // Identify the prevailing tag kind: this is the kind of the definition (if
17617 // there is a non-ignored definition), or otherwise the kind of the prior
17618 // (non-ignored) declaration.
17619 const TagDecl *PrevDef = Previous->getDefinition();
17620 if (PrevDef && IsIgnored(PrevDef))
17621 PrevDef = nullptr;
17622 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17623 if (Redecl->getTagKind() != NewTag) {
17624 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17626 << getRedeclDiagFromTagKind(OldTag);
17627 Diag(Redecl->getLocation(), diag::note_previous_use);
17628
17629 // If there is a previous definition, suggest a fix-it.
17630 if (PrevDef) {
17631 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17635 }
17636 }
17637
17638 return true;
17639}
17640
17641/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17642/// from an outer enclosing namespace or file scope inside a friend declaration.
17643/// This should provide the commented out code in the following snippet:
17644/// namespace N {
17645/// struct X;
17646/// namespace M {
17647/// struct Y { friend struct /*N::*/ X; };
17648/// }
17649/// }
17651 SourceLocation NameLoc) {
17652 // While the decl is in a namespace, do repeated lookup of that name and see
17653 // if we get the same namespace back. If we do not, continue until
17654 // translation unit scope, at which point we have a fully qualified NNS.
17657 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17658 // This tag should be declared in a namespace, which can only be enclosed by
17659 // other namespaces. Bail if there's an anonymous namespace in the chain.
17660 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17661 if (!Namespace || Namespace->isAnonymousNamespace())
17662 return FixItHint();
17663 IdentifierInfo *II = Namespace->getIdentifier();
17664 Namespaces.push_back(II);
17665 NamedDecl *Lookup = SemaRef.LookupSingleName(
17666 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17667 if (Lookup == Namespace)
17668 break;
17669 }
17670
17671 // Once we have all the namespaces, reverse them to go outermost first, and
17672 // build an NNS.
17673 SmallString<64> Insertion;
17674 llvm::raw_svector_ostream OS(Insertion);
17675 if (DC->isTranslationUnit())
17676 OS << "::";
17677 std::reverse(Namespaces.begin(), Namespaces.end());
17678 for (auto *II : Namespaces)
17679 OS << II->getName() << "::";
17680 return FixItHint::CreateInsertion(NameLoc, Insertion);
17681}
17682
17683/// Determine whether a tag originally declared in context \p OldDC can
17684/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17685/// found a declaration in \p OldDC as a previous decl, perhaps through a
17686/// using-declaration).
17688 DeclContext *NewDC) {
17689 OldDC = OldDC->getRedeclContext();
17690 NewDC = NewDC->getRedeclContext();
17691
17692 if (OldDC->Equals(NewDC))
17693 return true;
17694
17695 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17696 // encloses the other).
17697 if (S.getLangOpts().MSVCCompat &&
17698 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17699 return true;
17700
17701 return false;
17702}
17703
17705Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17706 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17707 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17708 SourceLocation ModulePrivateLoc,
17709 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17710 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17711 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17712 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17713 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17714 // If this is not a definition, it must have a name.
17715 IdentifierInfo *OrigName = Name;
17716 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17717 "Nameless record must be a definition!");
17718 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17719
17720 OwnedDecl = false;
17722 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17723
17724 // FIXME: Check member specializations more carefully.
17725 bool isMemberSpecialization = false;
17726 bool IsInjectedClassName = false;
17727 bool Invalid = false;
17728
17729 // We only need to do this matching if we have template parameters
17730 // or a scope specifier, which also conveniently avoids this work
17731 // for non-C++ cases.
17732 if (TemplateParameterLists.size() > 0 ||
17733 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17734 TemplateParameterList *TemplateParams =
17736 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17737 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17738
17739 // C++23 [dcl.type.elab] p2:
17740 // If an elaborated-type-specifier is the sole constituent of a
17741 // declaration, the declaration is ill-formed unless it is an explicit
17742 // specialization, an explicit instantiation or it has one of the
17743 // following forms: [...]
17744 // C++23 [dcl.enum] p1:
17745 // If the enum-head-name of an opaque-enum-declaration contains a
17746 // nested-name-specifier, the declaration shall be an explicit
17747 // specialization.
17748 //
17749 // FIXME: Class template partial specializations can be forward declared
17750 // per CWG2213, but the resolution failed to allow qualified forward
17751 // declarations. This is almost certainly unintentional, so we allow them.
17752 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17753 !isMemberSpecialization)
17754 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17756
17757 if (TemplateParams) {
17758 if (Kind == TagTypeKind::Enum) {
17759 Diag(KWLoc, diag::err_enum_template);
17760 return true;
17761 }
17762
17763 if (TemplateParams->size() > 0) {
17764 // This is a declaration or definition of a class template (which may
17765 // be a member of another template).
17766
17767 if (Invalid)
17768 return true;
17769
17770 OwnedDecl = false;
17772 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17773 AS, ModulePrivateLoc,
17774 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17775 TemplateParameterLists.data(), SkipBody);
17776 return Result.get();
17777 } else {
17778 // The "template<>" header is extraneous.
17779 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17780 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17781 isMemberSpecialization = true;
17782 }
17783 }
17784
17785 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17786 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17787 return true;
17788 }
17789
17790 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17791 // C++23 [dcl.type.elab]p4:
17792 // If an elaborated-type-specifier appears with the friend specifier as
17793 // an entire member-declaration, the member-declaration shall have one
17794 // of the following forms:
17795 // friend class-key nested-name-specifier(opt) identifier ;
17796 // friend class-key simple-template-id ;
17797 // friend class-key nested-name-specifier template(opt)
17798 // simple-template-id ;
17799 //
17800 // Since enum is not a class-key, so declarations like "friend enum E;"
17801 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17802 // invalid, most implementations accept so we issue a pedantic warning.
17803 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17804 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17805 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17806 Diag(KWLoc, diag::note_enum_friend)
17807 << (ScopedEnum + ScopedEnumUsesClassTag);
17808 }
17809
17810 // Figure out the underlying type if this a enum declaration. We need to do
17811 // this early, because it's needed to detect if this is an incompatible
17812 // redeclaration.
17813 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17814 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17815
17816 if (Kind == TagTypeKind::Enum) {
17817 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17818 // No underlying type explicitly specified, or we failed to parse the
17819 // type, default to int.
17820 EnumUnderlying = Context.IntTy.getTypePtr();
17821 } else if (UnderlyingType.get()) {
17822 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17823 // integral type; any cv-qualification is ignored.
17824 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17825 // unqualified, non-atomic version of the type specified by the type
17826 // specifiers in the specifier qualifier list.
17827 TypeSourceInfo *TI = nullptr;
17828 GetTypeFromParser(UnderlyingType.get(), &TI);
17829 EnumUnderlying = TI;
17830
17832 // Recover by falling back to int.
17833 EnumUnderlying = Context.IntTy.getTypePtr();
17834
17837 EnumUnderlying = Context.IntTy.getTypePtr();
17838
17839 // If the underlying type is atomic, we need to adjust the type before
17840 // continuing. This only happens in the case we stored a TypeSourceInfo
17841 // into EnumUnderlying because the other cases are error recovery up to
17842 // this point. But because it's not possible to gin up a TypeSourceInfo
17843 // for a non-atomic type from an atomic one, we'll store into the Type
17844 // field instead. FIXME: it would be nice to have an easy way to get a
17845 // derived TypeSourceInfo which strips qualifiers including the weird
17846 // ones like _Atomic where it forms a different type.
17847 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17848 TI && TI->getType()->isAtomicType())
17849 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17850
17851 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17852 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17853 // of 'int'. However, if this is an unfixed forward declaration, don't set
17854 // the underlying type unless the user enables -fms-compatibility. This
17855 // makes unfixed forward declared enums incomplete and is more conforming.
17856 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17857 EnumUnderlying = Context.IntTy.getTypePtr();
17858 }
17859 }
17860
17861 DeclContext *SearchDC = CurContext;
17862 DeclContext *DC = CurContext;
17863 bool isStdBadAlloc = false;
17864 bool isStdAlignValT = false;
17865
17867 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17869
17870 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17871 /// implemented asks for structural equivalence checking, the returned decl
17872 /// here is passed back to the parser, allowing the tag body to be parsed.
17873 auto createTagFromNewDecl = [&]() -> TagDecl * {
17874 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17875 // If there is an identifier, use the location of the identifier as the
17876 // location of the decl, otherwise use the location of the struct/union
17877 // keyword.
17878 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17879 TagDecl *New = nullptr;
17880
17881 if (Kind == TagTypeKind::Enum) {
17882 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17883 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17884 // If this is an undefined enum, bail.
17885 if (TUK != TagUseKind::Definition && !Invalid)
17886 return nullptr;
17887 if (EnumUnderlying) {
17889 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17891 else
17892 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17893 QualType EnumTy = ED->getIntegerType();
17894 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17895 ? Context.getPromotedIntegerType(EnumTy)
17896 : EnumTy);
17897 }
17898 } else { // struct/union
17899 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17900 nullptr);
17901 }
17902
17903 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17904 // Add alignment attributes if necessary; these attributes are checked
17905 // when the ASTContext lays out the structure.
17906 //
17907 // It is important for implementing the correct semantics that this
17908 // happen here (in ActOnTag). The #pragma pack stack is
17909 // maintained as a result of parser callbacks which can occur at
17910 // many points during the parsing of a struct declaration (because
17911 // the #pragma tokens are effectively skipped over during the
17912 // parsing of the struct).
17913 if (TUK == TagUseKind::Definition &&
17914 (!SkipBody || !SkipBody->ShouldSkip)) {
17915 if (LangOpts.HLSL)
17916 RD->addAttr(PackedAttr::CreateImplicit(Context));
17919 }
17920 }
17921 New->setLexicalDeclContext(CurContext);
17922 return New;
17923 };
17924
17925 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17926 if (Name && SS.isNotEmpty()) {
17927 // We have a nested-name tag ('struct foo::bar').
17928
17929 // Check for invalid 'foo::'.
17930 if (SS.isInvalid()) {
17931 Name = nullptr;
17932 goto CreateNewDecl;
17933 }
17934
17935 // If this is a friend or a reference to a class in a dependent
17936 // context, don't try to make a decl for it.
17937 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17938 DC = computeDeclContext(SS, false);
17939 if (!DC) {
17940 IsDependent = true;
17941 return true;
17942 }
17943 } else {
17944 DC = computeDeclContext(SS, true);
17945 if (!DC) {
17946 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17947 << SS.getRange();
17948 return true;
17949 }
17950 }
17951
17952 if (RequireCompleteDeclContext(SS, DC))
17953 return true;
17954
17955 SearchDC = DC;
17956 // Look-up name inside 'foo::'.
17958
17959 if (Previous.isAmbiguous())
17960 return true;
17961
17962 if (Previous.empty()) {
17963 // Name lookup did not find anything. However, if the
17964 // nested-name-specifier refers to the current instantiation,
17965 // and that current instantiation has any dependent base
17966 // classes, we might find something at instantiation time: treat
17967 // this as a dependent elaborated-type-specifier.
17968 // But this only makes any sense for reference-like lookups.
17969 if (Previous.wasNotFoundInCurrentInstantiation() &&
17970 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17971 IsDependent = true;
17972 return true;
17973 }
17974
17975 // A tag 'foo::bar' must already exist.
17976 Diag(NameLoc, diag::err_not_tag_in_scope)
17977 << Kind << Name << DC << SS.getRange();
17978 Name = nullptr;
17979 Invalid = true;
17980 goto CreateNewDecl;
17981 }
17982 } else if (Name) {
17983 // C++14 [class.mem]p14:
17984 // If T is the name of a class, then each of the following shall have a
17985 // name different from T:
17986 // -- every member of class T that is itself a type
17987 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17988 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17989 return true;
17990
17991 // If this is a named struct, check to see if there was a previous forward
17992 // declaration or definition.
17993 // FIXME: We're looking into outer scopes here, even when we
17994 // shouldn't be. Doing so can result in ambiguities that we
17995 // shouldn't be diagnosing.
17996 LookupName(Previous, S);
17997
17998 // When declaring or defining a tag, ignore ambiguities introduced
17999 // by types using'ed into this scope.
18000 if (Previous.isAmbiguous() &&
18002 LookupResult::Filter F = Previous.makeFilter();
18003 while (F.hasNext()) {
18004 NamedDecl *ND = F.next();
18005 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18006 SearchDC->getRedeclContext()))
18007 F.erase();
18008 }
18009 F.done();
18010 }
18011
18012 // C++11 [namespace.memdef]p3:
18013 // If the name in a friend declaration is neither qualified nor
18014 // a template-id and the declaration is a function or an
18015 // elaborated-type-specifier, the lookup to determine whether
18016 // the entity has been previously declared shall not consider
18017 // any scopes outside the innermost enclosing namespace.
18018 //
18019 // MSVC doesn't implement the above rule for types, so a friend tag
18020 // declaration may be a redeclaration of a type declared in an enclosing
18021 // scope. They do implement this rule for friend functions.
18022 //
18023 // Does it matter that this should be by scope instead of by
18024 // semantic context?
18025 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18026 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18027 LookupResult::Filter F = Previous.makeFilter();
18028 bool FriendSawTagOutsideEnclosingNamespace = false;
18029 while (F.hasNext()) {
18030 NamedDecl *ND = F.next();
18032 if (DC->isFileContext() &&
18033 !EnclosingNS->Encloses(ND->getDeclContext())) {
18034 if (getLangOpts().MSVCCompat)
18035 FriendSawTagOutsideEnclosingNamespace = true;
18036 else
18037 F.erase();
18038 }
18039 }
18040 F.done();
18041
18042 // Diagnose this MSVC extension in the easy case where lookup would have
18043 // unambiguously found something outside the enclosing namespace.
18044 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18045 NamedDecl *ND = Previous.getFoundDecl();
18046 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18047 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18048 }
18049 }
18050
18051 // Note: there used to be some attempt at recovery here.
18052 if (Previous.isAmbiguous())
18053 return true;
18054
18055 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18056 // FIXME: This makes sure that we ignore the contexts associated
18057 // with C structs, unions, and enums when looking for a matching
18058 // tag declaration or definition. See the similar lookup tweak
18059 // in Sema::LookupName; is there a better way to deal with this?
18061 SearchDC = SearchDC->getParent();
18062 } else if (getLangOpts().CPlusPlus) {
18063 // Inside ObjCContainer want to keep it as a lexical decl context but go
18064 // past it (most often to TranslationUnit) to find the semantic decl
18065 // context.
18066 while (isa<ObjCContainerDecl>(SearchDC))
18067 SearchDC = SearchDC->getParent();
18068 }
18069 } else if (getLangOpts().CPlusPlus) {
18070 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18071 // TagDecl the same way as we skip it for named TagDecl.
18072 while (isa<ObjCContainerDecl>(SearchDC))
18073 SearchDC = SearchDC->getParent();
18074 }
18075
18076 if (Previous.isSingleResult() &&
18077 Previous.getFoundDecl()->isTemplateParameter()) {
18078 // Maybe we will complain about the shadowed template parameter.
18079 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18080 // Just pretend that we didn't see the previous declaration.
18081 Previous.clear();
18082 }
18083
18084 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18085 DC->Equals(getStdNamespace())) {
18086 if (Name->isStr("bad_alloc")) {
18087 // This is a declaration of or a reference to "std::bad_alloc".
18088 isStdBadAlloc = true;
18089
18090 // If std::bad_alloc has been implicitly declared (but made invisible to
18091 // name lookup), fill in this implicit declaration as the previous
18092 // declaration, so that the declarations get chained appropriately.
18093 if (Previous.empty() && StdBadAlloc)
18094 Previous.addDecl(getStdBadAlloc());
18095 } else if (Name->isStr("align_val_t")) {
18096 isStdAlignValT = true;
18097 if (Previous.empty() && StdAlignValT)
18098 Previous.addDecl(getStdAlignValT());
18099 }
18100 }
18101
18102 // If we didn't find a previous declaration, and this is a reference
18103 // (or friend reference), move to the correct scope. In C++, we
18104 // also need to do a redeclaration lookup there, just in case
18105 // there's a shadow friend decl.
18106 if (Name && Previous.empty() &&
18107 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18108 IsTemplateParamOrArg)) {
18109 if (Invalid) goto CreateNewDecl;
18110 assert(SS.isEmpty());
18111
18112 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18113 // C++ [basic.scope.pdecl]p5:
18114 // -- for an elaborated-type-specifier of the form
18115 //
18116 // class-key identifier
18117 //
18118 // if the elaborated-type-specifier is used in the
18119 // decl-specifier-seq or parameter-declaration-clause of a
18120 // function defined in namespace scope, the identifier is
18121 // declared as a class-name in the namespace that contains
18122 // the declaration; otherwise, except as a friend
18123 // declaration, the identifier is declared in the smallest
18124 // non-class, non-function-prototype scope that contains the
18125 // declaration.
18126 //
18127 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18128 // C structs and unions.
18129 //
18130 // It is an error in C++ to declare (rather than define) an enum
18131 // type, including via an elaborated type specifier. We'll
18132 // diagnose that later; for now, declare the enum in the same
18133 // scope as we would have picked for any other tag type.
18134 //
18135 // GNU C also supports this behavior as part of its incomplete
18136 // enum types extension, while GNU C++ does not.
18137 //
18138 // Find the context where we'll be declaring the tag.
18139 // FIXME: We would like to maintain the current DeclContext as the
18140 // lexical context,
18141 SearchDC = getTagInjectionContext(SearchDC);
18142
18143 // Find the scope where we'll be declaring the tag.
18145 } else {
18146 assert(TUK == TagUseKind::Friend);
18147 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18148
18149 // C++ [namespace.memdef]p3:
18150 // If a friend declaration in a non-local class first declares a
18151 // class or function, the friend class or function is a member of
18152 // the innermost enclosing namespace.
18153 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18154 : SearchDC->getEnclosingNamespaceContext();
18155 }
18156
18157 // In C++, we need to do a redeclaration lookup to properly
18158 // diagnose some problems.
18159 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18160 // hidden declaration so that we don't get ambiguity errors when using a
18161 // type declared by an elaborated-type-specifier. In C that is not correct
18162 // and we should instead merge compatible types found by lookup.
18163 if (getLangOpts().CPlusPlus) {
18164 // FIXME: This can perform qualified lookups into function contexts,
18165 // which are meaningless.
18166 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18167 LookupQualifiedName(Previous, SearchDC);
18168 } else {
18169 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18170 LookupName(Previous, S);
18171 }
18172 }
18173
18174 // If we have a known previous declaration to use, then use it.
18175 if (Previous.empty() && SkipBody && SkipBody->Previous)
18176 Previous.addDecl(SkipBody->Previous);
18177
18178 if (!Previous.empty()) {
18179 NamedDecl *PrevDecl = Previous.getFoundDecl();
18180 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18181
18182 // It's okay to have a tag decl in the same scope as a typedef
18183 // which hides a tag decl in the same scope. Finding this
18184 // with a redeclaration lookup can only actually happen in C++.
18185 //
18186 // This is also okay for elaborated-type-specifiers, which is
18187 // technically forbidden by the current standard but which is
18188 // okay according to the likely resolution of an open issue;
18189 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18190 if (getLangOpts().CPlusPlus) {
18191 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18192 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18193 if (Tag->getDeclName() == Name &&
18194 Tag->getDeclContext()->getRedeclContext()
18195 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18196 PrevDecl = Tag;
18197 Previous.clear();
18198 Previous.addDecl(Tag);
18199 Previous.resolveKind();
18200 }
18201 }
18202 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18203 TUK == TagUseKind::Reference && RD &&
18204 RD->isInjectedClassName()) {
18205 // If lookup found the injected class name, the previous declaration is
18206 // the class being injected into.
18207 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18208 Previous.clear();
18209 Previous.addDecl(PrevDecl);
18210 Previous.resolveKind();
18211 IsInjectedClassName = true;
18212 }
18213 }
18214
18215 // If this is a redeclaration of a using shadow declaration, it must
18216 // declare a tag in the same context. In MSVC mode, we allow a
18217 // redefinition if either context is within the other.
18218 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18219 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18220 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18221 TUK != TagUseKind::Friend &&
18222 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18223 !(OldTag && isAcceptableTagRedeclContext(
18224 *this, OldTag->getDeclContext(), SearchDC))) {
18225 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18226 Diag(Shadow->getTargetDecl()->getLocation(),
18227 diag::note_using_decl_target);
18228 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18229 << 0;
18230 // Recover by ignoring the old declaration.
18231 Previous.clear();
18232 goto CreateNewDecl;
18233 }
18234 }
18235
18236 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18237 // If this is a use of a previous tag, or if the tag is already declared
18238 // in the same scope (so that the definition/declaration completes or
18239 // rementions the tag), reuse the decl.
18240 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18241 isDeclInScope(DirectPrevDecl, SearchDC, S,
18242 SS.isNotEmpty() || isMemberSpecialization)) {
18243 // Make sure that this wasn't declared as an enum and now used as a
18244 // struct or something similar.
18245 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18246 TUK == TagUseKind::Definition, KWLoc,
18247 Name)) {
18248 bool SafeToContinue =
18249 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18250 Kind != TagTypeKind::Enum);
18251 if (SafeToContinue)
18252 Diag(KWLoc, diag::err_use_with_wrong_tag)
18253 << Name
18255 PrevTagDecl->getKindName());
18256 else
18257 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18258 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18259
18260 if (SafeToContinue)
18261 Kind = PrevTagDecl->getTagKind();
18262 else {
18263 // Recover by making this an anonymous redefinition.
18264 Name = nullptr;
18265 Previous.clear();
18266 Invalid = true;
18267 }
18268 }
18269
18270 if (Kind == TagTypeKind::Enum &&
18271 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18272 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18273 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18274 return PrevTagDecl;
18275
18276 QualType EnumUnderlyingTy;
18277 if (TypeSourceInfo *TI =
18278 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18279 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18280 else if (const Type *T =
18281 dyn_cast_if_present<const Type *>(EnumUnderlying))
18282 EnumUnderlyingTy = QualType(T, 0);
18283
18284 // All conflicts with previous declarations are recovered by
18285 // returning the previous declaration, unless this is a definition,
18286 // in which case we want the caller to bail out.
18287 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18288 ScopedEnum, EnumUnderlyingTy,
18289 IsFixed, PrevEnum))
18290 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18291 }
18292
18293 // C++11 [class.mem]p1:
18294 // A member shall not be declared twice in the member-specification,
18295 // except that a nested class or member class template can be declared
18296 // and then later defined.
18297 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18298 S->isDeclScope(PrevDecl)) {
18299 Diag(NameLoc, diag::ext_member_redeclared);
18300 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18301 }
18302
18303 if (!Invalid) {
18304 // If this is a use, just return the declaration we found, unless
18305 // we have attributes.
18306 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18307 if (!Attrs.empty()) {
18308 // FIXME: Diagnose these attributes. For now, we create a new
18309 // declaration to hold them.
18310 } else if (TUK == TagUseKind::Reference &&
18311 (PrevTagDecl->getFriendObjectKind() ==
18313 PrevDecl->getOwningModule() != getCurrentModule()) &&
18314 SS.isEmpty()) {
18315 // This declaration is a reference to an existing entity, but
18316 // has different visibility from that entity: it either makes
18317 // a friend visible or it makes a type visible in a new module.
18318 // In either case, create a new declaration. We only do this if
18319 // the declaration would have meant the same thing if no prior
18320 // declaration were found, that is, if it was found in the same
18321 // scope where we would have injected a declaration.
18322 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18323 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18324 return PrevTagDecl;
18325 // This is in the injected scope, create a new declaration in
18326 // that scope.
18328 } else {
18329 return PrevTagDecl;
18330 }
18331 }
18332
18333 // Diagnose attempts to redefine a tag.
18334 if (TUK == TagUseKind::Definition) {
18335 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18336 // If the type is currently being defined, complain
18337 // about a nested redefinition.
18338 if (Def->isBeingDefined()) {
18339 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18340 Diag(PrevTagDecl->getLocation(),
18341 diag::note_previous_definition);
18342 Name = nullptr;
18343 Previous.clear();
18344 Invalid = true;
18345 } else {
18346 // If we're defining a specialization and the previous
18347 // definition is from an implicit instantiation, don't emit an
18348 // error here; we'll catch this in the general case below.
18349 bool IsExplicitSpecializationAfterInstantiation = false;
18350 if (isMemberSpecialization) {
18351 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18352 IsExplicitSpecializationAfterInstantiation =
18353 RD->getTemplateSpecializationKind() !=
18355 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18356 IsExplicitSpecializationAfterInstantiation =
18357 ED->getTemplateSpecializationKind() !=
18359 }
18360
18361 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18362 // do not keep more that one definition around (merge them).
18363 // However, ensure the decl passes the structural compatibility
18364 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18365 NamedDecl *Hidden = nullptr;
18366 bool HiddenDefVisible = false;
18367 if (SkipBody &&
18368 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18369 getLangOpts().C23)) {
18370 // There is a definition of this tag, but it is not visible.
18371 // We explicitly make use of C++'s one definition rule here,
18372 // and assume that this definition is identical to the hidden
18373 // one we already have. Make the existing definition visible
18374 // and use it in place of this one.
18375 if (!getLangOpts().CPlusPlus) {
18376 // Postpone making the old definition visible until after we
18377 // complete parsing the new one and do the structural
18378 // comparison.
18379 SkipBody->CheckSameAsPrevious = true;
18380 SkipBody->New = createTagFromNewDecl();
18381 SkipBody->Previous = Def;
18382
18383 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18384 return Def;
18385 }
18386
18387 SkipBody->ShouldSkip = true;
18388 SkipBody->Previous = Def;
18389 if (!HiddenDefVisible && Hidden)
18391 // Carry on and handle it like a normal definition. We'll
18392 // skip starting the definition later.
18393
18394 } else if (!IsExplicitSpecializationAfterInstantiation) {
18395 // A redeclaration in function prototype scope in C isn't
18396 // visible elsewhere, so merely issue a warning.
18397 if (!getLangOpts().CPlusPlus &&
18399 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18400 << Name;
18401 else
18402 Diag(NameLoc, diag::err_redefinition) << Name;
18404 NameLoc.isValid() ? NameLoc : KWLoc);
18405 // If this is a redefinition, recover by making this
18406 // struct be anonymous, which will make any later
18407 // references get the previous definition.
18408 Name = nullptr;
18409 Previous.clear();
18410 Invalid = true;
18411 }
18412 }
18413 }
18414
18415 // Okay, this is definition of a previously declared or referenced
18416 // tag. We're going to create a new Decl for it.
18417 }
18418
18419 // Okay, we're going to make a redeclaration. If this is some kind
18420 // of reference, make sure we build the redeclaration in the same DC
18421 // as the original, and ignore the current access specifier.
18422 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18423 SearchDC = PrevTagDecl->getDeclContext();
18424 AS = AS_none;
18425 }
18426 }
18427 // If we get here we have (another) forward declaration or we
18428 // have a definition. Just create a new decl.
18429
18430 } else {
18431 // If we get here, this is a definition of a new tag type in a nested
18432 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18433 // new decl/type. We set PrevDecl to NULL so that the entities
18434 // have distinct types.
18435 Previous.clear();
18436 }
18437 // If we get here, we're going to create a new Decl. If PrevDecl
18438 // is non-NULL, it's a definition of the tag declared by
18439 // PrevDecl. If it's NULL, we have a new definition.
18440
18441 // Otherwise, PrevDecl is not a tag, but was found with tag
18442 // lookup. This is only actually possible in C++, where a few
18443 // things like templates still live in the tag namespace.
18444 } else {
18445 // Use a better diagnostic if an elaborated-type-specifier
18446 // found the wrong kind of type on the first
18447 // (non-redeclaration) lookup.
18448 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18449 !Previous.isForRedeclaration()) {
18450 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18451 Diag(NameLoc, diag::err_tag_reference_non_tag)
18452 << PrevDecl << NTK << Kind;
18453 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18454 Invalid = true;
18455
18456 // Otherwise, only diagnose if the declaration is in scope.
18457 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18458 SS.isNotEmpty() || isMemberSpecialization)) {
18459 // do nothing
18460
18461 // Diagnose implicit declarations introduced by elaborated types.
18462 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18463 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18464 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18465 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18466 Invalid = true;
18467
18468 // Otherwise it's a declaration. Call out a particularly common
18469 // case here.
18470 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18471 unsigned Kind = 0;
18472 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18473 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18474 << Name << Kind << TND->getUnderlyingType();
18475 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18476 Invalid = true;
18477
18478 // Otherwise, diagnose.
18479 } else {
18480 // The tag name clashes with something else in the target scope,
18481 // issue an error and recover by making this tag be anonymous.
18482 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18483 notePreviousDefinition(PrevDecl, NameLoc);
18484 Name = nullptr;
18485 Invalid = true;
18486 }
18487
18488 // The existing declaration isn't relevant to us; we're in a
18489 // new scope, so clear out the previous declaration.
18490 Previous.clear();
18491 }
18492 }
18493
18494CreateNewDecl:
18495
18496 TagDecl *PrevDecl = nullptr;
18497 if (Previous.isSingleResult())
18498 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18499
18500 // If there is an identifier, use the location of the identifier as the
18501 // location of the decl, otherwise use the location of the struct/union
18502 // keyword.
18503 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18504
18505 // Otherwise, create a new declaration. If there is a previous
18506 // declaration of the same entity, the two will be linked via
18507 // PrevDecl.
18508 TagDecl *New;
18509
18510 if (Kind == TagTypeKind::Enum) {
18511 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18512 // enum X { A, B, C } D; D should chain to X.
18513 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18514 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18515 ScopedEnumUsesClassTag, IsFixed);
18516
18519 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18520
18521 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18523
18524 // If this is an undefined enum, warn.
18525 if (TUK != TagUseKind::Definition && !Invalid) {
18526 TagDecl *Def;
18527 if (IsFixed && ED->isFixed()) {
18528 // C++0x: 7.2p2: opaque-enum-declaration.
18529 // Conflicts are diagnosed above. Do nothing.
18530 } else if (PrevDecl &&
18531 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18532 Diag(Loc, diag::ext_forward_ref_enum_def)
18533 << New;
18534 Diag(Def->getLocation(), diag::note_previous_definition);
18535 } else {
18536 unsigned DiagID = diag::ext_forward_ref_enum;
18537 if (getLangOpts().MSVCCompat)
18538 DiagID = diag::ext_ms_forward_ref_enum;
18539 else if (getLangOpts().CPlusPlus)
18540 DiagID = diag::err_forward_ref_enum;
18541 Diag(Loc, DiagID);
18542 }
18543 }
18544
18545 if (EnumUnderlying) {
18547 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18549 else
18550 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18551 QualType EnumTy = ED->getIntegerType();
18552 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18553 ? Context.getPromotedIntegerType(EnumTy)
18554 : EnumTy);
18555 assert(ED->isComplete() && "enum with type should be complete");
18556 }
18557 } else {
18558 // struct/union/class
18559
18560 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18561 // struct X { int A; } D; D should chain to X.
18562 if (getLangOpts().CPlusPlus) {
18563 // FIXME: Look for a way to use RecordDecl for simple structs.
18564 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18565 cast_or_null<CXXRecordDecl>(PrevDecl));
18566
18567 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18569 } else
18570 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18571 cast_or_null<RecordDecl>(PrevDecl));
18572 }
18573
18574 // Only C23 and later allow defining new types in 'offsetof()'.
18575 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18577 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18578 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18579
18580 // C++11 [dcl.type]p3:
18581 // A type-specifier-seq shall not define a class or enumeration [...].
18582 if (!Invalid && getLangOpts().CPlusPlus &&
18583 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18584 TUK == TagUseKind::Definition) {
18585 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18586 << Context.getCanonicalTagType(New);
18587 Invalid = true;
18588 }
18589
18591 DC->getDeclKind() == Decl::Enum) {
18592 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18593 << Context.getCanonicalTagType(New);
18594 Invalid = true;
18595 }
18596
18597 // Maybe add qualifier info.
18598 if (SS.isNotEmpty()) {
18599 if (SS.isSet()) {
18600 // If this is either a declaration or a definition, check the
18601 // nested-name-specifier against the current context.
18602 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18603 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18604 /*TemplateId=*/nullptr,
18605 isMemberSpecialization))
18606 Invalid = true;
18607
18608 New->setQualifierInfo(SS.getWithLocInContext(Context));
18609 if (TemplateParameterLists.size() > 0) {
18610 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18611 }
18612 }
18613 else
18614 Invalid = true;
18615 }
18616
18617 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18618 // Add alignment attributes if necessary; these attributes are checked when
18619 // the ASTContext lays out the structure.
18620 //
18621 // It is important for implementing the correct semantics that this
18622 // happen here (in ActOnTag). The #pragma pack stack is
18623 // maintained as a result of parser callbacks which can occur at
18624 // many points during the parsing of a struct declaration (because
18625 // the #pragma tokens are effectively skipped over during the
18626 // parsing of the struct).
18627 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18628 if (LangOpts.HLSL)
18629 RD->addAttr(PackedAttr::CreateImplicit(Context));
18632 }
18633 }
18634
18635 if (ModulePrivateLoc.isValid()) {
18636 if (isMemberSpecialization)
18637 Diag(New->getLocation(), diag::err_module_private_specialization)
18638 << 2
18639 << FixItHint::CreateRemoval(ModulePrivateLoc);
18640 // __module_private__ does not apply to local classes. However, we only
18641 // diagnose this as an error when the declaration specifiers are
18642 // freestanding. Here, we just ignore the __module_private__.
18643 else if (!SearchDC->isFunctionOrMethod())
18644 New->setModulePrivate();
18645 }
18646
18647 // If this is a specialization of a member class (of a class template),
18648 // check the specialization.
18649 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18650 Invalid = true;
18651
18652 // If we're declaring or defining a tag in function prototype scope in C,
18653 // note that this type can only be used within the function and add it to
18654 // the list of decls to inject into the function definition scope. However,
18655 // in C23 and later, while the type is only visible within the function, the
18656 // function can be called with a compatible type defined in the same TU, so
18657 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18658 if ((Name || Kind == TagTypeKind::Enum) &&
18659 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18660 if (getLangOpts().CPlusPlus) {
18661 // C++ [dcl.fct]p6:
18662 // Types shall not be defined in return or parameter types.
18663 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18664 Diag(Loc, diag::err_type_defined_in_param_type)
18665 << Name;
18666 Invalid = true;
18667 }
18668 if (TUK == TagUseKind::Declaration)
18669 Invalid = true;
18670 } else if (!PrevDecl) {
18671 // In C23 mode, if the declaration is complete, we do not want to
18672 // diagnose.
18673 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18674 Diag(Loc, diag::warn_decl_in_param_list)
18675 << Context.getCanonicalTagType(New);
18676 }
18677 }
18678
18679 if (Invalid)
18680 New->setInvalidDecl();
18681
18682 // Set the lexical context. If the tag has a C++ scope specifier, the
18683 // lexical context will be different from the semantic context.
18684 New->setLexicalDeclContext(CurContext);
18685
18686 // Mark this as a friend decl if applicable.
18687 // In Microsoft mode, a friend declaration also acts as a forward
18688 // declaration so we always pass true to setObjectOfFriendDecl to make
18689 // the tag name visible.
18690 if (TUK == TagUseKind::Friend)
18691 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18692
18693 // Set the access specifier.
18694 if (!Invalid && SearchDC->isRecord())
18695 SetMemberAccessSpecifier(New, PrevDecl, AS);
18696
18697 if (PrevDecl)
18699
18700 if (TUK == TagUseKind::Definition) {
18701 if (!SkipBody || !SkipBody->ShouldSkip) {
18702 New->startDefinition();
18703 } else {
18704 New->setCompleteDefinition();
18705 New->demoteThisDefinitionToDeclaration();
18706 }
18707 }
18708
18709 ProcessDeclAttributeList(S, New, Attrs);
18711
18712 // If this has an identifier, add it to the scope stack.
18713 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18714 // We might be replacing an existing declaration in the lookup tables;
18715 // if so, borrow its access specifier.
18716 if (PrevDecl)
18717 New->setAccess(PrevDecl->getAccess());
18718
18719 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18721 if (Name) // can be null along some error paths
18722 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18723 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18724 } else if (Name) {
18725 S = getNonFieldDeclScope(S);
18726 PushOnScopeChains(New, S, true);
18727 } else {
18728 CurContext->addDecl(New);
18729 }
18730
18731 // If this is the C FILE type, notify the AST context.
18732 if (IdentifierInfo *II = New->getIdentifier())
18733 if (!New->isInvalidDecl() &&
18734 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18735 II->isStr("FILE"))
18736 Context.setFILEDecl(New);
18737
18738 if (PrevDecl)
18739 mergeDeclAttributes(New, PrevDecl);
18740
18741 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18744 }
18745
18746 // If there's a #pragma GCC visibility in scope, set the visibility of this
18747 // record.
18749
18750 // If this is not a definition, process API notes for it now.
18751 if (TUK != TagUseKind::Definition)
18753
18754 if (isMemberSpecialization && !New->isInvalidDecl())
18756
18757 OwnedDecl = true;
18758 // In C++, don't return an invalid declaration. We can't recover well from
18759 // the cases where we make the type anonymous.
18760 if (Invalid && getLangOpts().CPlusPlus) {
18761 if (New->isBeingDefined())
18762 if (auto RD = dyn_cast<RecordDecl>(New))
18763 RD->completeDefinition();
18764 return true;
18765 } else if (SkipBody && SkipBody->ShouldSkip) {
18766 return SkipBody->Previous;
18767 } else {
18768 return New;
18769 }
18770}
18771
18774 TagDecl *Tag = cast<TagDecl>(TagD);
18775
18776 // Enter the tag context.
18777 PushDeclContext(S, Tag);
18778
18780
18781 // If there's a #pragma GCC visibility in scope, set the visibility of this
18782 // record.
18784}
18785
18787 SkipBodyInfo &SkipBody) {
18788 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18789 return false;
18790
18791 // Make the previous decl visible.
18793 CleanupMergedEnum(S, SkipBody.New);
18794 return true;
18795}
18796
18798 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18799 bool IsAbstract, SourceLocation TriviallyRelocatable,
18800 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18803
18804 FieldCollector->StartClass();
18805
18806 if (!Record->getIdentifier())
18807 return;
18808
18809 if (IsAbstract)
18810 Record->markAbstract();
18811
18812 if (FinalLoc.isValid()) {
18813 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18814 IsFinalSpelledSealed
18815 ? FinalAttr::Keyword_sealed
18816 : FinalAttr::Keyword_final));
18817 }
18818
18819 if (TriviallyRelocatable.isValid())
18820 Record->addAttr(
18821 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
18822
18823 if (Replaceable.isValid())
18824 Record->addAttr(ReplaceableAttr::Create(Context, Replaceable));
18825
18826 // C++ [class]p2:
18827 // [...] The class-name is also inserted into the scope of the
18828 // class itself; this is known as the injected-class-name. For
18829 // purposes of access checking, the injected-class-name is treated
18830 // as if it were a public member name.
18831 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18832 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18833 Record->getLocation(), Record->getIdentifier());
18834 InjectedClassName->setImplicit();
18835 InjectedClassName->setAccess(AS_public);
18836 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18837 InjectedClassName->setDescribedClassTemplate(Template);
18838
18839 PushOnScopeChains(InjectedClassName, S);
18840 assert(InjectedClassName->isInjectedClassName() &&
18841 "Broken injected-class-name");
18842}
18843
18845 SourceRange BraceRange) {
18847 TagDecl *Tag = cast<TagDecl>(TagD);
18848 Tag->setBraceRange(BraceRange);
18849
18850 // Make sure we "complete" the definition even it is invalid.
18851 if (Tag->isBeingDefined()) {
18852 assert(Tag->isInvalidDecl() && "We should already have completed it");
18853 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18854 RD->completeDefinition();
18855 }
18856
18857 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18858 FieldCollector->FinishClass();
18859 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18860 auto *Def = RD->getDefinition();
18861 assert(Def && "The record is expected to have a completed definition");
18862 unsigned NumInitMethods = 0;
18863 for (auto *Method : Def->methods()) {
18864 if (!Method->getIdentifier())
18865 continue;
18866 if (Method->getName() == "__init")
18867 NumInitMethods++;
18868 }
18869 if (NumInitMethods > 1 || !Def->hasInitMethod())
18870 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18871 }
18872
18873 // If we're defining a dynamic class in a module interface unit, we always
18874 // need to produce the vtable for it, even if the vtable is not used in the
18875 // current TU.
18876 //
18877 // The case where the current class is not dynamic is handled in
18878 // MarkVTableUsed.
18879 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18880 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18881 }
18882
18883 // Exit this scope of this tag's definition.
18885
18886 if (getCurLexicalContext()->isObjCContainer() &&
18887 Tag->getDeclContext()->isFileContext())
18888 Tag->setTopLevelDeclInObjCContainer();
18889
18890 // Notify the consumer that we've defined a tag.
18891 if (!Tag->isInvalidDecl())
18892 Consumer.HandleTagDeclDefinition(Tag);
18893
18894 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18895 // from XLs and instead matches the XL #pragma pack(1) behavior.
18896 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18897 AlignPackStack.hasValue()) {
18898 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18899 // Only diagnose #pragma align(packed).
18900 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18901 return;
18902 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18903 if (!RD)
18904 return;
18905 // Only warn if there is at least 1 bitfield member.
18906 if (llvm::any_of(RD->fields(),
18907 [](const FieldDecl *FD) { return FD->isBitField(); }))
18908 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18909 }
18910}
18911
18914 TagDecl *Tag = cast<TagDecl>(TagD);
18915 Tag->setInvalidDecl();
18916
18917 // Make sure we "complete" the definition even it is invalid.
18918 if (Tag->isBeingDefined()) {
18919 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18920 RD->completeDefinition();
18921 }
18922
18923 // We're undoing ActOnTagStartDefinition here, not
18924 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18925 // the FieldCollector.
18926
18928}
18929
18930// Note that FieldName may be null for anonymous bitfields.
18932 const IdentifierInfo *FieldName,
18933 QualType FieldTy, bool IsMsStruct,
18934 Expr *BitWidth) {
18935 assert(BitWidth);
18936 if (BitWidth->containsErrors())
18937 return ExprError();
18938
18939 // C99 6.7.2.1p4 - verify the field type.
18940 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18941 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18942 // Handle incomplete and sizeless types with a specific error.
18943 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18944 diag::err_field_incomplete_or_sizeless))
18945 return ExprError();
18946 if (FieldName)
18947 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18948 << FieldName << FieldTy << BitWidth->getSourceRange();
18949 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18950 << FieldTy << BitWidth->getSourceRange();
18952 return ExprError();
18953
18954 // If the bit-width is type- or value-dependent, don't try to check
18955 // it now.
18956 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18957 return BitWidth;
18958
18959 llvm::APSInt Value;
18960 ExprResult ICE =
18962 if (ICE.isInvalid())
18963 return ICE;
18964 BitWidth = ICE.get();
18965
18966 // Zero-width bitfield is ok for anonymous field.
18967 if (Value == 0 && FieldName)
18968 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18969 << FieldName << BitWidth->getSourceRange();
18970
18971 if (Value.isSigned() && Value.isNegative()) {
18972 if (FieldName)
18973 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18974 << FieldName << toString(Value, 10);
18975 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18976 << toString(Value, 10);
18977 }
18978
18979 // The size of the bit-field must not exceed our maximum permitted object
18980 // size.
18981 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18982 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18983 << !FieldName << FieldName << toString(Value, 10);
18984 }
18985
18986 if (!FieldTy->isDependentType()) {
18987 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18988 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18989 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18990
18991 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18992 // ABI.
18993 bool CStdConstraintViolation =
18994 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18995 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
18996 if (CStdConstraintViolation || MSBitfieldViolation) {
18997 unsigned DiagWidth =
18998 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18999 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19000 << (bool)FieldName << FieldName << toString(Value, 10)
19001 << !CStdConstraintViolation << DiagWidth;
19002 }
19003
19004 // Warn on types where the user might conceivably expect to get all
19005 // specified bits as value bits: that's all integral types other than
19006 // 'bool'.
19007 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19008 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19009 << FieldName << Value << (unsigned)TypeWidth;
19010 }
19011 }
19012
19013 if (isa<ConstantExpr>(BitWidth))
19014 return BitWidth;
19015 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19016}
19017
19019 Declarator &D, Expr *BitfieldWidth) {
19020 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19021 D, BitfieldWidth,
19022 /*InitStyle=*/ICIS_NoInit, AS_public);
19023 return Res;
19024}
19025
19027 SourceLocation DeclStart,
19028 Declarator &D, Expr *BitWidth,
19029 InClassInitStyle InitStyle,
19030 AccessSpecifier AS) {
19031 if (D.isDecompositionDeclarator()) {
19033 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19034 << Decomp.getSourceRange();
19035 return nullptr;
19036 }
19037
19038 const IdentifierInfo *II = D.getIdentifier();
19039 SourceLocation Loc = DeclStart;
19040 if (II) Loc = D.getIdentifierLoc();
19041
19043 QualType T = TInfo->getType();
19044 if (getLangOpts().CPlusPlus) {
19046
19049 D.setInvalidType();
19050 T = Context.IntTy;
19051 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19052 }
19053 }
19054
19056
19058 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19059 << getLangOpts().CPlusPlus17;
19062 diag::err_invalid_thread)
19064
19065 // Check to see if this name was declared as a member previously
19066 NamedDecl *PrevDecl = nullptr;
19067 LookupResult Previous(*this, II, Loc, LookupMemberName,
19069 LookupName(Previous, S);
19070 switch (Previous.getResultKind()) {
19073 PrevDecl = Previous.getAsSingle<NamedDecl>();
19074 break;
19075
19077 PrevDecl = Previous.getRepresentativeDecl();
19078 break;
19079
19083 break;
19084 }
19085 Previous.suppressDiagnostics();
19086
19087 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19088 // Maybe we will complain about the shadowed template parameter.
19090 // Just pretend that we didn't see the previous declaration.
19091 PrevDecl = nullptr;
19092 }
19093
19094 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19095 PrevDecl = nullptr;
19096
19097 bool Mutable
19098 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19099 SourceLocation TSSL = D.getBeginLoc();
19100 FieldDecl *NewFD
19101 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19102 TSSL, AS, PrevDecl, &D);
19103
19104 if (NewFD->isInvalidDecl())
19105 Record->setInvalidDecl();
19106
19108 NewFD->setModulePrivate();
19109
19110 if (NewFD->isInvalidDecl() && PrevDecl) {
19111 // Don't introduce NewFD into scope; there's already something
19112 // with the same name in the same scope.
19113 } else if (II) {
19114 PushOnScopeChains(NewFD, S);
19115 } else
19116 Record->addDecl(NewFD);
19117
19118 return NewFD;
19119}
19120
19122 TypeSourceInfo *TInfo,
19124 bool Mutable, Expr *BitWidth,
19125 InClassInitStyle InitStyle,
19126 SourceLocation TSSL,
19127 AccessSpecifier AS, NamedDecl *PrevDecl,
19128 Declarator *D) {
19129 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19130 bool InvalidDecl = false;
19131 if (D) InvalidDecl = D->isInvalidType();
19132
19133 // If we receive a broken type, recover by assuming 'int' and
19134 // marking this declaration as invalid.
19135 if (T.isNull() || T->containsErrors()) {
19136 InvalidDecl = true;
19137 T = Context.IntTy;
19138 }
19139
19140 QualType EltTy = Context.getBaseElementType(T);
19141 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19142 bool isIncomplete =
19143 LangOpts.HLSL // HLSL allows sizeless builtin types
19144 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19145 : RequireCompleteSizedType(Loc, EltTy,
19146 diag::err_field_incomplete_or_sizeless);
19147 if (isIncomplete) {
19148 // Fields of incomplete type force their record to be invalid.
19149 Record->setInvalidDecl();
19150 InvalidDecl = true;
19151 } else {
19152 NamedDecl *Def;
19153 EltTy->isIncompleteType(&Def);
19154 if (Def && Def->isInvalidDecl()) {
19155 Record->setInvalidDecl();
19156 InvalidDecl = true;
19157 }
19158 }
19159 }
19160
19161 // TR 18037 does not allow fields to be declared with address space
19162 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19163 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19164 Diag(Loc, diag::err_field_with_address_space);
19165 Record->setInvalidDecl();
19166 InvalidDecl = true;
19167 }
19168
19169 if (LangOpts.OpenCL) {
19170 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19171 // used as structure or union field: image, sampler, event or block types.
19172 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19173 T->isBlockPointerType()) {
19174 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19175 Record->setInvalidDecl();
19176 InvalidDecl = true;
19177 }
19178 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19179 // is enabled.
19180 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19181 "__cl_clang_bitfields", LangOpts)) {
19182 Diag(Loc, diag::err_opencl_bitfields);
19183 InvalidDecl = true;
19184 }
19185 }
19186
19187 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19188 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19189 T.hasQualifiers()) {
19190 InvalidDecl = true;
19191 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19192 }
19193
19194 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19195 // than a variably modified type.
19196 if (!InvalidDecl && T->isVariablyModifiedType()) {
19198 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19199 InvalidDecl = true;
19200 }
19201
19202 // Fields can not have abstract class types
19203 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19204 diag::err_abstract_type_in_decl,
19206 InvalidDecl = true;
19207
19208 if (InvalidDecl)
19209 BitWidth = nullptr;
19210 // If this is declared as a bit-field, check the bit-field.
19211 if (BitWidth) {
19212 BitWidth =
19213 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19214 if (!BitWidth) {
19215 InvalidDecl = true;
19216 BitWidth = nullptr;
19217 }
19218 }
19219
19220 // Check that 'mutable' is consistent with the type of the declaration.
19221 if (!InvalidDecl && Mutable) {
19222 unsigned DiagID = 0;
19223 if (T->isReferenceType())
19224 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19225 : diag::err_mutable_reference;
19226 else if (T.isConstQualified())
19227 DiagID = diag::err_mutable_const;
19228
19229 if (DiagID) {
19230 SourceLocation ErrLoc = Loc;
19231 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19232 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19233 Diag(ErrLoc, DiagID);
19234 if (DiagID != diag::ext_mutable_reference) {
19235 Mutable = false;
19236 InvalidDecl = true;
19237 }
19238 }
19239 }
19240
19241 // C++11 [class.union]p8 (DR1460):
19242 // At most one variant member of a union may have a
19243 // brace-or-equal-initializer.
19244 if (InitStyle != ICIS_NoInit)
19246
19247 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19248 BitWidth, Mutable, InitStyle);
19249 if (InvalidDecl)
19250 NewFD->setInvalidDecl();
19251
19252 if (!InvalidDecl)
19254
19255 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19256 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19257 Diag(Loc, diag::err_duplicate_member) << II;
19258 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19259 NewFD->setInvalidDecl();
19260 }
19261
19262 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19263 if (Record->isUnion()) {
19264 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19265 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19266
19267 // C++ [class.union]p1: An object of a class with a non-trivial
19268 // constructor, a non-trivial copy constructor, a non-trivial
19269 // destructor, or a non-trivial copy assignment operator
19270 // cannot be a member of a union, nor can an array of such
19271 // objects.
19272 if (CheckNontrivialField(NewFD))
19273 NewFD->setInvalidDecl();
19274 }
19275
19276 // C++ [class.union]p1: If a union contains a member of reference type,
19277 // the program is ill-formed, except when compiling with MSVC extensions
19278 // enabled.
19279 if (EltTy->isReferenceType()) {
19280 const bool HaveMSExt =
19281 getLangOpts().MicrosoftExt &&
19283
19284 Diag(NewFD->getLocation(),
19285 HaveMSExt ? diag::ext_union_member_of_reference_type
19286 : diag::err_union_member_of_reference_type)
19287 << NewFD->getDeclName() << EltTy;
19288 if (!HaveMSExt)
19289 NewFD->setInvalidDecl();
19290 }
19291 }
19292 }
19293
19294 // FIXME: We need to pass in the attributes given an AST
19295 // representation, not a parser representation.
19296 if (D) {
19297 // FIXME: The current scope is almost... but not entirely... correct here.
19298 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19299
19300 if (NewFD->hasAttrs())
19302 }
19303
19304 // In auto-retain/release, infer strong retension for fields of
19305 // retainable type.
19306 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19307 NewFD->setInvalidDecl();
19308
19309 if (T.isObjCGCWeak())
19310 Diag(Loc, diag::warn_attribute_weak_on_field);
19311
19312 // PPC MMA non-pointer types are not allowed as field types.
19313 if (Context.getTargetInfo().getTriple().isPPC64() &&
19314 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19315 NewFD->setInvalidDecl();
19316
19317 NewFD->setAccess(AS);
19318 return NewFD;
19319}
19320
19322 assert(FD);
19323 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19324
19325 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19326 return false;
19327
19328 QualType EltTy = Context.getBaseElementType(FD->getType());
19329 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19330 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19331 // We check for copy constructors before constructors
19332 // because otherwise we'll never get complaints about
19333 // copy constructors.
19334
19336 // We're required to check for any non-trivial constructors. Since the
19337 // implicit default constructor is suppressed if there are any
19338 // user-declared constructors, we just need to check that there is a
19339 // trivial default constructor and a trivial copy constructor. (We don't
19340 // worry about move constructors here, since this is a C++98 check.)
19341 if (RDecl->hasNonTrivialCopyConstructor())
19343 else if (!RDecl->hasTrivialDefaultConstructor())
19345 else if (RDecl->hasNonTrivialCopyAssignment())
19347 else if (RDecl->hasNonTrivialDestructor())
19349
19350 if (member != CXXSpecialMemberKind::Invalid) {
19351 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19352 RDecl->hasObjectMember()) {
19353 // Objective-C++ ARC: it is an error to have a non-trivial field of
19354 // a union. However, system headers in Objective-C programs
19355 // occasionally have Objective-C lifetime objects within unions,
19356 // and rather than cause the program to fail, we make those
19357 // members unavailable.
19358 SourceLocation Loc = FD->getLocation();
19359 if (getSourceManager().isInSystemHeader(Loc)) {
19360 if (!FD->hasAttr<UnavailableAttr>())
19361 FD->addAttr(UnavailableAttr::CreateImplicit(
19362 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19363 return false;
19364 }
19365 }
19366
19367 Diag(FD->getLocation(),
19369 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19370 : diag::err_illegal_union_or_anon_struct_member)
19371 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19372 DiagnoseNontrivial(RDecl, member);
19373 return !getLangOpts().CPlusPlus11;
19374 }
19375 }
19376
19377 return false;
19378}
19379
19381 SmallVectorImpl<Decl *> &AllIvarDecls) {
19382 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19383 return;
19384
19385 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19386 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19387
19388 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19389 return;
19390 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19391 if (!ID) {
19392 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19393 if (!CD->IsClassExtension())
19394 return;
19395 }
19396 // No need to add this to end of @implementation.
19397 else
19398 return;
19399 }
19400 // All conditions are met. Add a new bitfield to the tail end of ivars.
19401 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19402 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19403 Expr *BitWidth =
19404 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19405
19406 Ivar = ObjCIvarDecl::Create(
19407 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19408 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19409 ObjCIvarDecl::Private, BitWidth, true);
19410 AllIvarDecls.push_back(Ivar);
19411}
19412
19413/// [class.dtor]p4:
19414/// At the end of the definition of a class, overload resolution is
19415/// performed among the prospective destructors declared in that class with
19416/// an empty argument list to select the destructor for the class, also
19417/// known as the selected destructor.
19418///
19419/// We do the overload resolution here, then mark the selected constructor in the AST.
19420/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19422 if (!Record->hasUserDeclaredDestructor()) {
19423 return;
19424 }
19425
19426 SourceLocation Loc = Record->getLocation();
19428
19429 for (auto *Decl : Record->decls()) {
19430 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19431 if (DD->isInvalidDecl())
19432 continue;
19433 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19434 OCS);
19435 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19436 }
19437 }
19438
19439 if (OCS.empty()) {
19440 return;
19441 }
19443 unsigned Msg = 0;
19444 OverloadCandidateDisplayKind DisplayKind;
19445
19446 switch (OCS.BestViableFunction(S, Loc, Best)) {
19447 case OR_Success:
19448 case OR_Deleted:
19449 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19450 break;
19451
19452 case OR_Ambiguous:
19453 Msg = diag::err_ambiguous_destructor;
19454 DisplayKind = OCD_AmbiguousCandidates;
19455 break;
19456
19458 Msg = diag::err_no_viable_destructor;
19459 DisplayKind = OCD_AllCandidates;
19460 break;
19461 }
19462
19463 if (Msg) {
19464 // OpenCL have got their own thing going with destructors. It's slightly broken,
19465 // but we allow it.
19466 if (!S.LangOpts.OpenCL) {
19467 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19468 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19469 Record->setInvalidDecl();
19470 }
19471 // It's a bit hacky: At this point we've raised an error but we want the
19472 // rest of the compiler to continue somehow working. However almost
19473 // everything we'll try to do with the class will depend on there being a
19474 // destructor. So let's pretend the first one is selected and hope for the
19475 // best.
19476 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19477 }
19478}
19479
19480/// [class.mem.special]p5
19481/// Two special member functions are of the same kind if:
19482/// - they are both default constructors,
19483/// - they are both copy or move constructors with the same first parameter
19484/// type, or
19485/// - they are both copy or move assignment operators with the same first
19486/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19488 CXXMethodDecl *M1,
19489 CXXMethodDecl *M2,
19491 // We don't want to compare templates to non-templates: See
19492 // https://github.com/llvm/llvm-project/issues/59206
19494 return bool(M1->getDescribedFunctionTemplate()) ==
19496 // FIXME: better resolve CWG
19497 // https://cplusplus.github.io/CWG/issues/2787.html
19498 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19499 M2->getNonObjectParameter(0)->getType()))
19500 return false;
19501 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19503 return false;
19504
19505 return true;
19506}
19507
19508/// [class.mem.special]p6:
19509/// An eligible special member function is a special member function for which:
19510/// - the function is not deleted,
19511/// - the associated constraints, if any, are satisfied, and
19512/// - no special member function of the same kind whose associated constraints
19513/// [CWG2595], if any, are satisfied is more constrained.
19517 SmallVector<bool, 4> SatisfactionStatus;
19518
19519 for (CXXMethodDecl *Method : Methods) {
19520 if (!Method->getTrailingRequiresClause())
19521 SatisfactionStatus.push_back(true);
19522 else {
19523 ConstraintSatisfaction Satisfaction;
19524 if (S.CheckFunctionConstraints(Method, Satisfaction))
19525 SatisfactionStatus.push_back(false);
19526 else
19527 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19528 }
19529 }
19530
19531 for (size_t i = 0; i < Methods.size(); i++) {
19532 if (!SatisfactionStatus[i])
19533 continue;
19534 CXXMethodDecl *Method = Methods[i];
19535 CXXMethodDecl *OrigMethod = Method;
19536 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19537 OrigMethod = cast<CXXMethodDecl>(MF);
19538
19540 bool AnotherMethodIsMoreConstrained = false;
19541 for (size_t j = 0; j < Methods.size(); j++) {
19542 if (i == j || !SatisfactionStatus[j])
19543 continue;
19544 CXXMethodDecl *OtherMethod = Methods[j];
19545 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19546 OtherMethod = cast<CXXMethodDecl>(MF);
19547
19548 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19549 CSM))
19550 continue;
19551
19553 if (!Other)
19554 continue;
19555 if (!Orig) {
19556 AnotherMethodIsMoreConstrained = true;
19557 break;
19558 }
19559 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19560 AnotherMethodIsMoreConstrained)) {
19561 // There was an error with the constraints comparison. Exit the loop
19562 // and don't consider this function eligible.
19563 AnotherMethodIsMoreConstrained = true;
19564 }
19565 if (AnotherMethodIsMoreConstrained)
19566 break;
19567 }
19568 // FIXME: Do not consider deleted methods as eligible after implementing
19569 // DR1734 and DR1496.
19570 if (!AnotherMethodIsMoreConstrained) {
19571 Method->setIneligibleOrNotSelected(false);
19572 Record->addedEligibleSpecialMemberFunction(Method,
19573 1 << llvm::to_underlying(CSM));
19574 }
19575 }
19576}
19577
19580 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19581 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19582 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19583 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19584 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19585
19586 for (auto *Decl : Record->decls()) {
19587 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19588 if (!MD) {
19589 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19590 if (FTD)
19591 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19592 }
19593 if (!MD)
19594 continue;
19595 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19596 if (CD->isInvalidDecl())
19597 continue;
19598 if (CD->isDefaultConstructor())
19599 DefaultConstructors.push_back(MD);
19600 else if (CD->isCopyConstructor())
19601 CopyConstructors.push_back(MD);
19602 else if (CD->isMoveConstructor())
19603 MoveConstructors.push_back(MD);
19604 } else if (MD->isCopyAssignmentOperator()) {
19605 CopyAssignmentOperators.push_back(MD);
19606 } else if (MD->isMoveAssignmentOperator()) {
19607 MoveAssignmentOperators.push_back(MD);
19608 }
19609 }
19610
19611 SetEligibleMethods(S, Record, DefaultConstructors,
19613 SetEligibleMethods(S, Record, CopyConstructors,
19615 SetEligibleMethods(S, Record, MoveConstructors,
19617 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19619 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19621}
19622
19623bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19624 // Check to see if a FieldDecl is a pointer to a function.
19625 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19626 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19627 if (!FD) {
19628 // Check whether this is a forward declaration that was inserted by
19629 // Clang. This happens when a non-forward declared / defined type is
19630 // used, e.g.:
19631 //
19632 // struct foo {
19633 // struct bar *(*f)();
19634 // struct bar *(*g)();
19635 // };
19636 //
19637 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19638 // incomplete definition.
19639 if (const auto *TD = dyn_cast<TagDecl>(D))
19640 return !TD->isCompleteDefinition();
19641 return false;
19642 }
19643 QualType FieldType = FD->getType().getDesugaredType(Context);
19644 if (isa<PointerType>(FieldType)) {
19645 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19646 return PointeeType.getDesugaredType(Context)->isFunctionType();
19647 }
19648 // If a member is a struct entirely of function pointers, that counts too.
19649 if (const auto *Record = FieldType->getAsRecordDecl();
19650 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19651 return true;
19652 return false;
19653 };
19654
19655 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19656}
19657
19658void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19659 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19660 SourceLocation RBrac,
19661 const ParsedAttributesView &Attrs) {
19662 assert(EnclosingDecl && "missing record or interface decl");
19663
19664 // If this is an Objective-C @implementation or category and we have
19665 // new fields here we should reset the layout of the interface since
19666 // it will now change.
19667 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19668 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19669 switch (DC->getKind()) {
19670 default: break;
19671 case Decl::ObjCCategory:
19672 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19673 break;
19674 case Decl::ObjCImplementation:
19675 Context.
19676 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19677 break;
19678 }
19679 }
19680
19681 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19682 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19683
19684 // Start counting up the number of named members; make sure to include
19685 // members of anonymous structs and unions in the total.
19686 unsigned NumNamedMembers = 0;
19687 if (Record) {
19688 for (const auto *I : Record->decls()) {
19689 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19690 if (IFD->getDeclName())
19691 ++NumNamedMembers;
19692 }
19693 }
19694
19695 // Verify that all the fields are okay.
19697 const FieldDecl *PreviousField = nullptr;
19698 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19699 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19700 FieldDecl *FD = cast<FieldDecl>(*i);
19701
19702 // Get the type for the field.
19703 const Type *FDTy = FD->getType().getTypePtr();
19704
19705 if (!FD->isAnonymousStructOrUnion()) {
19706 // Remember all fields written by the user.
19707 RecFields.push_back(FD);
19708 }
19709
19710 // If the field is already invalid for some reason, don't emit more
19711 // diagnostics about it.
19712 if (FD->isInvalidDecl()) {
19713 EnclosingDecl->setInvalidDecl();
19714 continue;
19715 }
19716
19717 // C99 6.7.2.1p2:
19718 // A structure or union shall not contain a member with
19719 // incomplete or function type (hence, a structure shall not
19720 // contain an instance of itself, but may contain a pointer to
19721 // an instance of itself), except that the last member of a
19722 // structure with more than one named member may have incomplete
19723 // array type; such a structure (and any union containing,
19724 // possibly recursively, a member that is such a structure)
19725 // shall not be a member of a structure or an element of an
19726 // array.
19727 bool IsLastField = (i + 1 == Fields.end());
19728 if (FDTy->isFunctionType()) {
19729 // Field declared as a function.
19730 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19731 << FD->getDeclName();
19732 FD->setInvalidDecl();
19733 EnclosingDecl->setInvalidDecl();
19734 continue;
19735 } else if (FDTy->isIncompleteArrayType() &&
19736 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19737 if (Record) {
19738 // Flexible array member.
19739 // Microsoft and g++ is more permissive regarding flexible array.
19740 // It will accept flexible array in union and also
19741 // as the sole element of a struct/class.
19742 unsigned DiagID = 0;
19743 if (!Record->isUnion() && !IsLastField) {
19744 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19745 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19746 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19747 FD->setInvalidDecl();
19748 EnclosingDecl->setInvalidDecl();
19749 continue;
19750 } else if (Record->isUnion())
19751 DiagID = getLangOpts().MicrosoftExt
19752 ? diag::ext_flexible_array_union_ms
19753 : diag::ext_flexible_array_union_gnu;
19754 else if (NumNamedMembers < 1)
19755 DiagID = getLangOpts().MicrosoftExt
19756 ? diag::ext_flexible_array_empty_aggregate_ms
19757 : diag::ext_flexible_array_empty_aggregate_gnu;
19758
19759 if (DiagID)
19760 Diag(FD->getLocation(), DiagID)
19761 << FD->getDeclName() << Record->getTagKind();
19762 // While the layout of types that contain virtual bases is not specified
19763 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19764 // virtual bases after the derived members. This would make a flexible
19765 // array member declared at the end of an object not adjacent to the end
19766 // of the type.
19767 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19768 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19769 << FD->getDeclName() << Record->getTagKind();
19770 if (!getLangOpts().C99)
19771 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19772 << FD->getDeclName() << Record->getTagKind();
19773
19774 // If the element type has a non-trivial destructor, we would not
19775 // implicitly destroy the elements, so disallow it for now.
19776 //
19777 // FIXME: GCC allows this. We should probably either implicitly delete
19778 // the destructor of the containing class, or just allow this.
19779 QualType BaseElem = Context.getBaseElementType(FD->getType());
19780 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19781 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19782 << FD->getDeclName() << FD->getType();
19783 FD->setInvalidDecl();
19784 EnclosingDecl->setInvalidDecl();
19785 continue;
19786 }
19787 // Okay, we have a legal flexible array member at the end of the struct.
19788 Record->setHasFlexibleArrayMember(true);
19789 } else {
19790 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19791 // unless they are followed by another ivar. That check is done
19792 // elsewhere, after synthesized ivars are known.
19793 }
19794 } else if (!FDTy->isDependentType() &&
19795 (LangOpts.HLSL // HLSL allows sizeless builtin types
19797 diag::err_incomplete_type)
19799 FD->getLocation(), FD->getType(),
19800 diag::err_field_incomplete_or_sizeless))) {
19801 // Incomplete type
19802 FD->setInvalidDecl();
19803 EnclosingDecl->setInvalidDecl();
19804 continue;
19805 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19806 if (Record && RD->hasFlexibleArrayMember()) {
19807 // A type which contains a flexible array member is considered to be a
19808 // flexible array member.
19809 Record->setHasFlexibleArrayMember(true);
19810 if (!Record->isUnion()) {
19811 // If this is a struct/class and this is not the last element, reject
19812 // it. Note that GCC supports variable sized arrays in the middle of
19813 // structures.
19814 if (!IsLastField)
19815 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19816 << FD->getDeclName() << FD->getType();
19817 else {
19818 // We support flexible arrays at the end of structs in
19819 // other structs as an extension.
19820 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19821 << FD->getDeclName();
19822 }
19823 }
19824 }
19825 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19827 diag::err_abstract_type_in_decl,
19829 // Ivars can not have abstract class types
19830 FD->setInvalidDecl();
19831 }
19832 if (Record && RD->hasObjectMember())
19833 Record->setHasObjectMember(true);
19834 if (Record && RD->hasVolatileMember())
19835 Record->setHasVolatileMember(true);
19836 } else if (FDTy->isObjCObjectType()) {
19837 /// A field cannot be an Objective-c object
19838 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19840 QualType T = Context.getObjCObjectPointerType(FD->getType());
19841 FD->setType(T);
19842 } else if (Record && Record->isUnion() &&
19844 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19845 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19847 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19848 // For backward compatibility, fields of C unions declared in system
19849 // headers that have non-trivial ObjC ownership qualifications are marked
19850 // as unavailable unless the qualifier is explicit and __strong. This can
19851 // break ABI compatibility between programs compiled with ARC and MRR, but
19852 // is a better option than rejecting programs using those unions under
19853 // ARC.
19854 FD->addAttr(UnavailableAttr::CreateImplicit(
19855 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19856 FD->getLocation()));
19857 } else if (getLangOpts().ObjC &&
19858 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19859 !Record->hasObjectMember()) {
19860 if (FD->getType()->isObjCObjectPointerType() ||
19861 FD->getType().isObjCGCStrong())
19862 Record->setHasObjectMember(true);
19863 else if (Context.getAsArrayType(FD->getType())) {
19864 QualType BaseType = Context.getBaseElementType(FD->getType());
19865 if (const auto *RD = BaseType->getAsRecordDecl();
19866 RD && RD->hasObjectMember())
19867 Record->setHasObjectMember(true);
19868 else if (BaseType->isObjCObjectPointerType() ||
19869 BaseType.isObjCGCStrong())
19870 Record->setHasObjectMember(true);
19871 }
19872 }
19873
19874 if (Record && !getLangOpts().CPlusPlus &&
19875 !shouldIgnoreForRecordTriviality(FD)) {
19876 QualType FT = FD->getType();
19878 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19880 Record->isUnion())
19881 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19882 }
19885 Record->setNonTrivialToPrimitiveCopy(true);
19886 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19887 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19888 }
19889 if (FD->hasAttr<ExplicitInitAttr>())
19890 Record->setHasUninitializedExplicitInitFields(true);
19891 if (FT.isDestructedType()) {
19892 Record->setNonTrivialToPrimitiveDestroy(true);
19893 Record->setParamDestroyedInCallee(true);
19894 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19895 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19896 }
19897
19898 if (const auto *RD = FT->getAsRecordDecl()) {
19899 if (RD->getArgPassingRestrictions() ==
19901 Record->setArgPassingRestrictions(
19903 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19904 Record->setArgPassingRestrictions(
19906 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19907 Q && Q.isAddressDiscriminated()) {
19908 Record->setArgPassingRestrictions(
19910 Record->setNonTrivialToPrimitiveCopy(true);
19911 }
19912 }
19913
19914 if (Record && FD->getType().isVolatileQualified())
19915 Record->setHasVolatileMember(true);
19916 bool ReportMSBitfieldStoragePacking =
19917 Record && PreviousField &&
19918 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
19919 Record->getLocation());
19920 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19921 return FD->isBitField() && !FD->getType()->isDependentType();
19922 };
19923
19924 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19925 IsNonDependentBitField(PreviousField)) {
19926 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
19927 CharUnits PreviousFieldStorageSize =
19928 Context.getTypeSizeInChars(PreviousField->getType());
19929 if (FDStorageSize != PreviousFieldStorageSize) {
19930 Diag(FD->getLocation(),
19931 diag::warn_ms_bitfield_mismatched_storage_packing)
19932 << FD << FD->getType() << FDStorageSize.getQuantity()
19933 << PreviousFieldStorageSize.getQuantity();
19934 Diag(PreviousField->getLocation(),
19935 diag::note_ms_bitfield_mismatched_storage_size_previous)
19936 << PreviousField << PreviousField->getType();
19937 }
19938 }
19939 // Keep track of the number of named members.
19940 if (FD->getIdentifier())
19941 ++NumNamedMembers;
19942 }
19943
19944 // Okay, we successfully defined 'Record'.
19945 if (Record) {
19946 bool Completed = false;
19947 if (S) {
19948 Scope *Parent = S->getParent();
19949 if (Parent && Parent->isTypeAliasScope() &&
19950 Parent->isTemplateParamScope())
19951 Record->setInvalidDecl();
19952 }
19953
19954 if (CXXRecord) {
19955 if (!CXXRecord->isInvalidDecl()) {
19956 // Set access bits correctly on the directly-declared conversions.
19958 I = CXXRecord->conversion_begin(),
19959 E = CXXRecord->conversion_end(); I != E; ++I)
19960 I.setAccess((*I)->getAccess());
19961 }
19962
19963 // Add any implicitly-declared members to this class.
19965
19966 if (!CXXRecord->isDependentType()) {
19967 if (!CXXRecord->isInvalidDecl()) {
19968 // If we have virtual base classes, we may end up finding multiple
19969 // final overriders for a given virtual function. Check for this
19970 // problem now.
19971 if (CXXRecord->getNumVBases()) {
19972 CXXFinalOverriderMap FinalOverriders;
19973 CXXRecord->getFinalOverriders(FinalOverriders);
19974
19975 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19976 MEnd = FinalOverriders.end();
19977 M != MEnd; ++M) {
19978 for (OverridingMethods::iterator SO = M->second.begin(),
19979 SOEnd = M->second.end();
19980 SO != SOEnd; ++SO) {
19981 assert(SO->second.size() > 0 &&
19982 "Virtual function without overriding functions?");
19983 if (SO->second.size() == 1)
19984 continue;
19985
19986 // C++ [class.virtual]p2:
19987 // In a derived class, if a virtual member function of a base
19988 // class subobject has more than one final overrider the
19989 // program is ill-formed.
19990 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19991 << (const NamedDecl *)M->first << Record;
19992 Diag(M->first->getLocation(),
19993 diag::note_overridden_virtual_function);
19995 OM = SO->second.begin(),
19996 OMEnd = SO->second.end();
19997 OM != OMEnd; ++OM)
19998 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19999 << (const NamedDecl *)M->first << OM->Method->getParent();
20000
20001 Record->setInvalidDecl();
20002 }
20003 }
20004 CXXRecord->completeDefinition(&FinalOverriders);
20005 Completed = true;
20006 }
20007 }
20008 ComputeSelectedDestructor(*this, CXXRecord);
20010 }
20011 }
20012
20013 if (!Completed)
20014 Record->completeDefinition();
20015
20016 // Handle attributes before checking the layout.
20018
20019 // Maybe randomize the record's decls. We automatically randomize a record
20020 // of function pointers, unless it has the "no_randomize_layout" attribute.
20021 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20022 !Record->isRandomized() && !Record->isUnion() &&
20023 (Record->hasAttr<RandomizeLayoutAttr>() ||
20024 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20025 EntirelyFunctionPointers(Record)))) {
20026 SmallVector<Decl *, 32> NewDeclOrdering;
20028 NewDeclOrdering))
20029 Record->reorderDecls(NewDeclOrdering);
20030 }
20031
20032 // We may have deferred checking for a deleted destructor. Check now.
20033 if (CXXRecord) {
20034 auto *Dtor = CXXRecord->getDestructor();
20035 if (Dtor && Dtor->isImplicit() &&
20037 CXXRecord->setImplicitDestructorIsDeleted();
20038 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20039 }
20040 }
20041
20042 if (Record->hasAttrs()) {
20044
20045 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20047 IA->getRange(), IA->getBestCase(),
20048 IA->getInheritanceModel());
20049 }
20050
20051 // Check if the structure/union declaration is a type that can have zero
20052 // size in C. For C this is a language extension, for C++ it may cause
20053 // compatibility problems.
20054 bool CheckForZeroSize;
20055 if (!getLangOpts().CPlusPlus) {
20056 CheckForZeroSize = true;
20057 } else {
20058 // For C++ filter out types that cannot be referenced in C code.
20060 CheckForZeroSize =
20061 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20062 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20063 CXXRecord->isCLike();
20064 }
20065 if (CheckForZeroSize) {
20066 bool ZeroSize = true;
20067 bool IsEmpty = true;
20068 unsigned NonBitFields = 0;
20069 for (RecordDecl::field_iterator I = Record->field_begin(),
20070 E = Record->field_end();
20071 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20072 IsEmpty = false;
20073 if (I->isUnnamedBitField()) {
20074 if (!I->isZeroLengthBitField())
20075 ZeroSize = false;
20076 } else {
20077 ++NonBitFields;
20078 QualType FieldType = I->getType();
20079 if (FieldType->isIncompleteType() ||
20080 !Context.getTypeSizeInChars(FieldType).isZero())
20081 ZeroSize = false;
20082 }
20083 }
20084
20085 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20086 // allowed in C++, but warn if its declaration is inside
20087 // extern "C" block.
20088 if (ZeroSize) {
20089 Diag(RecLoc, getLangOpts().CPlusPlus ?
20090 diag::warn_zero_size_struct_union_in_extern_c :
20091 diag::warn_zero_size_struct_union_compat)
20092 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20093 }
20094
20095 // Structs without named members are extension in C (C99 6.7.2.1p7),
20096 // but are accepted by GCC. In C2y, this became implementation-defined
20097 // (C2y 6.7.3.2p10).
20098 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20099 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20100 : diag::ext_no_named_members_in_struct_union)
20101 << Record->isUnion();
20102 }
20103 }
20104 } else {
20105 ObjCIvarDecl **ClsFields =
20106 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20107 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20108 ID->setEndOfDefinitionLoc(RBrac);
20109 // Add ivar's to class's DeclContext.
20110 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20111 ClsFields[i]->setLexicalDeclContext(ID);
20112 ID->addDecl(ClsFields[i]);
20113 }
20114 // Must enforce the rule that ivars in the base classes may not be
20115 // duplicates.
20116 if (ID->getSuperClass())
20117 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20118 } else if (ObjCImplementationDecl *IMPDecl =
20119 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20120 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20121 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20122 // Ivar declared in @implementation never belongs to the implementation.
20123 // Only it is in implementation's lexical context.
20124 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20125 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20126 RBrac);
20127 IMPDecl->setIvarLBraceLoc(LBrac);
20128 IMPDecl->setIvarRBraceLoc(RBrac);
20129 } else if (ObjCCategoryDecl *CDecl =
20130 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20131 // case of ivars in class extension; all other cases have been
20132 // reported as errors elsewhere.
20133 // FIXME. Class extension does not have a LocEnd field.
20134 // CDecl->setLocEnd(RBrac);
20135 // Add ivar's to class extension's DeclContext.
20136 // Diagnose redeclaration of private ivars.
20137 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20138 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20139 if (IDecl) {
20140 if (const ObjCIvarDecl *ClsIvar =
20141 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20142 Diag(ClsFields[i]->getLocation(),
20143 diag::err_duplicate_ivar_declaration);
20144 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20145 continue;
20146 }
20147 for (const auto *Ext : IDecl->known_extensions()) {
20148 if (const ObjCIvarDecl *ClsExtIvar
20149 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20150 Diag(ClsFields[i]->getLocation(),
20151 diag::err_duplicate_ivar_declaration);
20152 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20153 continue;
20154 }
20155 }
20156 }
20157 ClsFields[i]->setLexicalDeclContext(CDecl);
20158 CDecl->addDecl(ClsFields[i]);
20159 }
20160 CDecl->setIvarLBraceLoc(LBrac);
20161 CDecl->setIvarRBraceLoc(RBrac);
20162 }
20163 }
20165}
20166
20167// Given an integral type, return the next larger integral type
20168// (or a NULL type of no such type exists).
20170 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20171 // enum checking below.
20172 assert((T->isIntegralType(Context) ||
20173 T->isEnumeralType()) && "Integral type required!");
20174 const unsigned NumTypes = 4;
20175 QualType SignedIntegralTypes[NumTypes] = {
20176 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20177 };
20178 QualType UnsignedIntegralTypes[NumTypes] = {
20179 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20180 Context.UnsignedLongLongTy
20181 };
20182
20183 unsigned BitWidth = Context.getTypeSize(T);
20184 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20185 : UnsignedIntegralTypes;
20186 for (unsigned I = 0; I != NumTypes; ++I)
20187 if (Context.getTypeSize(Types[I]) > BitWidth)
20188 return Types[I];
20189
20190 return QualType();
20191}
20192
20194 EnumConstantDecl *LastEnumConst,
20195 SourceLocation IdLoc,
20196 IdentifierInfo *Id,
20197 Expr *Val) {
20198 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20199 llvm::APSInt EnumVal(IntWidth);
20200 QualType EltTy;
20201
20203 Val = nullptr;
20204
20205 if (Val)
20206 Val = DefaultLvalueConversion(Val).get();
20207
20208 if (Val) {
20209 if (Enum->isDependentType() || Val->isTypeDependent() ||
20210 Val->containsErrors())
20211 EltTy = Context.DependentTy;
20212 else {
20213 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20214 // underlying type, but do allow it in all other contexts.
20215 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20216 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20217 // constant-expression in the enumerator-definition shall be a converted
20218 // constant expression of the underlying type.
20219 EltTy = Enum->getIntegerType();
20221 Val, EltTy, EnumVal, CCEKind::Enumerator);
20222 if (Converted.isInvalid())
20223 Val = nullptr;
20224 else
20225 Val = Converted.get();
20226 } else if (!Val->isValueDependent() &&
20227 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20229 .get())) {
20230 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20231 } else {
20232 if (Enum->isComplete()) {
20233 EltTy = Enum->getIntegerType();
20234
20235 // In Obj-C and Microsoft mode, require the enumeration value to be
20236 // representable in the underlying type of the enumeration. In C++11,
20237 // we perform a non-narrowing conversion as part of converted constant
20238 // expression checking.
20239 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20240 if (Context.getTargetInfo()
20241 .getTriple()
20242 .isWindowsMSVCEnvironment()) {
20243 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20244 } else {
20245 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20246 }
20247 }
20248
20249 // Cast to the underlying type.
20250 Val = ImpCastExprToType(Val, EltTy,
20251 EltTy->isBooleanType() ? CK_IntegralToBoolean
20252 : CK_IntegralCast)
20253 .get();
20254 } else if (getLangOpts().CPlusPlus) {
20255 // C++11 [dcl.enum]p5:
20256 // If the underlying type is not fixed, the type of each enumerator
20257 // is the type of its initializing value:
20258 // - If an initializer is specified for an enumerator, the
20259 // initializing value has the same type as the expression.
20260 EltTy = Val->getType();
20261 } else {
20262 // C99 6.7.2.2p2:
20263 // The expression that defines the value of an enumeration constant
20264 // shall be an integer constant expression that has a value
20265 // representable as an int.
20266
20267 // Complain if the value is not representable in an int.
20268 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20269 Diag(IdLoc, getLangOpts().C23
20270 ? diag::warn_c17_compat_enum_value_not_int
20271 : diag::ext_c23_enum_value_not_int)
20272 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20273 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20274 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20275 // Force the type of the expression to 'int'.
20276 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20277 }
20278 EltTy = Val->getType();
20279 }
20280 }
20281 }
20282 }
20283
20284 if (!Val) {
20285 if (Enum->isDependentType())
20286 EltTy = Context.DependentTy;
20287 else if (!LastEnumConst) {
20288 // C++0x [dcl.enum]p5:
20289 // If the underlying type is not fixed, the type of each enumerator
20290 // is the type of its initializing value:
20291 // - If no initializer is specified for the first enumerator, the
20292 // initializing value has an unspecified integral type.
20293 //
20294 // GCC uses 'int' for its unspecified integral type, as does
20295 // C99 6.7.2.2p3.
20296 if (Enum->isFixed()) {
20297 EltTy = Enum->getIntegerType();
20298 }
20299 else {
20300 EltTy = Context.IntTy;
20301 }
20302 } else {
20303 // Assign the last value + 1.
20304 EnumVal = LastEnumConst->getInitVal();
20305 ++EnumVal;
20306 EltTy = LastEnumConst->getType();
20307
20308 // Check for overflow on increment.
20309 if (EnumVal < LastEnumConst->getInitVal()) {
20310 // C++0x [dcl.enum]p5:
20311 // If the underlying type is not fixed, the type of each enumerator
20312 // is the type of its initializing value:
20313 //
20314 // - Otherwise the type of the initializing value is the same as
20315 // the type of the initializing value of the preceding enumerator
20316 // unless the incremented value is not representable in that type,
20317 // in which case the type is an unspecified integral type
20318 // sufficient to contain the incremented value. If no such type
20319 // exists, the program is ill-formed.
20321 if (T.isNull() || Enum->isFixed()) {
20322 // There is no integral type larger enough to represent this
20323 // value. Complain, then allow the value to wrap around.
20324 EnumVal = LastEnumConst->getInitVal();
20325 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20326 ++EnumVal;
20327 if (Enum->isFixed())
20328 // When the underlying type is fixed, this is ill-formed.
20329 Diag(IdLoc, diag::err_enumerator_wrapped)
20330 << toString(EnumVal, 10)
20331 << EltTy;
20332 else
20333 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20334 << toString(EnumVal, 10);
20335 } else {
20336 EltTy = T;
20337 }
20338
20339 // Retrieve the last enumerator's value, extent that type to the
20340 // type that is supposed to be large enough to represent the incremented
20341 // value, then increment.
20342 EnumVal = LastEnumConst->getInitVal();
20343 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20344 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20345 ++EnumVal;
20346
20347 // If we're not in C++, diagnose the overflow of enumerator values,
20348 // which in C99 means that the enumerator value is not representable in
20349 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20350 // are representable in some larger integral type and we allow it in
20351 // older language modes as an extension.
20352 // Exclude fixed enumerators since they are diagnosed with an error for
20353 // this case.
20354 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20355 Diag(IdLoc, getLangOpts().C23
20356 ? diag::warn_c17_compat_enum_value_not_int
20357 : diag::ext_c23_enum_value_not_int)
20358 << 1 << toString(EnumVal, 10) << 1;
20359 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20360 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20361 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20362 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20363 : diag::ext_c23_enum_value_not_int)
20364 << 1 << toString(EnumVal, 10) << 1;
20365 }
20366 }
20367 }
20368
20369 if (!EltTy->isDependentType()) {
20370 // Make the enumerator value match the signedness and size of the
20371 // enumerator's type.
20372 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20373 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20374 }
20375
20376 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20377 Val, EnumVal);
20378}
20379
20381 SourceLocation IILoc) {
20382 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20384 return SkipBodyInfo();
20385
20386 // We have an anonymous enum definition. Look up the first enumerator to
20387 // determine if we should merge the definition with an existing one and
20388 // skip the body.
20389 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20391 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20392 if (!PrevECD)
20393 return SkipBodyInfo();
20394
20395 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20396 NamedDecl *Hidden;
20397 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20399 Skip.Previous = Hidden;
20400 return Skip;
20401 }
20402
20403 return SkipBodyInfo();
20404}
20405
20406Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20407 SourceLocation IdLoc, IdentifierInfo *Id,
20408 const ParsedAttributesView &Attrs,
20409 SourceLocation EqualLoc, Expr *Val,
20410 SkipBodyInfo *SkipBody) {
20411 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20412 EnumConstantDecl *LastEnumConst =
20413 cast_or_null<EnumConstantDecl>(lastEnumConst);
20414
20415 // The scope passed in may not be a decl scope. Zip up the scope tree until
20416 // we find one that is.
20417 S = getNonFieldDeclScope(S);
20418
20419 // Verify that there isn't already something declared with this name in this
20420 // scope.
20421 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20423 LookupName(R, S);
20424 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20425
20426 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20427 // Maybe we will complain about the shadowed template parameter.
20428 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20429 // Just pretend that we didn't see the previous declaration.
20430 PrevDecl = nullptr;
20431 }
20432
20433 // C++ [class.mem]p15:
20434 // If T is the name of a class, then each of the following shall have a name
20435 // different from T:
20436 // - every enumerator of every member of class T that is an unscoped
20437 // enumerated type
20438 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20440 DeclarationNameInfo(Id, IdLoc)))
20441 return nullptr;
20442
20444 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20445 if (!New)
20446 return nullptr;
20447
20448 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20449 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20450 // Check for other kinds of shadowing not already handled.
20451 CheckShadow(New, PrevDecl, R);
20452 }
20453
20454 // When in C++, we may get a TagDecl with the same name; in this case the
20455 // enum constant will 'hide' the tag.
20456 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20457 "Received TagDecl when not in C++!");
20458 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20459 if (isa<EnumConstantDecl>(PrevDecl))
20460 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20461 else
20462 Diag(IdLoc, diag::err_redefinition) << Id;
20463 notePreviousDefinition(PrevDecl, IdLoc);
20464 return nullptr;
20465 }
20466 }
20467
20468 // Process attributes.
20469 ProcessDeclAttributeList(S, New, Attrs);
20472
20473 // Register this decl in the current scope stack.
20474 New->setAccess(TheEnumDecl->getAccess());
20476
20478
20479 return New;
20480}
20481
20482// Returns true when the enum initial expression does not trigger the
20483// duplicate enum warning. A few common cases are exempted as follows:
20484// Element2 = Element1
20485// Element2 = Element1 + 1
20486// Element2 = Element1 - 1
20487// Where Element2 and Element1 are from the same enum.
20489 Expr *InitExpr = ECD->getInitExpr();
20490 if (!InitExpr)
20491 return true;
20492 InitExpr = InitExpr->IgnoreImpCasts();
20493
20494 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20495 if (!BO->isAdditiveOp())
20496 return true;
20497 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20498 if (!IL)
20499 return true;
20500 if (IL->getValue() != 1)
20501 return true;
20502
20503 InitExpr = BO->getLHS();
20504 }
20505
20506 // This checks if the elements are from the same enum.
20507 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20508 if (!DRE)
20509 return true;
20510
20511 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20512 if (!EnumConstant)
20513 return true;
20514
20516 Enum)
20517 return true;
20518
20519 return false;
20520}
20521
20522// Emits a warning when an element is implicitly set a value that
20523// a previous element has already been set to.
20525 EnumDecl *Enum, QualType EnumType) {
20526 // Avoid anonymous enums
20527 if (!Enum->getIdentifier())
20528 return;
20529
20530 // Only check for small enums.
20531 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20532 return;
20533
20534 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20535 return;
20536
20537 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20538 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20539
20540 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20541
20542 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20543 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20544
20545 // Use int64_t as a key to avoid needing special handling for map keys.
20546 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20547 llvm::APSInt Val = D->getInitVal();
20548 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20549 };
20550
20551 DuplicatesVector DupVector;
20552 ValueToVectorMap EnumMap;
20553
20554 // Populate the EnumMap with all values represented by enum constants without
20555 // an initializer.
20556 for (auto *Element : Elements) {
20557 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20558
20559 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20560 // this constant. Skip this enum since it may be ill-formed.
20561 if (!ECD) {
20562 return;
20563 }
20564
20565 // Constants with initializers are handled in the next loop.
20566 if (ECD->getInitExpr())
20567 continue;
20568
20569 // Duplicate values are handled in the next loop.
20570 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20571 }
20572
20573 if (EnumMap.size() == 0)
20574 return;
20575
20576 // Create vectors for any values that has duplicates.
20577 for (auto *Element : Elements) {
20578 // The last loop returned if any constant was null.
20580 if (!ValidDuplicateEnum(ECD, Enum))
20581 continue;
20582
20583 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20584 if (Iter == EnumMap.end())
20585 continue;
20586
20587 DeclOrVector& Entry = Iter->second;
20588 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20589 // Ensure constants are different.
20590 if (D == ECD)
20591 continue;
20592
20593 // Create new vector and push values onto it.
20594 auto Vec = std::make_unique<ECDVector>();
20595 Vec->push_back(D);
20596 Vec->push_back(ECD);
20597
20598 // Update entry to point to the duplicates vector.
20599 Entry = Vec.get();
20600
20601 // Store the vector somewhere we can consult later for quick emission of
20602 // diagnostics.
20603 DupVector.emplace_back(std::move(Vec));
20604 continue;
20605 }
20606
20607 ECDVector *Vec = cast<ECDVector *>(Entry);
20608 // Make sure constants are not added more than once.
20609 if (*Vec->begin() == ECD)
20610 continue;
20611
20612 Vec->push_back(ECD);
20613 }
20614
20615 // Emit diagnostics.
20616 for (const auto &Vec : DupVector) {
20617 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20618
20619 // Emit warning for one enum constant.
20620 auto *FirstECD = Vec->front();
20621 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20622 << FirstECD << toString(FirstECD->getInitVal(), 10)
20623 << FirstECD->getSourceRange();
20624
20625 // Emit one note for each of the remaining enum constants with
20626 // the same value.
20627 for (auto *ECD : llvm::drop_begin(*Vec))
20628 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20629 << ECD << toString(ECD->getInitVal(), 10)
20630 << ECD->getSourceRange();
20631 }
20632}
20633
20634bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20635 bool AllowMask) const {
20636 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20637 assert(ED->isCompleteDefinition() && "expected enum definition");
20638
20639 auto R = FlagBitsCache.try_emplace(ED);
20640 llvm::APInt &FlagBits = R.first->second;
20641
20642 if (R.second) {
20643 for (auto *E : ED->enumerators()) {
20644 const auto &EVal = E->getInitVal();
20645 // Only single-bit enumerators introduce new flag values.
20646 if (EVal.isPowerOf2())
20647 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20648 }
20649 }
20650
20651 // A value is in a flag enum if either its bits are a subset of the enum's
20652 // flag bits (the first condition) or we are allowing masks and the same is
20653 // true of its complement (the second condition). When masks are allowed, we
20654 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20655 //
20656 // While it's true that any value could be used as a mask, the assumption is
20657 // that a mask will have all of the insignificant bits set. Anything else is
20658 // likely a logic error.
20659 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20660 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20661}
20662
20663// Emits a warning when a suspicious comparison operator is used along side
20664// binary operators in enum initializers.
20666 const EnumDecl *Enum) {
20667 bool HasBitwiseOp = false;
20668 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20669
20670 // Iterate over all the enum values, gather suspisious comparison ops and
20671 // whether any enum initialisers contain a binary operator.
20672 for (const auto *ECD : Enum->enumerators()) {
20673 const Expr *InitExpr = ECD->getInitExpr();
20674 if (!InitExpr)
20675 continue;
20676
20677 const Expr *E = InitExpr->IgnoreParenImpCasts();
20678
20679 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20680 BinaryOperatorKind Op = BinOp->getOpcode();
20681
20682 // Check for bitwise ops (<<, >>, &, |)
20683 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20684 HasBitwiseOp = true;
20685 } else if (Op == BO_LT || Op == BO_GT) {
20686 // Check for the typo pattern (Comparison < or >)
20687 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20688 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20689 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20690 if (IntLiteral->getValue() == 1)
20691 SuspiciousCompares.push_back(BinOp);
20692 }
20693 }
20694 }
20695 }
20696
20697 // If we found a bitwise op and some sus compares, iterate over the compares
20698 // and warn.
20699 if (HasBitwiseOp) {
20700 for (const auto *BinOp : SuspiciousCompares) {
20701 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20704 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20705
20706 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20707 << BinOp->getOpcodeStr() << SuggestedOp;
20708
20709 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20710 << SuggestedOp
20711 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20712 }
20713 }
20714}
20715
20717 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20718 const ParsedAttributesView &Attrs) {
20719 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20720 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20721
20722 ProcessDeclAttributeList(S, Enum, Attrs);
20724
20725 if (Enum->isDependentType()) {
20726 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20727 EnumConstantDecl *ECD =
20728 cast_or_null<EnumConstantDecl>(Elements[i]);
20729 if (!ECD) continue;
20730
20731 ECD->setType(EnumType);
20732 }
20733
20734 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20735 return;
20736 }
20737
20738 // Verify that all the values are okay, compute the size of the values, and
20739 // reverse the list.
20740 unsigned NumNegativeBits = 0;
20741 unsigned NumPositiveBits = 0;
20742 bool MembersRepresentableByInt =
20743 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20744
20745 // Figure out the type that should be used for this enum.
20746 QualType BestType;
20747 unsigned BestWidth;
20748
20749 // C++0x N3000 [conv.prom]p3:
20750 // An rvalue of an unscoped enumeration type whose underlying
20751 // type is not fixed can be converted to an rvalue of the first
20752 // of the following types that can represent all the values of
20753 // the enumeration: int, unsigned int, long int, unsigned long
20754 // int, long long int, or unsigned long long int.
20755 // C99 6.4.4.3p2:
20756 // An identifier declared as an enumeration constant has type int.
20757 // The C99 rule is modified by C23.
20758 QualType BestPromotionType;
20759
20760 bool Packed = Enum->hasAttr<PackedAttr>();
20761 // -fshort-enums is the equivalent to specifying the packed attribute on all
20762 // enum definitions.
20763 if (LangOpts.ShortEnums)
20764 Packed = true;
20765
20766 // If the enum already has a type because it is fixed or dictated by the
20767 // target, promote that type instead of analyzing the enumerators.
20768 if (Enum->isComplete()) {
20769 BestType = Enum->getIntegerType();
20770 if (Context.isPromotableIntegerType(BestType))
20771 BestPromotionType = Context.getPromotedIntegerType(BestType);
20772 else
20773 BestPromotionType = BestType;
20774
20775 BestWidth = Context.getIntWidth(BestType);
20776 } else {
20777 bool EnumTooLarge = Context.computeBestEnumTypes(
20778 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20779 BestWidth = Context.getIntWidth(BestType);
20780 if (EnumTooLarge)
20781 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20782 }
20783
20784 // Loop over all of the enumerator constants, changing their types to match
20785 // the type of the enum if needed.
20786 for (auto *D : Elements) {
20787 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20788 if (!ECD) continue; // Already issued a diagnostic.
20789
20790 // C99 says the enumerators have int type, but we allow, as an
20791 // extension, the enumerators to be larger than int size. If each
20792 // enumerator value fits in an int, type it as an int, otherwise type it the
20793 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20794 // that X has type 'int', not 'unsigned'.
20795
20796 // Determine whether the value fits into an int.
20797 llvm::APSInt InitVal = ECD->getInitVal();
20798
20799 // If it fits into an integer type, force it. Otherwise force it to match
20800 // the enum decl type.
20801 QualType NewTy;
20802 unsigned NewWidth;
20803 bool NewSign;
20804 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20805 MembersRepresentableByInt) {
20806 // C23 6.7.3.3.3p15:
20807 // The enumeration member type for an enumerated type without fixed
20808 // underlying type upon completion is:
20809 // - int if all the values of the enumeration are representable as an
20810 // int; or,
20811 // - the enumerated type
20812 NewTy = Context.IntTy;
20813 NewWidth = Context.getTargetInfo().getIntWidth();
20814 NewSign = true;
20815 } else if (ECD->getType() == BestType) {
20816 // Already the right type!
20817 if (getLangOpts().CPlusPlus)
20818 // C++ [dcl.enum]p4: Following the closing brace of an
20819 // enum-specifier, each enumerator has the type of its
20820 // enumeration.
20821 ECD->setType(EnumType);
20822 continue;
20823 } else {
20824 NewTy = BestType;
20825 NewWidth = BestWidth;
20826 NewSign = BestType->isSignedIntegerOrEnumerationType();
20827 }
20828
20829 // Adjust the APSInt value.
20830 InitVal = InitVal.extOrTrunc(NewWidth);
20831 InitVal.setIsSigned(NewSign);
20832 ECD->setInitVal(Context, InitVal);
20833
20834 // Adjust the Expr initializer and type.
20835 if (ECD->getInitExpr() &&
20836 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20837 ECD->setInitExpr(ImplicitCastExpr::Create(
20838 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20839 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20840 if (getLangOpts().CPlusPlus)
20841 // C++ [dcl.enum]p4: Following the closing brace of an
20842 // enum-specifier, each enumerator has the type of its
20843 // enumeration.
20844 ECD->setType(EnumType);
20845 else
20846 ECD->setType(NewTy);
20847 }
20848
20849 Enum->completeDefinition(BestType, BestPromotionType,
20850 NumPositiveBits, NumNegativeBits);
20851
20852 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20854
20855 if (Enum->isClosedFlag()) {
20856 for (Decl *D : Elements) {
20857 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20858 if (!ECD) continue; // Already issued a diagnostic.
20859
20860 llvm::APSInt InitVal = ECD->getInitVal();
20861 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20862 !IsValueInFlagEnum(Enum, InitVal, true))
20863 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20864 << ECD << Enum;
20865 }
20866 }
20867
20868 // Now that the enum type is defined, ensure it's not been underaligned.
20869 if (Enum->hasAttrs())
20871}
20872
20874 SourceLocation EndLoc) {
20875
20877 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
20878 CurContext->addDecl(New);
20879 return New;
20880}
20881
20883 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20884 CurContext->addDecl(New);
20885 PushDeclContext(S, New);
20887 PushCompoundScope(false);
20888 return New;
20889}
20890
20892 if (Statement)
20893 D->setStmt(Statement);
20897}
20898
20900 IdentifierInfo* AliasName,
20901 SourceLocation PragmaLoc,
20902 SourceLocation NameLoc,
20903 SourceLocation AliasNameLoc) {
20904 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20906 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20908 AsmLabelAttr *Attr =
20909 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
20910
20911 // If a declaration that:
20912 // 1) declares a function or a variable
20913 // 2) has external linkage
20914 // already exists, add a label attribute to it.
20915 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20916 if (isDeclExternC(PrevDecl))
20917 PrevDecl->addAttr(Attr);
20918 else
20919 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20920 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20921 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20922 } else
20923 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20924}
20925
20927 SourceLocation PragmaLoc,
20928 SourceLocation NameLoc) {
20929 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20930
20931 if (PrevDecl) {
20932 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20933 } else {
20934 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20935 }
20936}
20937
20939 IdentifierInfo* AliasName,
20940 SourceLocation PragmaLoc,
20941 SourceLocation NameLoc,
20942 SourceLocation AliasNameLoc) {
20943 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20945 WeakInfo W = WeakInfo(Name, NameLoc);
20946
20947 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20948 if (!PrevDecl->hasAttr<AliasAttr>())
20949 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20951 } else {
20952 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20953 }
20954}
20955
20957 bool Final) {
20958 assert(FD && "Expected non-null FunctionDecl");
20959
20960 // SYCL functions can be template, so we check if they have appropriate
20961 // attribute prior to checking if it is a template.
20962 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20964
20965 // Templates are emitted when they're instantiated.
20966 if (FD->isDependentContext())
20968
20969 // Check whether this function is an externally visible definition.
20970 auto IsEmittedForExternalSymbol = [this, FD]() {
20971 // We have to check the GVA linkage of the function's *definition* -- if we
20972 // only have a declaration, we don't know whether or not the function will
20973 // be emitted, because (say) the definition could include "inline".
20974 const FunctionDecl *Def = FD->getDefinition();
20975
20976 // We can't compute linkage when we skip function bodies.
20977 return Def && !Def->hasSkippedBody() &&
20979 getASTContext().GetGVALinkageForFunction(Def));
20980 };
20981
20982 if (LangOpts.OpenMPIsTargetDevice) {
20983 // In OpenMP device mode we will not emit host only functions, or functions
20984 // we don't need due to their linkage.
20985 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20986 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20987 // DevTy may be changed later by
20988 // #pragma omp declare target to(*) device_type(*).
20989 // Therefore DevTy having no value does not imply host. The emission status
20990 // will be checked again at the end of compilation unit with Final = true.
20991 if (DevTy)
20992 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20994 // If we have an explicit value for the device type, or we are in a target
20995 // declare context, we need to emit all extern and used symbols.
20996 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20997 if (IsEmittedForExternalSymbol())
20999 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21000 // we'll omit it.
21001 if (Final)
21003 } else if (LangOpts.OpenMP > 45) {
21004 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21005 // function. In 5.0, no_host was introduced which might cause a function to
21006 // be omitted.
21007 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21008 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21009 if (DevTy)
21010 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21012 }
21013
21014 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21016
21017 if (LangOpts.CUDA) {
21018 // When compiling for device, host functions are never emitted. Similarly,
21019 // when compiling for host, device and global functions are never emitted.
21020 // (Technically, we do emit a host-side stub for global functions, but this
21021 // doesn't count for our purposes here.)
21023 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21025 if (!LangOpts.CUDAIsDevice &&
21028
21029 if (IsEmittedForExternalSymbol())
21031
21032 // If FD is a virtual destructor of an explicit instantiation
21033 // of a template class, return Emitted.
21034 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
21035 if (Destructor->isVirtual()) {
21036 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21037 Destructor->getParent())) {
21039 Spec->getTemplateSpecializationKind();
21043 }
21044 }
21045 }
21046 }
21047
21048 // Otherwise, the function is known-emitted if it's in our set of
21049 // known-emitted functions.
21051}
21052
21054 // Host-side references to a __global__ function refer to the stub, so the
21055 // function itself is never emitted and therefore should not be marked.
21056 // If we have host fn calls kernel fn calls host+device, the HD function
21057 // does not get instantiated on the host. We model this by omitting at the
21058 // call to the kernel from the callgraph. This ensures that, when compiling
21059 // for host, only HD functions actually called from the host get marked as
21060 // known-emitted.
21061 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21063}
21064
21066 bool &Visible) {
21067 Visible = hasVisibleDefinition(D, Suggested);
21068 // The redefinition of D in the **current** TU is allowed if D is invisible or
21069 // D is defined in the global module of other module units. We didn't check if
21070 // it is in global module as, we'll check the redefinition in named module
21071 // later with better diagnostic message.
21072 return D->isInAnotherModuleUnit() || !Visible;
21073}
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:2236
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.
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:74
#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 ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:178
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:233
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:833
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:597
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:616
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:848
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 isMainFileLoc(const Sema &S, SourceLocation Loc)
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:220
SourceManager & getSourceManager()
Definition ASTContext.h:852
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:791
const LangOptions & getLangOpts() const
Definition ASTContext.h:945
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:910
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:3489
Wrapper for source info for arrays.
Definition TypeLoc.h:1748
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1750
Expr * getSizeExpr() const
Definition TypeLoc.h:1770
TypeLoc getElementLoc() const
Definition TypeLoc.h:1778
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1758
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
QualType getElementType() const
Definition TypeBase.h:3734
Attr - This represents one attribute.
Definition Attr.h:45
attr::Kind getKind() const
Definition Attr.h:91
bool isInherited() const
Definition Attr.h:100
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:105
SourceLocation getLocation() const
Definition Attr.h:98
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
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4441
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4429
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
StringRef getOpcodeStr() const
Definition Expr.h:4038
Expr * getRHS() const
Definition Expr.h:4024
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
A binding in a decomposition declaration.
Definition DeclCXX.h:4181
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4668
bool doesNotEscape() const
Definition Decl.h:4819
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:235
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:382
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:1691
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
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:3008
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:2968
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
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:3223
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:2367
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
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:3098
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:2129
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:2703
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2755
bool isVirtual() const
Definition DeclCXX.h:2184
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:2488
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2735
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2290
bool isConst() const
Definition DeclCXX.h:2181
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2714
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
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:132
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:1366
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
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:1097
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2146
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1119
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
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:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
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:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
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:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
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:3081
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3024
arg_range arguments()
Definition Expr.h:3129
CastKind getCastKind() const
Definition Expr.h:3654
Expr * getSubExpr()
Definition Expr.h:3660
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:3760
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:214
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:254
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
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:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
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:2142
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
bool isNamespace() const
Definition DeclBase.h:2198
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:2185
bool isRecord() const
Definition DeclBase.h:2189
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:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
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:2102
DeclContext * getNonTransparentContext()
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:1270
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getBeginLoc() const
Definition Expr.h:1349
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
bool isModulePrivateSpecified() const
Definition DeclSpec.h:799
static const TST TST_typeof_unqualType
Definition DeclSpec.h:279
bool hasAutoTypeSpec() const
Definition DeclSpec.h:565
static const TST TST_typename
Definition DeclSpec.h:276
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:619
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:234
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
TST getTypeSpecType() const
Definition DeclSpec.h:507
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:834
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:679
static const TST TST_interface
Definition DeclSpec.h:274
static const TST TST_typeofExpr
Definition DeclSpec.h:278
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:586
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:678
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
bool isExternInLinkageSpec() const
Definition DeclSpec.h:475
static const TST TST_union
Definition DeclSpec.h:272
SCS
storage-class-specifier
Definition DeclSpec.h:221
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
static const TST TST_int
Definition DeclSpec.h:255
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:800
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:517
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:758
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:596
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:587
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:625
Expr * getRepAsExpr() const
Definition DeclSpec.h:525
static const TST TST_enum
Definition DeclSpec.h:271
static const TST TST_decltype
Definition DeclSpec.h:281
static bool isDeclRep(TST T)
Definition DeclSpec.h:439
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:588
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:280
static const TST TST_class
Definition DeclSpec.h:275
TypeSpecifierType TST
Definition DeclSpec.h:247
static const TST TST_void
Definition DeclSpec.h:249
void ClearConstexprSpec()
Definition DeclSpec.h:811
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:291
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
Decl * getRepAsDecl() const
Definition DeclSpec.h:521
static const TST TST_unspecified
Definition DeclSpec.h:248
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:590
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:552
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:762
static const TSCS TSCS_thread_local
Definition DeclSpec.h:237
static const TST TST_error
Definition DeclSpec.h:298
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:614
bool isTypeSpecOwned() const
Definition DeclSpec.h:511
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:591
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:589
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:791
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
static const TST TST_typeofType
Definition DeclSpec.h:277
static const TST TST_auto
Definition DeclSpec.h:288
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:802
static const TST TST_struct
Definition DeclSpec.h:273
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:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1076
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
bool isInStdNamespace() const
Definition DeclBase.cpp:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:573
bool hasAttrs() const
Definition DeclBase.h:518
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:520
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:771
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:1151
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:638
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1218
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp: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:600
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:842
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:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:594
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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:2057
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2097
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1995
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:2007
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:2041
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2430
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
Expr * getAsmLabel() const
Definition DeclSpec.h:2676
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2715
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2657
void setRedeclaration(bool Val)
Definition DeclSpec.h:2738
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2313
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2058
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2607
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2650
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2687
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2637
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
bool isRedeclaration() const
Definition DeclSpec.h:2739
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2660
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2042
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2711
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
bool hasInitializer() const
Definition DeclSpec.h:2720
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2707
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2327
bool isInvalidType() const
Definition DeclSpec.h:2688
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2300
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2723
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:2028
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2461
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
A decomposition declaration.
Definition DeclCXX.h:4245
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3682
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1762
SourceRange getSourceRange() const
Definition DeclSpec.h:1810
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1808
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2484
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2572
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2552
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2561
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
llvm::APSInt getInitVal() const
Definition Decl.h:3443
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5645
const Expr * getInitExpr() const
Definition Decl.h:3441
Represents an enum.
Definition Decl.h:4007
enumerator_range enumerators() const
Definition Decl.h:4153
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4225
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4189
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4192
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4239
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5008
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5047
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4234
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5022
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4175
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4087
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4180
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
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:3089
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:3085
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:3069
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
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:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4711
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
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:4696
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4757
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5778
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
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:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4201
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3729
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4194
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4189
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3294
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2701
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2680
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4020
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3758
param_iterator param_end()
Definition Decl.h:2787
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2695
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3702
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2389
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3610
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4309
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2448
void setWillHaveBody(bool V=true)
Definition Decl.h:2686
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2594
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2443
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4319
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3743
param_iterator param_begin()
Definition Decl.h:2786
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2823
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2326
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3134
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3371
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4253
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2888
bool isStatic() const
Definition Decl.h:2929
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4522
void setTrivial(bool IT)
Definition Decl.h:2378
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4140
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:2470
bool isDeletedAsWritten() const
Definition Decl.h:2544
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3614
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2357
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:2428
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2349
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2679
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2282
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3364
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2916
bool param_empty() const
Definition Decl.h:2785
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3219
void setRangeEnd(SourceLocation E)
Definition Decl.h:2218
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3698
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2421
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4545
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2933
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4134
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4413
void setDefaulted(bool D=true)
Definition Decl.h:2386
bool isConsteval() const
Definition Decl.h:2482
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:2862
void setBody(Stmt *B)
Definition Decl.cpp:3287
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3628
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3165
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2459
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4161
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3822
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2211
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3195
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2435
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:3242
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:2899
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3684
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5190
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5222
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5671
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5054
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5751
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5567
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
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.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Wrapper for source info for functions.
Definition TypeLoc.h:1615
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4561
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4673
CallingConv getCC() const
Definition TypeBase.h:4620
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4639
unsigned getRegParm() const
Definition TypeBase.h:4613
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4609
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4632
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4653
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4667
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3577
unsigned getRegParmType() const
Definition TypeBase.h:4793
CallingConv getCallConv() const
Definition TypeBase.h:4805
QualType getReturnType() const
Definition TypeBase.h:4790
bool getCmseNSCallAttr() const
Definition TypeBase.h:4804
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:2072
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5672
void setInherited(bool I)
Definition Attr.h:157
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2575
child_range children()
Definition Expr.h:5432
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:974
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:2083
@ 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 IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
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:1377
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3011
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3253
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
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition Lookup.h:672
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
LookupResultKind getResultKind() const
Definition Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
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:3381
Expr * getBase() const
Definition Expr.h:3375
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
Describes a module or submodule.
Definition Module.h:144
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
Module * Parent
The parent of this module.
Definition Module.h:193
bool isPrivateModule() const
Definition Module.h:249
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:664
bool isModulePartition() const
Is this a module partition.
Definition Module.h:653
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:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
@ 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:1865
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1937
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:1274
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1284
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:1159
@ CSK_Normal
Normal lookup.
Definition Overload.h:1163
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1375
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:273
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1386
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1399
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1382
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
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:2953
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2976
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:8096
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1465
Wrapper for source info for pointers.
Definition TypeLoc.h:1484
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1490
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
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:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8356
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:1453
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2920
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:109
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1214
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
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:2969
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
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:8318
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:2953
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1433
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8335
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2694
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1498
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8218
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8225
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4659
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
Represents a struct/union/class.
Definition Decl.h:4321
field_range fields() const
Definition Decl.h:4524
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5166
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4521
field_iterator field_begin() const
Definition Decl.cpp:5209
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7389
void setMemberSpecialization()
Note that this member template is a specialization.
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:5326
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3150
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3193
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:409
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:339
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:349
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:291
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:628
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:398
void RemoveDecl(Decl *D)
Definition Scope.h:370
void setLookupEntity(DeclContext *E)
Definition Scope.h:414
unsigned getMSLastManglingNumber() const
Definition Scope.h:386
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
unsigned getMSCurManglingNumber() const
Definition Scope.h:392
bool decl_empty() const
Definition Scope.h:360
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:343
Scope * getDeclParent()
Definition Scope.h:335
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:619
decl_range decls() const
Definition Scope.h:356
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:287
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:420
void applyNRVO()
Definition Scope.cpp:166
Scope * getTemplateParamParent()
Definition Scope.h:332
@ 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 CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1417
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:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:757
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:845
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:910
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:891
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:657
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:623
void deduceAddressSpace(VarDecl *Decl)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:726
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:693
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:637
void ActOnVariableDeclarator(VarDecl *VD)
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)
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:253
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body)
Definition SemaSYCL.cpp:437
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:270
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:334
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:313
bool IsAlignAttr() const
Definition Sema.h:1887
Mode getAlignMode() const
Definition Sema.h:1889
A RAII object to temporarily push a declaration context.
Definition Sema.h:3467
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1355
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1367
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3681
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3691
static NameClassification Unknown()
Definition Sema.h:3661
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3665
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3709
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3697
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3671
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3703
static NameClassification UndeclaredNonType()
Definition Sema.h:3677
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3685
static NameClassification Error()
Definition Sema.h:3657
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12436
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12470
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
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.
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:3559
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13030
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2540
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
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:8228
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6294
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9315
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9319
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9338
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9354
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9351
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9327
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9322
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.
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:1501
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...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1241
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:4731
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3541
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1813
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:6486
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:1441
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:277
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2443
Preprocessor & getPreprocessor() const
Definition Sema.h:924
void deduceOpenCLAddressSpace(ValueDecl *decl)
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2044
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2038
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:4132
@ Delete
deleted-function-body
Definition Sema.h:4138
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.
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)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1526
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:1654
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:674
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...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1283
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4356
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1486
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:78
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2041
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:3549
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:925
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:2037
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:756
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:698
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
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:1191
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:1659
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:12136
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8346
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:795
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:2331
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:168
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4569
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:920
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2349
void PopCompoundScope()
Definition Sema.cpp:2482
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:14361
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14364
@ UPPC_Initializer
An initializer.
Definition Sema.h:14376
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14370
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14349
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14388
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14373
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14352
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14355
const LangOptions & getLangOpts() const
Definition Sema.h:918
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition Sema.h:2077
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:220
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3566
SemaOpenACC & OpenACC()
Definition Sema.h:1491
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:1282
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
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:2121
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:1281
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:2558
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15439
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1451
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:1814
SemaRISCV & RISCV()
Definition Sema.h:1516
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:15615
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:213
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:1531
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:2026
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:6950
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2036
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1124
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:897
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:4746
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2477
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:6947
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.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
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:15433
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2076
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9845
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:1414
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1496
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:1634
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:3563
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:13909
SourceManager & getSourceManager() const
Definition Sema.h:923
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition Sema.h:3516
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:1815
@ NTCUK_Destruct
Definition Sema.h:4071
@ NTCUK_Init
Definition Sema.h:4070
@ NTCUK_Copy
Definition Sema.h:4072
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1812
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:6747
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
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".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
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:2498
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:6508
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:626
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.
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3537
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:273
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:1284
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4632
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6954
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1319
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1780
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9873
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
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:1506
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:75
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
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:1246
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:3556
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8301
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)
SourceManager & SourceMgr
Definition Sema.h:1286
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:1285
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:919
FPOptions CurFPFeatures
Definition Sema.h:1279
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...
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2035
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:11568
@ TPC_ClassTemplateMember
Definition Sema.h:11566
@ TPC_FunctionTemplate
Definition Sema.h:11565
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11569
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:1556
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
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:6524
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)
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...
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
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:3531
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2104
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1811
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6218
@ AbstractReturnType
Definition Sema.h:6216
@ AbstractFieldType
Definition Sema.h:6219
@ AbstractIvarType
Definition Sema.h:6220
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:8350
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:6405
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1275
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:3512
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:1541
IdentifierResolver IdResolver
Definition Sema.h:3460
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:2489
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:717
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:146
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:8309
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1274
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:3804
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:1421
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation Replaceable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8641
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:362
child_range children()
Definition Stmt.cpp:299
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1945
StringRef getString() const
Definition Expr.h:1867
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:3999
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4925
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3807
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3793
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isStruct() const
Definition Decl.h:3919
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4897
bool isUnion() const
Definition Decl.h:3922
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3944
TagKind getTagKind() const
Definition Decl.h:3911
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3857
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:226
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:102
bool isOneOf(Ts... Ks) const
Definition Token.h:103
bool isNot(tok::TokenKind K) const
Definition Token.h:109
A declaration that models statements at global scope.
Definition Decl.h:4631
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5796
void setStmt(Stmt *S)
Definition Decl.cpp:5816
Represents a declaration of a type.
Definition Decl.h:3513
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
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:1408
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:879
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:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8249
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:8260
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isStructureType() const
Definition Type.cpp:678
bool isDependentSizedArrayType() const
Definition TypeBase.h:8634
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isFunctionReferenceType() const
Definition TypeBase.h:8589
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9051
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2993
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9167
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:8618
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9031
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8614
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isPointerType() const
Definition TypeBase.h:8515
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isScalarType() const
Definition TypeBase.h:8973
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isClkEventT() const
Definition TypeBase.h:8757
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8989
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:8769
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isPipeType() const
Definition TypeBase.h:8776
bool isOpenCLSpecificType() const
Definition TypeBase.h:8805
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2411
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8875
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2056
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2557
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2776
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9044
bool isAtomicType() const
Definition TypeBase.h:8697
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isObjCIdType() const
Definition TypeBase.h:8717
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isObjCObjectType() const
Definition TypeBase.h:8688
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isEventT() const
Definition TypeBase.h:8753
bool isPointerOrReferenceType() const
Definition TypeBase.h:8519
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition TypeBase.h:9108
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8600
bool isFloatingType() const
Definition Type.cpp:2304
bool isAnyPointerType() const
Definition TypeBase.h:8523
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2061
bool isSamplerT() const
Definition TypeBase.h:8749
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5366
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isUnionType() const
Definition Type.cpp:718
bool isFunctionNoProtoType() const
Definition TypeBase.h:2600
bool isReserveIDT() const
Definition TypeBase.h:8765
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5695
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3612
QualType getUnderlyingType() const
Definition Decl.h:3617
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3623
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6099
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:2285
Opcode getOpcode() const
Definition Expr.h:2280
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2340
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1034
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1038
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1059
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1042
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1056
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1045
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
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:432
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:3395
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3459
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3427
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:5527
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5521
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2817
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2158
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1525
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:1569
TLSKind getTLSKind() const
Definition Decl.cpp:2175
bool hasInit() const
Definition Decl.cpp:2405
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
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:2267
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2197
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:2468
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2264
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
bool isCXXCondDecl() const
Definition Decl.h:1611
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:937
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:940
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2170
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1593
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2373
void setInlineSpecified()
Definition Decl.h:1558
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2779
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1342
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1173
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2436
void setConstexpr(bool IC)
Definition Decl.h:1572
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:949
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
void setInit(Expr *I)
Definition Decl.cpp:2484
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2352
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1298
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1301
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2822
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2252
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
void setImplicitlyInline()
Definition Decl.h:1563
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1476
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1588
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:2713
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1262
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:2786
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isVariableCapture() const
Definition ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1096
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
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.
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:81
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_enum
Definition Specifiers.h:79
@ TST_interface
Definition Specifiers.h:83
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
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:212
@ 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:61
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:35
@ 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:271
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ 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:602
@ TemplateTemplateArgument
Definition Sema.h:611
NonTrivialCUnionContext
Definition Sema.h:530
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:626
@ None
Don't merge availability attributes at all.
Definition Sema.h:628
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:634
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:640
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:631
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:637
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:994
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:986
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:984
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:988
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:980
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
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:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_PrivateExtern
Definition Specifiers.h:253
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:241
@ TSCS_unspecified
Definition Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:238
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:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:614
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:449
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5878
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5883
@ Struct
The "struct" keyword.
Definition TypeBase.h:5880
@ Class
The "class" keyword.
Definition TypeBase.h:5889
@ Union
The "union" keyword.
Definition TypeBase.h:5886
@ Enum
The "enum" keyword.
Definition TypeBase.h:5892
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:4314
@ TU_Complete
The translation unit is a complete translation unit.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
@ 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:135
MultiVersionKind
Definition Decl.h:1979
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:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86StdCall
Definition Specifiers.h:280
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:826
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:5874
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5871
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
@ 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:1398
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1549
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1373
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1332
const IdentifierInfo * Ident
Definition DeclSpec.h:1304
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1221
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1633
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:1614
FunctionTypeInfo Fun
Definition DeclSpec.h:1612
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1657
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
Extra information about a function prototype.
Definition TypeBase.h:5339
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5366
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5917
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3240
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:2011
SourceLocation CurrentPragmaLocation
Definition Sema.h:2012
bool CheckSameAsPrevious
Definition Sema.h:353
NamedDecl * Previous
Definition Sema.h:354
NamedDecl * New
Definition Sema.h:355
Information about a template-id annotation token.
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:1018
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009