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"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
49#include "clang/Sema/SemaARM.h"
50#include "clang/Sema/SemaCUDA.h"
51#include "clang/Sema/SemaHLSL.h"
53#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaPPC.h"
58#include "clang/Sema/SemaSYCL.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/Template.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallString.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/ADT/StringRef.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/TargetParser/Triple.h"
71#include <algorithm>
72#include <cstring>
73#include <optional>
74#include <unordered_map>
75
76using namespace clang;
77using namespace sema;
78
80 if (OwnedType) {
81 Decl *Group[2] = { OwnedType, Ptr };
83 }
84
86}
87
88namespace {
89
90class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
91 public:
92 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
93 bool AllowTemplates = false,
94 bool AllowNonTemplates = true)
95 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
96 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
97 WantExpressionKeywords = false;
98 WantCXXNamedCasts = false;
99 WantRemainingKeywords = false;
100 }
101
102 bool ValidateCandidate(const TypoCorrection &candidate) override {
103 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
104 if (!AllowInvalidDecl && ND->isInvalidDecl())
105 return false;
106
107 if (getAsTypeTemplateDecl(ND))
108 return AllowTemplates;
109
110 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
111 if (!IsType)
112 return false;
113
114 if (AllowNonTemplates)
115 return true;
116
117 // An injected-class-name of a class template (specialization) is valid
118 // as a template or as a non-template.
119 if (AllowTemplates) {
120 auto *RD = dyn_cast<CXXRecordDecl>(ND);
121 if (!RD || !RD->isInjectedClassName())
122 return false;
123 RD = cast<CXXRecordDecl>(RD->getDeclContext());
124 return RD->getDescribedClassTemplate() ||
126 }
127
128 return false;
129 }
130
131 return !WantClassName && candidate.isKeyword();
132 }
133
134 std::unique_ptr<CorrectionCandidateCallback> clone() override {
135 return std::make_unique<TypeNameValidatorCCC>(*this);
136 }
137
138 private:
139 bool AllowInvalidDecl;
140 bool WantClassName;
141 bool AllowTemplates;
142 bool AllowNonTemplates;
143};
144
145} // end anonymous namespace
146
148 TypeDecl *TD, SourceLocation NameLoc) {
149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
150 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
151 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
152 FoundRD->isInjectedClassName() &&
153 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
154 Diag(NameLoc,
156 ? diag::ext_out_of_line_qualified_id_type_names_constructor
157 : diag::err_out_of_line_qualified_id_type_names_constructor)
158 << TD->getIdentifier() << /*Type=*/1
159 << 0 /*if any keyword was present, it was 'typename'*/;
160 }
161
162 DiagnoseUseOfDecl(TD, NameLoc);
163 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
164}
165
166namespace {
167enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171};
172} // end anonymous namespace
173
174/// Tries to perform unqualified lookup of the type decls in bases for
175/// dependent class.
176/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177/// type decl, \a FoundType if only type decls are found.
178static UnqualifiedTypeNameLookupResult
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
189 if (BaseRD) {
190 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
191 Base.getType().getCanonicalType())) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
205 CTD->findPartialSpecialization(Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(&II)) {
213 if (!isa<TypeDecl>(ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232}
233
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
255 // allowed. We'll fully resolve the lookup during template instantiation.
256 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
257
258 ASTContext &Context = S.Context;
259 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
260 QualType T =
261 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
272}
273
275 Scope *S, CXXScopeSpec *SS, bool isClassName,
276 bool HasTrailingDot, ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 ImplicitTypenameContext AllowImplicitTypename,
281 IdentifierInfo **CorrectedII) {
282 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
283 // FIXME: Consider allowing this outside C++1z mode as an extension.
284 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
285 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
286 !HasTrailingDot;
287
288 // Determine where we will perform name lookup.
289 DeclContext *LookupCtx = nullptr;
290 if (ObjectTypePtr) {
291 QualType ObjectType = ObjectTypePtr.get();
292 if (ObjectType->isRecordType())
293 LookupCtx = computeDeclContext(ObjectType);
294 } else if (SS && SS->isNotEmpty()) {
295 LookupCtx = computeDeclContext(*SS, false);
296
297 if (!LookupCtx) {
298 if (isDependentScopeSpecifier(*SS)) {
299 // C++ [temp.res]p3:
300 // A qualified-id that refers to a type and in which the
301 // nested-name-specifier depends on a template-parameter (14.6.2)
302 // shall be prefixed by the keyword typename to indicate that the
303 // qualified-id denotes a type, forming an
304 // elaborated-type-specifier (7.1.5.3).
305 //
306 // We therefore do not perform any name lookup if the result would
307 // refer to a member of an unknown specialization.
308 // In C++2a, in several contexts a 'typename' is not required. Also
309 // allow this as an extension.
310 if (IsImplicitTypename) {
311 if (AllowImplicitTypename == ImplicitTypenameContext::No)
312 return nullptr;
313 SourceLocation QualifiedLoc = SS->getRange().getBegin();
314 // FIXME: Defer the diagnostic after we build the type and use it.
315 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
316 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
317 SS->getScopeRep(), &II);
319 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
320 }
321
322 // We know from the grammar that this name refers to a type,
323 // so build a dependent node to describe the type.
324 if (WantNontrivialTypeSourceInfo)
325 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
326 (ImplicitTypenameContext)IsImplicitTypename)
327 .get();
328
331 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
333 SourceLocation(), QualifierLoc, II, NameLoc);
334 return ParsedType::make(T);
335 }
336
337 return nullptr;
338 }
339
340 if (!LookupCtx->isDependentContext() &&
341 RequireCompleteDeclContext(*SS, LookupCtx))
342 return nullptr;
343 }
344
345 // In the case where we know that the identifier is a class name, we know that
346 // it is a type declaration (struct, class, union or enum) so we can use tag
347 // name lookup.
348 //
349 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
350 // the component name of the type-name or simple-template-id is type-only.
351 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
352 LookupResult Result(*this, &II, NameLoc, Kind);
353 if (LookupCtx) {
354 // Perform "qualified" name lookup into the declaration context we
355 // computed, which is either the type of the base of a member access
356 // expression or the declaration context associated with a prior
357 // nested-name-specifier.
358 LookupQualifiedName(Result, LookupCtx);
359
360 if (ObjectTypePtr && Result.empty()) {
361 // C++ [basic.lookup.classref]p3:
362 // If the unqualified-id is ~type-name, the type-name is looked up
363 // in the context of the entire postfix-expression. If the type T of
364 // the object expression is of a class type C, the type-name is also
365 // looked up in the scope of class C. At least one of the lookups shall
366 // find a name that refers to (possibly cv-qualified) T.
367 LookupName(Result, S);
368 }
369 } else {
370 // Perform unqualified name lookup.
371 LookupName(Result, S);
372
373 // For unqualified lookup in a class template in MSVC mode, look into
374 // dependent base classes where the primary class template is known.
375 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
376 if (ParsedType TypeInBase =
377 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
378 return TypeInBase;
379 }
380 }
381
382 NamedDecl *IIDecl = nullptr;
383 UsingShadowDecl *FoundUsingShadow = nullptr;
384 switch (Result.getResultKind()) {
386 if (CorrectedII) {
387 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
388 AllowDeducedTemplate);
389 TypoCorrection Correction =
390 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
392 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
394 bool MemberOfUnknownSpecialization;
396 TemplateName.setIdentifier(NewII, NameLoc);
398 CXXScopeSpec NewSS, *NewSSPtr = SS;
399 if (SS && NNS) {
400 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
401 NewSSPtr = &NewSS;
402 }
403 if (Correction && (NNS || NewII != &II) &&
404 // Ignore a correction to a template type as the to-be-corrected
405 // identifier is not a template (typo correction for template names
406 // is handled elsewhere).
407 !(getLangOpts().CPlusPlus && NewSSPtr &&
408 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
409 Template, MemberOfUnknownSpecialization))) {
410 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
411 isClassName, HasTrailingDot, ObjectTypePtr,
412 IsCtorOrDtorName,
413 WantNontrivialTypeSourceInfo,
414 IsClassTemplateDeductionContext);
415 if (Ty) {
416 diagnoseTypo(Correction,
417 PDiag(diag::err_unknown_type_or_class_name_suggest)
418 << Result.getLookupName() << isClassName);
419 if (SS && NNS)
420 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
421 *CorrectedII = NewII;
422 return Ty;
423 }
424 }
425 }
426 Result.suppressDiagnostics();
427 return nullptr;
429 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
430 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
431 SS->getScopeRep(), &II);
432 TypeLocBuilder TLB;
436 TL.setNameLoc(NameLoc);
438 }
439 [[fallthrough]];
442 Result.suppressDiagnostics();
443 return nullptr;
444
446 // Recover from type-hiding ambiguities by hiding the type. We'll
447 // do the lookup again when looking for an object, and we can
448 // diagnose the error then. If we don't do this, then the error
449 // about hiding the type will be immediately followed by an error
450 // that only makes sense if the identifier was treated like a type.
451 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
452 Result.suppressDiagnostics();
453 return nullptr;
454 }
455
456 // Look to see if we have a type anywhere in the list of results.
457 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
458 Res != ResEnd; ++Res) {
459 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
461 RealRes) ||
462 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
463 if (!IIDecl ||
464 // Make the selection of the recovery decl deterministic.
465 RealRes->getLocation() < IIDecl->getLocation()) {
466 IIDecl = RealRes;
467 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
468 }
469 }
470 }
471
472 if (!IIDecl) {
473 // None of the entities we found is a type, so there is no way
474 // to even assume that the result is a type. In this case, don't
475 // complain about the ambiguity. The parser will either try to
476 // perform this lookup again (e.g., as an object name), which
477 // will produce the ambiguity, or will complain that it expected
478 // a type name.
479 Result.suppressDiagnostics();
480 return nullptr;
481 }
482
483 // We found a type within the ambiguous lookup; diagnose the
484 // ambiguity and then return that type. This might be the right
485 // answer, or it might not be, but it suppresses any attempt to
486 // perform the name lookup again.
487 break;
488
490 IIDecl = Result.getFoundDecl();
491 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
492 break;
493 }
494
495 assert(IIDecl && "Didn't find decl");
496
497 TypeLocBuilder TLB;
498 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
499 checkTypeDeclType(LookupCtx,
500 IsImplicitTypename ? DiagCtorKind::Implicit
502 TD, NameLoc);
503 QualType T;
504 if (FoundUsingShadow) {
506 SS ? SS->getScopeRep() : std::nullopt,
507 FoundUsingShadow);
508 if (!WantNontrivialTypeSourceInfo)
509 return ParsedType::make(T);
510 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 NameLoc);
514 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
516 SS ? SS->getScopeRep() : std::nullopt, Tag,
517 /*OwnsTag=*/false);
518 if (!WantNontrivialTypeSourceInfo)
519 return ParsedType::make(T);
520 auto TL = TLB.push<TagTypeLoc>(T);
522 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
524 TL.setNameLoc(NameLoc);
525 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
526 TN && !isa<ObjCTypeParamDecl>(TN)) {
527 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
528 SS ? SS->getScopeRep() : std::nullopt, TN);
529 if (!WantNontrivialTypeSourceInfo)
530 return ParsedType::make(T);
531 TLB.push<TypedefTypeLoc>(T).set(
532 /*ElaboratedKeywordLoc=*/SourceLocation(),
534 NameLoc);
535 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
536 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
537 SS ? SS->getScopeRep() : std::nullopt,
538 UD);
539 if (!WantNontrivialTypeSourceInfo)
540 return ParsedType::make(T);
541 TLB.push<UnresolvedUsingTypeLoc>(T).set(
542 /*ElaboratedKeywordLoc=*/SourceLocation(),
544 NameLoc);
545 } else {
546 T = Context.getTypeDeclType(TD);
547 if (!WantNontrivialTypeSourceInfo)
548 return ParsedType::make(T);
550 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
551 else
552 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
553 }
555 }
556 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
557 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
558 if (!HasTrailingDot) {
559 // FIXME: Support UsingType for this case.
560 QualType T = Context.getObjCInterfaceType(IDecl);
561 if (!WantNontrivialTypeSourceInfo)
562 return ParsedType::make(T);
563 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
564 TL.setNameLoc(NameLoc);
565 // FIXME: Pass in this source location.
566 TL.setNameEndLoc(NameLoc);
568 }
569 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(UD, NameLoc);
571 // Recover with 'int'
572 return ParsedType::make(Context.IntTy);
573 } else if (AllowDeducedTemplate) {
574 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
575 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
576 // FIXME: Support UsingType here.
577 TemplateName Template = Context.getQualifiedTemplateName(
578 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
579 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
580 QualType T = Context.getDeducedTemplateSpecializationType(
584 TL.setNameLoc(NameLoc);
585 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
588 }
589 }
590
591 // As it's not plausibly a type, suppress diagnostics.
592 Result.suppressDiagnostics();
593 return nullptr;
594}
595
596// Builds a fake NNS for the given decl context.
599 for (;; DC = DC->getLookupParent()) {
600 DC = DC->getPrimaryContext();
601 auto *ND = dyn_cast<NamespaceDecl>(DC);
602 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
603 return NestedNameSpecifier(Context, ND, std::nullopt);
604 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
605 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
608 }
609 llvm_unreachable("something isn't in TU scope?");
610}
611
612/// Find the parent class with dependent bases of the innermost enclosing method
613/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
614/// up allowing unqualified dependent type names at class-level, which MSVC
615/// correctly rejects.
616static const CXXRecordDecl *
618 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
619 DC = DC->getPrimaryContext();
620 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
621 if (MD->getParent()->hasAnyDependentBases())
622 return MD->getParent();
623 }
624 return nullptr;
625}
626
628 SourceLocation NameLoc,
629 bool IsTemplateTypeArg) {
630 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
631
632 NestedNameSpecifier NNS = std::nullopt;
633 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
634 // If we weren't able to parse a default template argument, delay lookup
635 // until instantiation time by making a non-dependent DependentTypeName. We
636 // pretend we saw a NestedNameSpecifier referring to the current scope, and
637 // lookup is retried.
638 // FIXME: This hurts our diagnostic quality, since we get errors like "no
639 // type named 'Foo' in 'current_namespace'" when the user didn't write any
640 // name specifiers.
642 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
643 } else if (const CXXRecordDecl *RD =
645 // Build a DependentNameType that will perform lookup into RD at
646 // instantiation time.
647 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
648
649 // Diagnose that this identifier was undeclared, and retry the lookup during
650 // template instantiation.
651 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
652 << RD;
653 } else {
654 // This is not a situation that we should recover from.
655 return ParsedType();
656 }
657
658 QualType T =
659 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
660
661 // Build type location information. We synthesized the qualifier, so we have
662 // to build a fake NestedNameSpecifierLoc.
663 NestedNameSpecifierLocBuilder NNSLocBuilder;
664 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
665 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
666
667 TypeLocBuilder Builder;
668 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
669 DepTL.setNameLoc(NameLoc);
671 DepTL.setQualifierLoc(QualifierLoc);
672 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
673}
674
676 // Do a tag name lookup in this scope.
677 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
678 LookupName(R, S, false);
681 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
682 switch (TD->getTagKind()) {
688 return DeclSpec::TST_union;
690 return DeclSpec::TST_class;
692 return DeclSpec::TST_enum;
693 }
694 }
695
697}
698
700 if (!CurContext->isRecord())
701 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
702
703 switch (SS->getScopeRep().getKind()) {
705 return true;
707 QualType T(SS->getScopeRep().getAsType(), 0);
708 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
709 if (Context.hasSameUnqualifiedType(T, Base.getType()))
710 return true;
711 [[fallthrough]];
712 }
713 default:
714 return S->isFunctionPrototypeScope();
715 }
716}
717
719 SourceLocation IILoc,
720 Scope *S,
721 CXXScopeSpec *SS,
722 ParsedType &SuggestedType,
723 bool IsTemplateName) {
724 // Don't report typename errors for editor placeholders.
725 if (II->isEditorPlaceholder())
726 return;
727 // We don't have anything to suggest (yet).
728 SuggestedType = nullptr;
729
730 // There may have been a typo in the name of the type. Look up typo
731 // results, in case we have something that we can suggest.
732 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
733 /*AllowTemplates=*/IsTemplateName,
734 /*AllowNonTemplates=*/!IsTemplateName);
735 if (TypoCorrection Corrected =
738 // FIXME: Support error recovery for the template-name case.
739 bool CanRecover = !IsTemplateName;
740 if (Corrected.isKeyword()) {
741 // We corrected to a keyword.
742 diagnoseTypo(Corrected,
743 PDiag(IsTemplateName ? diag::err_no_template_suggest
744 : diag::err_unknown_typename_suggest)
745 << II);
746 II = Corrected.getCorrectionAsIdentifierInfo();
747 } else {
748 // We found a similarly-named type or interface; suggest that.
749 if (!SS || !SS->isSet()) {
750 diagnoseTypo(Corrected,
751 PDiag(IsTemplateName ? diag::err_no_template_suggest
752 : diag::err_unknown_typename_suggest)
753 << II, CanRecover);
754 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
755 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
756 bool DroppedSpecifier =
757 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
758 diagnoseTypo(Corrected,
759 PDiag(IsTemplateName
760 ? diag::err_no_member_template_suggest
761 : diag::err_unknown_nested_typename_suggest)
762 << II << DC << DroppedSpecifier << SS->getRange(),
763 CanRecover);
764 } else {
765 llvm_unreachable("could not have corrected a typo here");
766 }
767
768 if (!CanRecover)
769 return;
770
771 CXXScopeSpec tmpSS;
772 if (Corrected.getCorrectionSpecifier())
773 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
774 SourceRange(IILoc));
775 // FIXME: Support class template argument deduction here.
776 SuggestedType =
777 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
778 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
779 /*IsCtorOrDtorName=*/false,
780 /*WantNontrivialTypeSourceInfo=*/true);
781 }
782 return;
783 }
784
785 if (getLangOpts().CPlusPlus && !IsTemplateName) {
786 // See if II is a class template that the user forgot to pass arguments to.
787 UnqualifiedId Name;
788 Name.setIdentifier(II, IILoc);
789 CXXScopeSpec EmptySS;
790 TemplateTy TemplateResult;
791 bool MemberOfUnknownSpecialization;
792 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
793 Name, nullptr, true, TemplateResult,
794 MemberOfUnknownSpecialization) == TNK_Type_template) {
795 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
796 return;
797 }
798 }
799
800 // FIXME: Should we move the logic that tries to recover from a missing tag
801 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
802
803 if (!SS || (!SS->isSet() && !SS->isInvalid()))
804 Diag(IILoc, IsTemplateName ? diag::err_no_template
805 : diag::err_unknown_typename)
806 << II;
807 else if (DeclContext *DC = computeDeclContext(*SS, false))
808 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
809 : diag::err_typename_nested_not_found)
810 << II << DC << SS->getRange();
811 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
812 SuggestedType =
813 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
814 } else if (isDependentScopeSpecifier(*SS)) {
815 unsigned DiagID = diag::err_typename_missing;
816 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
817 DiagID = diag::ext_typename_missing;
818
819 SuggestedType =
820 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
821
822 Diag(SS->getRange().getBegin(), DiagID)
823 << GetTypeFromParser(SuggestedType)
824 << SourceRange(SS->getRange().getBegin(), IILoc)
825 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
826 } else {
827 assert(SS && SS->isInvalid() &&
828 "Invalid scope specifier has already been diagnosed");
829 }
830}
831
832/// Determine whether the given result set contains either a type name
833/// or
834static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
835 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
836 NextToken.is(tok::less);
837
838 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
840 return true;
841
842 if (CheckTemplate && isa<TemplateDecl>(*I))
843 return true;
844 }
845
846 return false;
847}
848
849static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
850 Scope *S, CXXScopeSpec &SS,
851 IdentifierInfo *&Name,
852 SourceLocation NameLoc) {
853 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
854 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
855 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
856 StringRef FixItTagName;
857 switch (Tag->getTagKind()) {
859 FixItTagName = "class ";
860 break;
861
863 FixItTagName = "enum ";
864 break;
865
867 FixItTagName = "struct ";
868 break;
869
871 FixItTagName = "__interface ";
872 break;
873
875 FixItTagName = "union ";
876 break;
877 }
878
879 StringRef TagName = FixItTagName.drop_back();
880 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
881 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
882 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
883
884 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
885 I != IEnd; ++I)
886 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
887 << Name << TagName;
888
889 // Replace lookup results with just the tag decl.
890 Result.clear(Sema::LookupTagName);
891 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
892 return true;
893 }
894
895 return false;
896}
897
899 IdentifierInfo *&Name,
900 SourceLocation NameLoc,
901 const Token &NextToken,
903 DeclarationNameInfo NameInfo(Name, NameLoc);
904 ObjCMethodDecl *CurMethod = getCurMethodDecl();
905
906 assert(NextToken.isNot(tok::coloncolon) &&
907 "parse nested name specifiers before calling ClassifyName");
908 if (getLangOpts().CPlusPlus && SS.isSet() &&
909 isCurrentClassName(*Name, S, &SS)) {
910 // Per [class.qual]p2, this names the constructors of SS, not the
911 // injected-class-name. We don't have a classification for that.
912 // There's not much point caching this result, since the parser
913 // will reject it later.
915 }
916
917 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
918 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
919 /*AllowBuiltinCreation=*/!CurMethod);
920
921 if (SS.isInvalid())
923
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927 if (ParsedType TypeInBase =
928 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
929 return TypeInBase;
930 }
931
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
937 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
938 if (Ivar.isInvalid())
940 if (Ivar.isUsable())
942
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
944 if (Result.empty())
946 }
947
948 bool SecondTry = false;
949 bool IsFilteredTemplateName = false;
950
951Corrected:
952 switch (Result.getResultKind()) {
954 // If an unqualified-id is followed by a '(', then we have a function
955 // call.
956 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
957 // In C++, this is an ADL-only call.
958 // FIXME: Reference?
961
962 // C90 6.3.2.2:
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
968 //
969 // extern int identifier ();
970 //
971 // appeared.
972 //
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
975 // be supported.
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
979 }
980 }
981
982 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
985 //
986 // FIXME: Find a way to still do typo correction in this case.
988 Context.getAssumedTemplateName(NameInfo.getName());
990 }
991
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus && !SecondTry &&
996 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
997 break;
998 }
999
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry && CCC) {
1003 SecondTry = true;
1004 if (TypoCorrection Corrected =
1005 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1006 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1007 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008 unsigned QualifiedDiag = diag::err_no_member_suggest;
1009
1010 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1013 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1014 UnqualifiedDiag = diag::err_no_template_suggest;
1015 QualifiedDiag = diag::err_no_member_template_suggest;
1016 } else if (UnderlyingFirstDecl &&
1017 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1018 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1020 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022 }
1023
1024 if (SS.isEmpty()) {
1025 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1028 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029 Name->getName() == CorrectedStr;
1030 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1031 << Name << computeDeclContext(SS, false)
1032 << DroppedSpecifier << SS.getRange());
1033 }
1034
1035 // Update the name, so that the caller has the new name.
1036 Name = Corrected.getCorrectionAsIdentifierInfo();
1037
1038 // Typo correction corrected to a keyword.
1039 if (Corrected.isKeyword())
1040 return Name;
1041
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1044 Result.clear();
1045 Result.setLookupName(Corrected.getCorrection());
1046 if (FirstDecl)
1047 Result.addDecl(FirstDecl);
1048
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054 DeclResult R =
1055 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1056 if (R.isInvalid())
1058 if (R.isUsable())
1059 return NameClassification::NonType(Ivar);
1060 }
1061
1062 goto Corrected;
1063 }
1064 }
1065
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result.suppressDiagnostics();
1069
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1074
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1080 //
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1084 // keyword here.
1086 }
1087
1091 break;
1092
1094 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1095 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1104 // ambiguous.
1105 //
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1109 if (!Result.isAmbiguous()) {
1110 IsFilteredTemplateName = true;
1111 break;
1112 }
1113 }
1114
1115 // Diagnose the ambiguity and return an error.
1117 }
1118
1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120 (IsFilteredTemplateName ||
1122 Result, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName)
1138
1139 bool IsFunctionTemplate;
1140 bool IsVarTemplate;
1142 if (Result.end() - Result.begin() > 1) {
1143 IsFunctionTemplate = true;
1144 Template = Context.getOverloadedTemplateName(Result.begin(),
1145 Result.end());
1146 } else if (!Result.empty()) {
1148 *Result.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1151 IsVarTemplate = isa<VarTemplateDecl>(TD);
1152
1153 UsingShadowDecl *FoundUsingShadow =
1154 dyn_cast<UsingShadowDecl>(*Result.begin());
1155 assert(!FoundUsingShadow ||
1156 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1157 Template = Context.getQualifiedTemplateName(
1158 SS.getScopeRep(),
1159 /*TemplateKeyword=*/false,
1160 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1161 } else {
1162 // All results were non-template functions. This is a function template
1163 // name.
1164 IsFunctionTemplate = true;
1165 Template = Context.getAssumedTemplateName(NameInfo.getName());
1166 }
1167
1168 if (IsFunctionTemplate) {
1169 // Function templates always go through overload resolution, at which
1170 // point we'll perform the various checks (e.g., accessibility) we need
1171 // to based on which function we selected.
1172 Result.suppressDiagnostics();
1173
1175 }
1176
1177 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1179 }
1180
1181 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1182 QualType T;
1183 TypeLocBuilder TLB;
1184 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1185 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1186 USD);
1187 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1188 SS.getWithLocInContext(Context), NameLoc);
1189 } else {
1190 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1191 Type);
1192 if (isa<TagType>(T)) {
1193 auto TTL = TLB.push<TagTypeLoc>(T);
1195 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1196 TTL.setNameLoc(NameLoc);
1197 } else if (isa<TypedefType>(T)) {
1198 TLB.push<TypedefTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 SS.getWithLocInContext(Context), NameLoc);
1201 } else if (isa<UnresolvedUsingType>(T)) {
1202 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1203 /*ElaboratedKeywordLoc=*/SourceLocation(),
1204 SS.getWithLocInContext(Context), NameLoc);
1205 } else {
1206 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1207 }
1208 }
1210 };
1211
1212 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1213 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1214 DiagnoseUseOfDecl(Type, NameLoc);
1215 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1216 return BuildTypeFor(Type, *Result.begin());
1217 }
1218
1219 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1220 if (!Class) {
1221 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1222 if (ObjCCompatibleAliasDecl *Alias =
1223 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1224 Class = Alias->getClassInterface();
1225 }
1226
1227 if (Class) {
1228 DiagnoseUseOfDecl(Class, NameLoc);
1229
1230 if (NextToken.is(tok::period)) {
1231 // Interface. <something> is parsed as a property reference expression.
1232 // Just return "unknown" as a fall-through for now.
1233 Result.suppressDiagnostics();
1235 }
1236
1237 QualType T = Context.getObjCInterfaceType(Class);
1238 return ParsedType::make(T);
1239 }
1240
1242 // We want to preserve the UsingShadowDecl for concepts.
1243 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1247 }
1248
1249 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1250 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1252 }
1253
1254 // We can have a type template here if we're classifying a template argument.
1259
1260 // Check for a tag type hidden by a non-type decl in a few cases where it
1261 // seems likely a type is wanted instead of the non-type that was found.
1262 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1263 if ((NextToken.is(tok::identifier) ||
1264 (NextIsOp &&
1265 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1266 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1267 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1268 DiagnoseUseOfDecl(Type, NameLoc);
1269 return BuildTypeFor(Type, *Result.begin());
1270 }
1271
1272 // If we already know which single declaration is referenced, just annotate
1273 // that declaration directly. Defer resolving even non-overloaded class
1274 // member accesses, as we need to defer certain access checks until we know
1275 // the context.
1276 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1277 if (Result.isSingleResult() && !ADL &&
1278 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1279 return NameClassification::NonType(Result.getRepresentativeDecl());
1280
1281 // Otherwise, this is an overload set that we will need to resolve later.
1282 Result.suppressDiagnostics();
1284 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1285 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1286 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1287}
1288
1291 SourceLocation NameLoc) {
1292 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1293 CXXScopeSpec SS;
1294 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1295 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1296}
1297
1300 IdentifierInfo *Name,
1301 SourceLocation NameLoc,
1302 bool IsAddressOfOperand) {
1303 DeclarationNameInfo NameInfo(Name, NameLoc);
1304 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1305 NameInfo, IsAddressOfOperand,
1306 /*TemplateArgs=*/nullptr);
1307}
1308
1311 SourceLocation NameLoc,
1312 const Token &NextToken) {
1313 if (getCurMethodDecl() && SS.isEmpty())
1314 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1315 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1316
1317 // Reconstruct the lookup result.
1318 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1319 Result.addDecl(Found);
1320 Result.resolveKind();
1321
1322 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1323 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1324}
1325
1327 // For an implicit class member access, transform the result into a member
1328 // access expression if necessary.
1329 auto *ULE = cast<UnresolvedLookupExpr>(E);
1330 if ((*ULE->decls_begin())->isCXXClassMember()) {
1331 CXXScopeSpec SS;
1332 SS.Adopt(ULE->getQualifierLoc());
1333
1334 // Reconstruct the lookup result.
1335 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1337 Result.setNamingClass(ULE->getNamingClass());
1338 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1339 Result.addDecl(*I, I.getAccess());
1340 Result.resolveKind();
1342 nullptr, S);
1343 }
1344
1345 // Otherwise, this is already in the form we needed, and no further checks
1346 // are necessary.
1347 return ULE;
1348}
1349
1369
1371 assert(DC->getLexicalParent() == CurContext &&
1372 "The next DeclContext should be lexically contained in the current one.");
1373 CurContext = DC;
1374 S->setEntity(DC);
1375}
1376
1378 assert(CurContext && "DeclContext imbalance!");
1379
1380 CurContext = CurContext->getLexicalParent();
1381 assert(CurContext && "Popped translation unit!");
1382}
1383
1385 Decl *D) {
1386 // Unlike PushDeclContext, the context to which we return is not necessarily
1387 // the containing DC of TD, because the new context will be some pre-existing
1388 // TagDecl definition instead of a fresh one.
1389 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1390 CurContext = cast<TagDecl>(D)->getDefinition();
1391 assert(CurContext && "skipping definition of undefined tag");
1392 // Start lookups from the parent of the current context; we don't want to look
1393 // into the pre-existing complete definition.
1394 S->setEntity(CurContext->getLookupParent());
1395 return Result;
1396}
1397
1401
1403 // C++0x [basic.lookup.unqual]p13:
1404 // A name used in the definition of a static data member of class
1405 // X (after the qualified-id of the static member) is looked up as
1406 // if the name was used in a member function of X.
1407 // C++0x [basic.lookup.unqual]p14:
1408 // If a variable member of a namespace is defined outside of the
1409 // scope of its namespace then any name used in the definition of
1410 // the variable member (after the declarator-id) is looked up as
1411 // if the definition of the variable member occurred in its
1412 // namespace.
1413 // Both of these imply that we should push a scope whose context
1414 // is the semantic context of the declaration. We can't use
1415 // PushDeclContext here because that context is not necessarily
1416 // lexically contained in the current context. Fortunately,
1417 // the containing scope should have the appropriate information.
1418
1419 assert(!S->getEntity() && "scope already has entity");
1420
1421#ifndef NDEBUG
1422 Scope *Ancestor = S->getParent();
1423 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1424 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1425#endif
1426
1427 CurContext = DC;
1428 S->setEntity(DC);
1429
1430 if (S->getParent()->isTemplateParamScope()) {
1431 // Also set the corresponding entities for all immediately-enclosing
1432 // template parameter scopes.
1434 }
1435}
1436
1438 assert(S->getEntity() == CurContext && "Context imbalance!");
1439
1440 // Switch back to the lexical context. The safety of this is
1441 // enforced by an assert in EnterDeclaratorContext.
1442 Scope *Ancestor = S->getParent();
1443 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1444 CurContext = Ancestor->getEntity();
1445
1446 // We don't need to do anything with the scope, which is going to
1447 // disappear.
1448}
1449
1451 assert(S->isTemplateParamScope() &&
1452 "expected to be initializing a template parameter scope");
1453
1454 // C++20 [temp.local]p7:
1455 // In the definition of a member of a class template that appears outside
1456 // of the class template definition, the name of a member of the class
1457 // template hides the name of a template-parameter of any enclosing class
1458 // templates (but not a template-parameter of the member if the member is a
1459 // class or function template).
1460 // C++20 [temp.local]p9:
1461 // In the definition of a class template or in the definition of a member
1462 // of such a template that appears outside of the template definition, for
1463 // each non-dependent base class (13.8.2.1), if the name of the base class
1464 // or the name of a member of the base class is the same as the name of a
1465 // template-parameter, the base class name or member name hides the
1466 // template-parameter name (6.4.10).
1467 //
1468 // This means that a template parameter scope should be searched immediately
1469 // after searching the DeclContext for which it is a template parameter
1470 // scope. For example, for
1471 // template<typename T> template<typename U> template<typename V>
1472 // void N::A<T>::B<U>::f(...)
1473 // we search V then B<U> (and base classes) then U then A<T> (and base
1474 // classes) then T then N then ::.
1475 unsigned ScopeDepth = getTemplateDepth(S);
1476 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1477 DeclContext *SearchDCAfterScope = DC;
1478 for (; DC; DC = DC->getLookupParent()) {
1479 if (const TemplateParameterList *TPL =
1480 cast<Decl>(DC)->getDescribedTemplateParams()) {
1481 unsigned DCDepth = TPL->getDepth() + 1;
1482 if (DCDepth > ScopeDepth)
1483 continue;
1484 if (ScopeDepth == DCDepth)
1485 SearchDCAfterScope = DC = DC->getLookupParent();
1486 break;
1487 }
1488 }
1489 S->setLookupEntity(SearchDCAfterScope);
1490 }
1491}
1492
1494 // We assume that the caller has already called
1495 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1496 FunctionDecl *FD = D->getAsFunction();
1497 if (!FD)
1498 return;
1499
1500 // Same implementation as PushDeclContext, but enters the context
1501 // from the lexical parent, rather than the top-level class.
1502 assert(CurContext == FD->getLexicalParent() &&
1503 "The next DeclContext should be lexically contained in the current one.");
1504 CurContext = FD;
1506
1507 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1508 ParmVarDecl *Param = FD->getParamDecl(P);
1509 // If the parameter has an identifier, then add it to the scope
1510 if (Param->getIdentifier()) {
1511 S->AddDecl(Param);
1512 IdResolver.AddDecl(Param);
1513 }
1514 }
1515}
1516
1518 // Same implementation as PopDeclContext, but returns to the lexical parent,
1519 // rather than the top-level class.
1520 assert(CurContext && "DeclContext imbalance!");
1521 CurContext = CurContext->getLexicalParent();
1522 assert(CurContext && "Popped translation unit!");
1523}
1524
1525/// Determine whether overloading is allowed for a new function
1526/// declaration considering prior declarations of the same name.
1527///
1528/// This routine determines whether overloading is possible, not
1529/// whether a new declaration actually overloads a previous one.
1530/// It will return true in C++ (where overloads are always permitted)
1531/// or, as a C extension, when either the new declaration or a
1532/// previous one is declared with the 'overloadable' attribute.
1534 ASTContext &Context,
1535 const FunctionDecl *New) {
1536 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1537 return true;
1538
1539 // Multiversion function declarations are not overloads in the
1540 // usual sense of that term, but lookup will report that an
1541 // overload set was found if more than one multiversion function
1542 // declaration is present for the same name. It is therefore
1543 // inadequate to assume that some prior declaration(s) had
1544 // the overloadable attribute; checking is required. Since one
1545 // declaration is permitted to omit the attribute, it is necessary
1546 // to check at least two; hence the 'any_of' check below. Note that
1547 // the overloadable attribute is implicitly added to declarations
1548 // that were required to have it but did not.
1549 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1550 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1551 return ND->hasAttr<OverloadableAttr>();
1552 });
1553 } else if (Previous.getResultKind() == LookupResultKind::Found)
1554 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1555
1556 return false;
1557}
1558
1559void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1560 // Move up the scope chain until we find the nearest enclosing
1561 // non-transparent context. The declaration will be introduced into this
1562 // scope.
1563 while (S->getEntity() && S->getEntity()->isTransparentContext())
1564 S = S->getParent();
1565
1566 // Add scoped declarations into their context, so that they can be
1567 // found later. Declarations without a context won't be inserted
1568 // into any context.
1569 if (AddToContext)
1570 CurContext->addDecl(D);
1571
1572 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1573 // are function-local declarations.
1574 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1575 return;
1576
1577 // Template instantiations should also not be pushed into scope.
1578 if (isa<FunctionDecl>(D) &&
1579 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1580 return;
1581
1582 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1583 S->AddDecl(D);
1584 return;
1585 }
1586 // If this replaces anything in the current scope,
1588 IEnd = IdResolver.end();
1589 for (; I != IEnd; ++I) {
1590 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1591 S->RemoveDecl(*I);
1592 IdResolver.RemoveDecl(*I);
1593
1594 // Should only need to replace one decl.
1595 break;
1596 }
1597 }
1598
1599 S->AddDecl(D);
1600
1601 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1602 // Implicitly-generated labels may end up getting generated in an order that
1603 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1604 // the label at the appropriate place in the identifier chain.
1605 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1606 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1607 if (IDC == CurContext) {
1608 if (!S->isDeclScope(*I))
1609 continue;
1610 } else if (IDC->Encloses(CurContext))
1611 break;
1612 }
1613
1614 IdResolver.InsertDeclAfter(I, D);
1615 } else {
1616 IdResolver.AddDecl(D);
1617 }
1619}
1620
1622 bool AllowInlineNamespace) const {
1623 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1624}
1625
1627 DeclContext *TargetDC = DC->getPrimaryContext();
1628 do {
1629 if (DeclContext *ScopeDC = S->getEntity())
1630 if (ScopeDC->getPrimaryContext() == TargetDC)
1631 return S;
1632 } while ((S = S->getParent()));
1633
1634 return nullptr;
1635}
1636
1638 DeclContext*,
1639 ASTContext&);
1640
1642 bool ConsiderLinkage,
1643 bool AllowInlineNamespace) {
1645 while (F.hasNext()) {
1646 NamedDecl *D = F.next();
1647
1648 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1649 continue;
1650
1651 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1652 continue;
1653
1654 F.erase();
1655 }
1656
1657 F.done();
1658}
1659
1661 if (auto *VD = dyn_cast<VarDecl>(D))
1662 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663 if (auto *FD = dyn_cast<FunctionDecl>(D))
1664 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1665 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1666 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1667
1668 return false;
1669}
1670
1672 // [module.interface]p7:
1673 // A declaration is attached to a module as follows:
1674 // - If the declaration is a non-dependent friend declaration that nominates a
1675 // function with a declarator-id that is a qualified-id or template-id or that
1676 // nominates a class other than with an elaborated-type-specifier with neither
1677 // a nested-name-specifier nor a simple-template-id, it is attached to the
1678 // module to which the friend is attached ([basic.link]).
1679 if (New->getFriendObjectKind() &&
1680 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1681 New->setLocalOwningModule(Old->getOwningModule());
1683 return false;
1684 }
1685
1686 // Although we have questions for the module ownership of implicit
1687 // instantiations, it should be sure that we shouldn't diagnose the
1688 // redeclaration of incorrect module ownership for different implicit
1689 // instantiations in different modules. We will diagnose the redeclaration of
1690 // incorrect module ownership for the template itself.
1692 return false;
1693
1694 Module *NewM = New->getOwningModule();
1695 Module *OldM = Old->getOwningModule();
1696
1697 if (NewM && NewM->isPrivateModule())
1698 NewM = NewM->Parent;
1699 if (OldM && OldM->isPrivateModule())
1700 OldM = OldM->Parent;
1701
1702 if (NewM == OldM)
1703 return false;
1704
1705 if (NewM && OldM) {
1706 // A module implementation unit has visibility of the decls in its
1707 // implicitly imported interface.
1708 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1709 return false;
1710
1711 // Partitions are part of the module, but a partition could import another
1712 // module, so verify that the PMIs agree.
1713 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1714 getASTContext().isInSameModule(NewM, OldM))
1715 return false;
1716 }
1717
1718 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1719 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1720 if (NewIsModuleInterface || OldIsModuleInterface) {
1721 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1722 // if a declaration of D [...] appears in the purview of a module, all
1723 // other such declarations shall appear in the purview of the same module
1724 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1725 << New
1726 << NewIsModuleInterface
1727 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1728 << OldIsModuleInterface
1729 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1730 Diag(Old->getLocation(), diag::note_previous_declaration);
1731 New->setInvalidDecl();
1732 return true;
1733 }
1734
1735 return false;
1736}
1737
1739 // [module.interface]p1:
1740 // An export-declaration shall inhabit a namespace scope.
1741 //
1742 // So it is meaningless to talk about redeclaration which is not at namespace
1743 // scope.
1744 if (!New->getLexicalDeclContext()
1745 ->getNonTransparentContext()
1746 ->isFileContext() ||
1747 !Old->getLexicalDeclContext()
1749 ->isFileContext())
1750 return false;
1751
1752 bool IsNewExported = New->isInExportDeclContext();
1753 bool IsOldExported = Old->isInExportDeclContext();
1754
1755 // It should be irrevelant if both of them are not exported.
1756 if (!IsNewExported && !IsOldExported)
1757 return false;
1758
1759 if (IsOldExported)
1760 return false;
1761
1762 // If the Old declaration are not attached to named modules
1763 // and the New declaration are attached to global module.
1764 // It should be fine to allow the export since it doesn't change
1765 // the linkage of declarations. See
1766 // https://github.com/llvm/llvm-project/issues/98583 for details.
1767 if (!Old->isInNamedModule() && New->getOwningModule() &&
1768 New->getOwningModule()->isImplicitGlobalModule())
1769 return false;
1770
1771 assert(IsNewExported);
1772
1773 auto Lk = Old->getFormalLinkage();
1774 int S = 0;
1775 if (Lk == Linkage::Internal)
1776 S = 1;
1777 else if (Lk == Linkage::Module)
1778 S = 2;
1779 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1780 Diag(Old->getLocation(), diag::note_previous_declaration);
1781 return true;
1782}
1783
1786 return true;
1787
1789 return true;
1790
1791 return false;
1792}
1793
1795 const NamedDecl *Old) const {
1796 assert(getASTContext().isSameEntity(New, Old) &&
1797 "New and Old are not the same definition, we should diagnostic it "
1798 "immediately instead of checking it.");
1799 assert(const_cast<Sema *>(this)->isReachable(New) &&
1800 const_cast<Sema *>(this)->isReachable(Old) &&
1801 "We shouldn't see unreachable definitions here.");
1802
1803 Module *NewM = New->getOwningModule();
1804 Module *OldM = Old->getOwningModule();
1805
1806 // We only checks for named modules here. The header like modules is skipped.
1807 // FIXME: This is not right if we import the header like modules in the module
1808 // purview.
1809 //
1810 // For example, assuming "header.h" provides definition for `D`.
1811 // ```C++
1812 // //--- M.cppm
1813 // export module M;
1814 // import "header.h"; // or #include "header.h" but import it by clang modules
1815 // actually.
1816 //
1817 // //--- Use.cpp
1818 // import M;
1819 // import "header.h"; // or uses clang modules.
1820 // ```
1821 //
1822 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1823 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1824 // reject it. But the current implementation couldn't detect the case since we
1825 // don't record the information about the importee modules.
1826 //
1827 // But this might not be painful in practice. Since the design of C++20 Named
1828 // Modules suggests us to use headers in global module fragment instead of
1829 // module purview.
1830 if (NewM && NewM->isHeaderLikeModule())
1831 NewM = nullptr;
1832 if (OldM && OldM->isHeaderLikeModule())
1833 OldM = nullptr;
1834
1835 if (!NewM && !OldM)
1836 return true;
1837
1838 // [basic.def.odr]p14.3
1839 // Each such definition shall not be attached to a named module
1840 // ([module.unit]).
1841 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1842 return true;
1843
1844 // Then New and Old lives in the same TU if their share one same module unit.
1845 if (NewM)
1846 NewM = NewM->getTopLevelModule();
1847 if (OldM)
1848 OldM = OldM->getTopLevelModule();
1849 return OldM == NewM;
1850}
1851
1853 if (D->getDeclContext()->isFileContext())
1854 return false;
1855
1856 return isa<UsingShadowDecl>(D) ||
1859}
1860
1861/// Removes using shadow declarations not at class scope from the lookup
1862/// results.
1865 while (F.hasNext())
1867 F.erase();
1868
1869 F.done();
1870}
1871
1872/// Check for this common pattern:
1873/// @code
1874/// class S {
1875/// S(const S&); // DO NOT IMPLEMENT
1876/// void operator=(const S&); // DO NOT IMPLEMENT
1877/// };
1878/// @endcode
1880 // FIXME: Should check for private access too but access is set after we get
1881 // the decl here.
1883 return false;
1884
1885 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1886 return CD->isCopyConstructor();
1887 return D->isCopyAssignmentOperator();
1888}
1889
1890bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1891 const DeclContext *DC = D->getDeclContext();
1892 while (!DC->isTranslationUnit()) {
1893 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1894 if (!RD->hasNameForLinkage())
1895 return true;
1896 }
1897 DC = DC->getParent();
1898 }
1899
1900 return !D->isExternallyVisible();
1901}
1902
1903// FIXME: This needs to be refactored; some other isInMainFile users want
1904// these semantics.
1905static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1907 return false;
1908 return S.SourceMgr.isInMainFile(Loc);
1909}
1910
1912 assert(D);
1913
1914 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1915 return false;
1916
1917 // Ignore all entities declared within templates, and out-of-line definitions
1918 // of members of class templates.
1919 if (D->getDeclContext()->isDependentContext() ||
1921 return false;
1922
1923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1924 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1925 return false;
1926 // A non-out-of-line declaration of a member specialization was implicitly
1927 // instantiated; it's the out-of-line declaration that we're interested in.
1928 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1929 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1930 return false;
1931
1932 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1933 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1934 return false;
1935 } else {
1936 // 'static inline' functions are defined in headers; don't warn.
1937 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1938 return false;
1939 }
1940
1941 if (FD->doesThisDeclarationHaveABody() &&
1942 Context.DeclMustBeEmitted(FD))
1943 return false;
1944 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1945 // Constants and utility variables are defined in headers with internal
1946 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1947 // like "inline".)
1948 if (!isMainFileLoc(*this, VD->getLocation()))
1949 return false;
1950
1951 if (Context.DeclMustBeEmitted(VD))
1952 return false;
1953
1954 if (VD->isStaticDataMember() &&
1955 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1956 return false;
1957 if (VD->isStaticDataMember() &&
1958 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1959 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1960 return false;
1961
1962 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1963 return false;
1964 } else {
1965 return false;
1966 }
1967
1968 // Only warn for unused decls internal to the translation unit.
1969 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1970 // for inline functions defined in the main source file, for instance.
1971 return mightHaveNonExternalLinkage(D);
1972}
1973
1975 if (!D)
1976 return;
1977
1978 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1979 const FunctionDecl *First = FD->getFirstDecl();
1981 return; // First should already be in the vector.
1982 }
1983
1984 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1985 const VarDecl *First = VD->getFirstDecl();
1987 return; // First should already be in the vector.
1988 }
1989
1991 UnusedFileScopedDecls.push_back(D);
1992}
1993
1994static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1995 const NamedDecl *D) {
1996 if (D->isInvalidDecl())
1997 return false;
1998
1999 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2000 // For a decomposition declaration, warn if none of the bindings are
2001 // referenced, instead of if the variable itself is referenced (which
2002 // it is, by the bindings' expressions).
2003 bool IsAllIgnored = true;
2004 for (const auto *BD : DD->bindings()) {
2005 if (BD->isReferenced())
2006 return false;
2007 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2008 BD->hasAttr<UnusedAttr>());
2009 }
2010 if (IsAllIgnored)
2011 return false;
2012 } else if (!D->getDeclName()) {
2013 return false;
2014 } else if (D->isReferenced() || D->isUsed()) {
2015 return false;
2016 }
2017
2018 if (D->isPlaceholderVar(LangOpts))
2019 return false;
2020
2021 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2022 D->hasAttr<CleanupAttr>())
2023 return false;
2024
2025 if (isa<LabelDecl>(D))
2026 return true;
2027
2028 // Except for labels, we only care about unused decls that are local to
2029 // functions.
2030 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2031 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2032 // For dependent types, the diagnostic is deferred.
2033 WithinFunction =
2034 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2035 if (!WithinFunction)
2036 return false;
2037
2038 if (isa<TypedefNameDecl>(D))
2039 return true;
2040
2041 // White-list anything that isn't a local variable.
2043 return false;
2044
2045 // Types of valid local variables should be complete, so this should succeed.
2046 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2047
2048 const Expr *Init = VD->getInit();
2049 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2050 Init = Cleanups->getSubExpr();
2051
2052 const auto *Ty = VD->getType().getTypePtr();
2053
2054 // Only look at the outermost level of typedef.
2055 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2056 // Allow anything marked with __attribute__((unused)).
2057 if (TT->getDecl()->hasAttr<UnusedAttr>())
2058 return false;
2059 }
2060
2061 // Warn for reference variables whose initializtion performs lifetime
2062 // extension.
2063 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2064 MTE && MTE->getExtendingDecl()) {
2065 Ty = VD->getType().getNonReferenceType().getTypePtr();
2066 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2067 }
2068
2069 // If we failed to complete the type for some reason, or if the type is
2070 // dependent, don't diagnose the variable.
2071 if (Ty->isIncompleteType() || Ty->isDependentType())
2072 return false;
2073
2074 // Look at the element type to ensure that the warning behaviour is
2075 // consistent for both scalars and arrays.
2076 Ty = Ty->getBaseElementTypeUnsafe();
2077
2078 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2079 if (Tag->hasAttr<UnusedAttr>())
2080 return false;
2081
2082 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2083 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2084 return false;
2085
2086 if (Init) {
2087 const auto *Construct =
2088 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2089 if (Construct && !Construct->isElidable()) {
2090 const CXXConstructorDecl *CD = Construct->getConstructor();
2091 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2092 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2093 return false;
2094 }
2095
2096 // Suppress the warning if we don't know how this is constructed, and
2097 // it could possibly be non-trivial constructor.
2098 if (Init->isTypeDependent()) {
2099 for (const CXXConstructorDecl *Ctor : RD->ctors())
2100 if (!Ctor->isTrivial())
2101 return false;
2102 }
2103
2104 // Suppress the warning if the constructor is unresolved because
2105 // its arguments are dependent.
2107 return false;
2108 }
2109 }
2110 }
2111
2112 // TODO: __attribute__((unused)) templates?
2113 }
2114
2115 return true;
2116}
2117
2119 FixItHint &Hint) {
2120 if (isa<LabelDecl>(D)) {
2122 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2123 /*SkipTrailingWhitespaceAndNewline=*/false);
2124 if (AfterColon.isInvalid())
2125 return;
2127 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2128 }
2129}
2130
2133 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2134}
2135
2137 DiagReceiverTy DiagReceiver) {
2138 if (D->isDependentType())
2139 return;
2140
2141 for (auto *TmpD : D->decls()) {
2142 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2143 DiagnoseUnusedDecl(T, DiagReceiver);
2144 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2145 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2146 }
2147}
2148
2151 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2152}
2153
2156 return;
2157
2158 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2159 // typedefs can be referenced later on, so the diagnostics are emitted
2160 // at end-of-translation-unit.
2162 return;
2163 }
2164
2165 FixItHint Hint;
2167
2168 unsigned DiagID;
2169 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2170 DiagID = diag::warn_unused_exception_param;
2171 else if (isa<LabelDecl>(D))
2172 DiagID = diag::warn_unused_label;
2173 else
2174 DiagID = diag::warn_unused_variable;
2175
2176 SourceLocation DiagLoc = D->getLocation();
2177 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2178}
2179
2181 DiagReceiverTy DiagReceiver) {
2182 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2183 // it's not really unused.
2184 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2185 return;
2186
2187 // In C++, `_` variables behave as if they were maybe_unused
2188 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2189 return;
2190
2191 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2192
2193 if (Ty->isReferenceType() || Ty->isDependentType())
2194 return;
2195
2196 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2197 if (Tag->hasAttr<UnusedAttr>())
2198 return;
2199 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2200 // mimic gcc's behavior.
2201 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2202 RD && !RD->hasAttr<WarnUnusedAttr>())
2203 return;
2204 }
2205
2206 // Don't warn about __block Objective-C pointer variables, as they might
2207 // be assigned in the block but not used elsewhere for the purpose of lifetime
2208 // extension.
2209 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2210 return;
2211
2212 // Don't warn about Objective-C pointer variables with precise lifetime
2213 // semantics; they can be used to ensure ARC releases the object at a known
2214 // time, which may mean assignment but no other references.
2215 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2216 return;
2217
2218 auto iter = RefsMinusAssignments.find(VD);
2219 if (iter == RefsMinusAssignments.end())
2220 return;
2221
2222 assert(iter->getSecond() >= 0 &&
2223 "Found a negative number of references to a VarDecl");
2224 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2225 // Assume the given VarDecl is "used" if its ref count stored in
2226 // `RefMinusAssignments` is positive, with one exception.
2227 //
2228 // For a C++ variable whose decl (with initializer) entirely consist the
2229 // condition expression of a if/while/for construct,
2230 // Clang creates a DeclRefExpr for the condition expression rather than a
2231 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2232 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2233 // used in the body of the if/while/for construct.
2234 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2235 if (!UnusedCXXCondDecl)
2236 return;
2237 }
2238
2239 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2240 : diag::warn_unused_but_set_variable;
2241 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2242}
2243
2245 Sema::DiagReceiverTy DiagReceiver) {
2246 // Verify that we have no forward references left. If so, there was a goto
2247 // or address of a label taken, but no definition of it. Label fwd
2248 // definitions are indicated with a null substmt which is also not a resolved
2249 // MS inline assembly label name.
2250 bool Diagnose = false;
2251 if (L->isMSAsmLabel())
2252 Diagnose = !L->isResolvedMSAsmLabel();
2253 else
2254 Diagnose = L->getStmt() == nullptr;
2255 if (Diagnose)
2256 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2257 << L);
2258}
2259
2261 S->applyNRVO();
2262
2263 if (S->decl_empty()) return;
2265 "Scope shouldn't contain decls!");
2266
2267 /// We visit the decls in non-deterministic order, but we want diagnostics
2268 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2269 /// and sort the diagnostics before emitting them, after we visited all decls.
2270 struct LocAndDiag {
2271 SourceLocation Loc;
2272 std::optional<SourceLocation> PreviousDeclLoc;
2274 };
2276 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2277 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2278 };
2279 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2280 SourceLocation PreviousDeclLoc,
2281 PartialDiagnostic PD) {
2282 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2283 };
2284
2285 for (auto *TmpD : S->decls()) {
2286 assert(TmpD && "This decl didn't get pushed??");
2287
2288 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2289 NamedDecl *D = cast<NamedDecl>(TmpD);
2290
2291 // Diagnose unused variables in this scope.
2293 DiagnoseUnusedDecl(D, addDiag);
2294 if (const auto *RD = dyn_cast<RecordDecl>(D))
2295 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2296 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2297 DiagnoseUnusedButSetDecl(VD, addDiag);
2298 RefsMinusAssignments.erase(VD);
2299 }
2300 }
2301
2302 if (!D->getDeclName()) continue;
2303
2304 // If this was a forward reference to a label, verify it was defined.
2305 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2306 CheckPoppedLabel(LD, *this, addDiag);
2307
2308 // Partial translation units that are created in incremental processing must
2309 // not clean up the IdResolver because PTUs should take into account the
2310 // declarations that came from previous PTUs.
2311 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2313 IdResolver.RemoveDecl(D);
2314
2315 // Warn on it if we are shadowing a declaration.
2316 auto ShadowI = ShadowingDecls.find(D);
2317 if (ShadowI != ShadowingDecls.end()) {
2318 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2319 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2320 PDiag(diag::warn_ctor_parm_shadows_field)
2321 << D << FD << FD->getParent());
2322 }
2323 ShadowingDecls.erase(ShadowI);
2324 }
2325 }
2326
2327 llvm::sort(DeclDiags,
2328 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2329 // The particular order for diagnostics is not important, as long
2330 // as the order is deterministic. Using the raw location is going
2331 // to generally be in source order unless there are macro
2332 // expansions involved.
2333 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2334 });
2335 for (const LocAndDiag &D : DeclDiags) {
2336 Diag(D.Loc, D.PD);
2337 if (D.PreviousDeclLoc)
2338 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2339 }
2340}
2341
2343 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2344 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2345 (S->isClassScope() && !getLangOpts().CPlusPlus))
2346 S = S->getParent();
2347 return S;
2348}
2349
2350static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2352 switch (Error) {
2354 return "";
2356 return BuiltinInfo.getHeaderName(ID);
2358 return "stdio.h";
2360 return "setjmp.h";
2362 return "ucontext.h";
2363 }
2364 llvm_unreachable("unhandled error kind");
2365}
2366
2368 unsigned ID, SourceLocation Loc) {
2369 DeclContext *Parent = Context.getTranslationUnitDecl();
2370
2371 if (getLangOpts().CPlusPlus) {
2373 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2374 CLinkageDecl->setImplicit();
2375 Parent->addDecl(CLinkageDecl);
2376 Parent = CLinkageDecl;
2377 }
2378
2380 if (Context.BuiltinInfo.isImmediate(ID)) {
2381 assert(getLangOpts().CPlusPlus20 &&
2382 "consteval builtins should only be available in C++20 mode");
2383 ConstexprKind = ConstexprSpecKind::Consteval;
2384 }
2385
2387 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2388 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2389 Type->isFunctionProtoType(), ConstexprKind);
2390 New->setImplicit();
2391 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2392
2393 // Create Decl objects for each parameter, adding them to the
2394 // FunctionDecl.
2395 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2397 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2399 Context, New, SourceLocation(), SourceLocation(), nullptr,
2400 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2401 parm->setScopeInfo(0, i);
2402 Params.push_back(parm);
2403 }
2404 New->setParams(Params);
2405 }
2406
2408 return New;
2409}
2410
2412 Scope *S, bool ForRedeclaration,
2413 SourceLocation Loc) {
2415
2417 QualType R = Context.GetBuiltinType(ID, Error);
2418 if (Error) {
2419 if (!ForRedeclaration)
2420 return nullptr;
2421
2422 // If we have a builtin without an associated type we should not emit a
2423 // warning when we were not able to find a type for it.
2425 Context.BuiltinInfo.allowTypeMismatch(ID))
2426 return nullptr;
2427
2428 // If we could not find a type for setjmp it is because the jmp_buf type was
2429 // not defined prior to the setjmp declaration.
2431 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2432 << Context.BuiltinInfo.getName(ID);
2433 return nullptr;
2434 }
2435
2436 // Generally, we emit a warning that the declaration requires the
2437 // appropriate header.
2438 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2439 << getHeaderName(Context.BuiltinInfo, ID, Error)
2440 << Context.BuiltinInfo.getName(ID);
2441 return nullptr;
2442 }
2443
2444 if (!ForRedeclaration &&
2445 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2446 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2447 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2448 : diag::ext_implicit_lib_function_decl)
2449 << Context.BuiltinInfo.getName(ID) << R;
2450 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2451 Diag(Loc, diag::note_include_header_or_declare)
2452 << Header << Context.BuiltinInfo.getName(ID);
2453 }
2454
2455 if (R.isNull())
2456 return nullptr;
2457
2458 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2460
2461 // TUScope is the translation-unit scope to insert this function into.
2462 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2463 // relate Scopes to DeclContexts, and probably eliminate CurContext
2464 // entirely, but we're not there yet.
2465 DeclContext *SavedContext = CurContext;
2466 CurContext = New->getDeclContext();
2468 CurContext = SavedContext;
2469 return New;
2470}
2471
2472/// Typedef declarations don't have linkage, but they still denote the same
2473/// entity if their types are the same.
2474/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2475/// isSameEntity.
2476static void
2479 // This is only interesting when modules are enabled.
2480 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2481 return;
2482
2483 // Empty sets are uninteresting.
2484 if (Previous.empty())
2485 return;
2486
2487 LookupResult::Filter Filter = Previous.makeFilter();
2488 while (Filter.hasNext()) {
2489 NamedDecl *Old = Filter.next();
2490
2491 // Non-hidden declarations are never ignored.
2492 if (S.isVisible(Old))
2493 continue;
2494
2495 // Declarations of the same entity are not ignored, even if they have
2496 // different linkages.
2497 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2498 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2499 Decl->getUnderlyingType()))
2500 continue;
2501
2502 // If both declarations give a tag declaration a typedef name for linkage
2503 // purposes, then they declare the same entity.
2504 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2505 Decl->getAnonDeclWithTypedefName())
2506 continue;
2507 }
2508
2509 Filter.erase();
2510 }
2511
2512 Filter.done();
2513}
2514
2516 QualType OldType;
2517 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2518 OldType = OldTypedef->getUnderlyingType();
2519 else
2520 OldType = Context.getTypeDeclType(Old);
2521 QualType NewType = New->getUnderlyingType();
2522
2523 if (NewType->isVariablyModifiedType()) {
2524 // Must not redefine a typedef with a variably-modified type.
2525 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2526 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2527 << Kind << NewType;
2528 if (Old->getLocation().isValid())
2529 notePreviousDefinition(Old, New->getLocation());
2530 New->setInvalidDecl();
2531 return true;
2532 }
2533
2534 if (OldType != NewType &&
2535 !OldType->isDependentType() &&
2536 !NewType->isDependentType() &&
2537 !Context.hasSameType(OldType, NewType)) {
2538 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2539 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2540 << Kind << NewType << OldType;
2541 if (Old->getLocation().isValid())
2542 notePreviousDefinition(Old, New->getLocation());
2543 New->setInvalidDecl();
2544 return true;
2545 }
2546 return false;
2547}
2548
2550 LookupResult &OldDecls) {
2551 // If the new decl is known invalid already, don't bother doing any
2552 // merging checks.
2553 if (New->isInvalidDecl()) return;
2554
2555 // Allow multiple definitions for ObjC built-in typedefs.
2556 // FIXME: Verify the underlying types are equivalent!
2557 if (getLangOpts().ObjC) {
2558 const IdentifierInfo *TypeID = New->getIdentifier();
2559 switch (TypeID->getLength()) {
2560 default: break;
2561 case 2:
2562 {
2563 if (!TypeID->isStr("id"))
2564 break;
2565 QualType T = New->getUnderlyingType();
2566 if (!T->isPointerType())
2567 break;
2568 if (!T->isVoidPointerType()) {
2569 QualType PT = T->castAs<PointerType>()->getPointeeType();
2570 if (!PT->isStructureType())
2571 break;
2572 }
2573 Context.setObjCIdRedefinitionType(T);
2574 // Install the built-in type for 'id', ignoring the current definition.
2575 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2576 Context.getObjCIdType());
2577 return;
2578 }
2579 case 5:
2580 if (!TypeID->isStr("Class"))
2581 break;
2582 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2583 // Install the built-in type for 'Class', ignoring the current definition.
2584 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2585 Context.getObjCClassType());
2586 return;
2587 case 3:
2588 if (!TypeID->isStr("SEL"))
2589 break;
2590 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2591 // Install the built-in type for 'SEL', ignoring the current definition.
2592 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2593 Context.getObjCSelType());
2594 return;
2595 }
2596 // Fall through - the typedef name was not a builtin type.
2597 }
2598
2599 // Verify the old decl was also a type.
2600 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2601 if (!Old) {
2602 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2603 << New->getDeclName();
2604
2605 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2606 if (OldD->getLocation().isValid())
2607 notePreviousDefinition(OldD, New->getLocation());
2608
2609 return New->setInvalidDecl();
2610 }
2611
2612 // If the old declaration is invalid, just give up here.
2613 if (Old->isInvalidDecl())
2614 return New->setInvalidDecl();
2615
2616 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2617 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2618 auto *NewTag = New->getAnonDeclWithTypedefName();
2619 NamedDecl *Hidden = nullptr;
2620 if (OldTag && NewTag &&
2621 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2622 !hasVisibleDefinition(OldTag, &Hidden)) {
2623 // There is a definition of this tag, but it is not visible. Use it
2624 // instead of our tag.
2625 if (OldTD->isModed())
2626 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2627 OldTD->getUnderlyingType());
2628 else
2629 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2630
2631 // Make the old tag definition visible.
2633
2635 }
2636 }
2637
2638 // If the typedef types are not identical, reject them in all languages and
2639 // with any extensions enabled.
2640 if (isIncompatibleTypedef(Old, New))
2641 return;
2642
2643 // The types match. Link up the redeclaration chain and merge attributes if
2644 // the old declaration was a typedef.
2645 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2646 New->setPreviousDecl(Typedef);
2648 }
2649
2650 if (getLangOpts().MicrosoftExt)
2651 return;
2652
2653 if (getLangOpts().CPlusPlus) {
2654 // C++ [dcl.typedef]p2:
2655 // In a given non-class scope, a typedef specifier can be used to
2656 // redefine the name of any type declared in that scope to refer
2657 // to the type to which it already refers.
2659 return;
2660
2661 // C++0x [dcl.typedef]p4:
2662 // In a given class scope, a typedef specifier can be used to redefine
2663 // any class-name declared in that scope that is not also a typedef-name
2664 // to refer to the type to which it already refers.
2665 //
2666 // This wording came in via DR424, which was a correction to the
2667 // wording in DR56, which accidentally banned code like:
2668 //
2669 // struct S {
2670 // typedef struct A { } A;
2671 // };
2672 //
2673 // in the C++03 standard. We implement the C++0x semantics, which
2674 // allow the above but disallow
2675 //
2676 // struct S {
2677 // typedef int I;
2678 // typedef int I;
2679 // };
2680 //
2681 // since that was the intent of DR56.
2682 if (!isa<TypedefNameDecl>(Old))
2683 return;
2684
2685 Diag(New->getLocation(), diag::err_redefinition)
2686 << New->getDeclName();
2687 notePreviousDefinition(Old, New->getLocation());
2688 return New->setInvalidDecl();
2689 }
2690
2691 // Modules always permit redefinition of typedefs, as does C11.
2692 if (getLangOpts().Modules || getLangOpts().C11)
2693 return;
2694
2695 // If we have a redefinition of a typedef in C, emit a warning. This warning
2696 // is normally mapped to an error, but can be controlled with
2697 // -Wtypedef-redefinition. If either the original or the redefinition is
2698 // in a system header, don't emit this for compatibility with GCC.
2699 if (getDiagnostics().getSuppressSystemWarnings() &&
2700 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2701 (Old->isImplicit() ||
2702 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2703 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2704 return;
2705
2706 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2707 << New->getDeclName();
2708 notePreviousDefinition(Old, New->getLocation());
2709}
2710
2712 // If this was an unscoped enumeration, yank all of its enumerators
2713 // out of the scope.
2714 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2715 Scope *EnumScope = getNonFieldDeclScope(S);
2716 for (auto *ECD : ED->enumerators()) {
2717 assert(EnumScope->isDeclScope(ECD));
2718 EnumScope->RemoveDecl(ECD);
2719 IdResolver.RemoveDecl(ECD);
2720 }
2721 }
2722}
2723
2724/// DeclhasAttr - returns true if decl Declaration already has the target
2725/// attribute.
2726static bool DeclHasAttr(const Decl *D, const Attr *A) {
2727 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2728 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2729 for (const auto *i : D->attrs())
2730 if (i->getKind() == A->getKind()) {
2731 if (Ann) {
2732 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2733 return true;
2734 continue;
2735 }
2736 // FIXME: Don't hardcode this check
2737 if (OA && isa<OwnershipAttr>(i))
2738 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2739 return true;
2740 }
2741
2742 return false;
2743}
2744
2746 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2747 return VD->isThisDeclarationADefinition();
2748 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2749 return TD->isCompleteDefinition() || TD->isBeingDefined();
2750 return true;
2751}
2752
2753/// Merge alignment attributes from \p Old to \p New, taking into account the
2754/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2755///
2756/// \return \c true if any attributes were added to \p New.
2757static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2758 // Look for alignas attributes on Old, and pick out whichever attribute
2759 // specifies the strictest alignment requirement.
2760 AlignedAttr *OldAlignasAttr = nullptr;
2761 AlignedAttr *OldStrictestAlignAttr = nullptr;
2762 unsigned OldAlign = 0;
2763 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2764 // FIXME: We have no way of representing inherited dependent alignments
2765 // in a case like:
2766 // template<int A, int B> struct alignas(A) X;
2767 // template<int A, int B> struct alignas(B) X {};
2768 // For now, we just ignore any alignas attributes which are not on the
2769 // definition in such a case.
2770 if (I->isAlignmentDependent())
2771 return false;
2772
2773 if (I->isAlignas())
2774 OldAlignasAttr = I;
2775
2776 unsigned Align = I->getAlignment(S.Context);
2777 if (Align > OldAlign) {
2778 OldAlign = Align;
2779 OldStrictestAlignAttr = I;
2780 }
2781 }
2782
2783 // Look for alignas attributes on New.
2784 AlignedAttr *NewAlignasAttr = nullptr;
2785 unsigned NewAlign = 0;
2786 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2787 if (I->isAlignmentDependent())
2788 return false;
2789
2790 if (I->isAlignas())
2791 NewAlignasAttr = I;
2792
2793 unsigned Align = I->getAlignment(S.Context);
2794 if (Align > NewAlign)
2795 NewAlign = Align;
2796 }
2797
2798 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2799 // Both declarations have 'alignas' attributes. We require them to match.
2800 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2801 // fall short. (If two declarations both have alignas, they must both match
2802 // every definition, and so must match each other if there is a definition.)
2803
2804 // If either declaration only contains 'alignas(0)' specifiers, then it
2805 // specifies the natural alignment for the type.
2806 if (OldAlign == 0 || NewAlign == 0) {
2807 QualType Ty;
2808 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2809 Ty = VD->getType();
2810 else
2812
2813 if (OldAlign == 0)
2814 OldAlign = S.Context.getTypeAlign(Ty);
2815 if (NewAlign == 0)
2816 NewAlign = S.Context.getTypeAlign(Ty);
2817 }
2818
2819 if (OldAlign != NewAlign) {
2820 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2823 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2824 }
2825 }
2826
2827 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2828 // C++11 [dcl.align]p6:
2829 // if any declaration of an entity has an alignment-specifier,
2830 // every defining declaration of that entity shall specify an
2831 // equivalent alignment.
2832 // C11 6.7.5/7:
2833 // If the definition of an object does not have an alignment
2834 // specifier, any other declaration of that object shall also
2835 // have no alignment specifier.
2836 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2837 << OldAlignasAttr;
2838 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2839 << OldAlignasAttr;
2840 }
2841
2842 bool AnyAdded = false;
2843
2844 // Ensure we have an attribute representing the strictest alignment.
2845 if (OldAlign > NewAlign) {
2846 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2847 Clone->setInherited(true);
2848 New->addAttr(Clone);
2849 AnyAdded = true;
2850 }
2851
2852 // Ensure we have an alignas attribute if the old declaration had one.
2853 if (OldAlignasAttr && !NewAlignasAttr &&
2854 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2855 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2856 Clone->setInherited(true);
2857 New->addAttr(Clone);
2858 AnyAdded = true;
2859 }
2860
2861 return AnyAdded;
2862}
2863
2864#define WANT_DECL_MERGE_LOGIC
2865#include "clang/Sema/AttrParsedAttrImpl.inc"
2866#undef WANT_DECL_MERGE_LOGIC
2867
2869 const InheritableAttr *Attr,
2871 // Diagnose any mutual exclusions between the attribute that we want to add
2872 // and attributes that already exist on the declaration.
2873 if (!DiagnoseMutualExclusions(S, D, Attr))
2874 return false;
2875
2876 // This function copies an attribute Attr from a previous declaration to the
2877 // new declaration D if the new declaration doesn't itself have that attribute
2878 // yet or if that attribute allows duplicates.
2879 // If you're adding a new attribute that requires logic different from
2880 // "use explicit attribute on decl if present, else use attribute from
2881 // previous decl", for example if the attribute needs to be consistent
2882 // between redeclarations, you need to call a custom merge function here.
2883 InheritableAttr *NewAttr = nullptr;
2884 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2885 NewAttr = S.mergeAvailabilityAttr(
2886 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2887 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2888 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2889 AA->getPriority(), AA->getEnvironment());
2890 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2891 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2892 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2893 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2894 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2895 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2896 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2897 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2898 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2899 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2900 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2901 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2902 FA->getFirstArg());
2903 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2904 NewAttr = S.mergeFormatMatchesAttr(
2905 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2906 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2907 NewAttr = S.mergeModularFormatAttr(
2908 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2909 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2910 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2911 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2912 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2913 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2914 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2915 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2916 IA->getInheritanceModel());
2917 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2918 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2919 &S.Context.Idents.get(AA->getSpelling()));
2920 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2923 // CUDA target attributes are part of function signature for
2924 // overloading purposes and must not be merged.
2925 return false;
2926 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2927 NewAttr = S.mergeMinSizeAttr(D, *MA);
2928 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2929 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2930 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2931 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2932 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2933 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2934 else if (isa<AlignedAttr>(Attr))
2935 // AlignedAttrs are handled separately, because we need to handle all
2936 // such attributes on a declaration at the same time.
2937 NewAttr = nullptr;
2942 NewAttr = nullptr;
2943 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2944 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2945 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2946 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2947 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2948 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2949 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2950 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2951 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2952 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2953 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2954 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2955 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2956 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2957 NT->getZ());
2958 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2959 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2960 WS->getPreferred(),
2961 WS->getSpelledArgsCount());
2962 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2963 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2964 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2965 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2966 else if (isa<SuppressAttr>(Attr))
2967 // Do nothing. Each redeclaration should be suppressed separately.
2968 NewAttr = nullptr;
2969 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2970 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2971 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2972 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2973
2974 if (NewAttr) {
2975 NewAttr->setInherited(true);
2976 D->addAttr(NewAttr);
2977 if (isa<MSInheritanceAttr>(NewAttr))
2979 return true;
2980 }
2981
2982 return false;
2983}
2984
2985static const NamedDecl *getDefinition(const Decl *D) {
2986 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
2987 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2988 return Def;
2989 return nullptr;
2990 }
2991 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2992 const VarDecl *Def = VD->getDefinition();
2993 if (Def)
2994 return Def;
2995 return VD->getActingDefinition();
2996 }
2997 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2998 const FunctionDecl *Def = nullptr;
2999 if (FD->isDefined(Def, true))
3000 return Def;
3001 }
3002 return nullptr;
3003}
3004
3005static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3006 for (const auto *Attribute : D->attrs())
3007 if (Attribute->getKind() == Kind)
3008 return true;
3009 return false;
3010}
3011
3012/// checkNewAttributesAfterDef - If we already have a definition, check that
3013/// there are no new attributes in this declaration.
3014static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3015 if (!New->hasAttrs())
3016 return;
3017
3018 const NamedDecl *Def = getDefinition(Old);
3019 if (!Def || Def == New)
3020 return;
3021
3022 AttrVec &NewAttributes = New->getAttrs();
3023 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3024 Attr *NewAttribute = NewAttributes[I];
3025
3026 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3028 SkipBodyInfo SkipBody;
3029 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3030
3031 // If we're skipping this definition, drop the "alias" attribute.
3032 if (SkipBody.ShouldSkip) {
3033 NewAttributes.erase(NewAttributes.begin() + I);
3034 --E;
3035 continue;
3036 }
3037 } else {
3038 VarDecl *VD = cast<VarDecl>(New);
3039 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3041 ? diag::err_alias_after_tentative
3042 : diag::err_redefinition;
3043 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3044 if (Diag == diag::err_redefinition)
3045 S.notePreviousDefinition(Def, VD->getLocation());
3046 else
3047 S.Diag(Def->getLocation(), diag::note_previous_definition);
3048 VD->setInvalidDecl();
3049 }
3050 ++I;
3051 continue;
3052 }
3053
3054 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3055 // Tentative definitions are only interesting for the alias check above.
3056 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3057 ++I;
3058 continue;
3059 }
3060 }
3061
3062 if (hasAttribute(Def, NewAttribute->getKind())) {
3063 ++I;
3064 continue; // regular attr merging will take care of validating this.
3065 }
3066
3067 if (isa<C11NoReturnAttr>(NewAttribute)) {
3068 // C's _Noreturn is allowed to be added to a function after it is defined.
3069 ++I;
3070 continue;
3071 } else if (isa<UuidAttr>(NewAttribute)) {
3072 // msvc will allow a subsequent definition to add an uuid to a class
3073 ++I;
3074 continue;
3076 NewAttribute) &&
3077 NewAttribute->isStandardAttributeSyntax()) {
3078 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3079 // deprecated attribute can later be re-declared with the attribute and
3080 // vice-versa.
3081 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3082 // maybe_unused attribute can later be redeclared with the attribute and
3083 // vice versa.
3084 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3085 // nodiscard attribute can later be redeclared with the attribute and
3086 // vice-versa.
3087 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3088 ++I;
3089 continue;
3090 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3091 if (AA->isAlignas()) {
3092 // C++11 [dcl.align]p6:
3093 // if any declaration of an entity has an alignment-specifier,
3094 // every defining declaration of that entity shall specify an
3095 // equivalent alignment.
3096 // C11 6.7.5/7:
3097 // If the definition of an object does not have an alignment
3098 // specifier, any other declaration of that object shall also
3099 // have no alignment specifier.
3100 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3101 << AA;
3102 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3103 << AA;
3104 NewAttributes.erase(NewAttributes.begin() + I);
3105 --E;
3106 continue;
3107 }
3108 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3109 // If there is a C definition followed by a redeclaration with this
3110 // attribute then there are two different definitions. In C++, prefer the
3111 // standard diagnostics.
3112 if (!S.getLangOpts().CPlusPlus) {
3113 S.Diag(NewAttribute->getLocation(),
3114 diag::err_loader_uninitialized_redeclaration);
3115 S.Diag(Def->getLocation(), diag::note_previous_definition);
3116 NewAttributes.erase(NewAttributes.begin() + I);
3117 --E;
3118 continue;
3119 }
3120 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3121 cast<VarDecl>(New)->isInline() &&
3122 !cast<VarDecl>(New)->isInlineSpecified()) {
3123 // Don't warn about applying selectany to implicitly inline variables.
3124 // Older compilers and language modes would require the use of selectany
3125 // to make such variables inline, and it would have no effect if we
3126 // honored it.
3127 ++I;
3128 continue;
3129 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3130 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3131 // declarations after definitions.
3132 ++I;
3133 continue;
3134 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3135 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3136 // error since the definition will have already been created without
3137 // the semantic effects of the attribute having been applied.
3138 S.Diag(NewAttribute->getLocation(),
3139 diag::err_sycl_entry_point_after_definition)
3140 << NewAttribute;
3141 S.Diag(Def->getLocation(), diag::note_previous_definition);
3142 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3143 ++I;
3144 continue;
3145 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3146 // SYCLExternalAttr may be added after a definition.
3147 ++I;
3148 continue;
3149 }
3150
3151 S.Diag(NewAttribute->getLocation(),
3152 diag::warn_attribute_precede_definition);
3153 S.Diag(Def->getLocation(), diag::note_previous_definition);
3154 NewAttributes.erase(NewAttributes.begin() + I);
3155 --E;
3156 }
3157}
3158
3159static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3160 const ConstInitAttr *CIAttr,
3161 bool AttrBeforeInit) {
3162 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3163
3164 // Figure out a good way to write this specifier on the old declaration.
3165 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3166 // enough of the attribute list spelling information to extract that without
3167 // heroics.
3168 std::string SuitableSpelling;
3169 if (S.getLangOpts().CPlusPlus20)
3170 SuitableSpelling = std::string(
3171 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3172 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3173 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3174 InsertLoc, {tok::l_square, tok::l_square,
3175 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3176 S.PP.getIdentifierInfo("require_constant_initialization"),
3177 tok::r_square, tok::r_square}));
3178 if (SuitableSpelling.empty())
3179 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3180 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3181 S.PP.getIdentifierInfo("require_constant_initialization"),
3182 tok::r_paren, tok::r_paren}));
3183 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3184 SuitableSpelling = "constinit";
3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3186 SuitableSpelling = "[[clang::require_constant_initialization]]";
3187 if (SuitableSpelling.empty())
3188 SuitableSpelling = "__attribute__((require_constant_initialization))";
3189 SuitableSpelling += " ";
3190
3191 if (AttrBeforeInit) {
3192 // extern constinit int a;
3193 // int a = 0; // error (missing 'constinit'), accepted as extension
3194 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3195 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3196 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3197 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3198 } else {
3199 // int a = 0;
3200 // constinit extern int a; // error (missing 'constinit')
3201 S.Diag(CIAttr->getLocation(),
3202 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3203 : diag::warn_require_const_init_added_too_late)
3204 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3205 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3206 << CIAttr->isConstinit()
3207 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3208 }
3209}
3210
3213 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3214 UsedAttr *NewAttr = OldAttr->clone(Context);
3215 NewAttr->setInherited(true);
3216 New->addAttr(NewAttr);
3217 }
3218 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3219 RetainAttr *NewAttr = OldAttr->clone(Context);
3220 NewAttr->setInherited(true);
3221 New->addAttr(NewAttr);
3222 }
3223
3224 if (!Old->hasAttrs() && !New->hasAttrs())
3225 return;
3226
3227 // [dcl.constinit]p1:
3228 // If the [constinit] specifier is applied to any declaration of a
3229 // variable, it shall be applied to the initializing declaration.
3230 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3231 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3232 if (bool(OldConstInit) != bool(NewConstInit)) {
3233 const auto *OldVD = cast<VarDecl>(Old);
3234 auto *NewVD = cast<VarDecl>(New);
3235
3236 // Find the initializing declaration. Note that we might not have linked
3237 // the new declaration into the redeclaration chain yet.
3238 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3239 if (!InitDecl &&
3240 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3241 InitDecl = NewVD;
3242
3243 if (InitDecl == NewVD) {
3244 // This is the initializing declaration. If it would inherit 'constinit',
3245 // that's ill-formed. (Note that we do not apply this to the attribute
3246 // form).
3247 if (OldConstInit && OldConstInit->isConstinit())
3248 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3249 /*AttrBeforeInit=*/true);
3250 } else if (NewConstInit) {
3251 // This is the first time we've been told that this declaration should
3252 // have a constant initializer. If we already saw the initializing
3253 // declaration, this is too late.
3254 if (InitDecl && InitDecl != NewVD) {
3255 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3256 /*AttrBeforeInit=*/false);
3257 NewVD->dropAttr<ConstInitAttr>();
3258 }
3259 }
3260 }
3261
3262 // Attributes declared post-definition are currently ignored.
3263 checkNewAttributesAfterDef(*this, New, Old);
3264
3265 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3266 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3267 if (!OldA->isEquivalent(NewA)) {
3268 // This redeclaration changes __asm__ label.
3269 Diag(New->getLocation(), diag::err_different_asm_label);
3270 Diag(OldA->getLocation(), diag::note_previous_declaration);
3271 }
3272 } else if (Old->isUsed()) {
3273 // This redeclaration adds an __asm__ label to a declaration that has
3274 // already been ODR-used.
3275 Diag(New->getLocation(), diag::err_late_asm_label_name)
3276 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3277 }
3278 }
3279
3280 // Re-declaration cannot add abi_tag's.
3281 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3282 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3283 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3284 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3285 Diag(NewAbiTagAttr->getLocation(),
3286 diag::err_new_abi_tag_on_redeclaration)
3287 << NewTag;
3288 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3289 }
3290 }
3291 } else {
3292 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3293 Diag(Old->getLocation(), diag::note_previous_declaration);
3294 }
3295 }
3296
3297 // This redeclaration adds a section attribute.
3298 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3299 if (auto *VD = dyn_cast<VarDecl>(New)) {
3300 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3301 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3302 Diag(Old->getLocation(), diag::note_previous_declaration);
3303 }
3304 }
3305 }
3306
3307 // Redeclaration adds code-seg attribute.
3308 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3309 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3310 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3311 Diag(New->getLocation(), diag::warn_mismatched_section)
3312 << 0 /*codeseg*/;
3313 Diag(Old->getLocation(), diag::note_previous_declaration);
3314 }
3315
3316 if (!Old->hasAttrs())
3317 return;
3318
3319 bool foundAny = New->hasAttrs();
3320
3321 // Ensure that any moving of objects within the allocated map is done before
3322 // we process them.
3323 if (!foundAny) New->setAttrs(AttrVec());
3324
3325 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3326 // Ignore deprecated/unavailable/availability attributes if requested.
3328 if (isa<DeprecatedAttr>(I) ||
3331 switch (AMK) {
3333 continue;
3334
3339 LocalAMK = AMK;
3340 break;
3341 }
3342 }
3343
3344 // Already handled.
3345 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3346 continue;
3347
3349 if (auto *FD = dyn_cast<FunctionDecl>(New);
3350 FD &&
3351 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3352 continue; // Don't propagate inferred noreturn attributes to explicit
3353 }
3354
3355 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3356 foundAny = true;
3357 }
3358
3359 if (mergeAlignedAttrs(*this, New, Old))
3360 foundAny = true;
3361
3362 if (!foundAny) New->dropAttrs();
3363}
3364
3366 for (const Attr *A : D->attrs())
3367 checkAttrIsTypeDependent(D, A);
3368}
3369
3370// Returns the number of added attributes.
3371template <class T>
3372static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3373 Sema &S) {
3374 unsigned found = 0;
3375 for (const auto *I : From->specific_attrs<T>()) {
3376 if (!DeclHasAttr(To, I)) {
3377 T *newAttr = cast<T>(I->clone(S.Context));
3378 newAttr->setInherited(true);
3379 To->addAttr(newAttr);
3380 ++found;
3381 }
3382 }
3383 return found;
3384}
3385
3386template <class F>
3387static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3388 F &&propagator) {
3389 if (!From->hasAttrs()) {
3390 return;
3391 }
3392
3393 bool foundAny = To->hasAttrs();
3394
3395 // Ensure that any moving of objects within the allocated map is
3396 // done before we process them.
3397 if (!foundAny)
3398 To->setAttrs(AttrVec());
3399
3400 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3401
3402 if (!foundAny)
3403 To->dropAttrs();
3404}
3405
3406/// mergeParamDeclAttributes - Copy attributes from the old parameter
3407/// to the new one.
3409 const ParmVarDecl *oldDecl,
3410 Sema &S) {
3411 // C++11 [dcl.attr.depend]p2:
3412 // The first declaration of a function shall specify the
3413 // carries_dependency attribute for its declarator-id if any declaration
3414 // of the function specifies the carries_dependency attribute.
3415 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3416 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3417 S.Diag(CDA->getLocation(),
3418 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3419 // Find the first declaration of the parameter.
3420 // FIXME: Should we build redeclaration chains for function parameters?
3421 const FunctionDecl *FirstFD =
3422 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3423 const ParmVarDecl *FirstVD =
3424 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3425 S.Diag(FirstVD->getLocation(),
3426 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3427 }
3428
3430 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3431 unsigned found = 0;
3432 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3433 // Propagate the lifetimebound attribute from parameters to the
3434 // most recent declaration. Note that this doesn't include the implicit
3435 // 'this' parameter, as the attribute is applied to the function type in
3436 // that case.
3437 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3438 return found;
3439 });
3440}
3441
3443 const ASTContext &Ctx) {
3444
3445 auto NoSizeInfo = [&Ctx](QualType Ty) {
3446 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3447 return true;
3448 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3449 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3450 return false;
3451 };
3452
3453 // `type[]` is equivalent to `type *` and `type[*]`.
3454 if (NoSizeInfo(Old) && NoSizeInfo(New))
3455 return true;
3456
3457 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3458 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3459 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3460 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3461 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3462 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3463 return false;
3464 return true;
3465 }
3466
3467 // Only compare size, ignore Size modifiers and CVR.
3468 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3469 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3471 }
3472
3473 // Don't try to compare dependent sized array
3474 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3475 return true;
3476 }
3477
3478 return Old == New;
3479}
3480
3481static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3482 const ParmVarDecl *OldParam,
3483 Sema &S) {
3484 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3485 if (auto Newnullability = NewParam->getType()->getNullability()) {
3486 if (*Oldnullability != *Newnullability) {
3487 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3489 *Newnullability,
3491 != 0))
3493 *Oldnullability,
3495 != 0));
3496 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3497 }
3498 } else {
3499 QualType NewT = NewParam->getType();
3500 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3501 NewParam->setType(NewT);
3502 }
3503 }
3504 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3505 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3506 if (OldParamDT && NewParamDT &&
3507 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3508 QualType OldParamOT = OldParamDT->getOriginalType();
3509 QualType NewParamOT = NewParamDT->getOriginalType();
3510 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3511 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3512 << NewParam << NewParamOT;
3513 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3514 << OldParamOT;
3515 }
3516 }
3517}
3518
3519namespace {
3520
3521/// Used in MergeFunctionDecl to keep track of function parameters in
3522/// C.
3523struct GNUCompatibleParamWarning {
3524 ParmVarDecl *OldParm;
3525 ParmVarDecl *NewParm;
3526 QualType PromotedType;
3527};
3528
3529} // end anonymous namespace
3530
3531// Determine whether the previous declaration was a definition, implicit
3532// declaration, or a declaration.
3533template <typename T>
3534static std::pair<diag::kind, SourceLocation>
3536 diag::kind PrevDiag;
3537 SourceLocation OldLocation = Old->getLocation();
3538 if (Old->isThisDeclarationADefinition())
3539 PrevDiag = diag::note_previous_definition;
3540 else if (Old->isImplicit()) {
3541 PrevDiag = diag::note_previous_implicit_declaration;
3542 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3543 if (FD->getBuiltinID())
3544 PrevDiag = diag::note_previous_builtin_declaration;
3545 }
3546 if (OldLocation.isInvalid())
3547 OldLocation = New->getLocation();
3548 } else
3549 PrevDiag = diag::note_previous_declaration;
3550 return std::make_pair(PrevDiag, OldLocation);
3551}
3552
3553/// canRedefineFunction - checks if a function can be redefined. Currently,
3554/// only extern inline functions can be redefined, and even then only in
3555/// GNU89 mode.
3556static bool canRedefineFunction(const FunctionDecl *FD,
3557 const LangOptions& LangOpts) {
3558 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3559 !LangOpts.CPlusPlus &&
3560 FD->isInlineSpecified() &&
3561 FD->getStorageClass() == SC_Extern);
3562}
3563
3564const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3565 const AttributedType *AT = T->getAs<AttributedType>();
3566 while (AT && !AT->isCallingConv())
3567 AT = AT->getModifiedType()->getAs<AttributedType>();
3568 return AT;
3569}
3570
3571template <typename T>
3572static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3573 const DeclContext *DC = Old->getDeclContext();
3574 if (DC->isRecord())
3575 return false;
3576
3577 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3578 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3579 return true;
3580 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3581 return true;
3582 return false;
3583}
3584
3585template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3586static bool isExternC(VarTemplateDecl *) { return false; }
3587static bool isExternC(FunctionTemplateDecl *) { return false; }
3588
3589/// Check whether a redeclaration of an entity introduced by a
3590/// using-declaration is valid, given that we know it's not an overload
3591/// (nor a hidden tag declaration).
3592template<typename ExpectedDecl>
3594 ExpectedDecl *New) {
3595 // C++11 [basic.scope.declarative]p4:
3596 // Given a set of declarations in a single declarative region, each of
3597 // which specifies the same unqualified name,
3598 // -- they shall all refer to the same entity, or all refer to functions
3599 // and function templates; or
3600 // -- exactly one declaration shall declare a class name or enumeration
3601 // name that is not a typedef name and the other declarations shall all
3602 // refer to the same variable or enumerator, or all refer to functions
3603 // and function templates; in this case the class name or enumeration
3604 // name is hidden (3.3.10).
3605
3606 // C++11 [namespace.udecl]p14:
3607 // If a function declaration in namespace scope or block scope has the
3608 // same name and the same parameter-type-list as a function introduced
3609 // by a using-declaration, and the declarations do not declare the same
3610 // function, the program is ill-formed.
3611
3612 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3613 if (Old &&
3614 !Old->getDeclContext()->getRedeclContext()->Equals(
3615 New->getDeclContext()->getRedeclContext()) &&
3616 !(isExternC(Old) && isExternC(New)))
3617 Old = nullptr;
3618
3619 if (!Old) {
3620 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3621 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3622 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3623 return true;
3624 }
3625 return false;
3626}
3627
3629 const FunctionDecl *B) {
3630 assert(A->getNumParams() == B->getNumParams());
3631
3632 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3633 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3634 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3635 if (AttrA == AttrB)
3636 return true;
3637 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3638 AttrA->isDynamic() == AttrB->isDynamic();
3639 };
3640
3641 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3642}
3643
3644/// If necessary, adjust the semantic declaration context for a qualified
3645/// declaration to name the correct inline namespace within the qualifier.
3647 DeclaratorDecl *OldD) {
3648 // The only case where we need to update the DeclContext is when
3649 // redeclaration lookup for a qualified name finds a declaration
3650 // in an inline namespace within the context named by the qualifier:
3651 //
3652 // inline namespace N { int f(); }
3653 // int ::f(); // Sema DC needs adjusting from :: to N::.
3654 //
3655 // For unqualified declarations, the semantic context *can* change
3656 // along the redeclaration chain (for local extern declarations,
3657 // extern "C" declarations, and friend declarations in particular).
3658 if (!NewD->getQualifier())
3659 return;
3660
3661 // NewD is probably already in the right context.
3662 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3663 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3664 if (NamedDC->Equals(SemaDC))
3665 return;
3666
3667 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3668 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3669 "unexpected context for redeclaration");
3670
3671 auto *LexDC = NewD->getLexicalDeclContext();
3672 auto FixSemaDC = [=](NamedDecl *D) {
3673 if (!D)
3674 return;
3675 D->setDeclContext(SemaDC);
3676 D->setLexicalDeclContext(LexDC);
3677 };
3678
3679 FixSemaDC(NewD);
3680 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3681 FixSemaDC(FD->getDescribedFunctionTemplate());
3682 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3683 FixSemaDC(VD->getDescribedVarTemplate());
3684}
3685
3687 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3688 // Verify the old decl was also a function.
3689 FunctionDecl *Old = OldD->getAsFunction();
3690 if (!Old) {
3691 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3692 // We don't need to check the using friend pattern from other module unit
3693 // since we should have diagnosed such cases in its unit already.
3694 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3695 Diag(New->getLocation(), diag::err_using_decl_friend);
3696 Diag(Shadow->getTargetDecl()->getLocation(),
3697 diag::note_using_decl_target);
3698 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3699 << 0;
3700 return true;
3701 }
3702
3703 // Check whether the two declarations might declare the same function or
3704 // function template.
3705 if (FunctionTemplateDecl *NewTemplate =
3706 New->getDescribedFunctionTemplate()) {
3708 NewTemplate))
3709 return true;
3710 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3711 ->getAsFunction();
3712 } else {
3713 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3714 return true;
3715 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3716 }
3717 } else {
3718 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3719 << New->getDeclName();
3720 notePreviousDefinition(OldD, New->getLocation());
3721 return true;
3722 }
3723 }
3724
3725 // If the old declaration was found in an inline namespace and the new
3726 // declaration was qualified, update the DeclContext to match.
3728
3729 // If the old declaration is invalid, just give up here.
3730 if (Old->isInvalidDecl())
3731 return true;
3732
3733 // Disallow redeclaration of some builtins.
3734 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3735 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3736 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3737 << Old << Old->getType();
3738 return true;
3739 }
3740
3741 diag::kind PrevDiag;
3742 SourceLocation OldLocation;
3743 std::tie(PrevDiag, OldLocation) =
3745
3746 // Don't complain about this if we're in GNU89 mode and the old function
3747 // is an extern inline function.
3748 // Don't complain about specializations. They are not supposed to have
3749 // storage classes.
3750 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3751 New->getStorageClass() == SC_Static &&
3752 Old->hasExternalFormalLinkage() &&
3753 !New->getTemplateSpecializationInfo() &&
3755 if (getLangOpts().MicrosoftExt) {
3756 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3757 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3758 } else {
3759 Diag(New->getLocation(), diag::err_static_non_static) << New;
3760 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3761 return true;
3762 }
3763 }
3764
3765 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3766 if (!Old->hasAttr<InternalLinkageAttr>()) {
3767 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3768 << ILA;
3769 Diag(Old->getLocation(), diag::note_previous_declaration);
3770 New->dropAttr<InternalLinkageAttr>();
3771 }
3772
3773 if (auto *EA = New->getAttr<ErrorAttr>()) {
3774 if (!Old->hasAttr<ErrorAttr>()) {
3775 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3776 Diag(Old->getLocation(), diag::note_previous_declaration);
3777 New->dropAttr<ErrorAttr>();
3778 }
3779 }
3780
3782 return true;
3783
3784 if (!getLangOpts().CPlusPlus) {
3785 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3786 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3787 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3788 << New << OldOvl;
3789
3790 // Try our best to find a decl that actually has the overloadable
3791 // attribute for the note. In most cases (e.g. programs with only one
3792 // broken declaration/definition), this won't matter.
3793 //
3794 // FIXME: We could do this if we juggled some extra state in
3795 // OverloadableAttr, rather than just removing it.
3796 const Decl *DiagOld = Old;
3797 if (OldOvl) {
3798 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3799 const auto *A = D->getAttr<OverloadableAttr>();
3800 return A && !A->isImplicit();
3801 });
3802 // If we've implicitly added *all* of the overloadable attrs to this
3803 // chain, emitting a "previous redecl" note is pointless.
3804 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3805 }
3806
3807 if (DiagOld)
3808 Diag(DiagOld->getLocation(),
3809 diag::note_attribute_overloadable_prev_overload)
3810 << OldOvl;
3811
3812 if (OldOvl)
3813 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3814 else
3815 New->dropAttr<OverloadableAttr>();
3816 }
3817 }
3818
3819 // It is not permitted to redeclare an SME function with different SME
3820 // attributes.
3821 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3822 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3823 << New->getType() << Old->getType();
3824 Diag(OldLocation, diag::note_previous_declaration);
3825 return true;
3826 }
3827
3828 // If a function is first declared with a calling convention, but is later
3829 // declared or defined without one, all following decls assume the calling
3830 // convention of the first.
3831 //
3832 // It's OK if a function is first declared without a calling convention,
3833 // but is later declared or defined with the default calling convention.
3834 //
3835 // To test if either decl has an explicit calling convention, we look for
3836 // AttributedType sugar nodes on the type as written. If they are missing or
3837 // were canonicalized away, we assume the calling convention was implicit.
3838 //
3839 // Note also that we DO NOT return at this point, because we still have
3840 // other tests to run.
3841 QualType OldQType = Context.getCanonicalType(Old->getType());
3842 QualType NewQType = Context.getCanonicalType(New->getType());
3843 const FunctionType *OldType = cast<FunctionType>(OldQType);
3844 const FunctionType *NewType = cast<FunctionType>(NewQType);
3845 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3846 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3847 bool RequiresAdjustment = false;
3848
3849 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3851 const FunctionType *FT =
3852 First->getType().getCanonicalType()->castAs<FunctionType>();
3854 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3855 if (!NewCCExplicit) {
3856 // Inherit the CC from the previous declaration if it was specified
3857 // there but not here.
3858 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3859 RequiresAdjustment = true;
3860 } else if (Old->getBuiltinID()) {
3861 // Builtin attribute isn't propagated to the new one yet at this point,
3862 // so we check if the old one is a builtin.
3863
3864 // Calling Conventions on a Builtin aren't really useful and setting a
3865 // default calling convention and cdecl'ing some builtin redeclarations is
3866 // common, so warn and ignore the calling convention on the redeclaration.
3867 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3868 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3870 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3871 RequiresAdjustment = true;
3872 } else {
3873 // Calling conventions aren't compatible, so complain.
3874 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3875 Diag(New->getLocation(), diag::err_cconv_change)
3876 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3877 << !FirstCCExplicit
3878 << (!FirstCCExplicit ? "" :
3880
3881 // Put the note on the first decl, since it is the one that matters.
3882 Diag(First->getLocation(), diag::note_previous_declaration);
3883 return true;
3884 }
3885 }
3886
3887 // FIXME: diagnose the other way around?
3888 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3889 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3890 RequiresAdjustment = true;
3891 }
3892
3893 // If the declaration is marked with cfi_unchecked_callee but the definition
3894 // isn't, the definition is also cfi_unchecked_callee.
3895 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3896 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3897 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3898 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3899
3900 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3901 EPI2.CFIUncheckedCallee = true;
3902 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3903 FPT2->getParamTypes(), EPI2);
3904 NewType = cast<FunctionType>(NewQType);
3905 New->setType(NewQType);
3906 }
3907 }
3908 }
3909
3910 // Merge regparm attribute.
3911 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3912 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3913 if (NewTypeInfo.getHasRegParm()) {
3914 Diag(New->getLocation(), diag::err_regparm_mismatch)
3915 << NewType->getRegParmType()
3916 << OldType->getRegParmType();
3917 Diag(OldLocation, diag::note_previous_declaration);
3918 return true;
3919 }
3920
3921 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3922 RequiresAdjustment = true;
3923 }
3924
3925 // Merge ns_returns_retained attribute.
3926 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3927 if (NewTypeInfo.getProducesResult()) {
3928 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3929 << "'ns_returns_retained'";
3930 Diag(OldLocation, diag::note_previous_declaration);
3931 return true;
3932 }
3933
3934 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3935 RequiresAdjustment = true;
3936 }
3937
3938 if (OldTypeInfo.getNoCallerSavedRegs() !=
3939 NewTypeInfo.getNoCallerSavedRegs()) {
3940 if (NewTypeInfo.getNoCallerSavedRegs()) {
3941 AnyX86NoCallerSavedRegistersAttr *Attr =
3942 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3943 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3944 Diag(OldLocation, diag::note_previous_declaration);
3945 return true;
3946 }
3947
3948 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3949 RequiresAdjustment = true;
3950 }
3951
3952 if (RequiresAdjustment) {
3953 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3954 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3955 New->setType(QualType(AdjustedType, 0));
3956 NewQType = Context.getCanonicalType(New->getType());
3957 }
3958
3959 // If this redeclaration makes the function inline, we may need to add it to
3960 // UndefinedButUsed.
3961 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3962 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3963 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3964 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3965 SourceLocation()));
3966
3967 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3968 // about it.
3969 if (New->hasAttr<GNUInlineAttr>() &&
3970 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3971 UndefinedButUsed.erase(Old->getCanonicalDecl());
3972 }
3973
3974 // If pass_object_size params don't match up perfectly, this isn't a valid
3975 // redeclaration.
3976 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3978 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3979 << New->getDeclName();
3980 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3981 return true;
3982 }
3983
3984 QualType OldQTypeForComparison = OldQType;
3985 if (Context.hasAnyFunctionEffects()) {
3986 const auto OldFX = Old->getFunctionEffects();
3987 const auto NewFX = New->getFunctionEffects();
3988 if (OldFX != NewFX) {
3989 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3990 for (const auto &Diff : Diffs) {
3991 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3992 Diag(New->getLocation(),
3993 diag::warn_mismatched_func_effect_redeclaration)
3994 << Diff.effectName();
3995 Diag(Old->getLocation(), diag::note_previous_declaration);
3996 }
3997 }
3998 // Following a warning, we could skip merging effects from the previous
3999 // declaration, but that would trigger an additional "conflicting types"
4000 // error.
4001 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4003 FunctionEffectSet MergedFX =
4004 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4005 if (!MergeErrs.empty())
4006 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4007 Old->getLocation());
4008
4009 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4010 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4011 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4012 NewFPT->getParamTypes(), EPI);
4013
4014 New->setType(ModQT);
4015 NewQType = New->getType();
4016
4017 // Revise OldQTForComparison to include the merged effects,
4018 // so as not to fail due to differences later.
4019 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4020 EPI = OldFPT->getExtProtoInfo();
4021 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4022 OldQTypeForComparison = Context.getFunctionType(
4023 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4024 }
4025 if (OldFX.empty()) {
4026 // A redeclaration may add the attribute to a previously seen function
4027 // body which needs to be verified.
4028 maybeAddDeclWithEffects(Old, MergedFX);
4029 }
4030 }
4031 }
4032 }
4033
4034 if (getLangOpts().CPlusPlus) {
4035 OldQType = Context.getCanonicalType(Old->getType());
4036 NewQType = Context.getCanonicalType(New->getType());
4037
4038 // Go back to the type source info to compare the declared return types,
4039 // per C++1y [dcl.type.auto]p13:
4040 // Redeclarations or specializations of a function or function template
4041 // with a declared return type that uses a placeholder type shall also
4042 // use that placeholder, not a deduced type.
4043 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4044 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4045 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4046 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4047 OldDeclaredReturnType)) {
4048 QualType ResQT;
4049 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4050 OldDeclaredReturnType->isObjCObjectPointerType())
4051 // FIXME: This does the wrong thing for a deduced return type.
4052 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4053 if (ResQT.isNull()) {
4054 if (New->isCXXClassMember() && New->isOutOfLine())
4055 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4056 << New << New->getReturnTypeSourceRange();
4057 else if (Old->isExternC() && New->isExternC() &&
4058 !Old->hasAttr<OverloadableAttr>() &&
4059 !New->hasAttr<OverloadableAttr>())
4060 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4061 else
4062 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4063 << New->getReturnTypeSourceRange();
4064 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4065 << Old->getReturnTypeSourceRange();
4066 return true;
4067 }
4068 else
4069 NewQType = ResQT;
4070 }
4071
4072 QualType OldReturnType = OldType->getReturnType();
4073 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4074 if (OldReturnType != NewReturnType) {
4075 // If this function has a deduced return type and has already been
4076 // defined, copy the deduced value from the old declaration.
4077 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4078 if (OldAT && OldAT->isDeduced()) {
4079 QualType DT = OldAT->getDeducedType();
4080 if (DT.isNull()) {
4081 New->setType(SubstAutoTypeDependent(New->getType()));
4082 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4083 } else {
4084 New->setType(SubstAutoType(New->getType(), DT));
4085 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4086 }
4087 }
4088 }
4089
4090 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4091 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4092 if (OldMethod && NewMethod) {
4093 // Preserve triviality.
4094 NewMethod->setTrivial(OldMethod->isTrivial());
4095
4096 // MSVC allows explicit template specialization at class scope:
4097 // 2 CXXMethodDecls referring to the same function will be injected.
4098 // We don't want a redeclaration error.
4099 bool IsClassScopeExplicitSpecialization =
4100 OldMethod->isFunctionTemplateSpecialization() &&
4102 bool isFriend = NewMethod->getFriendObjectKind();
4103
4104 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4105 !IsClassScopeExplicitSpecialization) {
4106 // -- Member function declarations with the same name and the
4107 // same parameter types cannot be overloaded if any of them
4108 // is a static member function declaration.
4109 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4110 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4111 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4112 return true;
4113 }
4114
4115 // C++ [class.mem]p1:
4116 // [...] A member shall not be declared twice in the
4117 // member-specification, except that a nested class or member
4118 // class template can be declared and then later defined.
4119 if (!inTemplateInstantiation()) {
4120 unsigned NewDiag;
4121 if (isa<CXXConstructorDecl>(OldMethod))
4122 NewDiag = diag::err_constructor_redeclared;
4123 else if (isa<CXXDestructorDecl>(NewMethod))
4124 NewDiag = diag::err_destructor_redeclared;
4125 else if (isa<CXXConversionDecl>(NewMethod))
4126 NewDiag = diag::err_conv_function_redeclared;
4127 else
4128 NewDiag = diag::err_member_redeclared;
4129
4130 Diag(New->getLocation(), NewDiag);
4131 } else {
4132 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4133 << New << New->getType();
4134 }
4135 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4136 return true;
4137
4138 // Complain if this is an explicit declaration of a special
4139 // member that was initially declared implicitly.
4140 //
4141 // As an exception, it's okay to befriend such methods in order
4142 // to permit the implicit constructor/destructor/operator calls.
4143 } else if (OldMethod->isImplicit()) {
4144 if (isFriend) {
4145 NewMethod->setImplicit();
4146 } else {
4147 Diag(NewMethod->getLocation(),
4148 diag::err_definition_of_implicitly_declared_member)
4149 << New << getSpecialMember(OldMethod);
4150 return true;
4151 }
4152 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4153 Diag(NewMethod->getLocation(),
4154 diag::err_definition_of_explicitly_defaulted_member)
4155 << getSpecialMember(OldMethod);
4156 return true;
4157 }
4158 }
4159
4160 // C++1z [over.load]p2
4161 // Certain function declarations cannot be overloaded:
4162 // -- Function declarations that differ only in the return type,
4163 // the exception specification, or both cannot be overloaded.
4164
4165 // Check the exception specifications match. This may recompute the type of
4166 // both Old and New if it resolved exception specifications, so grab the
4167 // types again after this. Because this updates the type, we do this before
4168 // any of the other checks below, which may update the "de facto" NewQType
4169 // but do not necessarily update the type of New.
4171 return true;
4172
4173 // C++11 [dcl.attr.noreturn]p1:
4174 // The first declaration of a function shall specify the noreturn
4175 // attribute if any declaration of that function specifies the noreturn
4176 // attribute.
4177 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4178 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4179 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4180 << NRA;
4181 Diag(Old->getLocation(), diag::note_previous_declaration);
4182 }
4183
4184 // C++11 [dcl.attr.depend]p2:
4185 // The first declaration of a function shall specify the
4186 // carries_dependency attribute for its declarator-id if any declaration
4187 // of the function specifies the carries_dependency attribute.
4188 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4189 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4190 Diag(CDA->getLocation(),
4191 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4192 Diag(Old->getFirstDecl()->getLocation(),
4193 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4194 }
4195
4196 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4197 // When a function is declared with SYCL_EXTERNAL, that macro must be
4198 // used on the first declaration of that function in the translation unit.
4199 // Redeclarations of the function in the same translation unit may
4200 // optionally use SYCL_EXTERNAL, but this is not required.
4201 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4202 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4203 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4204 << SEA;
4205 Diag(Old->getLocation(), diag::note_previous_declaration);
4206 }
4207
4208 // (C++98 8.3.5p3):
4209 // All declarations for a function shall agree exactly in both the
4210 // return type and the parameter-type-list.
4211 // We also want to respect all the extended bits except noreturn.
4212
4213 // noreturn should now match unless the old type info didn't have it.
4214 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4215 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4216 const FunctionType *OldTypeForComparison
4217 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4218 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4219 assert(OldQTypeForComparison.isCanonical());
4220 }
4221
4223 // As a special case, retain the language linkage from previous
4224 // declarations of a friend function as an extension.
4225 //
4226 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4227 // and is useful because there's otherwise no way to specify language
4228 // linkage within class scope.
4229 //
4230 // Check cautiously as the friend object kind isn't yet complete.
4231 if (New->getFriendObjectKind() != Decl::FOK_None) {
4232 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4233 Diag(OldLocation, PrevDiag);
4234 } else {
4235 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4236 Diag(OldLocation, PrevDiag);
4237 return true;
4238 }
4239 }
4240
4241 // HLSL check parameters for matching ABI specifications.
4242 if (getLangOpts().HLSL) {
4243 if (HLSL().CheckCompatibleParameterABI(New, Old))
4244 return true;
4245
4246 // If no errors are generated when checking parameter ABIs we can check if
4247 // the two declarations have the same type ignoring the ABIs and if so,
4248 // the declarations can be merged. This case for merging is only valid in
4249 // HLSL because there are no valid cases of merging mismatched parameter
4250 // ABIs except the HLSL implicit in and explicit in.
4251 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4252 NewQType))
4253 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4254 // Fall through for conflicting redeclarations and redefinitions.
4255 }
4256
4257 // If the function types are compatible, merge the declarations. Ignore the
4258 // exception specifier because it was already checked above in
4259 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4260 // about incompatible types under -fms-compatibility.
4261 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4262 NewQType))
4263 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4264
4265 // If the types are imprecise (due to dependent constructs in friends or
4266 // local extern declarations), it's OK if they differ. We'll check again
4267 // during instantiation.
4268 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4269 return false;
4270
4271 // Fall through for conflicting redeclarations and redefinitions.
4272 }
4273
4274 // C: Function types need to be compatible, not identical. This handles
4275 // duplicate function decls like "void f(int); void f(enum X);" properly.
4276 if (!getLangOpts().CPlusPlus) {
4277 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4278 // type is specified by a function definition that contains a (possibly
4279 // empty) identifier list, both shall agree in the number of parameters
4280 // and the type of each parameter shall be compatible with the type that
4281 // results from the application of default argument promotions to the
4282 // type of the corresponding identifier. ...
4283 // This cannot be handled by ASTContext::typesAreCompatible() because that
4284 // doesn't know whether the function type is for a definition or not when
4285 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4286 // we need to cover here is that the number of arguments agree as the
4287 // default argument promotion rules were already checked by
4288 // ASTContext::typesAreCompatible().
4289 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4290 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4291 if (Old->hasInheritedPrototype())
4292 Old = Old->getCanonicalDecl();
4293 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4294 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4295 return true;
4296 }
4297
4298 // If we are merging two functions where only one of them has a prototype,
4299 // we may have enough information to decide to issue a diagnostic that the
4300 // function without a prototype will change behavior in C23. This handles
4301 // cases like:
4302 // void i(); void i(int j);
4303 // void i(int j); void i();
4304 // void i(); void i(int j) {}
4305 // See ActOnFinishFunctionBody() for other cases of the behavior change
4306 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4307 // type without a prototype.
4308 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4309 !New->isImplicit() && !Old->isImplicit()) {
4310 const FunctionDecl *WithProto, *WithoutProto;
4311 if (New->hasWrittenPrototype()) {
4312 WithProto = New;
4313 WithoutProto = Old;
4314 } else {
4315 WithProto = Old;
4316 WithoutProto = New;
4317 }
4318
4319 if (WithProto->getNumParams() != 0) {
4320 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4321 // The one without the prototype will be changing behavior in C23, so
4322 // warn about that one so long as it's a user-visible declaration.
4323 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4324 if (WithoutProto == New)
4325 IsWithoutProtoADef = NewDeclIsDefn;
4326 else
4327 IsWithProtoADef = NewDeclIsDefn;
4328 Diag(WithoutProto->getLocation(),
4329 diag::warn_non_prototype_changes_behavior)
4330 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4331 << (WithoutProto == Old) << IsWithProtoADef;
4332
4333 // The reason the one without the prototype will be changing behavior
4334 // is because of the one with the prototype, so note that so long as
4335 // it's a user-visible declaration. There is one exception to this:
4336 // when the new declaration is a definition without a prototype, the
4337 // old declaration with a prototype is not the cause of the issue,
4338 // and that does not need to be noted because the one with a
4339 // prototype will not change behavior in C23.
4340 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4341 !IsWithoutProtoADef)
4342 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4343 }
4344 }
4345 }
4346
4347 if (Context.typesAreCompatible(OldQType, NewQType)) {
4348 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4349 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4350 const FunctionProtoType *OldProto = nullptr;
4351 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4352 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4353 // The old declaration provided a function prototype, but the
4354 // new declaration does not. Merge in the prototype.
4355 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4356 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4357 OldProto->getParamTypes(),
4358 OldProto->getExtProtoInfo());
4359 New->setType(NewQType);
4360 New->setHasInheritedPrototype();
4361
4362 // Synthesize parameters with the same types.
4364 for (const auto &ParamType : OldProto->param_types()) {
4366 Context, New, SourceLocation(), SourceLocation(), nullptr,
4367 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4368 Param->setScopeInfo(0, Params.size());
4369 Param->setImplicit();
4370 Params.push_back(Param);
4371 }
4372
4373 New->setParams(Params);
4374 }
4375
4376 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4377 }
4378 }
4379
4380 // Check if the function types are compatible when pointer size address
4381 // spaces are ignored.
4382 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4383 return false;
4384
4385 // GNU C permits a K&R definition to follow a prototype declaration
4386 // if the declared types of the parameters in the K&R definition
4387 // match the types in the prototype declaration, even when the
4388 // promoted types of the parameters from the K&R definition differ
4389 // from the types in the prototype. GCC then keeps the types from
4390 // the prototype.
4391 //
4392 // If a variadic prototype is followed by a non-variadic K&R definition,
4393 // the K&R definition becomes variadic. This is sort of an edge case, but
4394 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4395 // C99 6.9.1p8.
4396 if (!getLangOpts().CPlusPlus &&
4397 Old->hasPrototype() && !New->hasPrototype() &&
4398 New->getType()->getAs<FunctionProtoType>() &&
4399 Old->getNumParams() == New->getNumParams()) {
4402 const FunctionProtoType *OldProto
4403 = Old->getType()->getAs<FunctionProtoType>();
4404 const FunctionProtoType *NewProto
4405 = New->getType()->getAs<FunctionProtoType>();
4406
4407 // Determine whether this is the GNU C extension.
4408 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4409 NewProto->getReturnType());
4410 bool LooseCompatible = !MergedReturn.isNull();
4411 for (unsigned Idx = 0, End = Old->getNumParams();
4412 LooseCompatible && Idx != End; ++Idx) {
4413 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4414 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4415 if (Context.typesAreCompatible(OldParm->getType(),
4416 NewProto->getParamType(Idx))) {
4417 ArgTypes.push_back(NewParm->getType());
4418 } else if (Context.typesAreCompatible(OldParm->getType(),
4419 NewParm->getType(),
4420 /*CompareUnqualified=*/true)) {
4421 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4422 NewProto->getParamType(Idx) };
4423 Warnings.push_back(Warn);
4424 ArgTypes.push_back(NewParm->getType());
4425 } else
4426 LooseCompatible = false;
4427 }
4428
4429 if (LooseCompatible) {
4430 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4431 Diag(Warnings[Warn].NewParm->getLocation(),
4432 diag::ext_param_promoted_not_compatible_with_prototype)
4433 << Warnings[Warn].PromotedType
4434 << Warnings[Warn].OldParm->getType();
4435 if (Warnings[Warn].OldParm->getLocation().isValid())
4436 Diag(Warnings[Warn].OldParm->getLocation(),
4437 diag::note_previous_declaration);
4438 }
4439
4440 if (MergeTypeWithOld)
4441 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4442 OldProto->getExtProtoInfo()));
4443 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4444 }
4445
4446 // Fall through to diagnose conflicting types.
4447 }
4448
4449 // A function that has already been declared has been redeclared or
4450 // defined with a different type; show an appropriate diagnostic.
4451
4452 // If the previous declaration was an implicitly-generated builtin
4453 // declaration, then at the very least we should use a specialized note.
4454 unsigned BuiltinID;
4455 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4456 // If it's actually a library-defined builtin function like 'malloc'
4457 // or 'printf', just warn about the incompatible redeclaration.
4458 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4459 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4460 Diag(OldLocation, diag::note_previous_builtin_declaration)
4461 << Old << Old->getType();
4462 return false;
4463 }
4464
4465 PrevDiag = diag::note_previous_builtin_declaration;
4466 }
4467
4468 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4469 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4470 return true;
4471}
4472
4474 Scope *S, bool MergeTypeWithOld) {
4475 // Merge the attributes
4477
4478 // Merge "pure" flag.
4479 if (Old->isPureVirtual())
4480 New->setIsPureVirtual();
4481
4482 // Merge "used" flag.
4483 if (Old->getMostRecentDecl()->isUsed(false))
4484 New->setIsUsed();
4485
4486 // Merge attributes from the parameters. These can mismatch with K&R
4487 // declarations.
4488 if (New->getNumParams() == Old->getNumParams())
4489 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4490 ParmVarDecl *NewParam = New->getParamDecl(i);
4491 ParmVarDecl *OldParam = Old->getParamDecl(i);
4492 mergeParamDeclAttributes(NewParam, OldParam, *this);
4493 mergeParamDeclTypes(NewParam, OldParam, *this);
4494 }
4495
4496 if (getLangOpts().CPlusPlus)
4497 return MergeCXXFunctionDecl(New, Old, S);
4498
4499 // Merge the function types so the we get the composite types for the return
4500 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4501 // was visible.
4502 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4503 if (!Merged.isNull() && MergeTypeWithOld)
4504 New->setType(Merged);
4505
4506 return false;
4507}
4508
4510 ObjCMethodDecl *oldMethod) {
4511 // Merge the attributes, including deprecated/unavailable
4512 AvailabilityMergeKind MergeKind =
4514 ? (oldMethod->isOptional()
4517 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4520
4521 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4522
4523 // Merge attributes from the parameters.
4525 oe = oldMethod->param_end();
4527 ni = newMethod->param_begin(), ne = newMethod->param_end();
4528 ni != ne && oi != oe; ++ni, ++oi)
4529 mergeParamDeclAttributes(*ni, *oi, *this);
4530
4531 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4532}
4533
4535 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4536
4537 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4538 ? diag::err_redefinition_different_type
4539 : diag::err_redeclaration_different_type)
4540 << New->getDeclName() << New->getType() << Old->getType();
4541
4542 diag::kind PrevDiag;
4543 SourceLocation OldLocation;
4544 std::tie(PrevDiag, OldLocation)
4546 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4547 New->setInvalidDecl();
4548}
4549
4551 bool MergeTypeWithOld) {
4552 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4553 return;
4554
4555 QualType MergedT;
4556 if (getLangOpts().CPlusPlus) {
4557 if (New->getType()->isUndeducedType()) {
4558 // We don't know what the new type is until the initializer is attached.
4559 return;
4560 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4561 // These could still be something that needs exception specs checked.
4562 return MergeVarDeclExceptionSpecs(New, Old);
4563 }
4564 // C++ [basic.link]p10:
4565 // [...] the types specified by all declarations referring to a given
4566 // object or function shall be identical, except that declarations for an
4567 // array object can specify array types that differ by the presence or
4568 // absence of a major array bound (8.3.4).
4569 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4570 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4571 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4572
4573 // We are merging a variable declaration New into Old. If it has an array
4574 // bound, and that bound differs from Old's bound, we should diagnose the
4575 // mismatch.
4576 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4577 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4578 PrevVD = PrevVD->getPreviousDecl()) {
4579 QualType PrevVDTy = PrevVD->getType();
4580 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4581 continue;
4582
4583 if (!Context.hasSameType(New->getType(), PrevVDTy))
4584 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4585 }
4586 }
4587
4588 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4589 if (Context.hasSameType(OldArray->getElementType(),
4590 NewArray->getElementType()))
4591 MergedT = New->getType();
4592 }
4593 // FIXME: Check visibility. New is hidden but has a complete type. If New
4594 // has no array bound, it should not inherit one from Old, if Old is not
4595 // visible.
4596 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4597 if (Context.hasSameType(OldArray->getElementType(),
4598 NewArray->getElementType()))
4599 MergedT = Old->getType();
4600 }
4601 }
4602 else if (New->getType()->isObjCObjectPointerType() &&
4603 Old->getType()->isObjCObjectPointerType()) {
4604 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4605 Old->getType());
4606 }
4607 } else {
4608 // C 6.2.7p2:
4609 // All declarations that refer to the same object or function shall have
4610 // compatible type.
4611 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4612 }
4613 if (MergedT.isNull()) {
4614 // It's OK if we couldn't merge types if either type is dependent, for a
4615 // block-scope variable. In other cases (static data members of class
4616 // templates, variable templates, ...), we require the types to be
4617 // equivalent.
4618 // FIXME: The C++ standard doesn't say anything about this.
4619 if ((New->getType()->isDependentType() ||
4620 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4621 // If the old type was dependent, we can't merge with it, so the new type
4622 // becomes dependent for now. We'll reproduce the original type when we
4623 // instantiate the TypeSourceInfo for the variable.
4624 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4625 New->setType(Context.DependentTy);
4626 return;
4627 }
4628 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4629 }
4630
4631 // Don't actually update the type on the new declaration if the old
4632 // declaration was an extern declaration in a different scope.
4633 if (MergeTypeWithOld)
4634 New->setType(MergedT);
4635}
4636
4637static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4639 // C11 6.2.7p4:
4640 // For an identifier with internal or external linkage declared
4641 // in a scope in which a prior declaration of that identifier is
4642 // visible, if the prior declaration specifies internal or
4643 // external linkage, the type of the identifier at the later
4644 // declaration becomes the composite type.
4645 //
4646 // If the variable isn't visible, we do not merge with its type.
4647 if (Previous.isShadowed())
4648 return false;
4649
4650 if (S.getLangOpts().CPlusPlus) {
4651 // C++11 [dcl.array]p3:
4652 // If there is a preceding declaration of the entity in the same
4653 // scope in which the bound was specified, an omitted array bound
4654 // is taken to be the same as in that earlier declaration.
4655 return NewVD->isPreviousDeclInSameBlockScope() ||
4656 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4658 } else {
4659 // If the old declaration was function-local, don't merge with its
4660 // type unless we're in the same function.
4661 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4662 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4663 }
4664}
4665
4667 // If the new decl is already invalid, don't do any other checking.
4668 if (New->isInvalidDecl())
4669 return;
4670
4671 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4672 return;
4673
4674 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4675
4676 // Verify the old decl was also a variable or variable template.
4677 VarDecl *Old = nullptr;
4678 VarTemplateDecl *OldTemplate = nullptr;
4679 if (Previous.isSingleResult()) {
4680 if (NewTemplate) {
4681 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4682 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4683
4684 if (auto *Shadow =
4685 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4686 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4687 return New->setInvalidDecl();
4688 } else {
4689 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4690
4691 if (auto *Shadow =
4692 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4693 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4694 return New->setInvalidDecl();
4695 }
4696 }
4697 if (!Old) {
4698 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4699 << New->getDeclName();
4700 notePreviousDefinition(Previous.getRepresentativeDecl(),
4701 New->getLocation());
4702 return New->setInvalidDecl();
4703 }
4704
4705 // If the old declaration was found in an inline namespace and the new
4706 // declaration was qualified, update the DeclContext to match.
4708
4709 // Ensure the template parameters are compatible.
4710 if (NewTemplate &&
4712 OldTemplate->getTemplateParameters(),
4713 /*Complain=*/true, TPL_TemplateMatch))
4714 return New->setInvalidDecl();
4715
4716 // C++ [class.mem]p1:
4717 // A member shall not be declared twice in the member-specification [...]
4718 //
4719 // Here, we need only consider static data members.
4720 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4721 Diag(New->getLocation(), diag::err_duplicate_member)
4722 << New->getIdentifier();
4723 Diag(Old->getLocation(), diag::note_previous_declaration);
4724 New->setInvalidDecl();
4725 }
4726
4728 // Warn if an already-defined variable is made a weak_import in a subsequent
4729 // declaration
4730 if (New->hasAttr<WeakImportAttr>())
4731 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4732 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4733 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4734 Diag(D->getLocation(), diag::note_previous_definition);
4735 // Remove weak_import attribute on new declaration.
4736 New->dropAttr<WeakImportAttr>();
4737 break;
4738 }
4739 }
4740
4741 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4742 if (!Old->hasAttr<InternalLinkageAttr>()) {
4743 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4744 << ILA;
4745 Diag(Old->getLocation(), diag::note_previous_declaration);
4746 New->dropAttr<InternalLinkageAttr>();
4747 }
4748
4749 // Merge the types.
4750 VarDecl *MostRecent = Old->getMostRecentDecl();
4751 if (MostRecent != Old) {
4752 MergeVarDeclTypes(New, MostRecent,
4753 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4754 if (New->isInvalidDecl())
4755 return;
4756 }
4757
4759 if (New->isInvalidDecl())
4760 return;
4761
4762 diag::kind PrevDiag;
4763 SourceLocation OldLocation;
4764 std::tie(PrevDiag, OldLocation) =
4766
4767 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4768 if (New->getStorageClass() == SC_Static &&
4769 !New->isStaticDataMember() &&
4770 Old->hasExternalFormalLinkage()) {
4771 if (getLangOpts().MicrosoftExt) {
4772 Diag(New->getLocation(), diag::ext_static_non_static)
4773 << New->getDeclName();
4774 Diag(OldLocation, PrevDiag);
4775 } else {
4776 Diag(New->getLocation(), diag::err_static_non_static)
4777 << New->getDeclName();
4778 Diag(OldLocation, PrevDiag);
4779 return New->setInvalidDecl();
4780 }
4781 }
4782 // C99 6.2.2p4:
4783 // For an identifier declared with the storage-class specifier
4784 // extern in a scope in which a prior declaration of that
4785 // identifier is visible,23) if the prior declaration specifies
4786 // internal or external linkage, the linkage of the identifier at
4787 // the later declaration is the same as the linkage specified at
4788 // the prior declaration. If no prior declaration is visible, or
4789 // if the prior declaration specifies no linkage, then the
4790 // identifier has external linkage.
4791 if (New->hasExternalStorage() && Old->hasLinkage())
4792 /* Okay */;
4793 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4794 !New->isStaticDataMember() &&
4796 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4797 Diag(OldLocation, PrevDiag);
4798 return New->setInvalidDecl();
4799 }
4800
4801 // Check if extern is followed by non-extern and vice-versa.
4802 if (New->hasExternalStorage() &&
4803 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4804 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4805 Diag(OldLocation, PrevDiag);
4806 return New->setInvalidDecl();
4807 }
4808 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4809 !New->hasExternalStorage()) {
4810 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4811 Diag(OldLocation, PrevDiag);
4812 return New->setInvalidDecl();
4813 }
4814
4816 return;
4817
4818 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4819
4820 // FIXME: The test for external storage here seems wrong? We still
4821 // need to check for mismatches.
4822 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4823 // Don't complain about out-of-line definitions of static members.
4824 !(Old->getLexicalDeclContext()->isRecord() &&
4825 !New->getLexicalDeclContext()->isRecord())) {
4826 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4827 Diag(OldLocation, PrevDiag);
4828 return New->setInvalidDecl();
4829 }
4830
4831 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4832 if (VarDecl *Def = Old->getDefinition()) {
4833 // C++1z [dcl.fcn.spec]p4:
4834 // If the definition of a variable appears in a translation unit before
4835 // its first declaration as inline, the program is ill-formed.
4836 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4837 Diag(Def->getLocation(), diag::note_previous_definition);
4838 }
4839 }
4840
4841 // If this redeclaration makes the variable inline, we may need to add it to
4842 // UndefinedButUsed.
4843 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4844 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4845 !Old->isInAnotherModuleUnit())
4846 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4847 SourceLocation()));
4848
4849 if (New->getTLSKind() != Old->getTLSKind()) {
4850 if (!Old->getTLSKind()) {
4851 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4852 Diag(OldLocation, PrevDiag);
4853 } else if (!New->getTLSKind()) {
4854 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4855 Diag(OldLocation, PrevDiag);
4856 } else {
4857 // Do not allow redeclaration to change the variable between requiring
4858 // static and dynamic initialization.
4859 // FIXME: GCC allows this, but uses the TLS keyword on the first
4860 // declaration to determine the kind. Do we need to be compatible here?
4861 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4862 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4863 Diag(OldLocation, PrevDiag);
4864 }
4865 }
4866
4867 // C++ doesn't have tentative definitions, so go right ahead and check here.
4868 if (getLangOpts().CPlusPlus) {
4869 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4870 Old->getCanonicalDecl()->isConstexpr()) {
4871 // This definition won't be a definition any more once it's been merged.
4872 Diag(New->getLocation(),
4873 diag::warn_deprecated_redundant_constexpr_static_def);
4874 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4875 VarDecl *Def = Old->getDefinition();
4876 if (Def && checkVarDeclRedefinition(Def, New))
4877 return;
4878 }
4879 } else {
4880 // C++ may not have a tentative definition rule, but it has a different
4881 // rule about what constitutes a definition in the first place. See
4882 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4883 // contains the extern specifier and doesn't have an initializer, it's fine
4884 // in C++.
4885 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4886 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4887 << New;
4888 Diag(Old->getLocation(), diag::note_previous_declaration);
4889 }
4890 }
4891
4893 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4894 Diag(OldLocation, PrevDiag);
4895 New->setInvalidDecl();
4896 return;
4897 }
4898
4899 // Merge "used" flag.
4900 if (Old->getMostRecentDecl()->isUsed(false))
4901 New->setIsUsed();
4902
4903 // Keep a chain of previous declarations.
4904 New->setPreviousDecl(Old);
4905 if (NewTemplate)
4906 NewTemplate->setPreviousDecl(OldTemplate);
4907
4908 // Inherit access appropriately.
4909 New->setAccess(Old->getAccess());
4910 if (NewTemplate)
4911 NewTemplate->setAccess(New->getAccess());
4912
4913 if (Old->isInline())
4914 New->setImplicitlyInline();
4915}
4916
4919 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4920 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4921 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4922 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4923 auto &HSI = PP.getHeaderSearchInfo();
4924 StringRef HdrFilename =
4925 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4926
4927 auto noteFromModuleOrInclude = [&](Module *Mod,
4928 SourceLocation IncLoc) -> bool {
4929 // Redefinition errors with modules are common with non modular mapped
4930 // headers, example: a non-modular header H in module A that also gets
4931 // included directly in a TU. Pointing twice to the same header/definition
4932 // is confusing, try to get better diagnostics when modules is on.
4933 if (IncLoc.isValid()) {
4934 if (Mod) {
4935 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4936 << HdrFilename.str() << Mod->getFullModuleName();
4937 if (!Mod->DefinitionLoc.isInvalid())
4938 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4939 << Mod->getFullModuleName();
4940 } else {
4941 Diag(IncLoc, diag::note_redefinition_include_same_file)
4942 << HdrFilename.str();
4943 }
4944 return true;
4945 }
4946
4947 return false;
4948 };
4949
4950 // Is it the same file and same offset? Provide more information on why
4951 // this leads to a redefinition error.
4952 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4953 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4954 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4955 bool EmittedDiag =
4956 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4957 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4958
4959 // If the header has no guards, emit a note suggesting one.
4960 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4961 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4962
4963 if (EmittedDiag)
4964 return;
4965 }
4966
4967 // Redefinition coming from different files or couldn't do better above.
4968 if (Old->getLocation().isValid())
4969 Diag(Old->getLocation(), diag::note_previous_definition);
4970}
4971
4973 if (!hasVisibleDefinition(Old) &&
4974 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4976 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4977 New->getDeclContext()->isDependentContext() ||
4978 New->hasAttr<SelectAnyAttr>())) {
4979 // The previous definition is hidden, and multiple definitions are
4980 // permitted (in separate TUs). Demote this to a declaration.
4981 New->demoteThisDefinitionToDeclaration();
4982
4983 // Make the canonical definition visible.
4984 if (auto *OldTD = Old->getDescribedVarTemplate())
4987 return false;
4988 } else {
4989 Diag(New->getLocation(), diag::err_redefinition) << New;
4990 notePreviousDefinition(Old, New->getLocation());
4991 New->setInvalidDecl();
4992 return true;
4993 }
4994}
4995
4997 DeclSpec &DS,
4998 const ParsedAttributesView &DeclAttrs,
4999 RecordDecl *&AnonRecord) {
5001 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5002}
5003
5004// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5005// disambiguate entities defined in different scopes.
5006// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5007// compatibility.
5008// We will pick our mangling number depending on which version of MSVC is being
5009// targeted.
5010static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5014}
5015
5016void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5017 if (!Context.getLangOpts().CPlusPlus)
5018 return;
5019
5020 if (isa<CXXRecordDecl>(Tag->getParent())) {
5021 // If this tag is the direct child of a class, number it if
5022 // it is anonymous.
5023 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5024 return;
5026 Context.getManglingNumberContext(Tag->getParent());
5027 Context.setManglingNumber(
5028 Tag, MCtx.getManglingNumber(
5029 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5030 return;
5031 }
5032
5033 // If this tag isn't a direct child of a class, number it if it is local.
5035 Decl *ManglingContextDecl;
5036 std::tie(MCtx, ManglingContextDecl) =
5037 getCurrentMangleNumberContext(Tag->getDeclContext());
5038 if (MCtx) {
5039 Context.setManglingNumber(
5040 Tag, MCtx->getManglingNumber(
5041 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5042 }
5043}
5044
5045namespace {
5046struct NonCLikeKind {
5047 enum {
5048 None,
5049 BaseClass,
5050 DefaultMemberInit,
5051 Lambda,
5052 Friend,
5053 OtherMember,
5054 Invalid,
5055 } Kind = None;
5056 SourceRange Range;
5057
5058 explicit operator bool() { return Kind != None; }
5059};
5060}
5061
5062/// Determine whether a class is C-like, according to the rules of C++
5063/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5064static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5065 if (RD->isInvalidDecl())
5066 return {NonCLikeKind::Invalid, {}};
5067
5068 // C++ [dcl.typedef]p9: [P1766R1]
5069 // An unnamed class with a typedef name for linkage purposes shall not
5070 //
5071 // -- have any base classes
5072 if (RD->getNumBases())
5073 return {NonCLikeKind::BaseClass,
5075 RD->bases_end()[-1].getEndLoc())};
5076 bool Invalid = false;
5077 for (Decl *D : RD->decls()) {
5078 // Don't complain about things we already diagnosed.
5079 if (D->isInvalidDecl()) {
5080 Invalid = true;
5081 continue;
5082 }
5083
5084 // -- have any [...] default member initializers
5085 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5086 if (FD->hasInClassInitializer()) {
5087 auto *Init = FD->getInClassInitializer();
5088 return {NonCLikeKind::DefaultMemberInit,
5089 Init ? Init->getSourceRange() : D->getSourceRange()};
5090 }
5091 continue;
5092 }
5093
5094 // FIXME: We don't allow friend declarations. This violates the wording of
5095 // P1766, but not the intent.
5096 if (isa<FriendDecl>(D))
5097 return {NonCLikeKind::Friend, D->getSourceRange()};
5098
5099 // -- declare any members other than non-static data members, member
5100 // enumerations, or member classes,
5102 isa<EnumDecl>(D))
5103 continue;
5104 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5105 if (!MemberRD) {
5106 if (D->isImplicit())
5107 continue;
5108 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5109 }
5110
5111 // -- contain a lambda-expression,
5112 if (MemberRD->isLambda())
5113 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5114
5115 // and all member classes shall also satisfy these requirements
5116 // (recursively).
5117 if (MemberRD->isThisDeclarationADefinition()) {
5118 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5119 return Kind;
5120 }
5121 }
5122
5123 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5124}
5125
5127 TypedefNameDecl *NewTD) {
5128 if (TagFromDeclSpec->isInvalidDecl())
5129 return;
5130
5131 // Do nothing if the tag already has a name for linkage purposes.
5132 if (TagFromDeclSpec->hasNameForLinkage())
5133 return;
5134
5135 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5136 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5137
5138 // The type must match the tag exactly; no qualifiers allowed.
5139 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5140 Context.getCanonicalTagType(TagFromDeclSpec))) {
5141 if (getLangOpts().CPlusPlus)
5142 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5143 return;
5144 }
5145
5146 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5147 // An unnamed class with a typedef name for linkage purposes shall [be
5148 // C-like].
5149 //
5150 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5151 // shouldn't happen, but there are constructs that the language rule doesn't
5152 // disallow for which we can't reasonably avoid computing linkage early.
5153 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5154 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5155 : NonCLikeKind();
5156 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5157 if (NonCLike || ChangesLinkage) {
5158 if (NonCLike.Kind == NonCLikeKind::Invalid)
5159 return;
5160
5161 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5162 if (ChangesLinkage) {
5163 // If the linkage changes, we can't accept this as an extension.
5164 if (NonCLike.Kind == NonCLikeKind::None)
5165 DiagID = diag::err_typedef_changes_linkage;
5166 else
5167 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5168 }
5169
5170 SourceLocation FixitLoc =
5171 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5172 llvm::SmallString<40> TextToInsert;
5173 TextToInsert += ' ';
5174 TextToInsert += NewTD->getIdentifier()->getName();
5175
5176 Diag(FixitLoc, DiagID)
5177 << isa<TypeAliasDecl>(NewTD)
5178 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5179 if (NonCLike.Kind != NonCLikeKind::None) {
5180 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5181 << NonCLike.Kind - 1 << NonCLike.Range;
5182 }
5183 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5184 << NewTD << isa<TypeAliasDecl>(NewTD);
5185
5186 if (ChangesLinkage)
5187 return;
5188 }
5189
5190 // Otherwise, set this as the anon-decl typedef for the tag.
5191 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5192
5193 // Now that we have a name for the tag, process API notes again.
5194 ProcessAPINotes(TagFromDeclSpec);
5195}
5196
5197static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5199 switch (T) {
5201 return 0;
5203 return 1;
5205 return 2;
5207 return 3;
5208 case DeclSpec::TST_enum:
5209 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5210 if (ED->isScopedUsingClassTag())
5211 return 5;
5212 if (ED->isScoped())
5213 return 6;
5214 }
5215 return 4;
5216 default:
5217 llvm_unreachable("unexpected type specifier");
5218 }
5219}
5220
5222 DeclSpec &DS,
5223 const ParsedAttributesView &DeclAttrs,
5224 MultiTemplateParamsArg TemplateParams,
5225 bool IsExplicitInstantiation,
5226 RecordDecl *&AnonRecord,
5227 SourceLocation EllipsisLoc) {
5228 Decl *TagD = nullptr;
5229 TagDecl *Tag = nullptr;
5235 TagD = DS.getRepAsDecl();
5236
5237 if (!TagD) // We probably had an error
5238 return nullptr;
5239
5240 // Note that the above type specs guarantee that the
5241 // type rep is a Decl, whereas in many of the others
5242 // it's a Type.
5243 if (isa<TagDecl>(TagD))
5244 Tag = cast<TagDecl>(TagD);
5245 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5246 Tag = CTD->getTemplatedDecl();
5247 }
5248
5249 if (Tag) {
5250 handleTagNumbering(Tag, S);
5251 Tag->setFreeStanding();
5252 if (Tag->isInvalidDecl())
5253 return Tag;
5254 }
5255
5256 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5257 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5258 // or incomplete types shall not be restrict-qualified."
5259 if (TypeQuals & DeclSpec::TQ_restrict)
5261 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5262 << DS.getSourceRange();
5263 }
5264
5265 if (DS.isInlineSpecified())
5266 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5267 << getLangOpts().CPlusPlus17;
5268
5269 if (DS.hasConstexprSpecifier()) {
5270 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5271 // and definitions of functions and variables.
5272 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5273 // the declaration of a function or function template
5274 if (Tag)
5275 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5277 << static_cast<int>(DS.getConstexprSpecifier());
5278 else if (getLangOpts().C23)
5279 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5280 else
5281 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5282 << static_cast<int>(DS.getConstexprSpecifier());
5283 // Don't emit warnings after this error.
5284 return TagD;
5285 }
5286
5288
5289 if (DS.isFriendSpecified()) {
5290 // If we're dealing with a decl but not a TagDecl, assume that
5291 // whatever routines created it handled the friendship aspect.
5292 if (TagD && !Tag)
5293 return nullptr;
5294 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5295 }
5296
5297 assert(EllipsisLoc.isInvalid() &&
5298 "Friend ellipsis but not friend-specified?");
5299
5300 // Track whether this decl-specifier declares anything.
5301 bool DeclaresAnything = true;
5302
5303 // Handle anonymous struct definitions.
5304 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5305 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5307 if (getLangOpts().CPlusPlus ||
5308 Record->getDeclContext()->isRecord()) {
5309 // If CurContext is a DeclContext that can contain statements,
5310 // RecursiveASTVisitor won't visit the decls that
5311 // BuildAnonymousStructOrUnion() will put into CurContext.
5312 // Also store them here so that they can be part of the
5313 // DeclStmt that gets created in this case.
5314 // FIXME: Also return the IndirectFieldDecls created by
5315 // BuildAnonymousStructOr union, for the same reason?
5316 if (CurContext->isFunctionOrMethod())
5317 AnonRecord = Record;
5318 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5319 Context.getPrintingPolicy());
5320 }
5321
5322 DeclaresAnything = false;
5323 }
5324 }
5325
5326 // C11 6.7.2.1p2:
5327 // A struct-declaration that does not declare an anonymous structure or
5328 // anonymous union shall contain a struct-declarator-list.
5329 //
5330 // This rule also existed in C89 and C99; the grammar for struct-declaration
5331 // did not permit a struct-declaration without a struct-declarator-list.
5332 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5334 // Check for Microsoft C extension: anonymous struct/union member.
5335 // Handle 2 kinds of anonymous struct/union:
5336 // struct STRUCT;
5337 // union UNION;
5338 // and
5339 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5340 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5341 if ((Tag && Tag->getDeclName()) ||
5343 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5344 : DS.getRepAsType().get()->getAsRecordDecl();
5345 if (Record && getLangOpts().MicrosoftExt) {
5346 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5347 << Record->isUnion() << DS.getSourceRange();
5349 }
5350
5351 DeclaresAnything = false;
5352 }
5353 }
5354
5355 // Skip all the checks below if we have a type error.
5357 (TagD && TagD->isInvalidDecl()))
5358 return TagD;
5359
5360 if (getLangOpts().CPlusPlus &&
5362 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5363 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5364 !Enum->isInvalidDecl())
5365 DeclaresAnything = false;
5366
5367 if (!DS.isMissingDeclaratorOk()) {
5368 // Customize diagnostic for a typedef missing a name.
5370 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5371 << DS.getSourceRange();
5372 else
5373 DeclaresAnything = false;
5374 }
5375
5376 if (DS.isModulePrivateSpecified() &&
5377 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5378 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5379 << Tag->getTagKind()
5381
5383
5384 // C 6.7/2:
5385 // A declaration [...] shall declare at least a declarator [...], a tag,
5386 // or the members of an enumeration.
5387 // C++ [dcl.dcl]p3:
5388 // [If there are no declarators], and except for the declaration of an
5389 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5390 // names into the program, or shall redeclare a name introduced by a
5391 // previous declaration.
5392 if (!DeclaresAnything) {
5393 // In C, we allow this as a (popular) extension / bug. Don't bother
5394 // producing further diagnostics for redundant qualifiers after this.
5395 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5396 ? diag::err_no_declarators
5397 : diag::ext_no_declarators)
5398 << DS.getSourceRange();
5399 return TagD;
5400 }
5401
5402 // C++ [dcl.stc]p1:
5403 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5404 // init-declarator-list of the declaration shall not be empty.
5405 // C++ [dcl.fct.spec]p1:
5406 // If a cv-qualifier appears in a decl-specifier-seq, the
5407 // init-declarator-list of the declaration shall not be empty.
5408 //
5409 // Spurious qualifiers here appear to be valid in C.
5410 unsigned DiagID = diag::warn_standalone_specifier;
5411 if (getLangOpts().CPlusPlus)
5412 DiagID = diag::ext_standalone_specifier;
5413
5414 // Note that a linkage-specification sets a storage class, but
5415 // 'extern "C" struct foo;' is actually valid and not theoretically
5416 // useless.
5417 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5418 if (SCS == DeclSpec::SCS_mutable)
5419 // Since mutable is not a viable storage class specifier in C, there is
5420 // no reason to treat it as an extension. Instead, diagnose as an error.
5421 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5422 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5423 Diag(DS.getStorageClassSpecLoc(), DiagID)
5425 }
5426
5430 if (DS.getTypeQualifiers()) {
5432 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5434 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5435 // Restrict is covered above.
5437 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5439 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5440 }
5441
5442 // Warn about ignored type attributes, for example:
5443 // __attribute__((aligned)) struct A;
5444 // Attributes should be placed after tag to apply to type declaration.
5445 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5446 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5447 if (TypeSpecType == DeclSpec::TST_class ||
5448 TypeSpecType == DeclSpec::TST_struct ||
5449 TypeSpecType == DeclSpec::TST_interface ||
5450 TypeSpecType == DeclSpec::TST_union ||
5451 TypeSpecType == DeclSpec::TST_enum) {
5452
5453 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5454 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5455 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5456 DiagnosticId = diag::warn_attribute_ignored;
5457 else if (AL.isRegularKeywordAttribute())
5458 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5459 else
5460 DiagnosticId = diag::warn_declspec_attribute_ignored;
5461 Diag(AL.getLoc(), DiagnosticId)
5462 << AL << GetDiagnosticTypeSpecifierID(DS);
5463 };
5464
5465 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5466 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5467 }
5468 }
5469
5470 return TagD;
5471}
5472
5473/// We are trying to inject an anonymous member into the given scope;
5474/// check if there's an existing declaration that can't be overloaded.
5475///
5476/// \return true if this is a forbidden redeclaration
5477static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5478 DeclContext *Owner,
5479 DeclarationName Name,
5480 SourceLocation NameLoc, bool IsUnion,
5481 StorageClass SC) {
5482 LookupResult R(SemaRef, Name, NameLoc,
5486 if (!SemaRef.LookupName(R, S)) return false;
5487
5488 // Pick a representative declaration.
5490 assert(PrevDecl && "Expected a non-null Decl");
5491
5492 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5493 return false;
5494
5495 if (SC == StorageClass::SC_None &&
5496 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5497 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5498 if (!Owner->isRecord())
5499 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5500 return false;
5501 }
5502
5503 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5504 << IsUnion << Name;
5505 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5506
5507 return true;
5508}
5509
5511 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5513}
5514
5516 if (!getLangOpts().CPlusPlus)
5517 return;
5518
5519 // This function can be parsed before we have validated the
5520 // structure as an anonymous struct
5521 if (Record->isAnonymousStructOrUnion())
5522 return;
5523
5524 const NamedDecl *First = 0;
5525 for (const Decl *D : Record->decls()) {
5526 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5527 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5528 continue;
5529 if (!First)
5530 First = ND;
5531 else
5533 }
5534}
5535
5536/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5537/// anonymous struct or union AnonRecord into the owning context Owner
5538/// and scope S. This routine will be invoked just after we realize
5539/// that an unnamed union or struct is actually an anonymous union or
5540/// struct, e.g.,
5541///
5542/// @code
5543/// union {
5544/// int i;
5545/// float f;
5546/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5547/// // f into the surrounding scope.x
5548/// @endcode
5549///
5550/// This routine is recursive, injecting the names of nested anonymous
5551/// structs/unions into the owning context and scope as well.
5552static bool
5554 RecordDecl *AnonRecord, AccessSpecifier AS,
5555 StorageClass SC,
5556 SmallVectorImpl<NamedDecl *> &Chaining) {
5557 bool Invalid = false;
5558
5559 // Look every FieldDecl and IndirectFieldDecl with a name.
5560 for (auto *D : AnonRecord->decls()) {
5561 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5562 cast<NamedDecl>(D)->getDeclName()) {
5563 ValueDecl *VD = cast<ValueDecl>(D);
5564 // C++ [class.union]p2:
5565 // The names of the members of an anonymous union shall be
5566 // distinct from the names of any other entity in the
5567 // scope in which the anonymous union is declared.
5568
5569 bool FieldInvalid = CheckAnonMemberRedeclaration(
5570 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5571 AnonRecord->isUnion(), SC);
5572 if (FieldInvalid)
5573 Invalid = true;
5574
5575 // Inject the IndirectFieldDecl even if invalid, because later
5576 // diagnostics may depend on it being present, see findDefaultInitializer.
5577
5578 // C++ [class.union]p2:
5579 // For the purpose of name lookup, after the anonymous union
5580 // definition, the members of the anonymous union are
5581 // considered to have been defined in the scope in which the
5582 // anonymous union is declared.
5583 unsigned OldChainingSize = Chaining.size();
5584 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5585 Chaining.append(IF->chain_begin(), IF->chain_end());
5586 else
5587 Chaining.push_back(VD);
5588
5589 assert(Chaining.size() >= 2);
5590 NamedDecl **NamedChain =
5591 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5592 for (unsigned i = 0; i < Chaining.size(); i++)
5593 NamedChain[i] = Chaining[i];
5594
5596 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5597 VD->getType(), {NamedChain, Chaining.size()});
5598
5599 for (const auto *Attr : VD->attrs())
5600 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5601
5602 IndirectField->setAccess(AS);
5603 IndirectField->setImplicit();
5604 IndirectField->setInvalidDecl(FieldInvalid);
5605 SemaRef.PushOnScopeChains(IndirectField, S);
5606
5607 // That includes picking up the appropriate access specifier.
5608 if (AS != AS_none)
5609 IndirectField->setAccess(AS);
5610
5611 Chaining.resize(OldChainingSize);
5612 }
5613 }
5614
5615 return Invalid;
5616}
5617
5618/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5619/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5620/// illegal input values are mapped to SC_None.
5621static StorageClass
5623 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5624 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5625 "Parser allowed 'typedef' as storage class VarDecl.");
5626 switch (StorageClassSpec) {
5629 if (DS.isExternInLinkageSpec())
5630 return SC_None;
5631 return SC_Extern;
5632 case DeclSpec::SCS_static: return SC_Static;
5633 case DeclSpec::SCS_auto: return SC_Auto;
5636 // Illegal SCSs map to None: error reporting is up to the caller.
5637 case DeclSpec::SCS_mutable: // Fall through.
5638 case DeclSpec::SCS_typedef: return SC_None;
5639 }
5640 llvm_unreachable("unknown storage class specifier");
5641}
5642
5644 assert(Record->hasInClassInitializer());
5645
5646 for (const auto *I : Record->decls()) {
5647 const auto *FD = dyn_cast<FieldDecl>(I);
5648 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5649 FD = IFD->getAnonField();
5650 if (FD && FD->hasInClassInitializer())
5651 return FD->getLocation();
5652 }
5653
5654 llvm_unreachable("couldn't find in-class initializer");
5655}
5656
5658 SourceLocation DefaultInitLoc) {
5659 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5660 return;
5661
5662 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5663 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5664}
5665
5667 CXXRecordDecl *AnonUnion) {
5668 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5669 return;
5670
5672}
5673
5675 AccessSpecifier AS,
5677 const PrintingPolicy &Policy) {
5678 DeclContext *Owner = Record->getDeclContext();
5679
5680 // Diagnose whether this anonymous struct/union is an extension.
5681 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5682 Diag(Record->getLocation(), diag::ext_anonymous_union);
5683 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5684 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5685 else if (!Record->isUnion() && !getLangOpts().C11)
5686 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5687
5688 // C and C++ require different kinds of checks for anonymous
5689 // structs/unions.
5690 bool Invalid = false;
5691 if (getLangOpts().CPlusPlus) {
5692 const char *PrevSpec = nullptr;
5693 if (Record->isUnion()) {
5694 // C++ [class.union]p6:
5695 // C++17 [class.union.anon]p2:
5696 // Anonymous unions declared in a named namespace or in the
5697 // global namespace shall be declared static.
5698 unsigned DiagID;
5699 DeclContext *OwnerScope = Owner->getRedeclContext();
5701 (OwnerScope->isTranslationUnit() ||
5702 (OwnerScope->isNamespace() &&
5703 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5704 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5705 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5706
5707 // Recover by adding 'static'.
5709 PrevSpec, DiagID, Policy);
5710 }
5711 // C++ [class.union]p6:
5712 // A storage class is not allowed in a declaration of an
5713 // anonymous union in a class scope.
5715 isa<RecordDecl>(Owner)) {
5717 diag::err_anonymous_union_with_storage_spec)
5719
5720 // Recover by removing the storage specifier.
5723 PrevSpec, DiagID, Context.getPrintingPolicy());
5724 }
5725 }
5726
5727 // Ignore const/volatile/restrict qualifiers.
5728 if (DS.getTypeQualifiers()) {
5730 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5731 << Record->isUnion() << "const"
5735 diag::ext_anonymous_struct_union_qualified)
5736 << Record->isUnion() << "volatile"
5740 diag::ext_anonymous_struct_union_qualified)
5741 << Record->isUnion() << "restrict"
5745 diag::ext_anonymous_struct_union_qualified)
5746 << Record->isUnion() << "_Atomic"
5750 diag::ext_anonymous_struct_union_qualified)
5751 << Record->isUnion() << "__unaligned"
5753
5755 }
5756
5757 // C++ [class.union]p2:
5758 // The member-specification of an anonymous union shall only
5759 // define non-static data members. [Note: nested types and
5760 // functions cannot be declared within an anonymous union. ]
5761 for (auto *Mem : Record->decls()) {
5762 // Ignore invalid declarations; we already diagnosed them.
5763 if (Mem->isInvalidDecl())
5764 continue;
5765
5766 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5767 // C++ [class.union]p3:
5768 // An anonymous union shall not have private or protected
5769 // members (clause 11).
5770 assert(FD->getAccess() != AS_none);
5771 if (FD->getAccess() != AS_public) {
5772 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5773 << Record->isUnion() << (FD->getAccess() == AS_protected);
5774 Invalid = true;
5775 }
5776
5777 // C++ [class.union]p1
5778 // An object of a class with a non-trivial constructor, a non-trivial
5779 // copy constructor, a non-trivial destructor, or a non-trivial copy
5780 // assignment operator cannot be a member of a union, nor can an
5781 // array of such objects.
5782 if (CheckNontrivialField(FD))
5783 Invalid = true;
5784 } else if (Mem->isImplicit()) {
5785 // Any implicit members are fine.
5786 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5787 // This is a type that showed up in an
5788 // elaborated-type-specifier inside the anonymous struct or
5789 // union, but which actually declares a type outside of the
5790 // anonymous struct or union. It's okay.
5791 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5792 if (!MemRecord->isAnonymousStructOrUnion() &&
5793 MemRecord->getDeclName()) {
5794 // Visual C++ allows type definition in anonymous struct or union.
5795 if (getLangOpts().MicrosoftExt)
5796 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5797 << Record->isUnion();
5798 else {
5799 // This is a nested type declaration.
5800 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5801 << Record->isUnion();
5802 Invalid = true;
5803 }
5804 } else {
5805 // This is an anonymous type definition within another anonymous type.
5806 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5807 // not part of standard C++.
5808 Diag(MemRecord->getLocation(),
5809 diag::ext_anonymous_record_with_anonymous_type)
5810 << Record->isUnion();
5811 }
5812 } else if (isa<AccessSpecDecl>(Mem)) {
5813 // Any access specifier is fine.
5814 } else if (isa<StaticAssertDecl>(Mem)) {
5815 // In C++1z, static_assert declarations are also fine.
5816 } else {
5817 // We have something that isn't a non-static data
5818 // member. Complain about it.
5819 unsigned DK = diag::err_anonymous_record_bad_member;
5820 if (isa<TypeDecl>(Mem))
5821 DK = diag::err_anonymous_record_with_type;
5822 else if (isa<FunctionDecl>(Mem))
5823 DK = diag::err_anonymous_record_with_function;
5824 else if (isa<VarDecl>(Mem))
5825 DK = diag::err_anonymous_record_with_static;
5826
5827 // Visual C++ allows type definition in anonymous struct or union.
5828 if (getLangOpts().MicrosoftExt &&
5829 DK == diag::err_anonymous_record_with_type)
5830 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5831 << Record->isUnion();
5832 else {
5833 Diag(Mem->getLocation(), DK) << Record->isUnion();
5834 Invalid = true;
5835 }
5836 }
5837 }
5838
5839 // C++11 [class.union]p8 (DR1460):
5840 // At most one variant member of a union may have a
5841 // brace-or-equal-initializer.
5842 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5843 Owner->isRecord())
5846 }
5847
5848 if (!Record->isUnion() && !Owner->isRecord()) {
5849 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5850 << getLangOpts().CPlusPlus;
5851 Invalid = true;
5852 }
5853
5854 // C++ [dcl.dcl]p3:
5855 // [If there are no declarators], and except for the declaration of an
5856 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5857 // names into the program
5858 // C++ [class.mem]p2:
5859 // each such member-declaration shall either declare at least one member
5860 // name of the class or declare at least one unnamed bit-field
5861 //
5862 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5863 if (getLangOpts().CPlusPlus && Record->field_empty())
5864 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5865
5866 // Mock up a declarator.
5870 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5871
5872 // Create a declaration for this anonymous struct/union.
5873 NamedDecl *Anon = nullptr;
5874 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5875 Anon = FieldDecl::Create(
5876 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5877 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5878 /*BitWidth=*/nullptr, /*Mutable=*/false,
5879 /*InitStyle=*/ICIS_NoInit);
5880 Anon->setAccess(AS);
5881 ProcessDeclAttributes(S, Anon, Dc);
5882
5883 if (getLangOpts().CPlusPlus)
5884 FieldCollector->Add(cast<FieldDecl>(Anon));
5885 } else {
5886 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5887 if (SCSpec == DeclSpec::SCS_mutable) {
5888 // mutable can only appear on non-static class members, so it's always
5889 // an error here
5890 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5891 Invalid = true;
5892 SC = SC_None;
5893 }
5894
5895 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5896 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5897 Context.getCanonicalTagType(Record), TInfo, SC);
5898 if (Invalid)
5899 Anon->setInvalidDecl();
5900
5901 ProcessDeclAttributes(S, Anon, Dc);
5902
5903 // Default-initialize the implicit variable. This initialization will be
5904 // trivial in almost all cases, except if a union member has an in-class
5905 // initializer:
5906 // union { int n = 0; };
5908 }
5909 Anon->setImplicit();
5910
5911 // Mark this as an anonymous struct/union type.
5912 Record->setAnonymousStructOrUnion(true);
5913
5914 // Add the anonymous struct/union object to the current
5915 // context. We'll be referencing this object when we refer to one of
5916 // its members.
5917 Owner->addDecl(Anon);
5918
5919 // Inject the members of the anonymous struct/union into the owning
5920 // context and into the identifier resolver chain for name lookup
5921 // purposes.
5923 Chain.push_back(Anon);
5924
5925 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5926 Chain))
5927 Invalid = true;
5928
5929 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5930 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5932 Decl *ManglingContextDecl;
5933 std::tie(MCtx, ManglingContextDecl) =
5934 getCurrentMangleNumberContext(NewVD->getDeclContext());
5935 if (MCtx) {
5936 Context.setManglingNumber(
5937 NewVD, MCtx->getManglingNumber(
5938 NewVD, getMSManglingNumber(getLangOpts(), S)));
5939 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5940 }
5941 }
5942 }
5943
5944 if (Invalid)
5945 Anon->setInvalidDecl();
5946
5947 return Anon;
5948}
5949
5951 RecordDecl *Record) {
5952 assert(Record && "expected a record!");
5953
5954 // Mock up a declarator.
5957 assert(TInfo && "couldn't build declarator info for anonymous struct");
5958
5959 auto *ParentDecl = cast<RecordDecl>(CurContext);
5960 CanQualType RecTy = Context.getCanonicalTagType(Record);
5961
5962 // Create a declaration for this anonymous struct.
5963 NamedDecl *Anon =
5964 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5965 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5966 /*BitWidth=*/nullptr, /*Mutable=*/false,
5967 /*InitStyle=*/ICIS_NoInit);
5968 Anon->setImplicit();
5969
5970 // Add the anonymous struct object to the current context.
5971 CurContext->addDecl(Anon);
5972
5973 // Inject the members of the anonymous struct into the current
5974 // context and into the identifier resolver chain for name lookup
5975 // purposes.
5977 Chain.push_back(Anon);
5978
5979 RecordDecl *RecordDef = Record->getDefinition();
5980 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5981 diag::err_field_incomplete_or_sizeless) ||
5983 *this, S, CurContext, RecordDef, AS_none,
5985 Anon->setInvalidDecl();
5986 ParentDecl->setInvalidDecl();
5987 }
5988
5989 return Anon;
5990}
5991
5995
5998 DeclarationNameInfo NameInfo;
5999 NameInfo.setLoc(Name.StartLocation);
6000
6001 switch (Name.getKind()) {
6002
6005 NameInfo.setName(Name.Identifier);
6006 return NameInfo;
6007
6009 // C++ [temp.deduct.guide]p3:
6010 // The simple-template-id shall name a class template specialization.
6011 // The template-name shall be the same identifier as the template-name
6012 // of the simple-template-id.
6013 // These together intend to imply that the template-name shall name a
6014 // class template.
6015 // FIXME: template<typename T> struct X {};
6016 // template<typename T> using Y = X<T>;
6017 // Y(int) -> Y<int>;
6018 // satisfies these rules but does not name a class template.
6019 TemplateName TN = Name.TemplateName.get().get();
6020 auto *Template = TN.getAsTemplateDecl();
6022 Diag(Name.StartLocation,
6023 diag::err_deduction_guide_name_not_class_template)
6024 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6025 if (Template)
6027 return DeclarationNameInfo();
6028 }
6029
6030 NameInfo.setName(
6031 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6032 return NameInfo;
6033 }
6034
6036 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6040 return NameInfo;
6041
6043 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6044 Name.Identifier));
6046 return NameInfo;
6047
6049 TypeSourceInfo *TInfo;
6051 if (Ty.isNull())
6052 return DeclarationNameInfo();
6053 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6054 Context.getCanonicalType(Ty)));
6055 NameInfo.setNamedTypeInfo(TInfo);
6056 return NameInfo;
6057 }
6058
6060 TypeSourceInfo *TInfo;
6061 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6062 if (Ty.isNull())
6063 return DeclarationNameInfo();
6064 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6065 Context.getCanonicalType(Ty)));
6066 NameInfo.setNamedTypeInfo(TInfo);
6067 return NameInfo;
6068 }
6069
6071 // In well-formed code, we can only have a constructor
6072 // template-id that refers to the current context, so go there
6073 // to find the actual type being constructed.
6074 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6075 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6076 return DeclarationNameInfo();
6077
6078 // Determine the type of the class being constructed.
6079 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6080
6081 // FIXME: Check two things: that the template-id names the same type as
6082 // CurClassType, and that the template-id does not occur when the name
6083 // was qualified.
6084
6085 NameInfo.setName(
6086 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6087 // FIXME: should we retrieve TypeSourceInfo?
6088 NameInfo.setNamedTypeInfo(nullptr);
6089 return NameInfo;
6090 }
6091
6093 TypeSourceInfo *TInfo;
6094 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6095 if (Ty.isNull())
6096 return DeclarationNameInfo();
6097 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6098 Context.getCanonicalType(Ty)));
6099 NameInfo.setNamedTypeInfo(TInfo);
6100 return NameInfo;
6101 }
6102
6104 TemplateName TName = Name.TemplateId->Template.get();
6105 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6106 return Context.getNameForTemplate(TName, TNameLoc);
6107 }
6108
6109 } // switch (Name.getKind())
6110
6111 llvm_unreachable("Unknown name kind");
6112}
6113
6115 do {
6116 if (Ty->isPointerOrReferenceType())
6117 Ty = Ty->getPointeeType();
6118 else if (Ty->isArrayType())
6120 else
6121 return Ty.withoutLocalFastQualifiers();
6122 } while (true);
6123}
6124
6125/// hasSimilarParameters - Determine whether the C++ functions Declaration
6126/// and Definition have "nearly" matching parameters. This heuristic is
6127/// used to improve diagnostics in the case where an out-of-line function
6128/// definition doesn't match any declaration within the class or namespace.
6129/// Also sets Params to the list of indices to the parameters that differ
6130/// between the declaration and the definition. If hasSimilarParameters
6131/// returns true and Params is empty, then all of the parameters match.
6135 SmallVectorImpl<unsigned> &Params) {
6136 Params.clear();
6137 if (Declaration->param_size() != Definition->param_size())
6138 return false;
6139 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6140 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6141 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6142
6143 // The parameter types are identical
6144 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6145 continue;
6146
6147 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6148 QualType DefParamBaseTy = getCoreType(DefParamTy);
6149 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6150 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6151
6152 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6153 (DeclTyName && DeclTyName == DefTyName))
6154 Params.push_back(Idx);
6155 else // The two parameters aren't even close
6156 return false;
6157 }
6158
6159 return true;
6160}
6161
6162/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6163/// declarator needs to be rebuilt in the current instantiation.
6164/// Any bits of declarator which appear before the name are valid for
6165/// consideration here. That's specifically the type in the decl spec
6166/// and the base type in any member-pointer chunks.
6168 DeclarationName Name) {
6169 // The types we specifically need to rebuild are:
6170 // - typenames, typeofs, and decltypes
6171 // - types which will become injected class names
6172 // Of course, we also need to rebuild any type referencing such a
6173 // type. It's safest to just say "dependent", but we call out a
6174 // few cases here.
6175
6176 DeclSpec &DS = D.getMutableDeclSpec();
6177 switch (DS.getTypeSpecType()) {
6181#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6182#include "clang/Basic/TransformTypeTraits.def"
6183 case DeclSpec::TST_atomic: {
6184 // Grab the type from the parser.
6185 TypeSourceInfo *TSI = nullptr;
6186 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6187 if (T.isNull() || !T->isInstantiationDependentType()) break;
6188
6189 // Make sure there's a type source info. This isn't really much
6190 // of a waste; most dependent types should have type source info
6191 // attached already.
6192 if (!TSI)
6194
6195 // Rebuild the type in the current instantiation.
6197 if (!TSI) return true;
6198
6199 // Store the new type back in the decl spec.
6200 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6201 DS.UpdateTypeRep(LocType);
6202 break;
6203 }
6204
6208 Expr *E = DS.getRepAsExpr();
6210 if (Result.isInvalid()) return true;
6211 DS.UpdateExprRep(Result.get());
6212 break;
6213 }
6214
6215 default:
6216 // Nothing to do for these decl specs.
6217 break;
6218 }
6219
6220 // It doesn't matter what order we do this in.
6221 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6222 DeclaratorChunk &Chunk = D.getTypeObject(I);
6223
6224 // The only type information in the declarator which can come
6225 // before the declaration name is the base type of a member
6226 // pointer.
6228 continue;
6229
6230 // Rebuild the scope specifier in-place.
6231 CXXScopeSpec &SS = Chunk.Mem.Scope();
6233 return true;
6234 }
6235
6236 return false;
6237}
6238
6239/// Returns true if the declaration is declared in a system header or from a
6240/// system macro.
6241static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6242 return SM.isInSystemHeader(D->getLocation()) ||
6243 SM.isInSystemMacro(D->getLocation());
6244}
6245
6247 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6248 // of system decl.
6249 if (D->getPreviousDecl() || D->isImplicit())
6250 return;
6253 !isFromSystemHeader(Context.getSourceManager(), D)) {
6254 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6255 << D << static_cast<int>(Status);
6256 }
6257}
6258
6261
6262 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6263 // declaration only if the `bind_to_declaration` extension is set.
6265 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6266 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6267 llvm::omp::TraitProperty::
6268 implementation_extension_bind_to_declaration))
6270 S, D, MultiTemplateParamsArg(), Bases);
6271
6273
6274 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6275 Dcl && Dcl->getDeclContext()->isFileContext())
6277
6278 if (!Bases.empty())
6280 Bases);
6281
6282 return Dcl;
6283}
6284
6286 DeclarationNameInfo NameInfo) {
6287 DeclarationName Name = NameInfo.getName();
6288
6289 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6290 while (Record && Record->isAnonymousStructOrUnion())
6291 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6292 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6293 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6294 return true;
6295 }
6296
6297 return false;
6298}
6299
6301 DeclarationName Name,
6302 SourceLocation Loc,
6303 TemplateIdAnnotation *TemplateId,
6304 bool IsMemberSpecialization) {
6305 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6306 "without nested-name-specifier");
6307 DeclContext *Cur = CurContext;
6308 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6309 Cur = Cur->getParent();
6310
6311 // If the user provided a superfluous scope specifier that refers back to the
6312 // class in which the entity is already declared, diagnose and ignore it.
6313 //
6314 // class X {
6315 // void X::f();
6316 // };
6317 //
6318 // Note, it was once ill-formed to give redundant qualification in all
6319 // contexts, but that rule was removed by DR482.
6320 if (Cur->Equals(DC)) {
6321 if (Cur->isRecord()) {
6322 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6323 : diag::err_member_extra_qualification)
6324 << Name << FixItHint::CreateRemoval(SS.getRange());
6325 SS.clear();
6326 } else {
6327 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6328 }
6329 return false;
6330 }
6331
6332 // Check whether the qualifying scope encloses the scope of the original
6333 // declaration. For a template-id, we perform the checks in
6334 // CheckTemplateSpecializationScope.
6335 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6336 if (Cur->isRecord())
6337 Diag(Loc, diag::err_member_qualification)
6338 << Name << SS.getRange();
6339 else if (isa<TranslationUnitDecl>(DC))
6340 Diag(Loc, diag::err_invalid_declarator_global_scope)
6341 << Name << SS.getRange();
6342 else if (isa<FunctionDecl>(Cur))
6343 Diag(Loc, diag::err_invalid_declarator_in_function)
6344 << Name << SS.getRange();
6345 else if (isa<BlockDecl>(Cur))
6346 Diag(Loc, diag::err_invalid_declarator_in_block)
6347 << Name << SS.getRange();
6348 else if (isa<ExportDecl>(Cur)) {
6349 if (!isa<NamespaceDecl>(DC))
6350 Diag(Loc, diag::err_export_non_namespace_scope_name)
6351 << Name << SS.getRange();
6352 else
6353 // The cases that DC is not NamespaceDecl should be handled in
6354 // CheckRedeclarationExported.
6355 return false;
6356 } else
6357 Diag(Loc, diag::err_invalid_declarator_scope)
6358 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6359
6360 return true;
6361 }
6362
6363 if (Cur->isRecord()) {
6364 // Cannot qualify members within a class.
6365 Diag(Loc, diag::err_member_qualification)
6366 << Name << SS.getRange();
6367 SS.clear();
6368
6369 // C++ constructors and destructors with incorrect scopes can break
6370 // our AST invariants by having the wrong underlying types. If
6371 // that's the case, then drop this declaration entirely.
6374 !Context.hasSameType(
6375 Name.getCXXNameType(),
6376 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6377 return true;
6378
6379 return false;
6380 }
6381
6382 // C++23 [temp.names]p5:
6383 // The keyword template shall not appear immediately after a declarative
6384 // nested-name-specifier.
6385 //
6386 // First check the template-id (if any), and then check each component of the
6387 // nested-name-specifier in reverse order.
6388 //
6389 // FIXME: nested-name-specifiers in friend declarations are declarative,
6390 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6391 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6392 Diag(Loc, diag::ext_template_after_declarative_nns)
6394
6396 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6397 TL = std::exchange(NextTL, TypeLoc())) {
6398 SourceLocation TemplateKeywordLoc;
6399 switch (TL.getTypeLocClass()) {
6400 case TypeLoc::TemplateSpecialization: {
6401 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6402 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6403 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6404 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6405 << TST.getLocalSourceRange();
6406 break;
6407 }
6408 case TypeLoc::Decltype:
6409 case TypeLoc::PackIndexing: {
6410 const Type *T = TL.getTypePtr();
6411 // C++23 [expr.prim.id.qual]p2:
6412 // [...] A declarative nested-name-specifier shall not have a
6413 // computed-type-specifier.
6414 //
6415 // CWG2858 changed this from 'decltype-specifier' to
6416 // 'computed-type-specifier'.
6417 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6418 << T->isDecltypeType() << TL.getSourceRange();
6419 break;
6420 }
6421 case TypeLoc::DependentName:
6422 NextTL =
6423 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6424 break;
6425 default:
6426 break;
6427 }
6428 if (TemplateKeywordLoc.isValid())
6429 Diag(Loc, diag::ext_template_after_declarative_nns)
6430 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6431 }
6432
6433 return false;
6434}
6435
6437 MultiTemplateParamsArg TemplateParamLists) {
6438 // TODO: consider using NameInfo for diagnostic.
6440 DeclarationName Name = NameInfo.getName();
6441
6442 // All of these full declarators require an identifier. If it doesn't have
6443 // one, the ParsedFreeStandingDeclSpec action should be used.
6444 if (D.isDecompositionDeclarator()) {
6445 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6446 } else if (!Name) {
6447 if (!D.isInvalidType()) // Reject this if we think it is valid.
6448 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6450 return nullptr;
6452 return nullptr;
6453
6454 DeclContext *DC = CurContext;
6455 if (D.getCXXScopeSpec().isInvalid())
6456 D.setInvalidType();
6457 else if (D.getCXXScopeSpec().isSet()) {
6460 return nullptr;
6461
6462 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6463 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6464 if (!DC || isa<EnumDecl>(DC)) {
6465 // If we could not compute the declaration context, it's because the
6466 // declaration context is dependent but does not refer to a class,
6467 // class template, or class template partial specialization. Complain
6468 // and return early, to avoid the coming semantic disaster.
6470 diag::err_template_qualified_declarator_no_match)
6472 << D.getCXXScopeSpec().getRange();
6473 return nullptr;
6474 }
6475 bool IsDependentContext = DC->isDependentContext();
6476
6477 if (!IsDependentContext &&
6479 return nullptr;
6480
6481 // If a class is incomplete, do not parse entities inside it.
6484 diag::err_member_def_undefined_record)
6485 << Name << DC << D.getCXXScopeSpec().getRange();
6486 return nullptr;
6487 }
6488 if (!D.getDeclSpec().isFriendSpecified()) {
6489 TemplateIdAnnotation *TemplateId =
6491 ? D.getName().TemplateId
6492 : nullptr;
6494 D.getIdentifierLoc(), TemplateId,
6495 /*IsMemberSpecialization=*/false)) {
6496 if (DC->isRecord())
6497 return nullptr;
6498
6499 D.setInvalidType();
6500 }
6501 }
6502
6503 // Check whether we need to rebuild the type of the given
6504 // declaration in the current instantiation.
6505 if (EnteringContext && IsDependentContext &&
6506 TemplateParamLists.size() != 0) {
6507 ContextRAII SavedContext(*this, DC);
6508 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6509 D.setInvalidType();
6510 }
6511 }
6512
6514 QualType R = TInfo->getType();
6515
6518 D.setInvalidType();
6519
6520 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6522
6523 // See if this is a redefinition of a variable in the same scope.
6524 if (!D.getCXXScopeSpec().isSet()) {
6525 bool IsLinkageLookup = false;
6526 bool CreateBuiltins = false;
6527
6528 // If the declaration we're planning to build will be a function
6529 // or object with linkage, then look for another declaration with
6530 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6531 //
6532 // If the declaration we're planning to build will be declared with
6533 // external linkage in the translation unit, create any builtin with
6534 // the same name.
6536 /* Do nothing*/;
6537 else if (CurContext->isFunctionOrMethod() &&
6539 R->isFunctionType())) {
6540 IsLinkageLookup = true;
6541 CreateBuiltins =
6542 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6543 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6545 CreateBuiltins = true;
6546
6547 if (IsLinkageLookup) {
6549 Previous.setRedeclarationKind(
6551 }
6552
6553 LookupName(Previous, S, CreateBuiltins);
6554 } else { // Something like "int foo::x;"
6556
6557 // C++ [dcl.meaning]p1:
6558 // When the declarator-id is qualified, the declaration shall refer to a
6559 // previously declared member of the class or namespace to which the
6560 // qualifier refers (or, in the case of a namespace, of an element of the
6561 // inline namespace set of that namespace (7.3.1)) or to a specialization
6562 // thereof; [...]
6563 //
6564 // Note that we already checked the context above, and that we do not have
6565 // enough information to make sure that Previous contains the declaration
6566 // we want to match. For example, given:
6567 //
6568 // class X {
6569 // void f();
6570 // void f(float);
6571 // };
6572 //
6573 // void X::f(int) { } // ill-formed
6574 //
6575 // In this case, Previous will point to the overload set
6576 // containing the two f's declared in X, but neither of them
6577 // matches.
6578
6580 }
6581
6582 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6583 TPD && TPD->isTemplateParameter()) {
6584 // Older versions of clang allowed the names of function/variable templates
6585 // to shadow the names of their template parameters. For the compatibility
6586 // purposes we detect such cases and issue a default-to-error warning that
6587 // can be disabled with -Wno-strict-primary-template-shadow.
6588 if (!D.isInvalidType()) {
6589 bool AllowForCompatibility = false;
6590 if (Scope *DeclParent = S->getDeclParent();
6591 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6592 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6593 TemplateParamParent->isDeclScope(TPD);
6594 }
6596 AllowForCompatibility);
6597 }
6598
6599 // Just pretend that we didn't see the previous declaration.
6600 Previous.clear();
6601 }
6602
6603 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6604 // Forget that the previous declaration is the injected-class-name.
6605 Previous.clear();
6606
6607 // In C++, the previous declaration we find might be a tag type
6608 // (class or enum). In this case, the new declaration will hide the
6609 // tag type. Note that this applies to functions, function templates, and
6610 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6611 if (Previous.isSingleTagDecl() &&
6613 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6614 Previous.clear();
6615
6616 // Check that there are no default arguments other than in the parameters
6617 // of a function declaration (C++ only).
6618 if (getLangOpts().CPlusPlus)
6620
6621 /// Get the innermost enclosing declaration scope.
6622 S = S->getDeclParent();
6623
6624 NamedDecl *New;
6625
6626 bool AddToScope = true;
6628 if (TemplateParamLists.size()) {
6629 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6630 return nullptr;
6631 }
6632
6633 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6634 } else if (R->isFunctionType()) {
6635 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6636 TemplateParamLists,
6637 AddToScope);
6638 } else {
6639 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6640 AddToScope);
6641 }
6642
6643 if (!New)
6644 return nullptr;
6645
6647
6648 // If this has an identifier and is not a function template specialization,
6649 // add it to the scope stack.
6650 if (New->getDeclName() && AddToScope)
6652
6653 if (OpenMP().isInOpenMPDeclareTargetContext())
6655
6656 return New;
6657}
6658
6659/// Helper method to turn variable array types into constant array
6660/// types in certain situations which would otherwise be errors (for
6661/// GCC compatibility).
6663 ASTContext &Context,
6664 bool &SizeIsNegative,
6665 llvm::APSInt &Oversized) {
6666 // This method tries to turn a variable array into a constant
6667 // array even when the size isn't an ICE. This is necessary
6668 // for compatibility with code that depends on gcc's buggy
6669 // constant expression folding, like struct {char x[(int)(char*)2];}
6670 SizeIsNegative = false;
6671 Oversized = 0;
6672
6673 if (T->isDependentType())
6674 return QualType();
6675
6677 const Type *Ty = Qs.strip(T);
6678
6679 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6680 QualType Pointee = PTy->getPointeeType();
6681 QualType FixedType =
6682 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6683 Oversized);
6684 if (FixedType.isNull()) return FixedType;
6685 FixedType = Context.getPointerType(FixedType);
6686 return Qs.apply(Context, FixedType);
6687 }
6688 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6689 QualType Inner = PTy->getInnerType();
6690 QualType FixedType =
6691 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6692 Oversized);
6693 if (FixedType.isNull()) return FixedType;
6694 FixedType = Context.getParenType(FixedType);
6695 return Qs.apply(Context, FixedType);
6696 }
6697
6698 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6699 if (!VLATy)
6700 return QualType();
6701
6702 QualType ElemTy = VLATy->getElementType();
6703 if (ElemTy->isVariablyModifiedType()) {
6704 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6705 SizeIsNegative, Oversized);
6706 if (ElemTy.isNull())
6707 return QualType();
6708 }
6709
6710 Expr::EvalResult Result;
6711 if (!VLATy->getSizeExpr() ||
6712 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6713 return QualType();
6714
6715 llvm::APSInt Res = Result.Val.getInt();
6716
6717 // Check whether the array size is negative.
6718 if (Res.isSigned() && Res.isNegative()) {
6719 SizeIsNegative = true;
6720 return QualType();
6721 }
6722
6723 // Check whether the array is too large to be addressed.
6724 unsigned ActiveSizeBits =
6725 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6726 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6727 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6728 : Res.getActiveBits();
6729 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6730 Oversized = Res;
6731 return QualType();
6732 }
6733
6734 QualType FoldedArrayType = Context.getConstantArrayType(
6735 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6736 return Qs.apply(Context, FoldedArrayType);
6737}
6738
6739static void
6741 SrcTL = SrcTL.getUnqualifiedLoc();
6742 DstTL = DstTL.getUnqualifiedLoc();
6743 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6744 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6745 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6746 DstPTL.getPointeeLoc());
6747 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6748 return;
6749 }
6750 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6751 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6752 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6753 DstPTL.getInnerLoc());
6754 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6755 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6756 return;
6757 }
6758 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6759 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6760 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6761 TypeLoc DstElemTL = DstATL.getElementLoc();
6762 if (VariableArrayTypeLoc SrcElemATL =
6763 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6764 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6765 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6766 } else {
6767 DstElemTL.initializeFullCopy(SrcElemTL);
6768 }
6769 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6770 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6771 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6772}
6773
6774/// Helper method to turn variable array types into constant array
6775/// types in certain situations which would otherwise be errors (for
6776/// GCC compatibility).
6777static TypeSourceInfo*
6779 ASTContext &Context,
6780 bool &SizeIsNegative,
6781 llvm::APSInt &Oversized) {
6782 QualType FixedTy
6783 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6784 SizeIsNegative, Oversized);
6785 if (FixedTy.isNull())
6786 return nullptr;
6787 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6789 FixedTInfo->getTypeLoc());
6790 return FixedTInfo;
6791}
6792
6795 unsigned FailedFoldDiagID) {
6796 bool SizeIsNegative;
6797 llvm::APSInt Oversized;
6799 TInfo, Context, SizeIsNegative, Oversized);
6800 if (FixedTInfo) {
6801 Diag(Loc, diag::ext_vla_folded_to_constant);
6802 TInfo = FixedTInfo;
6803 T = FixedTInfo->getType();
6804 return true;
6805 }
6806
6807 if (SizeIsNegative)
6808 Diag(Loc, diag::err_typecheck_negative_array_size);
6809 else if (Oversized.getBoolValue())
6810 Diag(Loc, diag::err_array_too_large) << toString(
6811 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6812 /*UpperCase=*/false, /*InsertSeparators=*/true);
6813 else if (FailedFoldDiagID)
6814 Diag(Loc, FailedFoldDiagID);
6815 return false;
6816}
6817
6818void
6820 if (!getLangOpts().CPlusPlus &&
6822 // Don't need to track declarations in the TU in C.
6823 return;
6824
6825 // Note that we have a locally-scoped external with this name.
6826 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6827}
6828
6830 // FIXME: We can have multiple results via __attribute__((overloadable)).
6831 auto Result = Context.getExternCContextDecl()->lookup(Name);
6832 return Result.empty() ? nullptr : *Result.begin();
6833}
6834
6836 // FIXME: We should probably indicate the identifier in question to avoid
6837 // confusion for constructs like "virtual int a(), b;"
6838 if (DS.isVirtualSpecified())
6840 diag::err_virtual_non_function);
6841
6842 if (DS.hasExplicitSpecifier())
6844 diag::err_explicit_non_function);
6845
6846 if (DS.isNoreturnSpecified())
6848 diag::err_noreturn_non_function);
6849}
6850
6851NamedDecl*
6854 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6855 if (D.getCXXScopeSpec().isSet()) {
6856 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6857 << D.getCXXScopeSpec().getRange();
6858 D.setInvalidType();
6859 // Pretend we didn't see the scope specifier.
6860 DC = CurContext;
6861 Previous.clear();
6862 }
6863
6865
6868 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6869 ? diag::warn_ms_inline_non_function
6870 : diag::err_inline_non_function)
6871 << getLangOpts().CPlusPlus17;
6873 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6874 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6875
6879 diag::err_deduction_guide_invalid_specifier)
6880 << "typedef";
6881 else
6882 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6883 << D.getName().getSourceRange();
6884 return nullptr;
6885 }
6886
6887 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6888 if (!NewTD) return nullptr;
6889
6890 // Handle attributes prior to checking for duplicates in MergeVarDecl
6891 ProcessDeclAttributes(S, NewTD, D);
6892
6894
6895 bool Redeclaration = D.isRedeclaration();
6898 return ND;
6899}
6900
6901void
6903 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6904 // then it shall have block scope.
6905 // Note that variably modified types must be fixed before merging the decl so
6906 // that redeclarations will match.
6907 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6908 QualType T = TInfo->getType();
6909 if (T->isVariablyModifiedType()) {
6911
6912 if (S->getFnParent() == nullptr) {
6913 bool SizeIsNegative;
6914 llvm::APSInt Oversized;
6915 TypeSourceInfo *FixedTInfo =
6917 SizeIsNegative,
6918 Oversized);
6919 if (FixedTInfo) {
6920 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6921 NewTD->setTypeSourceInfo(FixedTInfo);
6922 } else {
6923 if (SizeIsNegative)
6924 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6925 else if (T->isVariableArrayType())
6926 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6927 else if (Oversized.getBoolValue())
6928 Diag(NewTD->getLocation(), diag::err_array_too_large)
6929 << toString(Oversized, 10);
6930 else
6931 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6932 NewTD->setInvalidDecl();
6933 }
6934 }
6935 }
6936}
6937
6938NamedDecl*
6941
6942 // Find the shadowed declaration before filtering for scope.
6943 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6944
6945 // Merge the decl with the existing one if appropriate. If the decl is
6946 // in an outer scope, it isn't the same thing.
6947 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6948 /*AllowInlineNamespace*/false);
6950 if (!Previous.empty()) {
6951 Redeclaration = true;
6952 MergeTypedefNameDecl(S, NewTD, Previous);
6953 } else {
6955 }
6956
6957 if (ShadowedDecl && !Redeclaration)
6958 CheckShadow(NewTD, ShadowedDecl, Previous);
6959
6960 // If this is the C FILE type, notify the AST context.
6961 if (IdentifierInfo *II = NewTD->getIdentifier())
6962 if (!NewTD->isInvalidDecl() &&
6964 switch (II->getNotableIdentifierID()) {
6965 case tok::NotableIdentifierKind::FILE:
6966 Context.setFILEDecl(NewTD);
6967 break;
6968 case tok::NotableIdentifierKind::jmp_buf:
6969 Context.setjmp_bufDecl(NewTD);
6970 break;
6971 case tok::NotableIdentifierKind::sigjmp_buf:
6972 Context.setsigjmp_bufDecl(NewTD);
6973 break;
6974 case tok::NotableIdentifierKind::ucontext_t:
6975 Context.setucontext_tDecl(NewTD);
6976 break;
6977 case tok::NotableIdentifierKind::float_t:
6978 case tok::NotableIdentifierKind::double_t:
6979 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6980 break;
6981 default:
6982 break;
6983 }
6984 }
6985
6986 return NewTD;
6987}
6988
6989/// Determines whether the given declaration is an out-of-scope
6990/// previous declaration.
6991///
6992/// This routine should be invoked when name lookup has found a
6993/// previous declaration (PrevDecl) that is not in the scope where a
6994/// new declaration by the same name is being introduced. If the new
6995/// declaration occurs in a local scope, previous declarations with
6996/// linkage may still be considered previous declarations (C99
6997/// 6.2.2p4-5, C++ [basic.link]p6).
6998///
6999/// \param PrevDecl the previous declaration found by name
7000/// lookup
7001///
7002/// \param DC the context in which the new declaration is being
7003/// declared.
7004///
7005/// \returns true if PrevDecl is an out-of-scope previous declaration
7006/// for a new delcaration with the same name.
7007static bool
7009 ASTContext &Context) {
7010 if (!PrevDecl)
7011 return false;
7012
7013 if (!PrevDecl->hasLinkage())
7014 return false;
7015
7016 if (Context.getLangOpts().CPlusPlus) {
7017 // C++ [basic.link]p6:
7018 // If there is a visible declaration of an entity with linkage
7019 // having the same name and type, ignoring entities declared
7020 // outside the innermost enclosing namespace scope, the block
7021 // scope declaration declares that same entity and receives the
7022 // linkage of the previous declaration.
7023 DeclContext *OuterContext = DC->getRedeclContext();
7024 if (!OuterContext->isFunctionOrMethod())
7025 // This rule only applies to block-scope declarations.
7026 return false;
7027
7028 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7029 if (PrevOuterContext->isRecord())
7030 // We found a member function: ignore it.
7031 return false;
7032
7033 // Find the innermost enclosing namespace for the new and
7034 // previous declarations.
7035 OuterContext = OuterContext->getEnclosingNamespaceContext();
7036 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7037
7038 // The previous declaration is in a different namespace, so it
7039 // isn't the same function.
7040 if (!OuterContext->Equals(PrevOuterContext))
7041 return false;
7042 }
7043
7044 return true;
7045}
7046
7048 CXXScopeSpec &SS = D.getCXXScopeSpec();
7049 if (!SS.isSet()) return;
7051}
7052
7054 if (Decl->getType().hasAddressSpace())
7055 return;
7056 if (Decl->getType()->isDependentType())
7057 return;
7058 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7059 QualType Type = Var->getType();
7060 if (Type->isSamplerT() || Type->isVoidType())
7061 return;
7063 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7064 // __opencl_c_program_scope_global_variables feature, the address space
7065 // for a variable at program scope or a static or extern variable inside
7066 // a function are inferred to be __global.
7067 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7068 Var->hasGlobalStorage())
7069 ImplAS = LangAS::opencl_global;
7070 // If the original type from a decayed type is an array type and that array
7071 // type has no address space yet, deduce it now.
7072 if (auto DT = dyn_cast<DecayedType>(Type)) {
7073 auto OrigTy = DT->getOriginalType();
7074 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7075 // Add the address space to the original array type and then propagate
7076 // that to the element type through `getAsArrayType`.
7077 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7078 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7079 // Re-generate the decayed type.
7080 Type = Context.getDecayedType(OrigTy);
7081 }
7082 }
7083 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7084 // Apply any qualifiers (including address space) from the array type to
7085 // the element type. This implements C99 6.7.3p8: "If the specification of
7086 // an array type includes any type qualifiers, the element type is so
7087 // qualified, not the array type."
7088 if (Type->isArrayType())
7089 Type = QualType(Context.getAsArrayType(Type), 0);
7090 Decl->setType(Type);
7091 }
7092}
7093
7094static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7095 // 'weak' only applies to declarations with external linkage.
7096 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7097 if (!ND.isExternallyVisible()) {
7098 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7099 ND.dropAttr<WeakAttr>();
7100 }
7101 }
7102}
7103
7104static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7105 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7106 if (ND.isExternallyVisible()) {
7107 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7108 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7109 }
7110 }
7111}
7112
7113static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7114 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7115 if (VD->hasInit()) {
7116 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7117 assert(VD->isThisDeclarationADefinition() &&
7118 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7119 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7120 VD->dropAttr<AliasAttr>();
7121 }
7122 }
7123 }
7124}
7125
7126static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7127 // 'selectany' only applies to externally visible variable declarations.
7128 // It does not apply to functions.
7129 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7130 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7131 S.Diag(Attr->getLocation(),
7132 diag::err_attribute_selectany_non_extern_data);
7133 ND.dropAttr<SelectAnyAttr>();
7134 }
7135 }
7136}
7137
7139 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7140 if (!ND.isExternallyVisible())
7141 S.Diag(Attr->getLocation(),
7142 diag::warn_attribute_hybrid_patchable_non_extern);
7143 }
7144}
7145
7147 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7148 auto *VD = dyn_cast<VarDecl>(&ND);
7149 bool IsAnonymousNS = false;
7150 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7151 if (VD) {
7152 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7153 while (NS && !IsAnonymousNS) {
7154 IsAnonymousNS = NS->isAnonymousNamespace();
7155 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7156 }
7157 }
7158 // dll attributes require external linkage. Static locals may have external
7159 // linkage but still cannot be explicitly imported or exported.
7160 // In Microsoft mode, a variable defined in anonymous namespace must have
7161 // external linkage in order to be exported.
7162 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7163 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7164 (!AnonNSInMicrosoftMode &&
7165 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7166 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7167 << &ND << Attr;
7168 ND.setInvalidDecl();
7169 }
7170 }
7171}
7172
7174 // Check the attributes on the function type and function params, if any.
7175 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7176 FD = FD->getMostRecentDecl();
7177 // Don't declare this variable in the second operand of the for-statement;
7178 // GCC miscompiles that by ending its lifetime before evaluating the
7179 // third operand. See gcc.gnu.org/PR86769.
7181 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7182 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7183 TL = ATL.getModifiedLoc()) {
7184 // The [[lifetimebound]] attribute can be applied to the implicit object
7185 // parameter of a non-static member function (other than a ctor or dtor)
7186 // by applying it to the function type.
7187 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7188 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7189 int NoImplicitObjectError = -1;
7190 if (!MD)
7191 NoImplicitObjectError = 0;
7192 else if (MD->isStatic())
7193 NoImplicitObjectError = 1;
7194 else if (MD->isExplicitObjectMemberFunction())
7195 NoImplicitObjectError = 2;
7196 if (NoImplicitObjectError != -1) {
7197 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7198 << NoImplicitObjectError << A->getRange();
7199 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7200 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7201 << isa<CXXDestructorDecl>(MD) << A->getRange();
7202 } else if (MD->getReturnType()->isVoidType()) {
7203 S.Diag(
7204 MD->getLocation(),
7205 diag::
7206 err_lifetimebound_implicit_object_parameter_void_return_type);
7207 }
7208 }
7209 }
7210
7211 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7212 const ParmVarDecl *P = FD->getParamDecl(I);
7213
7214 // The [[lifetimebound]] attribute can be applied to a function parameter
7215 // only if the function returns a value.
7216 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7217 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7218 S.Diag(A->getLocation(),
7219 diag::err_lifetimebound_parameter_void_return_type);
7220 }
7221 }
7222 }
7223 }
7224}
7225
7227 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7228 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7229}
7230
7232 // Ensure that an auto decl is deduced otherwise the checks below might cache
7233 // the wrong linkage.
7234 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7235
7236 checkWeakAttr(S, ND);
7237 checkWeakRefAttr(S, ND);
7238 checkAliasAttr(S, ND);
7239 checkSelectAnyAttr(S, ND);
7241 checkInheritableAttr(S, ND);
7244}
7245
7247 NamedDecl *NewDecl,
7248 bool IsSpecialization,
7249 bool IsDefinition) {
7250 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7251 return;
7252
7253 bool IsTemplate = false;
7254 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7255 OldDecl = OldTD->getTemplatedDecl();
7256 IsTemplate = true;
7257 if (!IsSpecialization)
7258 IsDefinition = false;
7259 }
7260 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7261 NewDecl = NewTD->getTemplatedDecl();
7262 IsTemplate = true;
7263 }
7264
7265 if (!OldDecl || !NewDecl)
7266 return;
7267
7268 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7269 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7270 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7271 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7272
7273 // dllimport and dllexport are inheritable attributes so we have to exclude
7274 // inherited attribute instances.
7275 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7276 (NewExportAttr && !NewExportAttr->isInherited());
7277
7278 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7279 // the only exception being explicit specializations.
7280 // Implicitly generated declarations are also excluded for now because there
7281 // is no other way to switch these to use dllimport or dllexport.
7282 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7283
7284 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7285 // Allow with a warning for free functions and global variables.
7286 bool JustWarn = false;
7287 if (!OldDecl->isCXXClassMember()) {
7288 auto *VD = dyn_cast<VarDecl>(OldDecl);
7289 if (VD && !VD->getDescribedVarTemplate())
7290 JustWarn = true;
7291 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7292 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7293 JustWarn = true;
7294 }
7295
7296 // We cannot change a declaration that's been used because IR has already
7297 // been emitted. Dllimported functions will still work though (modulo
7298 // address equality) as they can use the thunk.
7299 if (OldDecl->isUsed())
7300 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7301 JustWarn = false;
7302
7303 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7304 : diag::err_attribute_dll_redeclaration;
7305 S.Diag(NewDecl->getLocation(), DiagID)
7306 << NewDecl
7307 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7308 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7309 if (!JustWarn) {
7310 NewDecl->setInvalidDecl();
7311 return;
7312 }
7313 }
7314
7315 // A redeclaration is not allowed to drop a dllimport attribute, the only
7316 // exceptions being inline function definitions (except for function
7317 // templates), local extern declarations, qualified friend declarations or
7318 // special MSVC extension: in the last case, the declaration is treated as if
7319 // it were marked dllexport.
7320 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7321 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7322 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7323 // Ignore static data because out-of-line definitions are diagnosed
7324 // separately.
7325 IsStaticDataMember = VD->isStaticDataMember();
7326 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7328 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7329 IsInline = FD->isInlined();
7330 IsQualifiedFriend = FD->getQualifier() &&
7331 FD->getFriendObjectKind() == Decl::FOK_Declared;
7332 }
7333
7334 if (OldImportAttr && !HasNewAttr &&
7335 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7336 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7337 if (IsMicrosoftABI && IsDefinition) {
7338 if (IsSpecialization) {
7339 S.Diag(
7340 NewDecl->getLocation(),
7341 diag::err_attribute_dllimport_function_specialization_definition);
7342 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7343 NewDecl->dropAttr<DLLImportAttr>();
7344 } else {
7345 S.Diag(NewDecl->getLocation(),
7346 diag::warn_redeclaration_without_import_attribute)
7347 << NewDecl;
7348 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7349 NewDecl->dropAttr<DLLImportAttr>();
7350 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7351 S.Context, NewImportAttr->getRange()));
7352 }
7353 } else if (IsMicrosoftABI && IsSpecialization) {
7354 assert(!IsDefinition);
7355 // MSVC allows this. Keep the inherited attribute.
7356 } else {
7357 S.Diag(NewDecl->getLocation(),
7358 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7359 << NewDecl << OldImportAttr;
7360 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7361 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7362 OldDecl->dropAttr<DLLImportAttr>();
7363 NewDecl->dropAttr<DLLImportAttr>();
7364 }
7365 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7366 // In MinGW, seeing a function declared inline drops the dllimport
7367 // attribute.
7368 OldDecl->dropAttr<DLLImportAttr>();
7369 NewDecl->dropAttr<DLLImportAttr>();
7370 S.Diag(NewDecl->getLocation(),
7371 diag::warn_dllimport_dropped_from_inline_function)
7372 << NewDecl << OldImportAttr;
7373 }
7374
7375 // A specialization of a class template member function is processed here
7376 // since it's a redeclaration. If the parent class is dllexport, the
7377 // specialization inherits that attribute. This doesn't happen automatically
7378 // since the parent class isn't instantiated until later.
7379 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7380 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7381 !NewImportAttr && !NewExportAttr) {
7382 if (const DLLExportAttr *ParentExportAttr =
7383 MD->getParent()->getAttr<DLLExportAttr>()) {
7384 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7385 NewAttr->setInherited(true);
7386 NewDecl->addAttr(NewAttr);
7387 }
7388 }
7389 }
7390}
7391
7392/// Given that we are within the definition of the given function,
7393/// will that definition behave like C99's 'inline', where the
7394/// definition is discarded except for optimization purposes?
7396 // Try to avoid calling GetGVALinkageForFunction.
7397
7398 // All cases of this require the 'inline' keyword.
7399 if (!FD->isInlined()) return false;
7400
7401 // This is only possible in C++ with the gnu_inline attribute.
7402 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7403 return false;
7404
7405 // Okay, go ahead and call the relatively-more-expensive function.
7407}
7408
7409/// Determine whether a variable is extern "C" prior to attaching
7410/// an initializer. We can't just call isExternC() here, because that
7411/// will also compute and cache whether the declaration is externally
7412/// visible, which might change when we attach the initializer.
7413///
7414/// This can only be used if the declaration is known to not be a
7415/// redeclaration of an internal linkage declaration.
7416///
7417/// For instance:
7418///
7419/// auto x = []{};
7420///
7421/// Attaching the initializer here makes this declaration not externally
7422/// visible, because its type has internal linkage.
7423///
7424/// FIXME: This is a hack.
7425template<typename T>
7426static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7427 if (S.getLangOpts().CPlusPlus) {
7428 // In C++, the overloadable attribute negates the effects of extern "C".
7429 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7430 return false;
7431
7432 // So do CUDA's host/device attributes.
7433 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7434 D->template hasAttr<CUDAHostAttr>()))
7435 return false;
7436 }
7437 return D->isExternC();
7438}
7439
7440static bool shouldConsiderLinkage(const VarDecl *VD) {
7441 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7444 return VD->hasExternalStorage();
7445 if (DC->isFileContext())
7446 return true;
7447 if (DC->isRecord())
7448 return false;
7449 if (DC->getDeclKind() == Decl::HLSLBuffer)
7450 return false;
7451
7453 return false;
7454 llvm_unreachable("Unexpected context");
7455}
7456
7457static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7458 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7459 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7461 return true;
7462 if (DC->isRecord())
7463 return false;
7464 llvm_unreachable("Unexpected context");
7465}
7466
7467static bool hasParsedAttr(Scope *S, const Declarator &PD,
7468 ParsedAttr::Kind Kind) {
7469 // Check decl attributes on the DeclSpec.
7470 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7471 return true;
7472
7473 // Walk the declarator structure, checking decl attributes that were in a type
7474 // position to the decl itself.
7475 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7476 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7477 return true;
7478 }
7479
7480 // Finally, check attributes on the decl itself.
7481 return PD.getAttributes().hasAttribute(Kind) ||
7483}
7484
7486 if (!DC->isFunctionOrMethod())
7487 return false;
7488
7489 // If this is a local extern function or variable declared within a function
7490 // template, don't add it into the enclosing namespace scope until it is
7491 // instantiated; it might have a dependent type right now.
7492 if (DC->isDependentContext())
7493 return true;
7494
7495 // C++11 [basic.link]p7:
7496 // When a block scope declaration of an entity with linkage is not found to
7497 // refer to some other declaration, then that entity is a member of the
7498 // innermost enclosing namespace.
7499 //
7500 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7501 // semantically-enclosing namespace, not a lexically-enclosing one.
7502 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7503 DC = DC->getParent();
7504 return true;
7505}
7506
7507/// Returns true if given declaration has external C language linkage.
7508static bool isDeclExternC(const Decl *D) {
7509 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7510 return FD->isExternC();
7511 if (const auto *VD = dyn_cast<VarDecl>(D))
7512 return VD->isExternC();
7513
7514 llvm_unreachable("Unknown type of decl!");
7515}
7516
7517/// Returns true if there hasn't been any invalid type diagnosed.
7518static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7519 DeclContext *DC = NewVD->getDeclContext();
7520 QualType R = NewVD->getType();
7521
7522 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7523 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7524 // argument.
7525 if (R->isImageType() || R->isPipeType()) {
7526 Se.Diag(NewVD->getLocation(),
7527 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7528 << R;
7529 NewVD->setInvalidDecl();
7530 return false;
7531 }
7532
7533 // OpenCL v1.2 s6.9.r:
7534 // The event type cannot be used to declare a program scope variable.
7535 // OpenCL v2.0 s6.9.q:
7536 // The clk_event_t and reserve_id_t types cannot be declared in program
7537 // scope.
7538 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7539 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7540 Se.Diag(NewVD->getLocation(),
7541 diag::err_invalid_type_for_program_scope_var)
7542 << R;
7543 NewVD->setInvalidDecl();
7544 return false;
7545 }
7546 }
7547
7548 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7549 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7550 Se.getLangOpts())) {
7551 QualType NR = R.getCanonicalType();
7552 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7553 NR->isReferenceType()) {
7556 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7557 << NR->isReferenceType();
7558 NewVD->setInvalidDecl();
7559 return false;
7560 }
7561 NR = NR->getPointeeType();
7562 }
7563 }
7564
7565 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7566 Se.getLangOpts())) {
7567 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7568 // half array type (unless the cl_khr_fp16 extension is enabled).
7569 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7570 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7571 NewVD->setInvalidDecl();
7572 return false;
7573 }
7574 }
7575
7576 // OpenCL v1.2 s6.9.r:
7577 // The event type cannot be used with the __local, __constant and __global
7578 // address space qualifiers.
7579 if (R->isEventT()) {
7581 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7582 NewVD->setInvalidDecl();
7583 return false;
7584 }
7585 }
7586
7587 if (R->isSamplerT()) {
7588 // OpenCL v1.2 s6.9.b p4:
7589 // The sampler type cannot be used with the __local and __global address
7590 // space qualifiers.
7593 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7594 NewVD->setInvalidDecl();
7595 }
7596
7597 // OpenCL v1.2 s6.12.14.1:
7598 // A global sampler must be declared with either the constant address
7599 // space qualifier or with the const qualifier.
7600 if (DC->isTranslationUnit() &&
7602 R.isConstQualified())) {
7603 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7604 NewVD->setInvalidDecl();
7605 }
7606 if (NewVD->isInvalidDecl())
7607 return false;
7608 }
7609
7610 return true;
7611}
7612
7613template <typename AttrTy>
7614static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7615 const TypedefNameDecl *TND = TT->getDecl();
7616 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7617 AttrTy *Clone = Attribute->clone(S.Context);
7618 Clone->setInherited(true);
7619 D->addAttr(Clone);
7620 }
7621}
7622
7623// This function emits warning and a corresponding note based on the
7624// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7625// declarations of an annotated type must be const qualified.
7627 QualType VarType = VD->getType().getCanonicalType();
7628
7629 // Ignore local declarations (for now) and those with const qualification.
7630 // TODO: Local variables should not be allowed if their type declaration has
7631 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7632 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7633 return;
7634
7635 if (VarType->isArrayType()) {
7636 // Retrieve element type for array declarations.
7637 VarType = S.getASTContext().getBaseElementType(VarType);
7638 }
7639
7640 const RecordDecl *RD = VarType->getAsRecordDecl();
7641
7642 // Check if the record declaration is present and if it has any attributes.
7643 if (RD == nullptr)
7644 return;
7645
7646 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7647 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7648 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7649 return;
7650 }
7651}
7652
7653// Checks if VD is declared at global scope or with C language linkage.
7654static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7655 return Name.getAsIdentifierInfo() &&
7656 Name.getAsIdentifierInfo()->isStr("main") &&
7657 !VD->getDescribedVarTemplate() &&
7658 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7659 VD->isExternC());
7660}
7661
7662void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7663 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7664
7665 // Quickly return if the function does not have an `asm` attribute.
7666 if (E == nullptr)
7667 return;
7668
7669 // The parser guarantees this is a string.
7670 StringLiteral *SE = cast<StringLiteral>(E);
7671 StringRef Label = SE->getString();
7672 QualType R = TInfo->getType();
7673 if (S->getFnParent() != nullptr) {
7674 switch (SC) {
7675 case SC_None:
7676 case SC_Auto:
7677 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7678 break;
7679 case SC_Register:
7680 // Local Named register
7681 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7683 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7684 break;
7685 case SC_Static:
7686 case SC_Extern:
7687 case SC_PrivateExtern:
7688 break;
7689 }
7690 } else if (SC == SC_Register) {
7691 // Global Named register
7692 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7693 const auto &TI = Context.getTargetInfo();
7694 bool HasSizeMismatch;
7695
7696 if (!TI.isValidGCCRegisterName(Label))
7697 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7698 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7699 HasSizeMismatch))
7700 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7701 else if (HasSizeMismatch)
7702 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7703 }
7704
7705 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7706 Diag(TInfo->getTypeLoc().getBeginLoc(),
7707 diag::err_asm_unsupported_register_type)
7708 << TInfo->getTypeLoc().getSourceRange();
7709 NewVD->setInvalidDecl(true);
7710 }
7711 }
7712}
7713
7715 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7716 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7717 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7718 QualType R = TInfo->getType();
7720
7722 bool IsPlaceholderVariable = false;
7723
7724 if (D.isDecompositionDeclarator()) {
7725 // Take the name of the first declarator as our name for diagnostic
7726 // purposes.
7727 auto &Decomp = D.getDecompositionDeclarator();
7728 if (!Decomp.bindings().empty()) {
7729 II = Decomp.bindings()[0].Name;
7730 Name = II;
7731 }
7732 } else if (!II) {
7733 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7734 return nullptr;
7735 }
7736
7737
7740 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7741 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7742
7743 IsPlaceholderVariable = true;
7744
7745 if (!Previous.empty()) {
7746 NamedDecl *PrevDecl = *Previous.begin();
7747 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7748 DC->getRedeclContext());
7749 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7750 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7751 if (IsPlaceholderVariable)
7753 }
7754 }
7755 }
7756
7757 // dllimport globals without explicit storage class are treated as extern. We
7758 // have to change the storage class this early to get the right DeclContext.
7759 if (SC == SC_None && !DC->isRecord() &&
7760 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7761 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7762 SC = SC_Extern;
7763
7764 DeclContext *OriginalDC = DC;
7765 bool IsLocalExternDecl = SC == SC_Extern &&
7767
7768 if (SCSpec == DeclSpec::SCS_mutable) {
7769 // mutable can only appear on non-static class members, so it's always
7770 // an error here
7771 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7772 D.setInvalidType();
7773 SC = SC_None;
7774 }
7775
7776 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7777 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7779 // In C++11, the 'register' storage class specifier is deprecated.
7780 // Suppress the warning in system macros, it's used in macros in some
7781 // popular C system headers, such as in glibc's htonl() macro.
7783 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7784 : diag::warn_deprecated_register)
7786 }
7787
7789
7790 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7791 // C99 6.9p2: The storage-class specifiers auto and register shall not
7792 // appear in the declaration specifiers in an external declaration.
7793 // Global Register+Asm is a GNU extension we support.
7794 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7795 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7796 D.setInvalidType();
7797 }
7798 }
7799
7800 // If this variable has a VLA type and an initializer, try to
7801 // fold to a constant-sized type. This is otherwise invalid.
7802 if (D.hasInitializer() && R->isVariableArrayType())
7804 /*DiagID=*/0);
7805
7806 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7807 const AutoType *AT = TL.getTypePtr();
7808 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7809 }
7810
7811 bool IsMemberSpecialization = false;
7812 bool IsVariableTemplateSpecialization = false;
7813 bool IsPartialSpecialization = false;
7814 bool IsVariableTemplate = false;
7815 VarDecl *NewVD = nullptr;
7816 VarTemplateDecl *NewTemplate = nullptr;
7817 TemplateParameterList *TemplateParams = nullptr;
7818 if (!getLangOpts().CPlusPlus) {
7820 II, R, TInfo, SC);
7821
7822 if (R->getContainedDeducedType())
7823 ParsingInitForAutoVars.insert(NewVD);
7824
7825 if (D.isInvalidType())
7826 NewVD->setInvalidDecl();
7827
7829 NewVD->hasLocalStorage())
7830 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7832 } else {
7833 bool Invalid = false;
7834 // Match up the template parameter lists with the scope specifier, then
7835 // determine whether we have a template or a template specialization.
7838 D.getCXXScopeSpec(),
7840 ? D.getName().TemplateId
7841 : nullptr,
7842 TemplateParamLists,
7843 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7844
7845 if (TemplateParams) {
7846 if (DC->isDependentContext()) {
7847 ContextRAII SavedContext(*this, DC);
7849 Invalid = true;
7850 }
7851
7852 if (!TemplateParams->size() &&
7854 // There is an extraneous 'template<>' for this variable. Complain
7855 // about it, but allow the declaration of the variable.
7856 Diag(TemplateParams->getTemplateLoc(),
7857 diag::err_template_variable_noparams)
7858 << II
7859 << SourceRange(TemplateParams->getTemplateLoc(),
7860 TemplateParams->getRAngleLoc());
7861 TemplateParams = nullptr;
7862 } else {
7863 // Check that we can declare a template here.
7864 if (CheckTemplateDeclScope(S, TemplateParams))
7865 return nullptr;
7866
7868 // This is an explicit specialization or a partial specialization.
7869 IsVariableTemplateSpecialization = true;
7870 IsPartialSpecialization = TemplateParams->size() > 0;
7871 } else { // if (TemplateParams->size() > 0)
7872 // This is a template declaration.
7873 IsVariableTemplate = true;
7874
7875 // Only C++1y supports variable templates (N3651).
7876 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7877 }
7878 }
7879 } else {
7880 // Check that we can declare a member specialization here.
7881 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7882 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7883 return nullptr;
7884 assert((Invalid ||
7886 "should have a 'template<>' for this decl");
7887 }
7888
7889 bool IsExplicitSpecialization =
7890 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7891
7892 // C++ [temp.expl.spec]p2:
7893 // The declaration in an explicit-specialization shall not be an
7894 // export-declaration. An explicit specialization shall not use a
7895 // storage-class-specifier other than thread_local.
7896 //
7897 // We use the storage-class-specifier from DeclSpec because we may have
7898 // added implicit 'extern' for declarations with __declspec(dllimport)!
7899 if (SCSpec != DeclSpec::SCS_unspecified &&
7900 (IsExplicitSpecialization || IsMemberSpecialization)) {
7902 diag::ext_explicit_specialization_storage_class)
7904 }
7905
7906 if (CurContext->isRecord()) {
7907 if (SC == SC_Static) {
7908 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7909 // Walk up the enclosing DeclContexts to check for any that are
7910 // incompatible with static data members.
7911 const DeclContext *FunctionOrMethod = nullptr;
7912 const CXXRecordDecl *AnonStruct = nullptr;
7913 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7914 if (Ctxt->isFunctionOrMethod()) {
7915 FunctionOrMethod = Ctxt;
7916 break;
7917 }
7918 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7919 if (ParentDecl && !ParentDecl->getDeclName()) {
7920 AnonStruct = ParentDecl;
7921 break;
7922 }
7923 }
7924 if (FunctionOrMethod) {
7925 // C++ [class.static.data]p5: A local class shall not have static
7926 // data members.
7928 diag::err_static_data_member_not_allowed_in_local_class)
7929 << Name << RD->getDeclName() << RD->getTagKind();
7930 } else if (AnonStruct) {
7931 // C++ [class.static.data]p4: Unnamed classes and classes contained
7932 // directly or indirectly within unnamed classes shall not contain
7933 // static data members.
7935 diag::err_static_data_member_not_allowed_in_anon_struct)
7936 << Name << AnonStruct->getTagKind();
7937 Invalid = true;
7938 } else if (RD->isUnion()) {
7939 // C++98 [class.union]p1: If a union contains a static data member,
7940 // the program is ill-formed. C++11 drops this restriction.
7942 diag_compat::static_data_member_in_union)
7943 << Name;
7944 }
7945 }
7946 } else if (IsVariableTemplate || IsPartialSpecialization) {
7947 // There is no such thing as a member field template.
7948 Diag(D.getIdentifierLoc(), diag::err_template_member)
7949 << II << TemplateParams->getSourceRange();
7950 // Recover by pretending this is a static data member template.
7951 SC = SC_Static;
7952 }
7953 } else if (DC->isRecord()) {
7954 // This is an out-of-line definition of a static data member.
7955 switch (SC) {
7956 case SC_None:
7957 break;
7958 case SC_Static:
7960 diag::err_static_out_of_line)
7963 break;
7964 case SC_Auto:
7965 case SC_Register:
7966 case SC_Extern:
7967 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7968 // to names of variables declared in a block or to function parameters.
7969 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7970 // of class members
7971
7973 diag::err_storage_class_for_static_member)
7976 break;
7977 case SC_PrivateExtern:
7978 llvm_unreachable("C storage class in c++!");
7979 }
7980 }
7981
7982 if (IsVariableTemplateSpecialization) {
7983 SourceLocation TemplateKWLoc =
7984 TemplateParamLists.size() > 0
7985 ? TemplateParamLists[0]->getTemplateLoc()
7986 : SourceLocation();
7988 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7990 if (Res.isInvalid())
7991 return nullptr;
7992 NewVD = cast<VarDecl>(Res.get());
7993 AddToScope = false;
7994 } else if (D.isDecompositionDeclarator()) {
7996 D.getIdentifierLoc(), R, TInfo, SC,
7997 Bindings);
7998 } else
7999 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8000 D.getIdentifierLoc(), II, R, TInfo, SC);
8001
8002 // If this is supposed to be a variable template, create it as such.
8003 if (IsVariableTemplate) {
8004 NewTemplate =
8006 TemplateParams, NewVD);
8007 NewVD->setDescribedVarTemplate(NewTemplate);
8008 }
8009
8010 // If this decl has an auto type in need of deduction, make a note of the
8011 // Decl so we can diagnose uses of it in its own initializer.
8012 if (R->getContainedDeducedType())
8013 ParsingInitForAutoVars.insert(NewVD);
8014
8015 if (D.isInvalidType() || Invalid) {
8016 NewVD->setInvalidDecl();
8017 if (NewTemplate)
8018 NewTemplate->setInvalidDecl();
8019 }
8020
8021 SetNestedNameSpecifier(*this, NewVD, D);
8022
8023 // If we have any template parameter lists that don't directly belong to
8024 // the variable (matching the scope specifier), store them.
8025 // An explicit variable template specialization does not own any template
8026 // parameter lists.
8027 unsigned VDTemplateParamLists =
8028 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8029 if (TemplateParamLists.size() > VDTemplateParamLists)
8031 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8032 }
8033
8034 if (D.getDeclSpec().isInlineSpecified()) {
8035 if (!getLangOpts().CPlusPlus) {
8036 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8037 << 0;
8038 } else if (CurContext->isFunctionOrMethod()) {
8039 // 'inline' is not allowed on block scope variable declaration.
8041 diag::err_inline_declaration_block_scope) << Name
8043 } else {
8045 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8046 : diag::compat_pre_cxx17_inline_variable);
8047 NewVD->setInlineSpecified();
8048 }
8049 }
8050
8051 // Set the lexical context. If the declarator has a C++ scope specifier, the
8052 // lexical context will be different from the semantic context.
8054 if (NewTemplate)
8055 NewTemplate->setLexicalDeclContext(CurContext);
8056
8057 if (IsLocalExternDecl) {
8059 for (auto *B : Bindings)
8060 B->setLocalExternDecl();
8061 else
8062 NewVD->setLocalExternDecl();
8063 }
8064
8065 bool EmitTLSUnsupportedError = false;
8067 // C++11 [dcl.stc]p4:
8068 // When thread_local is applied to a variable of block scope the
8069 // storage-class-specifier static is implied if it does not appear
8070 // explicitly.
8071 // Core issue: 'static' is not implied if the variable is declared
8072 // 'extern'.
8073 if (NewVD->hasLocalStorage() &&
8074 (SCSpec != DeclSpec::SCS_unspecified ||
8076 !DC->isFunctionOrMethod()))
8078 diag::err_thread_non_global)
8080 else if (!Context.getTargetInfo().isTLSSupported()) {
8081 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8082 // Postpone error emission until we've collected attributes required to
8083 // figure out whether it's a host or device variable and whether the
8084 // error should be ignored.
8085 EmitTLSUnsupportedError = true;
8086 // We still need to mark the variable as TLS so it shows up in AST with
8087 // proper storage class for other tools to use even if we're not going
8088 // to emit any code for it.
8089 NewVD->setTSCSpec(TSCS);
8090 } else
8092 diag::err_thread_unsupported);
8093 } else
8094 NewVD->setTSCSpec(TSCS);
8095 }
8096
8097 switch (D.getDeclSpec().getConstexprSpecifier()) {
8099 break;
8100
8103 diag::err_constexpr_wrong_decl_kind)
8104 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8105 [[fallthrough]];
8106
8108 NewVD->setConstexpr(true);
8109 // C++1z [dcl.spec.constexpr]p1:
8110 // A static data member declared with the constexpr specifier is
8111 // implicitly an inline variable.
8112 if (NewVD->isStaticDataMember() &&
8114 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8115 NewVD->setImplicitlyInline();
8116 break;
8117
8119 if (!NewVD->hasGlobalStorage())
8121 diag::err_constinit_local_variable);
8122 else
8123 NewVD->addAttr(
8124 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8125 ConstInitAttr::Keyword_constinit));
8126 break;
8127 }
8128
8129 // C99 6.7.4p3
8130 // An inline definition of a function with external linkage shall
8131 // not contain a definition of a modifiable object with static or
8132 // thread storage duration...
8133 // We only apply this when the function is required to be defined
8134 // elsewhere, i.e. when the function is not 'extern inline'. Note
8135 // that a local variable with thread storage duration still has to
8136 // be marked 'static'. Also note that it's possible to get these
8137 // semantics in C++ using __attribute__((gnu_inline)).
8138 if (SC == SC_Static && S->getFnParent() != nullptr &&
8139 !NewVD->getType().isConstQualified()) {
8141 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8143 diag::warn_static_local_in_extern_inline);
8145 }
8146 }
8147
8149 if (IsVariableTemplateSpecialization)
8150 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8151 << (IsPartialSpecialization ? 1 : 0)
8154 else if (IsMemberSpecialization)
8155 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8156 << 2
8158 else if (NewVD->hasLocalStorage())
8159 Diag(NewVD->getLocation(), diag::err_module_private_local)
8160 << 0 << NewVD
8164 else {
8165 NewVD->setModulePrivate();
8166 if (NewTemplate)
8167 NewTemplate->setModulePrivate();
8168 for (auto *B : Bindings)
8169 B->setModulePrivate();
8170 }
8171 }
8172
8173 if (getLangOpts().OpenCL) {
8175
8177 if (TSC != TSCS_unspecified) {
8179 diag::err_opencl_unknown_type_specifier)
8181 << DeclSpec::getSpecifierName(TSC) << 1;
8182 NewVD->setInvalidDecl();
8183 }
8184 }
8185
8186 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8187 // address space if the table has local storage (semantic checks elsewhere
8188 // will produce an error anyway).
8189 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8190 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8191 !NewVD->hasLocalStorage()) {
8192 QualType Type = Context.getAddrSpaceQualType(
8193 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8194 NewVD->setType(Type);
8195 }
8196 }
8197
8198 if (Expr *E = D.getAsmLabel()) {
8199 // The parser guarantees this is a string.
8201 StringRef Label = SE->getString();
8202
8203 // Insert the asm attribute.
8204 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8205 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8206 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8208 if (I != ExtnameUndeclaredIdentifiers.end()) {
8209 if (isDeclExternC(NewVD)) {
8210 NewVD->addAttr(I->second);
8212 } else
8213 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8214 << /*Variable*/ 1 << NewVD;
8215 }
8216 }
8217
8218 // Handle attributes prior to checking for duplicates in MergeVarDecl
8219 ProcessDeclAttributes(S, NewVD, D);
8220
8221 if (getLangOpts().HLSL)
8223
8224 if (getLangOpts().OpenACC)
8226
8227 // FIXME: This is probably the wrong location to be doing this and we should
8228 // probably be doing this for more attributes (especially for function
8229 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8230 // the code to copy attributes would be generated by TableGen.
8231 if (R->isFunctionPointerType())
8232 if (const auto *TT = R->getAs<TypedefType>())
8234
8235 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8236 if (EmitTLSUnsupportedError &&
8238 (getLangOpts().OpenMPIsTargetDevice &&
8239 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8241 diag::err_thread_unsupported);
8242
8243 if (EmitTLSUnsupportedError &&
8244 (LangOpts.SYCLIsDevice ||
8245 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8246 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8247 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8248 // storage [duration]."
8249 if (SC == SC_None && S->getFnParent() != nullptr &&
8250 (NewVD->hasAttr<CUDASharedAttr>() ||
8251 NewVD->hasAttr<CUDAConstantAttr>())) {
8252 NewVD->setStorageClass(SC_Static);
8253 }
8254 }
8255
8256 // Ensure that dllimport globals without explicit storage class are treated as
8257 // extern. The storage class is set above using parsed attributes. Now we can
8258 // check the VarDecl itself.
8259 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8260 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8261 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8262
8263 // In auto-retain/release, infer strong retension for variables of
8264 // retainable type.
8265 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8266 NewVD->setInvalidDecl();
8267
8268 // Check the ASM label here, as we need to know all other attributes of the
8269 // Decl first. Otherwise, we can't know if the asm label refers to the
8270 // host or device in a CUDA context. The device has other registers than
8271 // host and we must know where the function will be placed.
8272 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8273
8274 // Find the shadowed declaration before filtering for scope.
8275 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8277 : nullptr;
8278
8279 // Don't consider existing declarations that are in a different
8280 // scope and are out-of-semantic-context declarations (if the new
8281 // declaration has linkage).
8284 IsMemberSpecialization ||
8285 IsVariableTemplateSpecialization);
8286
8287 // Check whether the previous declaration is in the same block scope. This
8288 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8289 if (getLangOpts().CPlusPlus &&
8290 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8292 Previous.isSingleResult() && !Previous.isShadowed() &&
8293 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8294
8295 if (!getLangOpts().CPlusPlus) {
8297 } else {
8298 // If this is an explicit specialization of a static data member, check it.
8299 if (IsMemberSpecialization && !IsVariableTemplate &&
8300 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8302 NewVD->setInvalidDecl();
8303
8304 // Merge the decl with the existing one if appropriate.
8305 if (!Previous.empty()) {
8306 if (Previous.isSingleResult() &&
8307 isa<FieldDecl>(Previous.getFoundDecl()) &&
8308 D.getCXXScopeSpec().isSet()) {
8309 // The user tried to define a non-static data member
8310 // out-of-line (C++ [dcl.meaning]p1).
8311 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8312 << D.getCXXScopeSpec().getRange();
8313 Previous.clear();
8314 NewVD->setInvalidDecl();
8315 }
8316 } else if (D.getCXXScopeSpec().isSet() &&
8317 !IsVariableTemplateSpecialization) {
8318 // No previous declaration in the qualifying scope.
8319 Diag(D.getIdentifierLoc(), diag::err_no_member)
8320 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8321 << D.getCXXScopeSpec().getRange();
8322 NewVD->setInvalidDecl();
8323 }
8324
8325 if (!IsPlaceholderVariable)
8327
8328 // CheckVariableDeclaration will set NewVD as invalid if something is in
8329 // error like WebAssembly tables being declared as arrays with a non-zero
8330 // size, but then parsing continues and emits further errors on that line.
8331 // To avoid that we check here if it happened and return nullptr.
8332 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8333 return nullptr;
8334
8335 if (NewTemplate) {
8336 VarTemplateDecl *PrevVarTemplate =
8337 NewVD->getPreviousDecl()
8339 : nullptr;
8340
8341 // Check the template parameter list of this declaration, possibly
8342 // merging in the template parameter list from the previous variable
8343 // template declaration.
8345 TemplateParams,
8346 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8347 : nullptr,
8348 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8349 DC->isDependentContext())
8351 : TPC_Other))
8352 NewVD->setInvalidDecl();
8353
8354 // If we are providing an explicit specialization of a static variable
8355 // template, make a note of that.
8356 if (PrevVarTemplate &&
8357 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8358 PrevVarTemplate->setMemberSpecialization();
8359 }
8360 }
8361
8362 // Diagnose shadowed variables iff this isn't a redeclaration.
8363 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8364 CheckShadow(NewVD, ShadowedDecl, Previous);
8365
8366 ProcessPragmaWeak(S, NewVD);
8367
8368 // If this is the first declaration of an extern C variable, update
8369 // the map of such variables.
8370 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8371 isIncompleteDeclExternC(*this, NewVD))
8373
8374 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8376 Decl *ManglingContextDecl;
8377 std::tie(MCtx, ManglingContextDecl) =
8379 if (MCtx) {
8380 Context.setManglingNumber(
8381 NewVD, MCtx->getManglingNumber(
8382 NewVD, getMSManglingNumber(getLangOpts(), S)));
8383 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8384 }
8385 }
8386
8387 // Special handling of variable named 'main'.
8388 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8389 // C++ [basic.start.main]p3:
8390 // A program that declares
8391 // - a variable main at global scope, or
8392 // - an entity named main with C language linkage (in any namespace)
8393 // is ill-formed
8394 if (getLangOpts().CPlusPlus)
8395 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8396 << NewVD->isExternC();
8397
8398 // In C, and external-linkage variable named main results in undefined
8399 // behavior.
8400 else if (NewVD->hasExternalFormalLinkage())
8401 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8402 }
8403
8404 if (D.isRedeclaration() && !Previous.empty()) {
8405 NamedDecl *Prev = Previous.getRepresentativeDecl();
8406 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8408 }
8409
8410 if (NewTemplate) {
8411 if (NewVD->isInvalidDecl())
8412 NewTemplate->setInvalidDecl();
8413 ActOnDocumentableDecl(NewTemplate);
8414 return NewTemplate;
8415 }
8416
8417 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8419
8421
8422 return NewVD;
8423}
8424
8425/// Enum describing the %select options in diag::warn_decl_shadow.
8435
8436/// Determine what kind of declaration we're shadowing.
8438 const DeclContext *OldDC) {
8439 if (isa<TypeAliasDecl>(ShadowedDecl))
8440 return SDK_Using;
8441 else if (isa<TypedefDecl>(ShadowedDecl))
8442 return SDK_Typedef;
8443 else if (isa<BindingDecl>(ShadowedDecl))
8444 return SDK_StructuredBinding;
8445 else if (isa<RecordDecl>(OldDC))
8446 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8447
8448 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8449}
8450
8451/// Return the location of the capture if the given lambda captures the given
8452/// variable \p VD, or an invalid source location otherwise.
8454 const ValueDecl *VD) {
8455 for (const Capture &Capture : LSI->Captures) {
8457 return Capture.getLocation();
8458 }
8459 return SourceLocation();
8460}
8461
8463 const LookupResult &R) {
8464 // Only diagnose if we're shadowing an unambiguous field or variable.
8466 return false;
8467
8468 // Return false if warning is ignored.
8469 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8470}
8471
8473 const LookupResult &R) {
8475 return nullptr;
8476
8477 // Don't diagnose declarations at file scope.
8478 if (D->hasGlobalStorage() && !D->isStaticLocal())
8479 return nullptr;
8480
8481 NamedDecl *ShadowedDecl = R.getFoundDecl();
8482 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8483 : nullptr;
8484}
8485
8487 const LookupResult &R) {
8488 // Don't warn if typedef declaration is part of a class
8489 if (D->getDeclContext()->isRecord())
8490 return nullptr;
8491
8493 return nullptr;
8494
8495 NamedDecl *ShadowedDecl = R.getFoundDecl();
8496 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8497}
8498
8500 const LookupResult &R) {
8502 return nullptr;
8503
8504 NamedDecl *ShadowedDecl = R.getFoundDecl();
8505 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8506 : nullptr;
8507}
8508
8510 const LookupResult &R) {
8511 DeclContext *NewDC = D->getDeclContext();
8512
8513 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8514 if (const auto *MD =
8515 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8516 // Fields aren't shadowed in C++ static members or in member functions
8517 // with an explicit object parameter.
8518 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8519 return;
8520 }
8521 // Fields shadowed by constructor parameters are a special case. Usually
8522 // the constructor initializes the field with the parameter.
8523 if (isa<CXXConstructorDecl>(NewDC))
8524 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8525 // Remember that this was shadowed so we can either warn about its
8526 // modification or its existence depending on warning settings.
8527 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8528 return;
8529 }
8530 }
8531
8532 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8533 if (shadowedVar->isExternC()) {
8534 // For shadowing external vars, make sure that we point to the global
8535 // declaration, not a locally scoped extern declaration.
8536 for (auto *I : shadowedVar->redecls())
8537 if (I->isFileVarDecl()) {
8538 ShadowedDecl = I;
8539 break;
8540 }
8541 }
8542
8543 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8544
8545 unsigned WarningDiag = diag::warn_decl_shadow;
8546 SourceLocation CaptureLoc;
8547 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8548 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8549 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8550 // Handle both VarDecl and BindingDecl in lambda contexts
8551 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8552 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8553 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8554 if (RD->getLambdaCaptureDefault() == LCD_None) {
8555 // Try to avoid warnings for lambdas with an explicit capture
8556 // list. Warn only when the lambda captures the shadowed decl
8557 // explicitly.
8558 CaptureLoc = getCaptureLocation(LSI, VD);
8559 if (CaptureLoc.isInvalid())
8560 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8561 } else {
8562 // Remember that this was shadowed so we can avoid the warning if
8563 // the shadowed decl isn't captured and the warning settings allow
8564 // it.
8566 ->ShadowingDecls.push_back({D, VD});
8567 return;
8568 }
8569 }
8570 if (isa<FieldDecl>(ShadowedDecl)) {
8571 // If lambda can capture this, then emit default shadowing warning,
8572 // Otherwise it is not really a shadowing case since field is not
8573 // available in lambda's body.
8574 // At this point we don't know that lambda can capture this, so
8575 // remember that this was shadowed and delay until we know.
8577 ->ShadowingDecls.push_back({D, ShadowedDecl});
8578 return;
8579 }
8580 }
8581 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8582 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8583 bool HasLocalStorage = false;
8584 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8585 HasLocalStorage = VD->hasLocalStorage();
8586 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8587 HasLocalStorage =
8588 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8589
8590 if (HasLocalStorage) {
8591 // A variable can't shadow a local variable or binding in an enclosing
8592 // scope, if they are separated by a non-capturing declaration
8593 // context.
8594 for (DeclContext *ParentDC = NewDC;
8595 ParentDC && !ParentDC->Equals(OldDC);
8596 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8597 // Only block literals, captured statements, and lambda expressions
8598 // can capture; other scopes don't.
8599 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8600 !isLambdaCallOperator(ParentDC))
8601 return;
8602 }
8603 }
8604 }
8605 }
8606 }
8607
8608 // Never warn about shadowing a placeholder variable.
8609 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8610 return;
8611
8612 // Only warn about certain kinds of shadowing for class members.
8613 if (NewDC) {
8614 // In particular, don't warn about shadowing non-class members.
8615 if (NewDC->isRecord() && !OldDC->isRecord())
8616 return;
8617
8618 // Skip shadowing check if we're in a class scope, dealing with an enum
8619 // constant in a different context.
8620 DeclContext *ReDC = NewDC->getRedeclContext();
8621 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8622 return;
8623
8624 // TODO: should we warn about static data members shadowing
8625 // static data members from base classes?
8626
8627 // TODO: don't diagnose for inaccessible shadowed members.
8628 // This is hard to do perfectly because we might friend the
8629 // shadowing context, but that's just a false negative.
8630 }
8631
8632 DeclarationName Name = R.getLookupName();
8633
8634 // Emit warning and note.
8635 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8636 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8637 if (!CaptureLoc.isInvalid())
8638 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8639 << Name << /*explicitly*/ 1;
8640 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8641}
8642
8644 for (const auto &Shadow : LSI->ShadowingDecls) {
8645 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8646 // Try to avoid the warning when the shadowed decl isn't captured.
8647 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8648 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8649 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8650 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8651 Diag(Shadow.VD->getLocation(),
8652 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8653 : diag::warn_decl_shadow)
8654 << Shadow.VD->getDeclName()
8655 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8656 if (CaptureLoc.isValid())
8657 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8658 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8659 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8660 } else if (isa<FieldDecl>(ShadowedDecl)) {
8661 Diag(Shadow.VD->getLocation(),
8662 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8663 : diag::warn_decl_shadow_uncaptured_local)
8664 << Shadow.VD->getDeclName()
8665 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8666 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8667 }
8668 }
8669}
8670
8672 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8673 return;
8674
8675 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8678 LookupName(R, S);
8679 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8680 CheckShadow(D, ShadowedDecl, R);
8681}
8682
8683/// Check if 'E', which is an expression that is about to be modified, refers
8684/// to a constructor parameter that shadows a field.
8686 // Quickly ignore expressions that can't be shadowing ctor parameters.
8687 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8688 return;
8689 E = E->IgnoreParenImpCasts();
8690 auto *DRE = dyn_cast<DeclRefExpr>(E);
8691 if (!DRE)
8692 return;
8693 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8694 auto I = ShadowingDecls.find(D);
8695 if (I == ShadowingDecls.end())
8696 return;
8697 const NamedDecl *ShadowedDecl = I->second;
8698 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8699 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8700 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8701 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8702
8703 // Avoid issuing multiple warnings about the same decl.
8704 ShadowingDecls.erase(I);
8705}
8706
8707/// Check for conflict between this global or extern "C" declaration and
8708/// previous global or extern "C" declarations. This is only used in C++.
8709template<typename T>
8711 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8712 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8713 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8714
8715 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8716 // The common case: this global doesn't conflict with any extern "C"
8717 // declaration.
8718 return false;
8719 }
8720
8721 if (Prev) {
8722 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8723 // Both the old and new declarations have C language linkage. This is a
8724 // redeclaration.
8725 Previous.clear();
8726 Previous.addDecl(Prev);
8727 return true;
8728 }
8729
8730 // This is a global, non-extern "C" declaration, and there is a previous
8731 // non-global extern "C" declaration. Diagnose if this is a variable
8732 // declaration.
8733 if (!isa<VarDecl>(ND))
8734 return false;
8735 } else {
8736 // The declaration is extern "C". Check for any declaration in the
8737 // translation unit which might conflict.
8738 if (IsGlobal) {
8739 // We have already performed the lookup into the translation unit.
8740 IsGlobal = false;
8741 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8742 I != E; ++I) {
8743 if (isa<VarDecl>(*I)) {
8744 Prev = *I;
8745 break;
8746 }
8747 }
8748 } else {
8750 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8751 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8752 I != E; ++I) {
8753 if (isa<VarDecl>(*I)) {
8754 Prev = *I;
8755 break;
8756 }
8757 // FIXME: If we have any other entity with this name in global scope,
8758 // the declaration is ill-formed, but that is a defect: it breaks the
8759 // 'stat' hack, for instance. Only variables can have mangled name
8760 // clashes with extern "C" declarations, so only they deserve a
8761 // diagnostic.
8762 }
8763 }
8764
8765 if (!Prev)
8766 return false;
8767 }
8768
8769 // Use the first declaration's location to ensure we point at something which
8770 // is lexically inside an extern "C" linkage-spec.
8771 assert(Prev && "should have found a previous declaration to diagnose");
8772 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8773 Prev = FD->getFirstDecl();
8774 else
8775 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8776
8777 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8778 << IsGlobal << ND;
8779 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8780 << IsGlobal;
8781 return false;
8782}
8783
8784/// Apply special rules for handling extern "C" declarations. Returns \c true
8785/// if we have found that this is a redeclaration of some prior entity.
8786///
8787/// Per C++ [dcl.link]p6:
8788/// Two declarations [for a function or variable] with C language linkage
8789/// with the same name that appear in different scopes refer to the same
8790/// [entity]. An entity with C language linkage shall not be declared with
8791/// the same name as an entity in global scope.
8792template<typename T>
8795 if (!S.getLangOpts().CPlusPlus) {
8796 // In C, when declaring a global variable, look for a corresponding 'extern'
8797 // variable declared in function scope. We don't need this in C++, because
8798 // we find local extern decls in the surrounding file-scope DeclContext.
8799 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8800 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8801 Previous.clear();
8802 Previous.addDecl(Prev);
8803 return true;
8804 }
8805 }
8806 return false;
8807 }
8808
8809 // A declaration in the translation unit can conflict with an extern "C"
8810 // declaration.
8811 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8812 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8813
8814 // An extern "C" declaration can conflict with a declaration in the
8815 // translation unit or can be a redeclaration of an extern "C" declaration
8816 // in another scope.
8817 if (isIncompleteDeclExternC(S,ND))
8818 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8819
8820 // Neither global nor extern "C": nothing to do.
8821 return false;
8822}
8823
8824static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8825 QualType T) {
8826 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8827 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8828 // any of its members, even recursively, shall not have an atomic type, or a
8829 // variably modified type, or a type that is volatile or restrict qualified.
8830 if (CanonT->isVariablyModifiedType()) {
8831 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8832 return true;
8833 }
8834
8835 // Arrays are qualified by their element type, so get the base type (this
8836 // works on non-arrays as well).
8837 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8838
8839 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8840 CanonT.isRestrictQualified()) {
8841 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8842 return true;
8843 }
8844
8845 if (CanonT->isRecordType()) {
8846 const RecordDecl *RD = CanonT->getAsRecordDecl();
8847 if (!RD->isInvalidDecl() &&
8848 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8849 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8850 }))
8851 return true;
8852 }
8853
8854 return false;
8855}
8856
8858 // If the decl is already known invalid, don't check it.
8859 if (NewVD->isInvalidDecl())
8860 return;
8861
8862 QualType T = NewVD->getType();
8863
8864 // Defer checking an 'auto' type until its initializer is attached.
8865 if (T->isUndeducedType())
8866 return;
8867
8868 if (NewVD->hasAttrs())
8870
8871 if (T->isObjCObjectType()) {
8872 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8873 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8874 T = Context.getObjCObjectPointerType(T);
8875 NewVD->setType(T);
8876 }
8877
8878 // Emit an error if an address space was applied to decl with local storage.
8879 // This includes arrays of objects with address space qualifiers, but not
8880 // automatic variables that point to other address spaces.
8881 // ISO/IEC TR 18037 S5.1.2
8882 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8883 T.getAddressSpace() != LangAS::Default) {
8884 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8885 NewVD->setInvalidDecl();
8886 return;
8887 }
8888
8889 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8890 // scope.
8891 if (getLangOpts().OpenCLVersion == 120 &&
8892 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8893 getLangOpts()) &&
8894 NewVD->isStaticLocal()) {
8895 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8896 NewVD->setInvalidDecl();
8897 return;
8898 }
8899
8900 if (getLangOpts().OpenCL) {
8901 if (!diagnoseOpenCLTypes(*this, NewVD))
8902 return;
8903
8904 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8905 if (NewVD->hasAttr<BlocksAttr>()) {
8906 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8907 return;
8908 }
8909
8910 if (T->isBlockPointerType()) {
8911 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8912 // can't use 'extern' storage class.
8913 if (!T.isConstQualified()) {
8914 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8915 << 0 /*const*/;
8916 NewVD->setInvalidDecl();
8917 return;
8918 }
8919 if (NewVD->hasExternalStorage()) {
8920 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8921 NewVD->setInvalidDecl();
8922 return;
8923 }
8924 }
8925
8926 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8927 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8928 NewVD->hasExternalStorage()) {
8929 if (!T->isSamplerT() && !T->isDependentType() &&
8930 !(T.getAddressSpace() == LangAS::opencl_constant ||
8931 (T.getAddressSpace() == LangAS::opencl_global &&
8932 getOpenCLOptions().areProgramScopeVariablesSupported(
8933 getLangOpts())))) {
8934 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8935 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8936 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8937 << Scope << "global or constant";
8938 else
8939 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8940 << Scope << "constant";
8941 NewVD->setInvalidDecl();
8942 return;
8943 }
8944 } else {
8945 if (T.getAddressSpace() == LangAS::opencl_global) {
8946 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8947 << 1 /*is any function*/ << "global";
8948 NewVD->setInvalidDecl();
8949 return;
8950 }
8951 if (T.getAddressSpace() == LangAS::opencl_constant ||
8952 T.getAddressSpace() == LangAS::opencl_local) {
8954 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8955 // in functions.
8956 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8957 if (T.getAddressSpace() == LangAS::opencl_constant)
8958 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8959 << 0 /*non-kernel only*/ << "constant";
8960 else
8961 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8962 << 0 /*non-kernel only*/ << "local";
8963 NewVD->setInvalidDecl();
8964 return;
8965 }
8966 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8967 // in the outermost scope of a kernel function.
8968 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8969 if (!getCurScope()->isFunctionScope()) {
8970 if (T.getAddressSpace() == LangAS::opencl_constant)
8971 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8972 << "constant";
8973 else
8974 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8975 << "local";
8976 NewVD->setInvalidDecl();
8977 return;
8978 }
8979 }
8980 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8981 // If we are parsing a template we didn't deduce an addr
8982 // space yet.
8983 T.getAddressSpace() != LangAS::Default) {
8984 // Do not allow other address spaces on automatic variable.
8985 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8986 NewVD->setInvalidDecl();
8987 return;
8988 }
8989 }
8990 }
8991
8992 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8993 && !NewVD->hasAttr<BlocksAttr>()) {
8994 if (getLangOpts().getGC() != LangOptions::NonGC)
8995 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8996 else {
8997 assert(!getLangOpts().ObjCAutoRefCount);
8998 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8999 }
9000 }
9001
9002 // WebAssembly tables must be static with a zero length and can't be
9003 // declared within functions.
9004 if (T->isWebAssemblyTableType()) {
9005 if (getCurScope()->getParent()) { // Parent is null at top-level
9006 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9007 NewVD->setInvalidDecl();
9008 return;
9009 }
9010 if (NewVD->getStorageClass() != SC_Static) {
9011 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9012 NewVD->setInvalidDecl();
9013 return;
9014 }
9015 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9016 if (!ATy || ATy->getZExtSize() != 0) {
9017 Diag(NewVD->getLocation(),
9018 diag::err_typecheck_wasm_table_must_have_zero_length);
9019 NewVD->setInvalidDecl();
9020 return;
9021 }
9022 }
9023
9024 // zero sized static arrays are not allowed in HIP device functions
9025 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9026 if (FunctionDecl *FD = getCurFunctionDecl();
9027 FD &&
9028 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9029 if (const ConstantArrayType *ArrayT =
9030 getASTContext().getAsConstantArrayType(T);
9031 ArrayT && ArrayT->isZeroSize()) {
9032 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9033 }
9034 }
9035 }
9036
9037 bool isVM = T->isVariablyModifiedType();
9038 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9039 NewVD->hasAttr<BlocksAttr>())
9041
9042 if ((isVM && NewVD->hasLinkage()) ||
9043 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9044 bool SizeIsNegative;
9045 llvm::APSInt Oversized;
9047 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9048 QualType FixedT;
9049 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9050 FixedT = FixedTInfo->getType();
9051 else if (FixedTInfo) {
9052 // Type and type-as-written are canonically different. We need to fix up
9053 // both types separately.
9054 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9055 Oversized);
9056 }
9057 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9058 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9059 // FIXME: This won't give the correct result for
9060 // int a[10][n];
9061 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9062
9063 if (NewVD->isFileVarDecl())
9064 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9065 << SizeRange;
9066 else if (NewVD->isStaticLocal())
9067 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9068 << SizeRange;
9069 else
9070 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9071 << SizeRange;
9072 NewVD->setInvalidDecl();
9073 return;
9074 }
9075
9076 if (!FixedTInfo) {
9077 if (NewVD->isFileVarDecl())
9078 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9079 else
9080 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9081 NewVD->setInvalidDecl();
9082 return;
9083 }
9084
9085 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9086 NewVD->setType(FixedT);
9087 NewVD->setTypeSourceInfo(FixedTInfo);
9088 }
9089
9090 if (T->isVoidType()) {
9091 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9092 // of objects and functions.
9094 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9095 << T;
9096 NewVD->setInvalidDecl();
9097 return;
9098 }
9099 }
9100
9101 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9102 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9103 NewVD->setInvalidDecl();
9104 return;
9105 }
9106
9107 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9108 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9109 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9110 NewVD->setInvalidDecl();
9111 return;
9112 }
9113
9114 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9115 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9116 NewVD->setInvalidDecl();
9117 return;
9118 }
9119
9120 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9121 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9122 NewVD->setInvalidDecl();
9123 return;
9124 }
9125
9126 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9127 !T->isDependentType() &&
9129 diag::err_constexpr_var_non_literal)) {
9130 NewVD->setInvalidDecl();
9131 return;
9132 }
9133
9134 // PPC MMA non-pointer types are not allowed as non-local variable types.
9135 if (Context.getTargetInfo().getTriple().isPPC64() &&
9136 !NewVD->isLocalVarDecl() &&
9137 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9138 NewVD->setInvalidDecl();
9139 return;
9140 }
9141
9142 // Check that SVE types are only used in functions with SVE available.
9143 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9145 llvm::StringMap<bool> CallerFeatureMap;
9146 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9147 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9148 CallerFeatureMap)) {
9149 NewVD->setInvalidDecl();
9150 return;
9151 }
9152 }
9153
9154 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9156 llvm::StringMap<bool> CallerFeatureMap;
9157 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9159 CallerFeatureMap);
9160 }
9161}
9162
9165
9166 // If the decl is already known invalid, don't check it.
9167 if (NewVD->isInvalidDecl())
9168 return false;
9169
9170 // If we did not find anything by this name, look for a non-visible
9171 // extern "C" declaration with the same name.
9172 if (Previous.empty() &&
9174 Previous.setShadowed();
9175
9176 if (!Previous.empty()) {
9177 MergeVarDecl(NewVD, Previous);
9178 return true;
9179 }
9180 return false;
9181}
9182
9185
9186 // Look for methods in base classes that this method might override.
9187 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9188 /*DetectVirtual=*/false);
9189 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9190 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9191 DeclarationName Name = MD->getDeclName();
9192
9194 // We really want to find the base class destructor here.
9195 Name = Context.DeclarationNames.getCXXDestructorName(
9196 Context.getCanonicalTagType(BaseRecord));
9197 }
9198
9199 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9200 CXXMethodDecl *BaseMD =
9201 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9202 if (!BaseMD || !BaseMD->isVirtual() ||
9203 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9204 /*ConsiderCudaAttrs=*/true))
9205 continue;
9206 if (!CheckExplicitObjectOverride(MD, BaseMD))
9207 continue;
9208 if (Overridden.insert(BaseMD).second) {
9209 MD->addOverriddenMethod(BaseMD);
9214 }
9215
9216 // A method can only override one function from each base class. We
9217 // don't track indirectly overridden methods from bases of bases.
9218 return true;
9219 }
9220
9221 return false;
9222 };
9223
9224 DC->lookupInBases(VisitBase, Paths);
9225 return !Overridden.empty();
9226}
9227
9228namespace {
9229 // Struct for holding all of the extra arguments needed by
9230 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9231 struct ActOnFDArgs {
9232 Scope *S;
9233 Declarator &D;
9234 MultiTemplateParamsArg TemplateParamLists;
9235 bool AddToScope;
9236 };
9237} // end anonymous namespace
9238
9239namespace {
9240
9241// Callback to only accept typo corrections that have a non-zero edit distance.
9242// Also only accept corrections that have the same parent decl.
9243class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9244 public:
9245 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9246 CXXRecordDecl *Parent)
9247 : Context(Context), OriginalFD(TypoFD),
9248 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9249
9250 bool ValidateCandidate(const TypoCorrection &candidate) override {
9251 if (candidate.getEditDistance() == 0)
9252 return false;
9253
9254 SmallVector<unsigned, 1> MismatchedParams;
9255 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9256 CDeclEnd = candidate.end();
9257 CDecl != CDeclEnd; ++CDecl) {
9258 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9259
9260 if (FD && !FD->hasBody() &&
9261 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9262 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9263 CXXRecordDecl *Parent = MD->getParent();
9264 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9265 return true;
9266 } else if (!ExpectedParent) {
9267 return true;
9268 }
9269 }
9270 }
9271
9272 return false;
9273 }
9274
9275 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9276 return std::make_unique<DifferentNameValidatorCCC>(*this);
9277 }
9278
9279 private:
9280 ASTContext &Context;
9281 FunctionDecl *OriginalFD;
9282 CXXRecordDecl *ExpectedParent;
9283};
9284
9285} // end anonymous namespace
9286
9290
9291/// Generate diagnostics for an invalid function redeclaration.
9292///
9293/// This routine handles generating the diagnostic messages for an invalid
9294/// function redeclaration, including finding possible similar declarations
9295/// or performing typo correction if there are no previous declarations with
9296/// the same name.
9297///
9298/// Returns a NamedDecl iff typo correction was performed and substituting in
9299/// the new declaration name does not cause new errors.
9301 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9302 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9303 DeclarationName Name = NewFD->getDeclName();
9304 DeclContext *NewDC = NewFD->getDeclContext();
9305 SmallVector<unsigned, 1> MismatchedParams;
9307 TypoCorrection Correction;
9308 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9309 unsigned DiagMsg =
9310 IsLocalFriend ? diag::err_no_matching_local_friend :
9311 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9312 diag::err_member_decl_does_not_match;
9313 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9314 IsLocalFriend ? Sema::LookupLocalFriendName
9317
9318 NewFD->setInvalidDecl();
9319 if (IsLocalFriend)
9320 SemaRef.LookupName(Prev, S);
9321 else
9322 SemaRef.LookupQualifiedName(Prev, NewDC);
9323 assert(!Prev.isAmbiguous() &&
9324 "Cannot have an ambiguity in previous-declaration lookup");
9325 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9326 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9327 MD ? MD->getParent() : nullptr);
9328 if (!Prev.empty()) {
9329 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9330 Func != FuncEnd; ++Func) {
9331 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9332 if (FD &&
9333 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9334 // Add 1 to the index so that 0 can mean the mismatch didn't
9335 // involve a parameter
9336 unsigned ParamNum =
9337 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9338 NearMatches.push_back(std::make_pair(FD, ParamNum));
9339 }
9340 }
9341 // If the qualified name lookup yielded nothing, try typo correction
9342 } else if ((Correction = SemaRef.CorrectTypo(
9343 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9344 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9346 IsLocalFriend ? nullptr : NewDC))) {
9347 // Set up everything for the call to ActOnFunctionDeclarator
9348 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9349 ExtraArgs.D.getIdentifierLoc());
9350 Previous.clear();
9351 Previous.setLookupName(Correction.getCorrection());
9352 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9353 CDeclEnd = Correction.end();
9354 CDecl != CDeclEnd; ++CDecl) {
9355 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9356 if (FD && !FD->hasBody() &&
9357 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9358 Previous.addDecl(FD);
9359 }
9360 }
9361 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9362
9363 NamedDecl *Result;
9364 // Retry building the function declaration with the new previous
9365 // declarations, and with errors suppressed.
9366 {
9367 // Trap errors.
9368 Sema::SFINAETrap Trap(SemaRef);
9369
9370 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9371 // pieces need to verify the typo-corrected C++ declaration and hopefully
9372 // eliminate the need for the parameter pack ExtraArgs.
9373 Result = SemaRef.ActOnFunctionDeclarator(
9374 ExtraArgs.S, ExtraArgs.D,
9375 Correction.getCorrectionDecl()->getDeclContext(),
9376 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9377 ExtraArgs.AddToScope);
9378
9379 if (Trap.hasErrorOccurred())
9380 Result = nullptr;
9381 }
9382
9383 if (Result) {
9384 // Determine which correction we picked.
9385 Decl *Canonical = Result->getCanonicalDecl();
9386 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9387 I != E; ++I)
9388 if ((*I)->getCanonicalDecl() == Canonical)
9389 Correction.setCorrectionDecl(*I);
9390
9391 // Let Sema know about the correction.
9393 SemaRef.diagnoseTypo(
9394 Correction,
9395 SemaRef.PDiag(IsLocalFriend
9396 ? diag::err_no_matching_local_friend_suggest
9397 : diag::err_member_decl_does_not_match_suggest)
9398 << Name << NewDC << IsDefinition);
9399 return Result;
9400 }
9401
9402 // Pretend the typo correction never occurred
9403 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9404 ExtraArgs.D.getIdentifierLoc());
9405 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9406 Previous.clear();
9407 Previous.setLookupName(Name);
9408 }
9409
9410 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9411 << Name << NewDC << IsDefinition << NewFD->getLocation();
9412
9413 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9414 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9415 CXXRecordDecl *RD = NewMD->getParent();
9416 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9417 << RD->getName() << RD->getLocation();
9418 }
9419
9420 bool NewFDisConst = NewMD && NewMD->isConst();
9421
9422 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9423 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9424 NearMatch != NearMatchEnd; ++NearMatch) {
9425 FunctionDecl *FD = NearMatch->first;
9426 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9427 bool FDisConst = MD && MD->isConst();
9428 bool IsMember = MD || !IsLocalFriend;
9429
9430 // FIXME: These notes are poorly worded for the local friend case.
9431 if (unsigned Idx = NearMatch->second) {
9432 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9433 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9434 if (Loc.isInvalid()) Loc = FD->getLocation();
9435 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9436 : diag::note_local_decl_close_param_match)
9437 << Idx << FDParam->getType()
9438 << NewFD->getParamDecl(Idx - 1)->getType();
9439 } else if (FDisConst != NewFDisConst) {
9440 auto DB = SemaRef.Diag(FD->getLocation(),
9441 diag::note_member_def_close_const_match)
9442 << NewFDisConst << FD->getSourceRange().getEnd();
9443 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9444 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9445 " const");
9446 else if (FTI.hasMethodTypeQualifiers() &&
9447 FTI.getConstQualifierLoc().isValid())
9448 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9449 } else {
9450 SemaRef.Diag(FD->getLocation(),
9451 IsMember ? diag::note_member_def_close_match
9452 : diag::note_local_decl_close_match);
9453 }
9454 }
9455 return nullptr;
9456}
9457
9459 switch (D.getDeclSpec().getStorageClassSpec()) {
9460 default: llvm_unreachable("Unknown storage class!");
9461 case DeclSpec::SCS_auto:
9465 diag::err_typecheck_sclass_func);
9467 D.setInvalidType();
9468 break;
9469 case DeclSpec::SCS_unspecified: break;
9472 return SC_None;
9473 return SC_Extern;
9474 case DeclSpec::SCS_static: {
9476 // C99 6.7.1p5:
9477 // The declaration of an identifier for a function that has
9478 // block scope shall have no explicit storage-class specifier
9479 // other than extern
9480 // See also (C++ [dcl.stc]p4).
9482 diag::err_static_block_func);
9483 break;
9484 } else
9485 return SC_Static;
9486 }
9488 }
9489
9490 // No explicit storage class has already been returned
9491 return SC_None;
9492}
9493
9495 DeclContext *DC, QualType &R,
9496 TypeSourceInfo *TInfo,
9497 StorageClass SC,
9498 bool &IsVirtualOkay) {
9499 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9500 DeclarationName Name = NameInfo.getName();
9501
9502 FunctionDecl *NewFD = nullptr;
9503 bool isInline = D.getDeclSpec().isInlineSpecified();
9504
9506 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9507 (SemaRef.getLangOpts().C23 &&
9508 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9509
9510 if (SemaRef.getLangOpts().C23)
9511 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9512 diag::err_c23_constexpr_not_variable);
9513 else
9514 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9515 diag::err_constexpr_wrong_decl_kind)
9516 << static_cast<int>(ConstexprKind);
9517 ConstexprKind = ConstexprSpecKind::Unspecified;
9519 }
9520
9521 if (!SemaRef.getLangOpts().CPlusPlus) {
9522 // Determine whether the function was written with a prototype. This is
9523 // true when:
9524 // - there is a prototype in the declarator, or
9525 // - the type R of the function is some kind of typedef or other non-
9526 // attributed reference to a type name (which eventually refers to a
9527 // function type). Note, we can't always look at the adjusted type to
9528 // check this case because attributes may cause a non-function
9529 // declarator to still have a function type. e.g.,
9530 // typedef void func(int a);
9531 // __attribute__((noreturn)) func other_func; // This has a prototype
9532 bool HasPrototype =
9534 (D.getDeclSpec().isTypeRep() &&
9535 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9536 ->isFunctionProtoType()) ||
9538 assert(
9539 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9540 "Strict prototypes are required");
9541
9542 NewFD = FunctionDecl::Create(
9543 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9544 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9546 /*TrailingRequiresClause=*/{});
9547 if (D.isInvalidType())
9548 NewFD->setInvalidDecl();
9549
9550 return NewFD;
9551 }
9552
9554 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9555
9556 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9557
9559 // This is a C++ constructor declaration.
9560 assert(DC->isRecord() &&
9561 "Constructors can only be declared in a member context");
9562
9563 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9565 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9567 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9568 InheritedConstructor(), TrailingRequiresClause);
9569
9570 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9571 // This is a C++ destructor declaration.
9572 if (DC->isRecord()) {
9573 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9576 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9577 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9578 /*isImplicitlyDeclared=*/false, ConstexprKind,
9579 TrailingRequiresClause);
9580 // User defined destructors start as not selected if the class definition is still
9581 // not done.
9582 if (Record->isBeingDefined())
9583 NewDD->setIneligibleOrNotSelected(true);
9584
9585 // If the destructor needs an implicit exception specification, set it
9586 // now. FIXME: It'd be nice to be able to create the right type to start
9587 // with, but the type needs to reference the destructor declaration.
9588 if (SemaRef.getLangOpts().CPlusPlus11)
9589 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9590
9591 IsVirtualOkay = true;
9592 return NewDD;
9593
9594 } else {
9595 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9596 D.setInvalidType();
9597
9598 // Create a FunctionDecl to satisfy the function definition parsing
9599 // code path.
9600 return FunctionDecl::Create(
9601 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9602 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9603 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9604 }
9605
9607 if (!DC->isRecord()) {
9608 SemaRef.Diag(D.getIdentifierLoc(),
9609 diag::err_conv_function_not_member);
9610 return nullptr;
9611 }
9612
9613 SemaRef.CheckConversionDeclarator(D, R, SC);
9614 if (D.isInvalidType())
9615 return nullptr;
9616
9617 IsVirtualOkay = true;
9619 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9620 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9621 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9622 TrailingRequiresClause);
9623
9625 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9626 return nullptr;
9628 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9629 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9630 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9631 } else if (DC->isRecord()) {
9632 // If the name of the function is the same as the name of the record,
9633 // then this must be an invalid constructor that has a return type.
9634 // (The parser checks for a return type and makes the declarator a
9635 // constructor if it has no return type).
9636 if (Name.getAsIdentifierInfo() &&
9637 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9638 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9641 return nullptr;
9642 }
9643
9644 // This is a C++ method declaration.
9646 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9647 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9648 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9649 IsVirtualOkay = !Ret->isStatic();
9650 return Ret;
9651 } else {
9652 bool isFriend =
9653 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9654 if (!isFriend && SemaRef.CurContext->isRecord())
9655 return nullptr;
9656
9657 // Determine whether the function was written with a
9658 // prototype. This true when:
9659 // - we're in C++ (where every function has a prototype),
9660 return FunctionDecl::Create(
9661 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9662 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9663 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9664 }
9665}
9666
9675
9677 // Size dependent types are just typedefs to normal integer types
9678 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9679 // integers other than by their names.
9680 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9681
9682 // Remove typedefs one by one until we reach a typedef
9683 // for a size dependent type.
9684 QualType DesugaredTy = Ty;
9685 do {
9686 ArrayRef<StringRef> Names(SizeTypeNames);
9687 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9688 if (Names.end() != Match)
9689 return true;
9690
9691 Ty = DesugaredTy;
9692 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9693 } while (DesugaredTy != Ty);
9694
9695 return false;
9696}
9697
9699 if (PT->isDependentType())
9700 return InvalidKernelParam;
9701
9702 if (PT->isPointerOrReferenceType()) {
9703 QualType PointeeType = PT->getPointeeType();
9704 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9705 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9706 PointeeType.getAddressSpace() == LangAS::Default)
9708
9709 if (PointeeType->isPointerType()) {
9710 // This is a pointer to pointer parameter.
9711 // Recursively check inner type.
9712 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9713 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9714 ParamKind == InvalidKernelParam)
9715 return ParamKind;
9716
9717 // OpenCL v3.0 s6.11.a:
9718 // A restriction to pass pointers to pointers only applies to OpenCL C
9719 // v1.2 or below.
9721 return ValidKernelParam;
9722
9723 return PtrPtrKernelParam;
9724 }
9725
9726 // C++ for OpenCL v1.0 s2.4:
9727 // Moreover the types used in parameters of the kernel functions must be:
9728 // Standard layout types for pointer parameters. The same applies to
9729 // reference if an implementation supports them in kernel parameters.
9730 if (S.getLangOpts().OpenCLCPlusPlus &&
9732 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9733 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9734 bool IsStandardLayoutType = true;
9735 if (CXXRec) {
9736 // If template type is not ODR-used its definition is only available
9737 // in the template definition not its instantiation.
9738 // FIXME: This logic doesn't work for types that depend on template
9739 // parameter (PR58590).
9740 if (!CXXRec->hasDefinition())
9741 CXXRec = CXXRec->getTemplateInstantiationPattern();
9742 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9743 IsStandardLayoutType = false;
9744 }
9745 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9746 !IsStandardLayoutType)
9747 return InvalidKernelParam;
9748 }
9749
9750 // OpenCL v1.2 s6.9.p:
9751 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9753 return ValidKernelParam;
9754
9755 return PtrKernelParam;
9756 }
9757
9758 // OpenCL v1.2 s6.9.k:
9759 // Arguments to kernel functions in a program cannot be declared with the
9760 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9761 // uintptr_t or a struct and/or union that contain fields declared to be one
9762 // of these built-in scalar types.
9764 return InvalidKernelParam;
9765
9766 if (PT->isImageType())
9767 return PtrKernelParam;
9768
9769 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9770 return InvalidKernelParam;
9771
9772 // OpenCL extension spec v1.2 s9.5:
9773 // This extension adds support for half scalar and vector types as built-in
9774 // types that can be used for arithmetic operations, conversions etc.
9775 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9776 PT->isHalfType())
9777 return InvalidKernelParam;
9778
9779 // Look into an array argument to check if it has a forbidden type.
9780 if (PT->isArrayType()) {
9781 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9782 // Call ourself to check an underlying type of an array. Since the
9783 // getPointeeOrArrayElementType returns an innermost type which is not an
9784 // array, this recursive call only happens once.
9785 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9786 }
9787
9788 // C++ for OpenCL v1.0 s2.4:
9789 // Moreover the types used in parameters of the kernel functions must be:
9790 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9791 // types) for parameters passed by value;
9792 if (S.getLangOpts().OpenCLCPlusPlus &&
9794 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9795 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9796 return InvalidKernelParam;
9797
9798 if (PT->isRecordType())
9799 return RecordKernelParam;
9800
9801 return ValidKernelParam;
9802}
9803
9805 Sema &S,
9806 Declarator &D,
9807 ParmVarDecl *Param,
9808 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9809 QualType PT = Param->getType();
9810
9811 // Cache the valid types we encounter to avoid rechecking structs that are
9812 // used again
9813 if (ValidTypes.count(PT.getTypePtr()))
9814 return;
9815
9816 switch (getOpenCLKernelParameterType(S, PT)) {
9817 case PtrPtrKernelParam:
9818 // OpenCL v3.0 s6.11.a:
9819 // A kernel function argument cannot be declared as a pointer to a pointer
9820 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9821 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9822 D.setInvalidType();
9823 return;
9824
9826 // OpenCL v1.0 s6.5:
9827 // __kernel function arguments declared to be a pointer of a type can point
9828 // to one of the following address spaces only : __global, __local or
9829 // __constant.
9830 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9831 D.setInvalidType();
9832 return;
9833
9834 // OpenCL v1.2 s6.9.k:
9835 // Arguments to kernel functions in a program cannot be declared with the
9836 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9837 // uintptr_t or a struct and/or union that contain fields declared to be
9838 // one of these built-in scalar types.
9839
9840 case InvalidKernelParam:
9841 // OpenCL v1.2 s6.8 n:
9842 // A kernel function argument cannot be declared
9843 // of event_t type.
9844 // Do not diagnose half type since it is diagnosed as invalid argument
9845 // type for any function elsewhere.
9846 if (!PT->isHalfType()) {
9847 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9848
9849 // Explain what typedefs are involved.
9850 const TypedefType *Typedef = nullptr;
9851 while ((Typedef = PT->getAs<TypedefType>())) {
9852 SourceLocation Loc = Typedef->getDecl()->getLocation();
9853 // SourceLocation may be invalid for a built-in type.
9854 if (Loc.isValid())
9855 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9856 PT = Typedef->desugar();
9857 }
9858 }
9859
9860 D.setInvalidType();
9861 return;
9862
9863 case PtrKernelParam:
9864 case ValidKernelParam:
9865 ValidTypes.insert(PT.getTypePtr());
9866 return;
9867
9868 case RecordKernelParam:
9869 break;
9870 }
9871
9872 // Track nested structs we will inspect
9874
9875 // Track where we are in the nested structs. Items will migrate from
9876 // VisitStack to HistoryStack as we do the DFS for bad field.
9878 HistoryStack.push_back(nullptr);
9879
9880 // At this point we already handled everything except of a RecordType.
9881 assert(PT->isRecordType() && "Unexpected type.");
9882 const auto *PD = PT->castAsRecordDecl();
9883 VisitStack.push_back(PD);
9884 assert(VisitStack.back() && "First decl null?");
9885
9886 do {
9887 const Decl *Next = VisitStack.pop_back_val();
9888 if (!Next) {
9889 assert(!HistoryStack.empty());
9890 // Found a marker, we have gone up a level
9891 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9892 ValidTypes.insert(Hist->getType().getTypePtr());
9893
9894 continue;
9895 }
9896
9897 // Adds everything except the original parameter declaration (which is not a
9898 // field itself) to the history stack.
9899 const RecordDecl *RD;
9900 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9901 HistoryStack.push_back(Field);
9902
9903 QualType FieldTy = Field->getType();
9904 // Other field types (known to be valid or invalid) are handled while we
9905 // walk around RecordDecl::fields().
9906 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9907 "Unexpected type.");
9908 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9909
9910 RD = FieldRecTy->castAsRecordDecl();
9911 } else {
9912 RD = cast<RecordDecl>(Next);
9913 }
9914
9915 // Add a null marker so we know when we've gone back up a level
9916 VisitStack.push_back(nullptr);
9917
9918 for (const auto *FD : RD->fields()) {
9919 QualType QT = FD->getType();
9920
9921 if (ValidTypes.count(QT.getTypePtr()))
9922 continue;
9923
9925 if (ParamType == ValidKernelParam)
9926 continue;
9927
9928 if (ParamType == RecordKernelParam) {
9929 VisitStack.push_back(FD);
9930 continue;
9931 }
9932
9933 // OpenCL v1.2 s6.9.p:
9934 // Arguments to kernel functions that are declared to be a struct or union
9935 // do not allow OpenCL objects to be passed as elements of the struct or
9936 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9937 // of SVM.
9938 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9939 ParamType == InvalidAddrSpacePtrKernelParam) {
9940 S.Diag(Param->getLocation(),
9941 diag::err_record_with_pointers_kernel_param)
9942 << PT->isUnionType()
9943 << PT;
9944 } else {
9945 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9946 }
9947
9948 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9949 << PD->getDeclName();
9950
9951 // We have an error, now let's go back up through history and show where
9952 // the offending field came from
9954 I = HistoryStack.begin() + 1,
9955 E = HistoryStack.end();
9956 I != E; ++I) {
9957 const FieldDecl *OuterField = *I;
9958 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9959 << OuterField->getType();
9960 }
9961
9962 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9963 << QT->isPointerType()
9964 << QT;
9965 D.setInvalidType();
9966 return;
9967 }
9968 } while (!VisitStack.empty());
9969}
9970
9971/// Find the DeclContext in which a tag is implicitly declared if we see an
9972/// elaborated type specifier in the specified context, and lookup finds
9973/// nothing.
9975 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9976 DC = DC->getParent();
9977 return DC;
9978}
9979
9980/// Find the Scope in which a tag is implicitly declared if we see an
9981/// elaborated type specifier in the specified context, and lookup finds
9982/// nothing.
9983static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9984 while (S->isClassScope() ||
9985 (LangOpts.CPlusPlus &&
9987 ((S->getFlags() & Scope::DeclScope) == 0) ||
9988 (S->getEntity() && S->getEntity()->isTransparentContext()))
9989 S = S->getParent();
9990 return S;
9991}
9992
9993/// Determine whether a declaration matches a known function in namespace std.
9995 unsigned BuiltinID) {
9996 switch (BuiltinID) {
9997 case Builtin::BI__GetExceptionInfo:
9998 // No type checking whatsoever.
9999 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10000
10001 case Builtin::BIaddressof:
10002 case Builtin::BI__addressof:
10003 case Builtin::BIforward:
10004 case Builtin::BIforward_like:
10005 case Builtin::BImove:
10006 case Builtin::BImove_if_noexcept:
10007 case Builtin::BIas_const: {
10008 // Ensure that we don't treat the algorithm
10009 // OutputIt std::move(InputIt, InputIt, OutputIt)
10010 // as the builtin std::move.
10011 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10012 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10013 }
10014
10015 default:
10016 return false;
10017 }
10018}
10019
10020NamedDecl*
10023 MultiTemplateParamsArg TemplateParamListsRef,
10024 bool &AddToScope) {
10025 QualType R = TInfo->getType();
10026
10027 assert(R->isFunctionType());
10029 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10030
10031 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10032 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10034 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10035 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10036 TemplateParamLists.back() = Invented;
10037 else
10038 TemplateParamLists.push_back(Invented);
10039 }
10040
10041 // TODO: consider using NameInfo for diagnostic.
10043 DeclarationName Name = NameInfo.getName();
10045
10048 diag::err_invalid_thread)
10050
10055
10056 bool isFriend = false;
10058 bool isMemberSpecialization = false;
10059 bool isFunctionTemplateSpecialization = false;
10060
10061 bool HasExplicitTemplateArgs = false;
10062 TemplateArgumentListInfo TemplateArgs;
10063
10064 bool isVirtualOkay = false;
10065
10066 DeclContext *OriginalDC = DC;
10067 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10068
10069 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10070 isVirtualOkay);
10071 if (!NewFD) return nullptr;
10072
10073 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10075
10076 // Set the lexical context. If this is a function-scope declaration, or has a
10077 // C++ scope specifier, or is the object of a friend declaration, the lexical
10078 // context will be different from the semantic context.
10080
10081 if (IsLocalExternDecl)
10082 NewFD->setLocalExternDecl();
10083
10084 if (getLangOpts().CPlusPlus) {
10085 // The rules for implicit inlines changed in C++20 for methods and friends
10086 // with an in-class definition (when such a definition is not attached to
10087 // the global module). This does not affect declarations that are already
10088 // inline (whether explicitly or implicitly by being declared constexpr,
10089 // consteval, etc).
10090 // FIXME: We need a better way to separate C++ standard and clang modules.
10091 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10092 !NewFD->getOwningModule() ||
10093 NewFD->isFromGlobalModule() ||
10095 bool isInline = D.getDeclSpec().isInlineSpecified();
10096 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10097 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10098 isFriend = D.getDeclSpec().isFriendSpecified();
10099 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10100 // Pre-C++20 [class.friend]p5
10101 // A function can be defined in a friend declaration of a
10102 // class . . . . Such a function is implicitly inline.
10103 // Post C++20 [class.friend]p7
10104 // Such a function is implicitly an inline function if it is attached
10105 // to the global module.
10106 NewFD->setImplicitlyInline();
10107 }
10108
10109 // If this is a method defined in an __interface, and is not a constructor
10110 // or an overloaded operator, then set the pure flag (isVirtual will already
10111 // return true).
10112 if (const CXXRecordDecl *Parent =
10113 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10114 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10115 NewFD->setIsPureVirtual(true);
10116
10117 // C++ [class.union]p2
10118 // A union can have member functions, but not virtual functions.
10119 if (isVirtual && Parent->isUnion()) {
10120 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10121 NewFD->setInvalidDecl();
10122 }
10123 if ((Parent->isClass() || Parent->isStruct()) &&
10124 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10125 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10126 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10127 if (auto *Def = Parent->getDefinition())
10128 Def->setInitMethod(true);
10129 }
10130 }
10131
10132 SetNestedNameSpecifier(*this, NewFD, D);
10133 isMemberSpecialization = false;
10134 isFunctionTemplateSpecialization = false;
10135 if (D.isInvalidType())
10136 NewFD->setInvalidDecl();
10137
10138 // Match up the template parameter lists with the scope specifier, then
10139 // determine whether we have a template or a template specialization.
10140 bool Invalid = false;
10141 TemplateIdAnnotation *TemplateId =
10143 ? D.getName().TemplateId
10144 : nullptr;
10145 TemplateParameterList *TemplateParams =
10148 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10149 isMemberSpecialization, Invalid);
10150 if (TemplateParams) {
10151 // Check that we can declare a template here.
10152 if (CheckTemplateDeclScope(S, TemplateParams))
10153 NewFD->setInvalidDecl();
10154
10155 if (TemplateParams->size() > 0) {
10156 // This is a function template
10157
10158 // A destructor cannot be a template.
10160 Diag(NewFD->getLocation(), diag::err_destructor_template);
10161 NewFD->setInvalidDecl();
10162 // Function template with explicit template arguments.
10163 } else if (TemplateId) {
10164 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10165 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10166 NewFD->setInvalidDecl();
10167 }
10168
10169 // If we're adding a template to a dependent context, we may need to
10170 // rebuilding some of the types used within the template parameter list,
10171 // now that we know what the current instantiation is.
10172 if (DC->isDependentContext()) {
10173 ContextRAII SavedContext(*this, DC);
10175 Invalid = true;
10176 }
10177
10179 NewFD->getLocation(),
10180 Name, TemplateParams,
10181 NewFD);
10182 FunctionTemplate->setLexicalDeclContext(CurContext);
10184
10185 // For source fidelity, store the other template param lists.
10186 if (TemplateParamLists.size() > 1) {
10188 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10189 .drop_back(1));
10190 }
10191 } else {
10192 // This is a function template specialization.
10193 isFunctionTemplateSpecialization = true;
10194 // For source fidelity, store all the template param lists.
10195 if (TemplateParamLists.size() > 0)
10196 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10197
10198 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10199 if (isFriend) {
10200 // We want to remove the "template<>", found here.
10201 SourceRange RemoveRange = TemplateParams->getSourceRange();
10202
10203 // If we remove the template<> and the name is not a
10204 // template-id, we're actually silently creating a problem:
10205 // the friend declaration will refer to an untemplated decl,
10206 // and clearly the user wants a template specialization. So
10207 // we need to insert '<>' after the name.
10208 SourceLocation InsertLoc;
10210 InsertLoc = D.getName().getSourceRange().getEnd();
10211 InsertLoc = getLocForEndOfToken(InsertLoc);
10212 }
10213
10214 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10215 << Name << RemoveRange
10216 << FixItHint::CreateRemoval(RemoveRange)
10217 << FixItHint::CreateInsertion(InsertLoc, "<>");
10218 Invalid = true;
10219
10220 // Recover by faking up an empty template argument list.
10221 HasExplicitTemplateArgs = true;
10222 TemplateArgs.setLAngleLoc(InsertLoc);
10223 TemplateArgs.setRAngleLoc(InsertLoc);
10224 }
10225 }
10226 } else {
10227 // Check that we can declare a template here.
10228 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10229 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10230 NewFD->setInvalidDecl();
10231
10232 // All template param lists were matched against the scope specifier:
10233 // this is NOT (an explicit specialization of) a template.
10234 if (TemplateParamLists.size() > 0)
10235 // For source fidelity, store all the template param lists.
10236 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10237
10238 // "friend void foo<>(int);" is an implicit specialization decl.
10239 if (isFriend && TemplateId)
10240 isFunctionTemplateSpecialization = true;
10241 }
10242
10243 // If this is a function template specialization and the unqualified-id of
10244 // the declarator-id is a template-id, convert the template argument list
10245 // into our AST format and check for unexpanded packs.
10246 if (isFunctionTemplateSpecialization && TemplateId) {
10247 HasExplicitTemplateArgs = true;
10248
10249 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10250 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10251 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10252 TemplateId->NumArgs);
10253 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10254
10255 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10256 // declaration of a function template partial specialization? Should we
10257 // consider the unexpanded pack context to be a partial specialization?
10258 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10260 ArgLoc, isFriend ? UPPC_FriendDeclaration
10262 NewFD->setInvalidDecl();
10263 }
10264 }
10265
10266 if (Invalid) {
10267 NewFD->setInvalidDecl();
10268 if (FunctionTemplate)
10269 FunctionTemplate->setInvalidDecl();
10270 }
10271
10272 // C++ [dcl.fct.spec]p5:
10273 // The virtual specifier shall only be used in declarations of
10274 // nonstatic class member functions that appear within a
10275 // member-specification of a class declaration; see 10.3.
10276 //
10277 if (isVirtual && !NewFD->isInvalidDecl()) {
10278 if (!isVirtualOkay) {
10280 diag::err_virtual_non_function);
10281 } else if (!CurContext->isRecord()) {
10282 // 'virtual' was specified outside of the class.
10284 diag::err_virtual_out_of_class)
10286 } else if (NewFD->getDescribedFunctionTemplate()) {
10287 // C++ [temp.mem]p3:
10288 // A member function template shall not be virtual.
10290 diag::err_virtual_member_function_template)
10292 } else {
10293 // Okay: Add virtual to the method.
10294 NewFD->setVirtualAsWritten(true);
10295 }
10296
10297 if (getLangOpts().CPlusPlus14 &&
10298 NewFD->getReturnType()->isUndeducedType())
10299 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10300 }
10301
10302 // C++ [dcl.fct.spec]p3:
10303 // The inline specifier shall not appear on a block scope function
10304 // declaration.
10305 if (isInline && !NewFD->isInvalidDecl()) {
10306 if (CurContext->isFunctionOrMethod()) {
10307 // 'inline' is not allowed on block scope function declaration.
10309 diag::err_inline_declaration_block_scope) << Name
10311 }
10312 }
10313
10314 // C++ [dcl.fct.spec]p6:
10315 // The explicit specifier shall be used only in the declaration of a
10316 // constructor or conversion function within its class definition;
10317 // see 12.3.1 and 12.3.2.
10318 if (hasExplicit && !NewFD->isInvalidDecl() &&
10320 if (!CurContext->isRecord()) {
10321 // 'explicit' was specified outside of the class.
10323 diag::err_explicit_out_of_class)
10325 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10326 !isa<CXXConversionDecl>(NewFD)) {
10327 // 'explicit' was specified on a function that wasn't a constructor
10328 // or conversion function.
10330 diag::err_explicit_non_ctor_or_conv_function)
10332 }
10333 }
10334
10336 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10337 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10338 // are implicitly inline.
10339 NewFD->setImplicitlyInline();
10340
10341 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10342 // be either constructors or to return a literal type. Therefore,
10343 // destructors cannot be declared constexpr.
10344 if (isa<CXXDestructorDecl>(NewFD) &&
10346 ConstexprKind == ConstexprSpecKind::Consteval)) {
10347 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10348 << static_cast<int>(ConstexprKind);
10352 }
10353 // C++20 [dcl.constexpr]p2: An allocation function, or a
10354 // deallocation function shall not be declared with the consteval
10355 // specifier.
10356 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10359 diag::err_invalid_consteval_decl_kind)
10360 << NewFD;
10362 }
10363 }
10364
10365 // If __module_private__ was specified, mark the function accordingly.
10367 if (isFunctionTemplateSpecialization) {
10368 SourceLocation ModulePrivateLoc
10370 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10371 << 0
10372 << FixItHint::CreateRemoval(ModulePrivateLoc);
10373 } else {
10374 NewFD->setModulePrivate();
10375 if (FunctionTemplate)
10376 FunctionTemplate->setModulePrivate();
10377 }
10378 }
10379
10380 if (isFriend) {
10381 if (FunctionTemplate) {
10382 FunctionTemplate->setObjectOfFriendDecl();
10383 FunctionTemplate->setAccess(AS_public);
10384 }
10385 NewFD->setObjectOfFriendDecl();
10386 NewFD->setAccess(AS_public);
10387 }
10388
10389 // If a function is defined as defaulted or deleted, mark it as such now.
10390 // We'll do the relevant checks on defaulted / deleted functions later.
10391 switch (D.getFunctionDefinitionKind()) {
10394 break;
10395
10397 NewFD->setDefaulted();
10398 break;
10399
10401 NewFD->setDeletedAsWritten();
10402 break;
10403 }
10404
10405 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10407 // Pre C++20 [class.mfct]p2:
10408 // A member function may be defined (8.4) in its class definition, in
10409 // which case it is an inline member function (7.1.2)
10410 // Post C++20 [class.mfct]p1:
10411 // If a member function is attached to the global module and is defined
10412 // in its class definition, it is inline.
10413 NewFD->setImplicitlyInline();
10414 }
10415
10416 if (!isFriend && SC != SC_None) {
10417 // C++ [temp.expl.spec]p2:
10418 // The declaration in an explicit-specialization shall not be an
10419 // export-declaration. An explicit specialization shall not use a
10420 // storage-class-specifier other than thread_local.
10421 //
10422 // We diagnose friend declarations with storage-class-specifiers
10423 // elsewhere.
10424 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10426 diag::ext_explicit_specialization_storage_class)
10429 }
10430
10431 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10432 assert(isa<CXXMethodDecl>(NewFD) &&
10433 "Out-of-line member function should be a CXXMethodDecl");
10434 // C++ [class.static]p1:
10435 // A data or function member of a class may be declared static
10436 // in a class definition, in which case it is a static member of
10437 // the class.
10438
10439 // Complain about the 'static' specifier if it's on an out-of-line
10440 // member function definition.
10441
10442 // MSVC permits the use of a 'static' storage specifier on an
10443 // out-of-line member function template declaration and class member
10444 // template declaration (MSVC versions before 2015), warn about this.
10446 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10447 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10448 (getLangOpts().MSVCCompat &&
10450 ? diag::ext_static_out_of_line
10451 : diag::err_static_out_of_line)
10454 }
10455 }
10456
10457 // C++11 [except.spec]p15:
10458 // A deallocation function with no exception-specification is treated
10459 // as if it were specified with noexcept(true).
10460 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10461 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10462 !FPT->hasExceptionSpec())
10463 NewFD->setType(Context.getFunctionType(
10464 FPT->getReturnType(), FPT->getParamTypes(),
10466
10467 // C++20 [dcl.inline]/7
10468 // If an inline function or variable that is attached to a named module
10469 // is declared in a definition domain, it shall be defined in that
10470 // domain.
10471 // So, if the current declaration does not have a definition, we must
10472 // check at the end of the TU (or when the PMF starts) to see that we
10473 // have a definition at that point.
10474 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10475 NewFD->isInNamedModule()) {
10476 PendingInlineFuncDecls.insert(NewFD);
10477 }
10478 }
10479
10480 // Filter out previous declarations that don't match the scope.
10483 isMemberSpecialization ||
10484 isFunctionTemplateSpecialization);
10485
10486 // Handle GNU asm-label extension (encoded as an attribute).
10487 if (Expr *E = D.getAsmLabel()) {
10488 // The parser guarantees this is a string.
10490 NewFD->addAttr(
10491 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10492 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10493 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10495 if (I != ExtnameUndeclaredIdentifiers.end()) {
10496 if (isDeclExternC(NewFD)) {
10497 NewFD->addAttr(I->second);
10499 } else
10500 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10501 << /*Variable*/0 << NewFD;
10502 }
10503 }
10504
10505 // Copy the parameter declarations from the declarator D to the function
10506 // declaration NewFD, if they are available. First scavenge them into Params.
10508 unsigned FTIIdx;
10509 if (D.isFunctionDeclarator(FTIIdx)) {
10511
10512 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10513 // function that takes no arguments, not a function that takes a
10514 // single void argument.
10515 // We let through "const void" here because Sema::GetTypeForDeclarator
10516 // already checks for that case.
10517 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10518 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10519 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10520 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10521 Param->setDeclContext(NewFD);
10522 Params.push_back(Param);
10523
10524 if (Param->isInvalidDecl())
10525 NewFD->setInvalidDecl();
10526 }
10527 }
10528
10529 if (!getLangOpts().CPlusPlus) {
10530 // In C, find all the tag declarations from the prototype and move them
10531 // into the function DeclContext. Remove them from the surrounding tag
10532 // injection context of the function, which is typically but not always
10533 // the TU.
10534 DeclContext *PrototypeTagContext =
10536 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10537 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10538
10539 // We don't want to reparent enumerators. Look at their parent enum
10540 // instead.
10541 if (!TD) {
10542 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10543 TD = cast<EnumDecl>(ECD->getDeclContext());
10544 }
10545 if (!TD)
10546 continue;
10547 DeclContext *TagDC = TD->getLexicalDeclContext();
10548 if (!TagDC->containsDecl(TD))
10549 continue;
10550 TagDC->removeDecl(TD);
10551 TD->setDeclContext(NewFD);
10552 NewFD->addDecl(TD);
10553
10554 // Preserve the lexical DeclContext if it is not the surrounding tag
10555 // injection context of the FD. In this example, the semantic context of
10556 // E will be f and the lexical context will be S, while both the
10557 // semantic and lexical contexts of S will be f:
10558 // void f(struct S { enum E { a } f; } s);
10559 if (TagDC != PrototypeTagContext)
10560 TD->setLexicalDeclContext(TagDC);
10561 }
10562 }
10563 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10564 // When we're declaring a function with a typedef, typeof, etc as in the
10565 // following example, we'll need to synthesize (unnamed)
10566 // parameters for use in the declaration.
10567 //
10568 // @code
10569 // typedef void fn(int);
10570 // fn f;
10571 // @endcode
10572
10573 // Synthesize a parameter for each argument type.
10574 for (const auto &AI : FT->param_types()) {
10575 ParmVarDecl *Param =
10577 Param->setScopeInfo(0, Params.size());
10578 Params.push_back(Param);
10579 }
10580 } else {
10581 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10582 "Should not need args for typedef of non-prototype fn");
10583 }
10584
10585 // Finally, we know we have the right number of parameters, install them.
10586 NewFD->setParams(Params);
10587
10588 // If this declarator is a declaration and not a definition, its parameters
10589 // will not be pushed onto a scope chain. That means we will not issue any
10590 // reserved identifier warnings for the declaration, but we will for the
10591 // definition. Handle those here.
10592 if (!D.isFunctionDefinition()) {
10593 for (const ParmVarDecl *PVD : Params)
10595 }
10596
10598 NewFD->addAttr(
10599 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10600
10601 // Functions returning a variably modified type violate C99 6.7.5.2p2
10602 // because all functions have linkage.
10603 if (!NewFD->isInvalidDecl() &&
10605 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10606 NewFD->setInvalidDecl();
10607 }
10608
10609 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10611 !NewFD->hasAttr<SectionAttr>())
10612 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10613 Context, PragmaClangTextSection.SectionName,
10614 PragmaClangTextSection.PragmaLocation));
10615
10616 // Apply an implicit SectionAttr if #pragma code_seg is active.
10617 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10618 !NewFD->hasAttr<SectionAttr>()) {
10619 NewFD->addAttr(SectionAttr::CreateImplicit(
10620 Context, CodeSegStack.CurrentValue->getString(),
10621 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10622 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10625 NewFD))
10626 NewFD->dropAttr<SectionAttr>();
10627 }
10628
10629 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10630 // active.
10631 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10632 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10633 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10634 Context, PragmaClangTextSection.PragmaLocation));
10635
10636 // Apply an implicit CodeSegAttr from class declspec or
10637 // apply an implicit SectionAttr from #pragma code_seg if active.
10638 if (!NewFD->hasAttr<CodeSegAttr>()) {
10640 D.isFunctionDefinition())) {
10641 NewFD->addAttr(SAttr);
10642 }
10643 }
10644
10645 // Handle attributes.
10646 ProcessDeclAttributes(S, NewFD, D);
10647 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10648 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10649 !NewTVA->isDefaultVersion() &&
10650 !Context.getTargetInfo().hasFeature("fmv")) {
10651 // Don't add to scope fmv functions declarations if fmv disabled
10652 AddToScope = false;
10653 return NewFD;
10654 }
10655
10656 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10657 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10658 // type.
10659 //
10660 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10661 // type declaration will generate a compilation error.
10662 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10663 if (AddressSpace != LangAS::Default) {
10664 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10665 NewFD->setInvalidDecl();
10666 }
10667 }
10668
10669 if (!getLangOpts().CPlusPlus) {
10670 // Perform semantic checking on the function declaration.
10671 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10672 CheckMain(NewFD, D.getDeclSpec());
10673
10674 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10675 CheckMSVCRTEntryPoint(NewFD);
10676
10677 if (!NewFD->isInvalidDecl())
10679 isMemberSpecialization,
10681 else if (!Previous.empty())
10682 // Recover gracefully from an invalid redeclaration.
10683 D.setRedeclaration(true);
10684 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10685 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10686 "previous declaration set still overloaded");
10687
10688 // Diagnose no-prototype function declarations with calling conventions that
10689 // don't support variadic calls. Only do this in C and do it after merging
10690 // possibly prototyped redeclarations.
10691 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10693 CallingConv CC = FT->getExtInfo().getCC();
10694 if (!supportsVariadicCall(CC)) {
10695 // Windows system headers sometimes accidentally use stdcall without
10696 // (void) parameters, so we relax this to a warning.
10697 int DiagID =
10698 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10699 Diag(NewFD->getLocation(), DiagID)
10701 }
10702 }
10703
10707 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10709 } else {
10710 // C++11 [replacement.functions]p3:
10711 // The program's definitions shall not be specified as inline.
10712 //
10713 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10714 //
10715 // Suppress the diagnostic if the function is __attribute__((used)), since
10716 // that forces an external definition to be emitted.
10717 if (D.getDeclSpec().isInlineSpecified() &&
10719 !NewFD->hasAttr<UsedAttr>())
10721 diag::ext_operator_new_delete_declared_inline)
10722 << NewFD->getDeclName();
10723
10724 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10725 // C++20 [dcl.decl.general]p4:
10726 // The optional requires-clause in an init-declarator or
10727 // member-declarator shall be present only if the declarator declares a
10728 // templated function.
10729 //
10730 // C++20 [temp.pre]p8:
10731 // An entity is templated if it is
10732 // - a template,
10733 // - an entity defined or created in a templated entity,
10734 // - a member of a templated entity,
10735 // - an enumerator for an enumeration that is a templated entity, or
10736 // - the closure type of a lambda-expression appearing in the
10737 // declaration of a templated entity.
10738 //
10739 // [Note 6: A local class, a local or block variable, or a friend
10740 // function defined in a templated entity is a templated entity.
10741 // — end note]
10742 //
10743 // A templated function is a function template or a function that is
10744 // templated. A templated class is a class template or a class that is
10745 // templated. A templated variable is a variable template or a variable
10746 // that is templated.
10747 if (!FunctionTemplate) {
10748 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10749 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10750 // An explicit specialization shall not have a trailing
10751 // requires-clause unless it declares a function template.
10752 //
10753 // Since a friend function template specialization cannot be
10754 // definition, and since a non-template friend declaration with a
10755 // trailing requires-clause must be a definition, we diagnose
10756 // friend function template specializations with trailing
10757 // requires-clauses on the same path as explicit specializations
10758 // even though they aren't necessarily prohibited by the same
10759 // language rule.
10760 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10761 << isFriend;
10762 } else if (isFriend && NewFD->isTemplated() &&
10763 !D.isFunctionDefinition()) {
10764 // C++ [temp.friend]p9:
10765 // A non-template friend declaration with a requires-clause shall be
10766 // a definition.
10767 Diag(NewFD->getBeginLoc(),
10768 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10769 NewFD->setInvalidDecl();
10770 } else if (!NewFD->isTemplated() ||
10771 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10772 Diag(TRC->getBeginLoc(),
10773 diag::err_constrained_non_templated_function);
10774 }
10775 }
10776 }
10777
10778 // We do not add HD attributes to specializations here because
10779 // they may have different constexpr-ness compared to their
10780 // templates and, after maybeAddHostDeviceAttrs() is applied,
10781 // may end up with different effective targets. Instead, a
10782 // specialization inherits its target attributes from its template
10783 // in the CheckFunctionTemplateSpecialization() call below.
10784 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10786
10787 // Handle explicit specializations of function templates
10788 // and friend function declarations with an explicit
10789 // template argument list.
10790 if (isFunctionTemplateSpecialization) {
10791 bool isDependentSpecialization = false;
10792 if (isFriend) {
10793 // For friend function specializations, this is a dependent
10794 // specialization if its semantic context is dependent, its
10795 // type is dependent, or if its template-id is dependent.
10796 isDependentSpecialization =
10797 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10798 (HasExplicitTemplateArgs &&
10799 TemplateSpecializationType::
10800 anyInstantiationDependentTemplateArguments(
10801 TemplateArgs.arguments()));
10802 assert((!isDependentSpecialization ||
10803 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10804 "dependent friend function specialization without template "
10805 "args");
10806 } else {
10807 // For class-scope explicit specializations of function templates,
10808 // if the lexical context is dependent, then the specialization
10809 // is dependent.
10810 isDependentSpecialization =
10811 CurContext->isRecord() && CurContext->isDependentContext();
10812 }
10813
10814 TemplateArgumentListInfo *ExplicitTemplateArgs =
10815 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10816 if (isDependentSpecialization) {
10817 // If it's a dependent specialization, it may not be possible
10818 // to determine the primary template (for explicit specializations)
10819 // or befriended declaration (for friends) until the enclosing
10820 // template is instantiated. In such cases, we store the declarations
10821 // found by name lookup and defer resolution until instantiation.
10823 NewFD, ExplicitTemplateArgs, Previous))
10824 NewFD->setInvalidDecl();
10825 } else if (!NewFD->isInvalidDecl()) {
10826 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10827 Previous))
10828 NewFD->setInvalidDecl();
10829 }
10830 } else if (isMemberSpecialization && !FunctionTemplate) {
10832 NewFD->setInvalidDecl();
10833 }
10834
10835 // Perform semantic checking on the function declaration.
10836 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10837 CheckMain(NewFD, D.getDeclSpec());
10838
10839 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10840 CheckMSVCRTEntryPoint(NewFD);
10841
10842 if (!NewFD->isInvalidDecl())
10844 isMemberSpecialization,
10846 else if (!Previous.empty())
10847 // Recover gracefully from an invalid redeclaration.
10848 D.setRedeclaration(true);
10849
10850 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10851 !D.isRedeclaration() ||
10852 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10853 "previous declaration set still overloaded");
10854
10855 NamedDecl *PrincipalDecl = (FunctionTemplate
10857 : NewFD);
10858
10859 if (isFriend && NewFD->getPreviousDecl()) {
10860 AccessSpecifier Access = AS_public;
10861 if (!NewFD->isInvalidDecl())
10862 Access = NewFD->getPreviousDecl()->getAccess();
10863
10864 NewFD->setAccess(Access);
10865 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10866 }
10867
10868 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10870 PrincipalDecl->setNonMemberOperator();
10871
10872 // If we have a function template, check the template parameter
10873 // list. This will check and merge default template arguments.
10874 if (FunctionTemplate) {
10875 FunctionTemplateDecl *PrevTemplate =
10876 FunctionTemplate->getPreviousDecl();
10877 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10878 PrevTemplate ? PrevTemplate->getTemplateParameters()
10879 : nullptr,
10884 : (D.getCXXScopeSpec().isSet() &&
10885 DC && DC->isRecord() &&
10886 DC->isDependentContext())
10889 }
10890
10891 if (NewFD->isInvalidDecl()) {
10892 // Ignore all the rest of this.
10893 } else if (!D.isRedeclaration()) {
10894 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10895 AddToScope };
10896 // Fake up an access specifier if it's supposed to be a class member.
10897 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10898 NewFD->setAccess(AS_public);
10899
10900 // Qualified decls generally require a previous declaration.
10901 if (D.getCXXScopeSpec().isSet()) {
10902 // ...with the major exception of templated-scope or
10903 // dependent-scope friend declarations.
10904
10905 // TODO: we currently also suppress this check in dependent
10906 // contexts because (1) the parameter depth will be off when
10907 // matching friend templates and (2) we might actually be
10908 // selecting a friend based on a dependent factor. But there
10909 // are situations where these conditions don't apply and we
10910 // can actually do this check immediately.
10911 //
10912 // Unless the scope is dependent, it's always an error if qualified
10913 // redeclaration lookup found nothing at all. Diagnose that now;
10914 // nothing will diagnose that error later.
10915 if (isFriend &&
10917 (!Previous.empty() && CurContext->isDependentContext()))) {
10918 // ignore these
10919 } else if (NewFD->isCPUDispatchMultiVersion() ||
10920 NewFD->isCPUSpecificMultiVersion()) {
10921 // ignore this, we allow the redeclaration behavior here to create new
10922 // versions of the function.
10923 } else {
10924 // The user tried to provide an out-of-line definition for a
10925 // function that is a member of a class or namespace, but there
10926 // was no such member function declared (C++ [class.mfct]p2,
10927 // C++ [namespace.memdef]p2). For example:
10928 //
10929 // class X {
10930 // void f() const;
10931 // };
10932 //
10933 // void X::f() { } // ill-formed
10934 //
10935 // Complain about this problem, and attempt to suggest close
10936 // matches (e.g., those that differ only in cv-qualifiers and
10937 // whether the parameter types are references).
10938
10940 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10941 AddToScope = ExtraArgs.AddToScope;
10942 return Result;
10943 }
10944 }
10945
10946 // Unqualified local friend declarations are required to resolve
10947 // to something.
10948 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10950 *this, Previous, NewFD, ExtraArgs, true, S)) {
10951 AddToScope = ExtraArgs.AddToScope;
10952 return Result;
10953 }
10954 }
10955 } else if (!D.isFunctionDefinition() &&
10956 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10957 !isFriend && !isFunctionTemplateSpecialization &&
10958 !isMemberSpecialization) {
10959 // An out-of-line member function declaration must also be a
10960 // definition (C++ [class.mfct]p2).
10961 // Note that this is not the case for explicit specializations of
10962 // function templates or member functions of class templates, per
10963 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10964 // extension for compatibility with old SWIG code which likes to
10965 // generate them.
10966 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10967 << D.getCXXScopeSpec().getRange();
10968 }
10969 }
10970
10971 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10972 // Any top level function could potentially be specified as an entry.
10973 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10974 HLSL().ActOnTopLevelFunction(NewFD);
10975
10976 if (NewFD->hasAttr<HLSLShaderAttr>())
10977 HLSL().CheckEntryPoint(NewFD);
10978 }
10979
10980 // If this is the first declaration of a library builtin function, add
10981 // attributes as appropriate.
10982 if (!D.isRedeclaration()) {
10983 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10984 if (unsigned BuiltinID = II->getBuiltinID()) {
10985 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10986 if (!InStdNamespace &&
10988 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10989 // Validate the type matches unless this builtin is specified as
10990 // matching regardless of its declared type.
10991 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10992 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10993 } else {
10995 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10996 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10997
10998 if (!Error && !BuiltinType.isNull() &&
10999 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11000 NewFD->getType(), BuiltinType))
11001 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11002 }
11003 }
11004 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11005 isStdBuiltin(Context, NewFD, BuiltinID)) {
11006 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11007 }
11008 }
11009 }
11010 }
11011
11012 ProcessPragmaWeak(S, NewFD);
11013 checkAttributesAfterMerging(*this, *NewFD);
11014
11016
11017 if (NewFD->hasAttr<OverloadableAttr>() &&
11018 !NewFD->getType()->getAs<FunctionProtoType>()) {
11019 Diag(NewFD->getLocation(),
11020 diag::err_attribute_overloadable_no_prototype)
11021 << NewFD;
11022 NewFD->dropAttr<OverloadableAttr>();
11023 }
11024
11025 // If there's a #pragma GCC visibility in scope, and this isn't a class
11026 // member, set the visibility of this function.
11027 if (!DC->isRecord() && NewFD->isExternallyVisible())
11029
11030 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11031 // marking the function.
11032 ObjC().AddCFAuditedAttribute(NewFD);
11033
11034 // If this is a function definition, check if we have to apply any
11035 // attributes (i.e. optnone and no_builtin) due to a pragma.
11036 if (D.isFunctionDefinition()) {
11037 AddRangeBasedOptnone(NewFD);
11039 AddSectionMSAllocText(NewFD);
11041 }
11042
11043 // If this is the first declaration of an extern C variable, update
11044 // the map of such variables.
11045 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11046 isIncompleteDeclExternC(*this, NewFD))
11048
11049 // Set this FunctionDecl's range up to the right paren.
11050 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11051
11052 if (D.isRedeclaration() && !Previous.empty()) {
11053 NamedDecl *Prev = Previous.getRepresentativeDecl();
11054 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11055 isMemberSpecialization ||
11056 isFunctionTemplateSpecialization,
11058 }
11059
11060 if (getLangOpts().CUDA) {
11061 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11062 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11065 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11067 Context.setcudaConfigureCallDecl(NewFD);
11068 }
11069 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11070 !NewFD->isInvalidDecl() &&
11073 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11075 Context.setcudaGetParameterBufferDecl(NewFD);
11076 }
11077 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11078 !NewFD->isInvalidDecl() &&
11081 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11083 Context.setcudaLaunchDeviceDecl(NewFD);
11084 }
11085 }
11086 }
11087
11089
11090 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11091 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11092 if (SC == SC_Static) {
11093 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11094 D.setInvalidType();
11095 }
11096
11097 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11098 if (!NewFD->getReturnType()->isVoidType()) {
11099 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11100 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11101 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11102 : FixItHint());
11103 D.setInvalidType();
11104 }
11105
11107 for (auto *Param : NewFD->parameters())
11108 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11109
11110 if (getLangOpts().OpenCLCPlusPlus) {
11111 if (DC->isRecord()) {
11112 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11113 D.setInvalidType();
11114 }
11115 if (FunctionTemplate) {
11116 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11117 D.setInvalidType();
11118 }
11119 }
11120 }
11121
11122 if (getLangOpts().CPlusPlus) {
11123 // Precalculate whether this is a friend function template with a constraint
11124 // that depends on an enclosing template, per [temp.friend]p9.
11125 if (isFriend && FunctionTemplate &&
11128
11129 // C++ [temp.friend]p9:
11130 // A friend function template with a constraint that depends on a
11131 // template parameter from an enclosing template shall be a definition.
11132 if (!D.isFunctionDefinition()) {
11133 Diag(NewFD->getBeginLoc(),
11134 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11135 NewFD->setInvalidDecl();
11136 }
11137 }
11138
11139 if (FunctionTemplate) {
11140 if (NewFD->isInvalidDecl())
11141 FunctionTemplate->setInvalidDecl();
11142 return FunctionTemplate;
11143 }
11144
11145 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11147 }
11148
11149 for (const ParmVarDecl *Param : NewFD->parameters()) {
11150 QualType PT = Param->getType();
11151
11152 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11153 // types.
11154 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11155 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11156 QualType ElemTy = PipeTy->getElementType();
11157 if (ElemTy->isPointerOrReferenceType()) {
11158 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11159 D.setInvalidType();
11160 }
11161 }
11162 }
11163 // WebAssembly tables can't be used as function parameters.
11164 if (Context.getTargetInfo().getTriple().isWasm()) {
11166 Diag(Param->getTypeSpecStartLoc(),
11167 diag::err_wasm_table_as_function_parameter);
11168 D.setInvalidType();
11169 }
11170 }
11171 }
11172
11173 // Diagnose availability attributes. Availability cannot be used on functions
11174 // that are run during load/unload.
11175 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11176 if (NewFD->hasAttr<ConstructorAttr>()) {
11177 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11178 << 1;
11179 NewFD->dropAttr<AvailabilityAttr>();
11180 }
11181 if (NewFD->hasAttr<DestructorAttr>()) {
11182 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11183 << 2;
11184 NewFD->dropAttr<AvailabilityAttr>();
11185 }
11186 }
11187
11188 // Diagnose no_builtin attribute on function declaration that are not a
11189 // definition.
11190 // FIXME: We should really be doing this in
11191 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11192 // the FunctionDecl and at this point of the code
11193 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11194 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11195 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11196 switch (D.getFunctionDefinitionKind()) {
11199 Diag(NBA->getLocation(),
11200 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11201 << NBA->getSpelling();
11202 break;
11204 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11205 << NBA->getSpelling();
11206 break;
11208 break;
11209 }
11210
11211 // Similar to no_builtin logic above, at this point of the code
11212 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11213 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11214 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11215 !NewFD->isInvalidDecl() &&
11217 ExternalDeclarations.push_back(NewFD);
11218
11219 // Used for a warning on the 'next' declaration when used with a
11220 // `routine(name)`.
11221 if (getLangOpts().OpenACC)
11223
11224 return NewFD;
11225}
11226
11227/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11228/// when __declspec(code_seg) "is applied to a class, all member functions of
11229/// the class and nested classes -- this includes compiler-generated special
11230/// member functions -- are put in the specified segment."
11231/// The actual behavior is a little more complicated. The Microsoft compiler
11232/// won't check outer classes if there is an active value from #pragma code_seg.
11233/// The CodeSeg is always applied from the direct parent but only from outer
11234/// classes when the #pragma code_seg stack is empty. See:
11235/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11236/// available since MS has removed the page.
11238 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11239 if (!Method)
11240 return nullptr;
11241 const CXXRecordDecl *Parent = Method->getParent();
11242 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11243 Attr *NewAttr = SAttr->clone(S.getASTContext());
11244 NewAttr->setImplicit(true);
11245 return NewAttr;
11246 }
11247
11248 // The Microsoft compiler won't check outer classes for the CodeSeg
11249 // when the #pragma code_seg stack is active.
11250 if (S.CodeSegStack.CurrentValue)
11251 return nullptr;
11252
11253 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11254 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11255 Attr *NewAttr = SAttr->clone(S.getASTContext());
11256 NewAttr->setImplicit(true);
11257 return NewAttr;
11258 }
11259 }
11260 return nullptr;
11261}
11262
11264 bool IsDefinition) {
11265 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11266 return A;
11267 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11268 CodeSegStack.CurrentValue)
11269 return SectionAttr::CreateImplicit(
11270 getASTContext(), CodeSegStack.CurrentValue->getString(),
11271 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11272 return nullptr;
11273}
11274
11276 QualType NewT, QualType OldT) {
11278 return true;
11279
11280 // For dependently-typed local extern declarations and friends, we can't
11281 // perform a correct type check in general until instantiation:
11282 //
11283 // int f();
11284 // template<typename T> void g() { T f(); }
11285 //
11286 // (valid if g() is only instantiated with T = int).
11287 if (NewT->isDependentType() &&
11288 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11289 return false;
11290
11291 // Similarly, if the previous declaration was a dependent local extern
11292 // declaration, we don't really know its type yet.
11293 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11294 return false;
11295
11296 return true;
11297}
11298
11301 return true;
11302
11303 // Don't chain dependent friend function definitions until instantiation, to
11304 // permit cases like
11305 //
11306 // void func();
11307 // template<typename T> class C1 { friend void func() {} };
11308 // template<typename T> class C2 { friend void func() {} };
11309 //
11310 // ... which is valid if only one of C1 and C2 is ever instantiated.
11311 //
11312 // FIXME: This need only apply to function definitions. For now, we proxy
11313 // this by checking for a file-scope function. We do not want this to apply
11314 // to friend declarations nominating member functions, because that gets in
11315 // the way of access checks.
11317 return false;
11318
11319 auto *VD = dyn_cast<ValueDecl>(D);
11320 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11321 return !VD || !PrevVD ||
11322 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11323 PrevVD->getType());
11324}
11325
11326/// Check the target or target_version attribute of the function for
11327/// MultiVersion validity.
11328///
11329/// Returns true if there was an error, false otherwise.
11330static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11331 const auto *TA = FD->getAttr<TargetAttr>();
11332 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11333
11334 assert((TA || TVA) && "Expecting target or target_version attribute");
11335
11337 enum ErrType { Feature = 0, Architecture = 1 };
11338
11339 if (TA) {
11340 ParsedTargetAttr ParseInfo =
11341 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11342 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11343 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11344 << Architecture << ParseInfo.CPU;
11345 return true;
11346 }
11347 for (const auto &Feat : ParseInfo.Features) {
11348 auto BareFeat = StringRef{Feat}.substr(1);
11349 if (Feat[0] == '-') {
11350 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11351 << Feature << ("no-" + BareFeat).str();
11352 return true;
11353 }
11354
11355 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11356 !TargetInfo.isValidFeatureName(BareFeat) ||
11357 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11358 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11359 << Feature << BareFeat;
11360 return true;
11361 }
11362 }
11363 }
11364
11365 if (TVA) {
11367 ParsedTargetAttr ParseInfo;
11368 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11369 ParseInfo =
11370 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11371 for (auto &Feat : ParseInfo.Features)
11372 Feats.push_back(StringRef{Feat}.substr(1));
11373 } else {
11374 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11375 TVA->getFeatures(Feats);
11376 }
11377 for (const auto &Feat : Feats) {
11378 if (!TargetInfo.validateCpuSupports(Feat)) {
11379 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11380 << Feature << Feat;
11381 return true;
11382 }
11383 }
11384 }
11385 return false;
11386}
11387
11388// Provide a white-list of attributes that are allowed to be combined with
11389// multiversion functions.
11391 MultiVersionKind MVKind) {
11392 // Note: this list/diagnosis must match the list in
11393 // checkMultiversionAttributesAllSame.
11394 switch (Kind) {
11395 default:
11396 return false;
11397 case attr::ArmLocallyStreaming:
11398 return MVKind == MultiVersionKind::TargetVersion ||
11400 case attr::Used:
11401 return MVKind == MultiVersionKind::Target;
11402 case attr::NonNull:
11403 case attr::NoThrow:
11404 return true;
11405 }
11406}
11407
11409 const FunctionDecl *FD,
11410 const FunctionDecl *CausedFD,
11411 MultiVersionKind MVKind) {
11412 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11413 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11414 << static_cast<unsigned>(MVKind) << A;
11415 if (CausedFD)
11416 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11417 return true;
11418 };
11419
11420 for (const Attr *A : FD->attrs()) {
11421 switch (A->getKind()) {
11422 case attr::CPUDispatch:
11423 case attr::CPUSpecific:
11424 if (MVKind != MultiVersionKind::CPUDispatch &&
11426 return Diagnose(S, A);
11427 break;
11428 case attr::Target:
11429 if (MVKind != MultiVersionKind::Target)
11430 return Diagnose(S, A);
11431 break;
11432 case attr::TargetVersion:
11433 if (MVKind != MultiVersionKind::TargetVersion &&
11435 return Diagnose(S, A);
11436 break;
11437 case attr::TargetClones:
11438 if (MVKind != MultiVersionKind::TargetClones &&
11440 return Diagnose(S, A);
11441 break;
11442 default:
11443 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11444 return Diagnose(S, A);
11445 break;
11446 }
11447 }
11448 return false;
11449}
11450
11452 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11453 const PartialDiagnostic &NoProtoDiagID,
11454 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11455 const PartialDiagnosticAt &NoSupportDiagIDAt,
11456 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11457 bool ConstexprSupported, bool CLinkageMayDiffer) {
11458 enum DoesntSupport {
11459 FuncTemplates = 0,
11460 VirtFuncs = 1,
11461 DeducedReturn = 2,
11462 Constructors = 3,
11463 Destructors = 4,
11464 DeletedFuncs = 5,
11465 DefaultedFuncs = 6,
11466 ConstexprFuncs = 7,
11467 ConstevalFuncs = 8,
11468 Lambda = 9,
11469 };
11470 enum Different {
11471 CallingConv = 0,
11472 ReturnType = 1,
11473 ConstexprSpec = 2,
11474 InlineSpec = 3,
11475 Linkage = 4,
11476 LanguageLinkage = 5,
11477 };
11478
11479 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11480 !OldFD->getType()->getAs<FunctionProtoType>()) {
11481 Diag(OldFD->getLocation(), NoProtoDiagID);
11482 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11483 return true;
11484 }
11485
11486 if (NoProtoDiagID.getDiagID() != 0 &&
11487 !NewFD->getType()->getAs<FunctionProtoType>())
11488 return Diag(NewFD->getLocation(), NoProtoDiagID);
11489
11490 if (!TemplatesSupported &&
11492 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11493 << FuncTemplates;
11494
11495 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11496 if (NewCXXFD->isVirtual())
11497 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11498 << VirtFuncs;
11499
11500 if (isa<CXXConstructorDecl>(NewCXXFD))
11501 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11502 << Constructors;
11503
11504 if (isa<CXXDestructorDecl>(NewCXXFD))
11505 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11506 << Destructors;
11507 }
11508
11509 if (NewFD->isDeleted())
11510 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11511 << DeletedFuncs;
11512
11513 if (NewFD->isDefaulted())
11514 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11515 << DefaultedFuncs;
11516
11517 if (!ConstexprSupported && NewFD->isConstexpr())
11518 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11519 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11520
11521 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11522 const auto *NewType = cast<FunctionType>(NewQType);
11523 QualType NewReturnType = NewType->getReturnType();
11524
11525 if (NewReturnType->isUndeducedType())
11526 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11527 << DeducedReturn;
11528
11529 // Ensure the return type is identical.
11530 if (OldFD) {
11531 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11532 const auto *OldType = cast<FunctionType>(OldQType);
11533 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11534 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11535
11536 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11537 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11538
11539 bool ArmStreamingCCMismatched = false;
11540 if (OldFPT && NewFPT) {
11541 unsigned Diff =
11542 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11543 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11544 // cannot be mixed.
11547 ArmStreamingCCMismatched = true;
11548 }
11549
11550 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11551 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11552
11553 QualType OldReturnType = OldType->getReturnType();
11554
11555 if (OldReturnType != NewReturnType)
11556 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11557
11558 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11559 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11560
11561 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11562 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11563
11564 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11565 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11566
11567 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11568 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11569
11570 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11571 NewFD->getLocation()))
11572 return true;
11573 }
11574 return false;
11575}
11576
11578 const FunctionDecl *NewFD,
11579 bool CausesMV,
11580 MultiVersionKind MVKind) {
11582 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11583 if (OldFD)
11584 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11585 return true;
11586 }
11587
11588 bool IsCPUSpecificCPUDispatchMVKind =
11591
11592 if (CausesMV && OldFD &&
11593 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11594 return true;
11595
11596 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11597 return true;
11598
11599 // Only allow transition to MultiVersion if it hasn't been used.
11600 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11601 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11602 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11603 return true;
11604 }
11605
11607 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11609 S.PDiag(diag::note_multiversioning_caused_here)),
11611 S.PDiag(diag::err_multiversion_doesnt_support)
11612 << static_cast<unsigned>(MVKind)),
11614 S.PDiag(diag::err_multiversion_diff)),
11615 /*TemplatesSupported=*/false,
11616 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11617 /*CLinkageMayDiffer=*/false);
11618}
11619
11620/// Check the validity of a multiversion function declaration that is the
11621/// first of its kind. Also sets the multiversion'ness' of the function itself.
11622///
11623/// This sets NewFD->isInvalidDecl() to true if there was an error.
11624///
11625/// Returns true if there was an error, false otherwise.
11628 assert(MVKind != MultiVersionKind::None &&
11629 "Function lacks multiversion attribute");
11630 const auto *TA = FD->getAttr<TargetAttr>();
11631 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11632 // The target attribute only causes MV if this declaration is the default,
11633 // otherwise it is treated as a normal function.
11634 if (TA && !TA->isDefaultVersion())
11635 return false;
11636
11637 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11638 FD->setInvalidDecl();
11639 return true;
11640 }
11641
11642 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11643 FD->setInvalidDecl();
11644 return true;
11645 }
11646
11647 FD->setIsMultiVersion();
11648 return false;
11649}
11650
11652 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11654 return true;
11655 }
11656
11657 return false;
11658}
11659
11661 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11662 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11663 return;
11664
11665 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11666 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11667
11668 if (MVKindTo == MultiVersionKind::None &&
11669 (MVKindFrom == MultiVersionKind::TargetVersion ||
11670 MVKindFrom == MultiVersionKind::TargetClones))
11671 To->addAttr(TargetVersionAttr::CreateImplicit(
11672 To->getASTContext(), "default", To->getSourceRange()));
11673}
11674
11676 FunctionDecl *NewFD,
11677 bool &Redeclaration,
11678 NamedDecl *&OldDecl,
11680 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11681
11682 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11683 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11684 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11685 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11686
11687 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11688
11689 // The definitions should be allowed in any order. If we have discovered
11690 // a new target version and the preceeding was the default, then add the
11691 // corresponding attribute to it.
11692 patchDefaultTargetVersion(NewFD, OldFD);
11693
11694 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11695 // to change, this is a simple redeclaration.
11696 if (NewTA && !NewTA->isDefaultVersion() &&
11697 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11698 return false;
11699
11700 // Otherwise, this decl causes MultiVersioning.
11701 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11704 NewFD->setInvalidDecl();
11705 return true;
11706 }
11707
11708 if (CheckMultiVersionValue(S, NewFD)) {
11709 NewFD->setInvalidDecl();
11710 return true;
11711 }
11712
11713 // If this is 'default', permit the forward declaration.
11714 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11715 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11716 Redeclaration = true;
11717 OldDecl = OldFD;
11718 OldFD->setIsMultiVersion();
11719 NewFD->setIsMultiVersion();
11720 return false;
11721 }
11722
11723 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11724 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11725 NewFD->setInvalidDecl();
11726 return true;
11727 }
11728
11729 if (NewTA) {
11730 ParsedTargetAttr OldParsed =
11732 OldTA->getFeaturesStr());
11733 llvm::sort(OldParsed.Features);
11734 ParsedTargetAttr NewParsed =
11736 NewTA->getFeaturesStr());
11737 // Sort order doesn't matter, it just needs to be consistent.
11738 llvm::sort(NewParsed.Features);
11739 if (OldParsed == NewParsed) {
11740 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11741 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11742 NewFD->setInvalidDecl();
11743 return true;
11744 }
11745 }
11746
11747 for (const auto *FD : OldFD->redecls()) {
11748 const auto *CurTA = FD->getAttr<TargetAttr>();
11749 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11750 // We allow forward declarations before ANY multiversioning attributes, but
11751 // nothing after the fact.
11753 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11754 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11755 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11756 << (NewTA ? 0 : 2);
11757 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11758 NewFD->setInvalidDecl();
11759 return true;
11760 }
11761 }
11762
11763 OldFD->setIsMultiVersion();
11764 NewFD->setIsMultiVersion();
11765 Redeclaration = false;
11766 OldDecl = nullptr;
11767 Previous.clear();
11768 return false;
11769}
11770
11772 MultiVersionKind OldKind = Old->getMultiVersionKind();
11773 MultiVersionKind NewKind = New->getMultiVersionKind();
11774
11775 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11776 NewKind == MultiVersionKind::None)
11777 return true;
11778
11779 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11780 switch (OldKind) {
11782 return NewKind == MultiVersionKind::TargetClones;
11784 return NewKind == MultiVersionKind::TargetVersion;
11785 default:
11786 return false;
11787 }
11788 } else {
11789 switch (OldKind) {
11791 return NewKind == MultiVersionKind::CPUSpecific;
11793 return NewKind == MultiVersionKind::CPUDispatch;
11794 default:
11795 return false;
11796 }
11797 }
11798}
11799
11800/// Check the validity of a new function declaration being added to an existing
11801/// multiversioned declaration collection.
11803 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11804 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11805 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11807
11808 // Disallow mixing of multiversioning types.
11809 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11810 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11811 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11812 NewFD->setInvalidDecl();
11813 return true;
11814 }
11815
11816 // Add the default target_version attribute if it's missing.
11817 patchDefaultTargetVersion(OldFD, NewFD);
11818 patchDefaultTargetVersion(NewFD, OldFD);
11819
11820 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11821 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11822 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11823 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11824
11825 ParsedTargetAttr NewParsed;
11826 if (NewTA) {
11828 NewTA->getFeaturesStr());
11829 llvm::sort(NewParsed.Features);
11830 }
11832 if (NewTVA) {
11833 NewTVA->getFeatures(NewFeats);
11834 llvm::sort(NewFeats);
11835 }
11836
11837 bool UseMemberUsingDeclRules =
11838 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11839
11840 bool MayNeedOverloadableChecks =
11842
11843 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11844 // of a previous member of the MultiVersion set.
11845 for (NamedDecl *ND : Previous) {
11846 FunctionDecl *CurFD = ND->getAsFunction();
11847 if (!CurFD || CurFD->isInvalidDecl())
11848 continue;
11849 if (MayNeedOverloadableChecks &&
11850 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11851 continue;
11852
11853 switch (NewMVKind) {
11855 assert(OldMVKind == MultiVersionKind::TargetClones &&
11856 "Only target_clones can be omitted in subsequent declarations");
11857 break;
11859 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11860 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11861 NewFD->setIsMultiVersion();
11862 Redeclaration = true;
11863 OldDecl = ND;
11864 return false;
11865 }
11866
11867 ParsedTargetAttr CurParsed =
11869 CurTA->getFeaturesStr());
11870 llvm::sort(CurParsed.Features);
11871 if (CurParsed == NewParsed) {
11872 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11873 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11874 NewFD->setInvalidDecl();
11875 return true;
11876 }
11877 break;
11878 }
11880 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11881 if (CurTVA->getName() == NewTVA->getName()) {
11882 NewFD->setIsMultiVersion();
11883 Redeclaration = true;
11884 OldDecl = ND;
11885 return false;
11886 }
11888 CurTVA->getFeatures(CurFeats);
11889 llvm::sort(CurFeats);
11890
11891 if (CurFeats == NewFeats) {
11892 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11893 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11894 NewFD->setInvalidDecl();
11895 return true;
11896 }
11897 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11898 // Default
11899 if (NewFeats.empty())
11900 break;
11901
11902 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11904 CurClones->getFeatures(CurFeats, I);
11905 llvm::sort(CurFeats);
11906
11907 if (CurFeats == NewFeats) {
11908 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11909 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11910 NewFD->setInvalidDecl();
11911 return true;
11912 }
11913 }
11914 }
11915 break;
11916 }
11918 assert(NewClones && "MultiVersionKind does not match attribute type");
11919 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11920 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11921 !std::equal(CurClones->featuresStrs_begin(),
11922 CurClones->featuresStrs_end(),
11923 NewClones->featuresStrs_begin())) {
11924 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11925 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11926 NewFD->setInvalidDecl();
11927 return true;
11928 }
11929 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11931 CurTVA->getFeatures(CurFeats);
11932 llvm::sort(CurFeats);
11933
11934 // Default
11935 if (CurFeats.empty())
11936 break;
11937
11938 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11939 NewFeats.clear();
11940 NewClones->getFeatures(NewFeats, I);
11941 llvm::sort(NewFeats);
11942
11943 if (CurFeats == NewFeats) {
11944 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11945 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11946 NewFD->setInvalidDecl();
11947 return true;
11948 }
11949 }
11950 break;
11951 }
11952 Redeclaration = true;
11953 OldDecl = CurFD;
11954 NewFD->setIsMultiVersion();
11955 return false;
11956 }
11959 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11960 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11961 // Handle CPUDispatch/CPUSpecific versions.
11962 // Only 1 CPUDispatch function is allowed, this will make it go through
11963 // the redeclaration errors.
11964 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11965 CurFD->hasAttr<CPUDispatchAttr>()) {
11966 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11967 std::equal(
11968 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11969 NewCPUDisp->cpus_begin(),
11970 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11971 return Cur->getName() == New->getName();
11972 })) {
11973 NewFD->setIsMultiVersion();
11974 Redeclaration = true;
11975 OldDecl = ND;
11976 return false;
11977 }
11978
11979 // If the declarations don't match, this is an error condition.
11980 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11981 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11982 NewFD->setInvalidDecl();
11983 return true;
11984 }
11985 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11986 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11987 std::equal(
11988 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11989 NewCPUSpec->cpus_begin(),
11990 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11991 return Cur->getName() == New->getName();
11992 })) {
11993 NewFD->setIsMultiVersion();
11994 Redeclaration = true;
11995 OldDecl = ND;
11996 return false;
11997 }
11998
11999 // Only 1 version of CPUSpecific is allowed for each CPU.
12000 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12001 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12002 if (CurII == NewII) {
12003 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12004 << NewII;
12005 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12006 NewFD->setInvalidDecl();
12007 return true;
12008 }
12009 }
12010 }
12011 }
12012 break;
12013 }
12014 }
12015 }
12016
12017 // Redeclarations of a target_clones function may omit the attribute, in which
12018 // case it will be inherited during declaration merging.
12019 if (NewMVKind == MultiVersionKind::None &&
12020 OldMVKind == MultiVersionKind::TargetClones) {
12021 NewFD->setIsMultiVersion();
12022 Redeclaration = true;
12023 OldDecl = OldFD;
12024 return false;
12025 }
12026
12027 // Else, this is simply a non-redecl case. Checking the 'value' is only
12028 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12029 // handled in the attribute adding step.
12030 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12031 NewFD->setInvalidDecl();
12032 return true;
12033 }
12034
12035 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12036 !OldFD->isMultiVersion(), NewMVKind)) {
12037 NewFD->setInvalidDecl();
12038 return true;
12039 }
12040
12041 // Permit forward declarations in the case where these two are compatible.
12042 if (!OldFD->isMultiVersion()) {
12043 OldFD->setIsMultiVersion();
12044 NewFD->setIsMultiVersion();
12045 Redeclaration = true;
12046 OldDecl = OldFD;
12047 return false;
12048 }
12049
12050 NewFD->setIsMultiVersion();
12051 Redeclaration = false;
12052 OldDecl = nullptr;
12053 Previous.clear();
12054 return false;
12055}
12056
12057/// Check the validity of a mulitversion function declaration.
12058/// Also sets the multiversion'ness' of the function itself.
12059///
12060/// This sets NewFD->isInvalidDecl() to true if there was an error.
12061///
12062/// Returns true if there was an error, false otherwise.
12064 bool &Redeclaration, NamedDecl *&OldDecl,
12066 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12067
12068 // Check if FMV is disabled.
12069 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12070 return false;
12071
12072 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12073 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12074 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12075 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12076 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12077 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12078
12079 // Main isn't allowed to become a multiversion function, however it IS
12080 // permitted to have 'main' be marked with the 'target' optimization hint,
12081 // for 'target_version' only default is allowed.
12082 if (NewFD->isMain()) {
12083 if (MVKind != MultiVersionKind::None &&
12084 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12085 !(MVKind == MultiVersionKind::TargetVersion &&
12086 NewTVA->isDefaultVersion())) {
12087 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12088 NewFD->setInvalidDecl();
12089 return true;
12090 }
12091 return false;
12092 }
12093
12094 // Target attribute on AArch64 is not used for multiversioning
12095 if (NewTA && TI.getTriple().isAArch64())
12096 return false;
12097
12098 // Target attribute on RISCV is not used for multiversioning
12099 if (NewTA && TI.getTriple().isRISCV())
12100 return false;
12101
12102 if (!OldDecl || !OldDecl->getAsFunction() ||
12103 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12104 NewFD->getDeclContext()->getRedeclContext())) {
12105 // If there's no previous declaration, AND this isn't attempting to cause
12106 // multiversioning, this isn't an error condition.
12107 if (MVKind == MultiVersionKind::None)
12108 return false;
12109 return CheckMultiVersionFirstFunction(S, NewFD);
12110 }
12111
12112 FunctionDecl *OldFD = OldDecl->getAsFunction();
12113
12114 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12115 return false;
12116
12117 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12118 // for target_clones and target_version.
12119 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12122 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12124 NewFD->setInvalidDecl();
12125 return true;
12126 }
12127
12128 if (!OldFD->isMultiVersion()) {
12129 switch (MVKind) {
12133 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12135 if (OldFD->isUsed(false)) {
12136 NewFD->setInvalidDecl();
12137 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12138 }
12139 OldFD->setIsMultiVersion();
12140 break;
12141
12145 break;
12146 }
12147 }
12148
12149 // At this point, we have a multiversion function decl (in OldFD) AND an
12150 // appropriate attribute in the current function decl (unless it's allowed to
12151 // omit the attribute). Resolve that these are still compatible with previous
12152 // declarations.
12153 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12154 NewCPUSpec, NewClones, Redeclaration,
12155 OldDecl, Previous);
12156}
12157
12159 bool IsPure = NewFD->hasAttr<PureAttr>();
12160 bool IsConst = NewFD->hasAttr<ConstAttr>();
12161
12162 // If there are no pure or const attributes, there's nothing to check.
12163 if (!IsPure && !IsConst)
12164 return;
12165
12166 // If the function is marked both pure and const, we retain the const
12167 // attribute because it makes stronger guarantees than the pure attribute, and
12168 // we drop the pure attribute explicitly to prevent later confusion about
12169 // semantics.
12170 if (IsPure && IsConst) {
12171 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12172 NewFD->dropAttrs<PureAttr>();
12173 }
12174
12175 // Constructors and destructors are functions which return void, so are
12176 // handled here as well.
12177 if (NewFD->getReturnType()->isVoidType()) {
12178 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12179 << IsConst;
12180 NewFD->dropAttrs<PureAttr, ConstAttr>();
12181 }
12182}
12183
12186 bool IsMemberSpecialization,
12187 bool DeclIsDefn) {
12188 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12189 "Variably modified return types are not handled here");
12190
12191 // Determine whether the type of this function should be merged with
12192 // a previous visible declaration. This never happens for functions in C++,
12193 // and always happens in C if the previous declaration was visible.
12194 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12195 !Previous.isShadowed();
12196
12197 bool Redeclaration = false;
12198 NamedDecl *OldDecl = nullptr;
12199 bool MayNeedOverloadableChecks = false;
12200
12202 // Merge or overload the declaration with an existing declaration of
12203 // the same name, if appropriate.
12204 if (!Previous.empty()) {
12205 // Determine whether NewFD is an overload of PrevDecl or
12206 // a declaration that requires merging. If it's an overload,
12207 // there's no more work to do here; we'll just add the new
12208 // function to the scope.
12210 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12211 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12212 Redeclaration = true;
12213 OldDecl = Candidate;
12214 }
12215 } else {
12216 MayNeedOverloadableChecks = true;
12217 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12218 /*NewIsUsingDecl*/ false)) {
12220 Redeclaration = true;
12221 break;
12222
12224 Redeclaration = true;
12225 break;
12226
12228 Redeclaration = false;
12229 break;
12230 }
12231 }
12232 }
12233
12234 // Check for a previous extern "C" declaration with this name.
12235 if (!Redeclaration &&
12237 if (!Previous.empty()) {
12238 // This is an extern "C" declaration with the same name as a previous
12239 // declaration, and thus redeclares that entity...
12240 Redeclaration = true;
12241 OldDecl = Previous.getFoundDecl();
12242 MergeTypeWithPrevious = false;
12243
12244 // ... except in the presence of __attribute__((overloadable)).
12245 if (OldDecl->hasAttr<OverloadableAttr>() ||
12246 NewFD->hasAttr<OverloadableAttr>()) {
12247 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12248 MayNeedOverloadableChecks = true;
12249 Redeclaration = false;
12250 OldDecl = nullptr;
12251 }
12252 }
12253 }
12254 }
12255
12256 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12257 return Redeclaration;
12258
12259 // PPC MMA non-pointer types are not allowed as function return types.
12260 if (Context.getTargetInfo().getTriple().isPPC64() &&
12261 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12262 NewFD->setInvalidDecl();
12263 }
12264
12265 CheckConstPureAttributesUsage(*this, NewFD);
12266
12267 // C++ [dcl.spec.auto.general]p12:
12268 // Return type deduction for a templated function with a placeholder in its
12269 // declared type occurs when the definition is instantiated even if the
12270 // function body contains a return statement with a non-type-dependent
12271 // operand.
12272 //
12273 // C++ [temp.dep.expr]p3:
12274 // An id-expression is type-dependent if it is a template-id that is not a
12275 // concept-id and is dependent; or if its terminal name is:
12276 // - [...]
12277 // - associated by name lookup with one or more declarations of member
12278 // functions of a class that is the current instantiation declared with a
12279 // return type that contains a placeholder type,
12280 // - [...]
12281 //
12282 // If this is a templated function with a placeholder in its return type,
12283 // make the placeholder type dependent since it won't be deduced until the
12284 // definition is instantiated. We do this here because it needs to happen
12285 // for implicitly instantiated member functions/member function templates.
12286 if (getLangOpts().CPlusPlus14 &&
12287 (NewFD->isDependentContext() &&
12288 NewFD->getReturnType()->isUndeducedType())) {
12289 const FunctionProtoType *FPT =
12290 NewFD->getType()->castAs<FunctionProtoType>();
12291 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12292 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12293 FPT->getExtProtoInfo()));
12294 }
12295
12296 // C++11 [dcl.constexpr]p8:
12297 // A constexpr specifier for a non-static member function that is not
12298 // a constructor declares that member function to be const.
12299 //
12300 // This needs to be delayed until we know whether this is an out-of-line
12301 // definition of a static member function.
12302 //
12303 // This rule is not present in C++1y, so we produce a backwards
12304 // compatibility warning whenever it happens in C++11.
12305 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12306 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12307 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12309 CXXMethodDecl *OldMD = nullptr;
12310 if (OldDecl)
12311 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12312 if (!OldMD || !OldMD->isStatic()) {
12313 const FunctionProtoType *FPT =
12316 EPI.TypeQuals.addConst();
12317 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12318 FPT->getParamTypes(), EPI));
12319
12320 // Warn that we did this, if we're not performing template instantiation.
12321 // In that case, we'll have warned already when the template was defined.
12322 if (!inTemplateInstantiation()) {
12323 SourceLocation AddConstLoc;
12326 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12327
12328 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12329 << FixItHint::CreateInsertion(AddConstLoc, " const");
12330 }
12331 }
12332 }
12333
12334 if (Redeclaration) {
12335 // NewFD and OldDecl represent declarations that need to be
12336 // merged.
12337 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12338 DeclIsDefn)) {
12339 NewFD->setInvalidDecl();
12340 return Redeclaration;
12341 }
12342
12343 Previous.clear();
12344 Previous.addDecl(OldDecl);
12345
12346 if (FunctionTemplateDecl *OldTemplateDecl =
12347 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12348 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12349 FunctionTemplateDecl *NewTemplateDecl
12351 assert(NewTemplateDecl && "Template/non-template mismatch");
12352
12353 // The call to MergeFunctionDecl above may have created some state in
12354 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12355 // can add it as a redeclaration.
12356 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12357
12358 NewFD->setPreviousDeclaration(OldFD);
12359 if (NewFD->isCXXClassMember()) {
12360 NewFD->setAccess(OldTemplateDecl->getAccess());
12361 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12362 }
12363
12364 // If this is an explicit specialization of a member that is a function
12365 // template, mark it as a member specialization.
12366 if (IsMemberSpecialization &&
12367 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12368 NewTemplateDecl->setMemberSpecialization();
12369 assert(OldTemplateDecl->isMemberSpecialization());
12370 // Explicit specializations of a member template do not inherit deleted
12371 // status from the parent member template that they are specializing.
12372 if (OldFD->isDeleted()) {
12373 // FIXME: This assert will not hold in the presence of modules.
12374 assert(OldFD->getCanonicalDecl() == OldFD);
12375 // FIXME: We need an update record for this AST mutation.
12376 OldFD->setDeletedAsWritten(false);
12377 }
12378 }
12379
12380 } else {
12381 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12382 auto *OldFD = cast<FunctionDecl>(OldDecl);
12383 // This needs to happen first so that 'inline' propagates.
12384 NewFD->setPreviousDeclaration(OldFD);
12385 if (NewFD->isCXXClassMember())
12386 NewFD->setAccess(OldFD->getAccess());
12387 }
12388 }
12389 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12390 !NewFD->getAttr<OverloadableAttr>()) {
12391 assert((Previous.empty() ||
12392 llvm::any_of(Previous,
12393 [](const NamedDecl *ND) {
12394 return ND->hasAttr<OverloadableAttr>();
12395 })) &&
12396 "Non-redecls shouldn't happen without overloadable present");
12397
12398 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12399 const auto *FD = dyn_cast<FunctionDecl>(ND);
12400 return FD && !FD->hasAttr<OverloadableAttr>();
12401 });
12402
12403 if (OtherUnmarkedIter != Previous.end()) {
12404 Diag(NewFD->getLocation(),
12405 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12406 Diag((*OtherUnmarkedIter)->getLocation(),
12407 diag::note_attribute_overloadable_prev_overload)
12408 << false;
12409
12410 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12411 }
12412 }
12413
12414 if (LangOpts.OpenMP)
12416
12417 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12419
12420 if (NewFD->hasAttr<SYCLExternalAttr>())
12422
12423 // Semantic checking for this function declaration (in isolation).
12424
12425 if (getLangOpts().CPlusPlus) {
12426 // C++-specific checks.
12427 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12429 } else if (CXXDestructorDecl *Destructor =
12430 dyn_cast<CXXDestructorDecl>(NewFD)) {
12431 // We check here for invalid destructor names.
12432 // If we have a friend destructor declaration that is dependent, we can't
12433 // diagnose right away because cases like this are still valid:
12434 // template <class T> struct A { friend T::X::~Y(); };
12435 // struct B { struct Y { ~Y(); }; using X = Y; };
12436 // template struct A<B>;
12438 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12439 CanQualType ClassType =
12440 Context.getCanonicalTagType(Destructor->getParent());
12441
12442 DeclarationName Name =
12443 Context.DeclarationNames.getCXXDestructorName(ClassType);
12444 if (NewFD->getDeclName() != Name) {
12445 Diag(NewFD->getLocation(), diag::err_destructor_name);
12446 NewFD->setInvalidDecl();
12447 return Redeclaration;
12448 }
12449 }
12450 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12451 if (auto *TD = Guide->getDescribedFunctionTemplate())
12453
12454 // A deduction guide is not on the list of entities that can be
12455 // explicitly specialized.
12456 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12457 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12458 << /*explicit specialization*/ 1;
12459 }
12460
12461 // Find any virtual functions that this function overrides.
12462 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12463 if (!Method->isFunctionTemplateSpecialization() &&
12464 !Method->getDescribedFunctionTemplate() &&
12465 Method->isCanonicalDecl()) {
12466 AddOverriddenMethods(Method->getParent(), Method);
12467 }
12468 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12469 // C++2a [class.virtual]p6
12470 // A virtual method shall not have a requires-clause.
12472 diag::err_constrained_virtual_method);
12473
12474 if (Method->isStatic())
12476 }
12477
12478 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12479 ActOnConversionDeclarator(Conversion);
12480
12481 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12482 if (NewFD->isOverloadedOperator() &&
12484 NewFD->setInvalidDecl();
12485 return Redeclaration;
12486 }
12487
12488 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12489 if (NewFD->getLiteralIdentifier() &&
12491 NewFD->setInvalidDecl();
12492 return Redeclaration;
12493 }
12494
12495 // In C++, check default arguments now that we have merged decls. Unless
12496 // the lexical context is the class, because in this case this is done
12497 // during delayed parsing anyway.
12498 if (!CurContext->isRecord())
12500
12501 // If this function is declared as being extern "C", then check to see if
12502 // the function returns a UDT (class, struct, or union type) that is not C
12503 // compatible, and if it does, warn the user.
12504 // But, issue any diagnostic on the first declaration only.
12505 if (Previous.empty() && NewFD->isExternC()) {
12506 QualType R = NewFD->getReturnType();
12507 if (R->isIncompleteType() && !R->isVoidType())
12508 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12509 << NewFD << R;
12510 else if (!R.isPODType(Context) && !R->isVoidType() &&
12512 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12513 }
12514
12515 // C++1z [dcl.fct]p6:
12516 // [...] whether the function has a non-throwing exception-specification
12517 // [is] part of the function type
12518 //
12519 // This results in an ABI break between C++14 and C++17 for functions whose
12520 // declared type includes an exception-specification in a parameter or
12521 // return type. (Exception specifications on the function itself are OK in
12522 // most cases, and exception specifications are not permitted in most other
12523 // contexts where they could make it into a mangling.)
12524 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12525 auto HasNoexcept = [&](QualType T) -> bool {
12526 // Strip off declarator chunks that could be between us and a function
12527 // type. We don't need to look far, exception specifications are very
12528 // restricted prior to C++17.
12529 if (auto *RT = T->getAs<ReferenceType>())
12530 T = RT->getPointeeType();
12531 else if (T->isAnyPointerType())
12532 T = T->getPointeeType();
12533 else if (auto *MPT = T->getAs<MemberPointerType>())
12534 T = MPT->getPointeeType();
12535 if (auto *FPT = T->getAs<FunctionProtoType>())
12536 if (FPT->isNothrow())
12537 return true;
12538 return false;
12539 };
12540
12541 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12542 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12543 for (QualType T : FPT->param_types())
12544 AnyNoexcept |= HasNoexcept(T);
12545 if (AnyNoexcept)
12546 Diag(NewFD->getLocation(),
12547 diag::warn_cxx17_compat_exception_spec_in_signature)
12548 << NewFD;
12549 }
12550
12551 if (!Redeclaration && LangOpts.CUDA) {
12552 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12553 for (auto *Parm : NewFD->parameters()) {
12554 if (!Parm->getType()->isDependentType() &&
12555 Parm->hasAttr<CUDAGridConstantAttr>() &&
12556 !(IsKernel && Parm->getType().isConstQualified()))
12557 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12558 diag::err_cuda_grid_constant_not_allowed);
12559 }
12561 }
12562 }
12563
12564 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12566
12567 return Redeclaration;
12568}
12569
12571 // [basic.start.main]p3
12572 // The main function shall not be declared with C linkage-specification.
12573 if (FD->isExternCContext())
12574 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12575
12576 // C++11 [basic.start.main]p3:
12577 // A program that [...] declares main to be inline, static or
12578 // constexpr is ill-formed.
12579 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12580 // appear in a declaration of main.
12581 // static main is not an error under C99, but we should warn about it.
12582 // We accept _Noreturn main as an extension.
12583 if (FD->getStorageClass() == SC_Static)
12585 ? diag::err_static_main : diag::warn_static_main)
12587 if (FD->isInlineSpecified())
12588 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12590 if (DS.isNoreturnSpecified()) {
12591 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12592 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12593 Diag(NoreturnLoc, diag::ext_noreturn_main);
12594 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12595 << FixItHint::CreateRemoval(NoreturnRange);
12596 }
12597 if (FD->isConstexpr()) {
12598 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12599 << FD->isConsteval()
12602 }
12603
12604 if (getLangOpts().OpenCL) {
12605 Diag(FD->getLocation(), diag::err_opencl_no_main)
12606 << FD->hasAttr<DeviceKernelAttr>();
12607 FD->setInvalidDecl();
12608 return;
12609 }
12610
12611 if (FD->hasAttr<SYCLExternalAttr>()) {
12612 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12613 << FD->getAttr<SYCLExternalAttr>();
12614 FD->setInvalidDecl();
12615 return;
12616 }
12617
12618 // Functions named main in hlsl are default entries, but don't have specific
12619 // signatures they are required to conform to.
12620 if (getLangOpts().HLSL)
12621 return;
12622
12623 QualType T = FD->getType();
12624 assert(T->isFunctionType() && "function decl is not of function type");
12625 const FunctionType* FT = T->castAs<FunctionType>();
12626
12627 // Set default calling convention for main()
12628 if (FT->getCallConv() != CC_C) {
12629 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12630 FD->setType(QualType(FT, 0));
12631 T = Context.getCanonicalType(FD->getType());
12632 }
12633
12635 // In C with GNU extensions we allow main() to have non-integer return
12636 // type, but we should warn about the extension, and we disable the
12637 // implicit-return-zero rule.
12638
12639 // GCC in C mode accepts qualified 'int'.
12640 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12641 FD->setHasImplicitReturnZero(true);
12642 else {
12643 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12644 SourceRange RTRange = FD->getReturnTypeSourceRange();
12645 if (RTRange.isValid())
12646 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12647 << FixItHint::CreateReplacement(RTRange, "int");
12648 }
12649 } else {
12650 // In C and C++, main magically returns 0 if you fall off the end;
12651 // set the flag which tells us that.
12652 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12653
12654 // All the standards say that main() should return 'int'.
12655 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12656 FD->setHasImplicitReturnZero(true);
12657 else {
12658 // Otherwise, this is just a flat-out error.
12659 SourceRange RTRange = FD->getReturnTypeSourceRange();
12660 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12661 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12662 : FixItHint());
12663 FD->setInvalidDecl(true);
12664 }
12665
12666 // [basic.start.main]p3:
12667 // A program that declares a function main that belongs to the global scope
12668 // and is attached to a named module is ill-formed.
12669 if (FD->isInNamedModule()) {
12670 const SourceLocation start = FD->getTypeSpecStartLoc();
12671 Diag(start, diag::warn_main_in_named_module)
12672 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12673 }
12674 }
12675
12676 // Treat protoless main() as nullary.
12677 if (isa<FunctionNoProtoType>(FT)) return;
12678
12680 unsigned nparams = FTP->getNumParams();
12681 assert(FD->getNumParams() == nparams);
12682
12683 bool HasExtraParameters = (nparams > 3);
12684
12685 if (FTP->isVariadic()) {
12686 Diag(FD->getLocation(), diag::ext_variadic_main);
12687 // FIXME: if we had information about the location of the ellipsis, we
12688 // could add a FixIt hint to remove it as a parameter.
12689 }
12690
12691 // Darwin passes an undocumented fourth argument of type char**. If
12692 // other platforms start sprouting these, the logic below will start
12693 // getting shifty.
12694 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12695 HasExtraParameters = false;
12696
12697 if (HasExtraParameters) {
12698 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12699 FD->setInvalidDecl(true);
12700 nparams = 3;
12701 }
12702
12703 // FIXME: a lot of the following diagnostics would be improved
12704 // if we had some location information about types.
12705
12706 QualType CharPP =
12707 Context.getPointerType(Context.getPointerType(Context.CharTy));
12708 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12709
12710 for (unsigned i = 0; i < nparams; ++i) {
12711 QualType AT = FTP->getParamType(i);
12712
12713 bool mismatch = true;
12714
12715 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12716 mismatch = false;
12717 else if (Expected[i] == CharPP) {
12718 // As an extension, the following forms are okay:
12719 // char const **
12720 // char const * const *
12721 // char * const *
12722
12724 const PointerType* PT;
12725 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12726 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12727 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12728 Context.CharTy)) {
12729 qs.removeConst();
12730 mismatch = !qs.empty();
12731 }
12732 }
12733
12734 if (mismatch) {
12735 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12736 // TODO: suggest replacing given type with expected type
12737 FD->setInvalidDecl(true);
12738 }
12739 }
12740
12741 if (nparams == 1 && !FD->isInvalidDecl()) {
12742 Diag(FD->getLocation(), diag::warn_main_one_arg);
12743 }
12744
12745 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12746 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12747 FD->setInvalidDecl();
12748 }
12749}
12750
12751static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12752
12753 // Default calling convention for main and wmain is __cdecl
12754 if (FD->getName() == "main" || FD->getName() == "wmain")
12755 return false;
12756
12757 // Default calling convention for MinGW and Cygwin is __cdecl
12758 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12759 if (T.isOSCygMing())
12760 return false;
12761
12762 // Default calling convention for WinMain, wWinMain and DllMain
12763 // is __stdcall on 32 bit Windows
12764 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12765 return true;
12766
12767 return false;
12768}
12769
12771 QualType T = FD->getType();
12772 assert(T->isFunctionType() && "function decl is not of function type");
12773 const FunctionType *FT = T->castAs<FunctionType>();
12774
12775 // Set an implicit return of 'zero' if the function can return some integral,
12776 // enumeration, pointer or nullptr type.
12780 // DllMain is exempt because a return value of zero means it failed.
12781 if (FD->getName() != "DllMain")
12782 FD->setHasImplicitReturnZero(true);
12783
12784 // Explicitly specified calling conventions are applied to MSVC entry points
12785 if (!hasExplicitCallingConv(T)) {
12786 if (isDefaultStdCall(FD, *this)) {
12787 if (FT->getCallConv() != CC_X86StdCall) {
12788 FT = Context.adjustFunctionType(
12790 FD->setType(QualType(FT, 0));
12791 }
12792 } else if (FT->getCallConv() != CC_C) {
12793 FT = Context.adjustFunctionType(FT,
12795 FD->setType(QualType(FT, 0));
12796 }
12797 }
12798
12799 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12800 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12801 FD->setInvalidDecl();
12802 }
12803}
12804
12806 // FIXME: Need strict checking. In C89, we need to check for
12807 // any assignment, increment, decrement, function-calls, or
12808 // commas outside of a sizeof. In C99, it's the same list,
12809 // except that the aforementioned are allowed in unevaluated
12810 // expressions. Everything else falls under the
12811 // "may accept other forms of constant expressions" exception.
12812 //
12813 // Regular C++ code will not end up here (exceptions: language extensions,
12814 // OpenCL C++ etc), so the constant expression rules there don't matter.
12815 if (Init->isValueDependent()) {
12816 assert(Init->containsErrors() &&
12817 "Dependent code should only occur in error-recovery path.");
12818 return true;
12819 }
12820 const Expr *Culprit;
12821 if (Init->isConstantInitializer(Context, false, &Culprit))
12822 return false;
12823 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12824 return true;
12825}
12826
12827namespace {
12828 // Visits an initialization expression to see if OrigDecl is evaluated in
12829 // its own initialization and throws a warning if it does.
12830 class SelfReferenceChecker
12831 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12832 Sema &S;
12833 Decl *OrigDecl;
12834 bool isRecordType;
12835 bool isPODType;
12836 bool isReferenceType;
12837 bool isInCXXOperatorCall;
12838
12839 bool isInitList;
12840 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12841
12842 public:
12844
12845 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12846 S(S), OrigDecl(OrigDecl) {
12847 isPODType = false;
12848 isRecordType = false;
12849 isReferenceType = false;
12850 isInCXXOperatorCall = false;
12851 isInitList = false;
12852 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12853 isPODType = VD->getType().isPODType(S.Context);
12854 isRecordType = VD->getType()->isRecordType();
12855 isReferenceType = VD->getType()->isReferenceType();
12856 }
12857 }
12858
12859 // For most expressions, just call the visitor. For initializer lists,
12860 // track the index of the field being initialized since fields are
12861 // initialized in order allowing use of previously initialized fields.
12862 void CheckExpr(Expr *E) {
12863 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12864 if (!InitList) {
12865 Visit(E);
12866 return;
12867 }
12868
12869 // Track and increment the index here.
12870 isInitList = true;
12871 InitFieldIndex.push_back(0);
12872 for (auto *Child : InitList->children()) {
12873 CheckExpr(cast<Expr>(Child));
12874 ++InitFieldIndex.back();
12875 }
12876 InitFieldIndex.pop_back();
12877 }
12878
12879 // Returns true if MemberExpr is checked and no further checking is needed.
12880 // Returns false if additional checking is required.
12881 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12882 llvm::SmallVector<FieldDecl*, 4> Fields;
12883 Expr *Base = E;
12884 bool ReferenceField = false;
12885
12886 // Get the field members used.
12887 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12888 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12889 if (!FD)
12890 return false;
12891 Fields.push_back(FD);
12892 if (FD->getType()->isReferenceType())
12893 ReferenceField = true;
12894 Base = ME->getBase()->IgnoreParenImpCasts();
12895 }
12896
12897 // Keep checking only if the base Decl is the same.
12898 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12899 if (!DRE || DRE->getDecl() != OrigDecl)
12900 return false;
12901
12902 // A reference field can be bound to an unininitialized field.
12903 if (CheckReference && !ReferenceField)
12904 return true;
12905
12906 // Convert FieldDecls to their index number.
12907 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12908 for (const FieldDecl *I : llvm::reverse(Fields))
12909 UsedFieldIndex.push_back(I->getFieldIndex());
12910
12911 // See if a warning is needed by checking the first difference in index
12912 // numbers. If field being used has index less than the field being
12913 // initialized, then the use is safe.
12914 for (auto UsedIter = UsedFieldIndex.begin(),
12915 UsedEnd = UsedFieldIndex.end(),
12916 OrigIter = InitFieldIndex.begin(),
12917 OrigEnd = InitFieldIndex.end();
12918 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12919 if (*UsedIter < *OrigIter)
12920 return true;
12921 if (*UsedIter > *OrigIter)
12922 break;
12923 }
12924
12925 // TODO: Add a different warning which will print the field names.
12926 HandleDeclRefExpr(DRE);
12927 return true;
12928 }
12929
12930 // For most expressions, the cast is directly above the DeclRefExpr.
12931 // For conditional operators, the cast can be outside the conditional
12932 // operator if both expressions are DeclRefExpr's.
12933 void HandleValue(Expr *E) {
12934 E = E->IgnoreParens();
12935 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12936 HandleDeclRefExpr(DRE);
12937 return;
12938 }
12939
12940 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12941 Visit(CO->getCond());
12942 HandleValue(CO->getTrueExpr());
12943 HandleValue(CO->getFalseExpr());
12944 return;
12945 }
12946
12947 if (BinaryConditionalOperator *BCO =
12948 dyn_cast<BinaryConditionalOperator>(E)) {
12949 Visit(BCO->getCond());
12950 HandleValue(BCO->getFalseExpr());
12951 return;
12952 }
12953
12954 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12955 if (Expr *SE = OVE->getSourceExpr())
12956 HandleValue(SE);
12957 return;
12958 }
12959
12960 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12961 if (BO->getOpcode() == BO_Comma) {
12962 Visit(BO->getLHS());
12963 HandleValue(BO->getRHS());
12964 return;
12965 }
12966 }
12967
12968 if (isa<MemberExpr>(E)) {
12969 if (isInitList) {
12970 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12971 false /*CheckReference*/))
12972 return;
12973 }
12974
12975 Expr *Base = E->IgnoreParenImpCasts();
12976 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12977 // Check for static member variables and don't warn on them.
12978 if (!isa<FieldDecl>(ME->getMemberDecl()))
12979 return;
12980 Base = ME->getBase()->IgnoreParenImpCasts();
12981 }
12982 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12983 HandleDeclRefExpr(DRE);
12984 return;
12985 }
12986
12987 Visit(E);
12988 }
12989
12990 // Reference types not handled in HandleValue are handled here since all
12991 // uses of references are bad, not just r-value uses.
12992 void VisitDeclRefExpr(DeclRefExpr *E) {
12993 if (isReferenceType)
12994 HandleDeclRefExpr(E);
12995 }
12996
12997 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12998 if (E->getCastKind() == CK_LValueToRValue) {
12999 HandleValue(E->getSubExpr());
13000 return;
13001 }
13002
13003 Inherited::VisitImplicitCastExpr(E);
13004 }
13005
13006 void VisitMemberExpr(MemberExpr *E) {
13007 if (isInitList) {
13008 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13009 return;
13010 }
13011
13012 // Don't warn on arrays since they can be treated as pointers.
13013 if (E->getType()->canDecayToPointerType()) return;
13014
13015 // Warn when a non-static method call is followed by non-static member
13016 // field accesses, which is followed by a DeclRefExpr.
13017 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13018 bool Warn = (MD && !MD->isStatic());
13019 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13020 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13021 if (!isa<FieldDecl>(ME->getMemberDecl()))
13022 Warn = false;
13023 Base = ME->getBase()->IgnoreParenImpCasts();
13024 }
13025
13026 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13027 if (Warn)
13028 HandleDeclRefExpr(DRE);
13029 return;
13030 }
13031
13032 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13033 // Visit that expression.
13034 Visit(Base);
13035 }
13036
13037 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13038 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13039 Expr *Callee = E->getCallee();
13040
13041 if (isa<UnresolvedLookupExpr>(Callee))
13042 return Inherited::VisitCXXOperatorCallExpr(E);
13043
13044 Visit(Callee);
13045 for (auto Arg: E->arguments())
13046 HandleValue(Arg->IgnoreParenImpCasts());
13047 }
13048
13049 void VisitLambdaExpr(LambdaExpr *E) {
13050 if (!isInCXXOperatorCall) {
13051 Inherited::VisitLambdaExpr(E);
13052 return;
13053 }
13054
13055 for (Expr *Init : E->capture_inits())
13056 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13057 HandleDeclRefExpr(DRE);
13058 else if (Init)
13059 Visit(Init);
13060 }
13061
13062 void VisitUnaryOperator(UnaryOperator *E) {
13063 // For POD record types, addresses of its own members are well-defined.
13064 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13066 if (!isPODType)
13067 HandleValue(E->getSubExpr());
13068 return;
13069 }
13070
13071 if (E->isIncrementDecrementOp()) {
13072 HandleValue(E->getSubExpr());
13073 return;
13074 }
13075
13076 Inherited::VisitUnaryOperator(E);
13077 }
13078
13079 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13080
13081 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13082 if (E->getConstructor()->isCopyConstructor()) {
13083 Expr *ArgExpr = E->getArg(0);
13084 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13085 if (ILE->getNumInits() == 1)
13086 ArgExpr = ILE->getInit(0);
13087 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13088 if (ICE->getCastKind() == CK_NoOp)
13089 ArgExpr = ICE->getSubExpr();
13090 HandleValue(ArgExpr);
13091 return;
13092 }
13093 Inherited::VisitCXXConstructExpr(E);
13094 }
13095
13096 void VisitCallExpr(CallExpr *E) {
13097 // Treat std::move as a use.
13098 if (E->isCallToStdMove()) {
13099 HandleValue(E->getArg(0));
13100 return;
13101 }
13102
13103 Inherited::VisitCallExpr(E);
13104 }
13105
13106 void VisitBinaryOperator(BinaryOperator *E) {
13107 if (E->isCompoundAssignmentOp()) {
13108 HandleValue(E->getLHS());
13109 Visit(E->getRHS());
13110 return;
13111 }
13112
13113 Inherited::VisitBinaryOperator(E);
13114 }
13115
13116 // A custom visitor for BinaryConditionalOperator is needed because the
13117 // regular visitor would check the condition and true expression separately
13118 // but both point to the same place giving duplicate diagnostics.
13119 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13120 Visit(E->getCond());
13121 Visit(E->getFalseExpr());
13122 }
13123
13124 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13125 Decl* ReferenceDecl = DRE->getDecl();
13126 if (OrigDecl != ReferenceDecl) return;
13127 unsigned diag;
13128 if (isReferenceType) {
13129 diag = diag::warn_uninit_self_reference_in_reference_init;
13130 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13131 diag = diag::warn_static_self_reference_in_init;
13132 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13133 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13134 DRE->getDecl()->getType()->isRecordType()) {
13135 diag = diag::warn_uninit_self_reference_in_init;
13136 } else {
13137 // Local variables will be handled by the CFG analysis.
13138 return;
13139 }
13140
13141 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13142 S.PDiag(diag)
13143 << DRE->getDecl() << OrigDecl->getLocation()
13144 << DRE->getSourceRange());
13145 }
13146 };
13147
13148 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13149 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13150 bool DirectInit) {
13151 // Parameters arguments are occassionially constructed with itself,
13152 // for instance, in recursive functions. Skip them.
13153 if (isa<ParmVarDecl>(OrigDecl))
13154 return;
13155
13156 // Skip checking for file-scope constexpr variables - constant evaluation
13157 // will produce appropriate errors without needing runtime diagnostics.
13158 // Local constexpr should still emit runtime warnings.
13159 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13160 VD && VD->isConstexpr() && VD->isFileVarDecl())
13161 return;
13162
13163 E = E->IgnoreParens();
13164
13165 // Skip checking T a = a where T is not a record or reference type.
13166 // Doing so is a way to silence uninitialized warnings.
13167 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13168 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13169 if (ICE->getCastKind() == CK_LValueToRValue)
13170 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13171 if (DRE->getDecl() == OrigDecl)
13172 return;
13173
13174 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13175 }
13176} // end anonymous namespace
13177
13178namespace {
13179 // Simple wrapper to add the name of a variable or (if no variable is
13180 // available) a DeclarationName into a diagnostic.
13181 struct VarDeclOrName {
13182 VarDecl *VDecl;
13183 DeclarationName Name;
13184
13185 friend const Sema::SemaDiagnosticBuilder &
13186 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13187 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13188 }
13189 };
13190} // end anonymous namespace
13191
13194 TypeSourceInfo *TSI,
13195 SourceRange Range, bool DirectInit,
13196 Expr *Init) {
13197 bool IsInitCapture = !VDecl;
13198 assert((!VDecl || !VDecl->isInitCapture()) &&
13199 "init captures are expected to be deduced prior to initialization");
13200
13201 VarDeclOrName VN{VDecl, Name};
13202
13203 DeducedType *Deduced = Type->getContainedDeducedType();
13204 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13205
13206 // Diagnose auto array declarations in C23, unless it's a supported extension.
13207 if (getLangOpts().C23 && Type->isArrayType() &&
13208 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13209 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13210 << (int)Deduced->getContainedAutoType()->getKeyword()
13211 << /*in array decl*/ 23 << Range;
13212 return QualType();
13213 }
13214
13215 // C++11 [dcl.spec.auto]p3
13216 if (!Init) {
13217 assert(VDecl && "no init for init capture deduction?");
13218
13219 // Except for class argument deduction, and then for an initializing
13220 // declaration only, i.e. no static at class scope or extern.
13222 VDecl->hasExternalStorage() ||
13223 VDecl->isStaticDataMember()) {
13224 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13225 << VDecl->getDeclName() << Type;
13226 return QualType();
13227 }
13228 }
13229
13230 ArrayRef<Expr*> DeduceInits;
13231 if (Init)
13232 DeduceInits = Init;
13233
13234 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13235 if (DirectInit && PL)
13236 DeduceInits = PL->exprs();
13237
13239 assert(VDecl && "non-auto type for init capture deduction?");
13242 VDecl->getLocation(), DirectInit, Init);
13243 // FIXME: Initialization should not be taking a mutable list of inits.
13244 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13245 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13246 InitsCopy);
13247 }
13248
13249 if (DirectInit) {
13250 if (auto *IL = dyn_cast<InitListExpr>(Init))
13251 DeduceInits = IL->inits();
13252 }
13253
13254 // Deduction only works if we have exactly one source expression.
13255 if (DeduceInits.empty()) {
13256 // It isn't possible to write this directly, but it is possible to
13257 // end up in this situation with "auto x(some_pack...);"
13258 Diag(Init->getBeginLoc(), IsInitCapture
13259 ? diag::err_init_capture_no_expression
13260 : diag::err_auto_var_init_no_expression)
13261 << VN << Type << Range;
13262 return QualType();
13263 }
13264
13265 if (DeduceInits.size() > 1) {
13266 Diag(DeduceInits[1]->getBeginLoc(),
13267 IsInitCapture ? diag::err_init_capture_multiple_expressions
13268 : diag::err_auto_var_init_multiple_expressions)
13269 << VN << Type << Range;
13270 return QualType();
13271 }
13272
13273 Expr *DeduceInit = DeduceInits[0];
13274 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13275 Diag(Init->getBeginLoc(), IsInitCapture
13276 ? diag::err_init_capture_paren_braces
13277 : diag::err_auto_var_init_paren_braces)
13278 << isa<InitListExpr>(Init) << VN << Type << Range;
13279 return QualType();
13280 }
13281
13282 // Expressions default to 'id' when we're in a debugger.
13283 bool DefaultedAnyToId = false;
13284 if (getLangOpts().DebuggerCastResultToId &&
13285 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13287 if (Result.isInvalid()) {
13288 return QualType();
13289 }
13290 Init = Result.get();
13291 DefaultedAnyToId = true;
13292 }
13293
13294 // C++ [dcl.decomp]p1:
13295 // If the assignment-expression [...] has array type A and no ref-qualifier
13296 // is present, e has type cv A
13297 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13298 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13299 DeduceInit->getType()->isConstantArrayType())
13300 return Context.getQualifiedType(DeduceInit->getType(),
13301 Type.getQualifiers());
13302
13303 QualType DeducedType;
13304 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13306 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13309 if (!IsInitCapture)
13310 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13311 else if (isa<InitListExpr>(Init))
13312 Diag(Range.getBegin(),
13313 diag::err_init_capture_deduction_failure_from_init_list)
13314 << VN
13315 << (DeduceInit->getType().isNull() ? TSI->getType()
13316 : DeduceInit->getType())
13317 << DeduceInit->getSourceRange();
13318 else
13319 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13320 << VN << TSI->getType()
13321 << (DeduceInit->getType().isNull() ? TSI->getType()
13322 : DeduceInit->getType())
13323 << DeduceInit->getSourceRange();
13324 }
13325
13326 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13327 // 'id' instead of a specific object type prevents most of our usual
13328 // checks.
13329 // We only want to warn outside of template instantiations, though:
13330 // inside a template, the 'id' could have come from a parameter.
13331 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13332 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13333 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13334 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13335 }
13336
13337 return DeducedType;
13338}
13339
13341 Expr *Init) {
13342 assert(!Init || !Init->containsErrors());
13344 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13345 VDecl->getSourceRange(), DirectInit, Init);
13346 if (DeducedType.isNull()) {
13347 VDecl->setInvalidDecl();
13348 return true;
13349 }
13350
13351 VDecl->setType(DeducedType);
13352 assert(VDecl->isLinkageValid());
13353
13354 // In ARC, infer lifetime.
13355 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13356 VDecl->setInvalidDecl();
13357
13358 if (getLangOpts().OpenCL)
13360
13361 if (getLangOpts().HLSL)
13362 HLSL().deduceAddressSpace(VDecl);
13363
13364 // If this is a redeclaration, check that the type we just deduced matches
13365 // the previously declared type.
13366 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13367 // We never need to merge the type, because we cannot form an incomplete
13368 // array of auto, nor deduce such a type.
13369 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13370 }
13371
13372 // Check the deduced type is valid for a variable declaration.
13374 return VDecl->isInvalidDecl();
13375}
13376
13378 SourceLocation Loc) {
13379 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13380 Init = EWC->getSubExpr();
13381
13382 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13383 Init = CE->getSubExpr();
13384
13385 QualType InitType = Init->getType();
13388 "shouldn't be called if type doesn't have a non-trivial C struct");
13389 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13390 for (auto *I : ILE->inits()) {
13391 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13392 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13393 continue;
13394 SourceLocation SL = I->getExprLoc();
13395 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13396 }
13397 return;
13398 }
13399
13402 checkNonTrivialCUnion(InitType, Loc,
13404 NTCUK_Init);
13405 } else {
13406 // Assume all other explicit initializers involving copying some existing
13407 // object.
13408 // TODO: ignore any explicit initializers where we can guarantee
13409 // copy-elision.
13412 NTCUK_Copy);
13413 }
13414}
13415
13416namespace {
13417
13418bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13419 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13420 // in the source code or implicitly by the compiler if it is in a union
13421 // defined in a system header and has non-trivial ObjC ownership
13422 // qualifications. We don't want those fields to participate in determining
13423 // whether the containing union is non-trivial.
13424 return FD->hasAttr<UnavailableAttr>();
13425}
13426
13427struct DiagNonTrivalCUnionDefaultInitializeVisitor
13428 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13429 void> {
13430 using Super =
13431 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13432 void>;
13433
13434 DiagNonTrivalCUnionDefaultInitializeVisitor(
13435 QualType OrigTy, SourceLocation OrigLoc,
13436 NonTrivialCUnionContext UseContext, Sema &S)
13437 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13438
13439 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13440 const FieldDecl *FD, bool InNonTrivialUnion) {
13441 if (const auto *AT = S.Context.getAsArrayType(QT))
13442 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13443 InNonTrivialUnion);
13444 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13445 }
13446
13447 void visitARCStrong(QualType QT, const FieldDecl *FD,
13448 bool InNonTrivialUnion) {
13449 if (InNonTrivialUnion)
13450 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13451 << 1 << 0 << QT << FD->getName();
13452 }
13453
13454 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13455 if (InNonTrivialUnion)
13456 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13457 << 1 << 0 << QT << FD->getName();
13458 }
13459
13460 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13461 const auto *RD = QT->castAsRecordDecl();
13462 if (RD->isUnion()) {
13463 if (OrigLoc.isValid()) {
13464 bool IsUnion = false;
13465 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13466 IsUnion = OrigRD->isUnion();
13467 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13468 << 0 << OrigTy << IsUnion << UseContext;
13469 // Reset OrigLoc so that this diagnostic is emitted only once.
13470 OrigLoc = SourceLocation();
13471 }
13472 InNonTrivialUnion = true;
13473 }
13474
13475 if (InNonTrivialUnion)
13476 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13477 << 0 << 0 << QT.getUnqualifiedType() << "";
13478
13479 for (const FieldDecl *FD : RD->fields())
13480 if (!shouldIgnoreForRecordTriviality(FD))
13481 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13482 }
13483
13484 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13485
13486 // The non-trivial C union type or the struct/union type that contains a
13487 // non-trivial C union.
13488 QualType OrigTy;
13489 SourceLocation OrigLoc;
13490 NonTrivialCUnionContext UseContext;
13491 Sema &S;
13492};
13493
13494struct DiagNonTrivalCUnionDestructedTypeVisitor
13495 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13496 using Super =
13497 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13498
13499 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13500 SourceLocation OrigLoc,
13501 NonTrivialCUnionContext UseContext,
13502 Sema &S)
13503 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13504
13505 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13506 const FieldDecl *FD, bool InNonTrivialUnion) {
13507 if (const auto *AT = S.Context.getAsArrayType(QT))
13508 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13509 InNonTrivialUnion);
13510 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13511 }
13512
13513 void visitARCStrong(QualType QT, const FieldDecl *FD,
13514 bool InNonTrivialUnion) {
13515 if (InNonTrivialUnion)
13516 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13517 << 1 << 1 << QT << FD->getName();
13518 }
13519
13520 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13521 if (InNonTrivialUnion)
13522 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13523 << 1 << 1 << QT << FD->getName();
13524 }
13525
13526 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13527 const auto *RD = QT->castAsRecordDecl();
13528 if (RD->isUnion()) {
13529 if (OrigLoc.isValid()) {
13530 bool IsUnion = false;
13531 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13532 IsUnion = OrigRD->isUnion();
13533 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13534 << 1 << OrigTy << IsUnion << UseContext;
13535 // Reset OrigLoc so that this diagnostic is emitted only once.
13536 OrigLoc = SourceLocation();
13537 }
13538 InNonTrivialUnion = true;
13539 }
13540
13541 if (InNonTrivialUnion)
13542 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13543 << 0 << 1 << QT.getUnqualifiedType() << "";
13544
13545 for (const FieldDecl *FD : RD->fields())
13546 if (!shouldIgnoreForRecordTriviality(FD))
13547 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13548 }
13549
13550 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13551 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13552 bool InNonTrivialUnion) {}
13553
13554 // The non-trivial C union type or the struct/union type that contains a
13555 // non-trivial C union.
13556 QualType OrigTy;
13557 SourceLocation OrigLoc;
13558 NonTrivialCUnionContext UseContext;
13559 Sema &S;
13560};
13561
13562struct DiagNonTrivalCUnionCopyVisitor
13563 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13564 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13565
13566 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13567 NonTrivialCUnionContext UseContext, Sema &S)
13568 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13569
13570 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13571 const FieldDecl *FD, bool InNonTrivialUnion) {
13572 if (const auto *AT = S.Context.getAsArrayType(QT))
13573 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13574 InNonTrivialUnion);
13575 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13576 }
13577
13578 void visitARCStrong(QualType QT, const FieldDecl *FD,
13579 bool InNonTrivialUnion) {
13580 if (InNonTrivialUnion)
13581 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13582 << 1 << 2 << QT << FD->getName();
13583 }
13584
13585 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13586 if (InNonTrivialUnion)
13587 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13588 << 1 << 2 << QT << FD->getName();
13589 }
13590
13591 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13592 const auto *RD = QT->castAsRecordDecl();
13593 if (RD->isUnion()) {
13594 if (OrigLoc.isValid()) {
13595 bool IsUnion = false;
13596 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13597 IsUnion = OrigRD->isUnion();
13598 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13599 << 2 << OrigTy << IsUnion << UseContext;
13600 // Reset OrigLoc so that this diagnostic is emitted only once.
13601 OrigLoc = SourceLocation();
13602 }
13603 InNonTrivialUnion = true;
13604 }
13605
13606 if (InNonTrivialUnion)
13607 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13608 << 0 << 2 << QT.getUnqualifiedType() << "";
13609
13610 for (const FieldDecl *FD : RD->fields())
13611 if (!shouldIgnoreForRecordTriviality(FD))
13612 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13613 }
13614
13615 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13616 if (InNonTrivialUnion)
13617 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13618 << 1 << 2 << QT << FD->getName();
13619 }
13620
13621 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13622 const FieldDecl *FD, bool InNonTrivialUnion) {}
13623 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13624 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13625 bool InNonTrivialUnion) {}
13626
13627 // The non-trivial C union type or the struct/union type that contains a
13628 // non-trivial C union.
13629 QualType OrigTy;
13630 SourceLocation OrigLoc;
13631 NonTrivialCUnionContext UseContext;
13632 Sema &S;
13633};
13634
13635} // namespace
13636
13638 NonTrivialCUnionContext UseContext,
13639 unsigned NonTrivialKind) {
13643 "shouldn't be called if type doesn't have a non-trivial C union");
13644
13645 if ((NonTrivialKind & NTCUK_Init) &&
13647 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13648 .visit(QT, nullptr, false);
13649 if ((NonTrivialKind & NTCUK_Destruct) &&
13651 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13652 .visit(QT, nullptr, false);
13653 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13654 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13655 .visit(QT, nullptr, false);
13656}
13657
13659 const VarDecl *Dcl) {
13660 if (!getLangOpts().CPlusPlus)
13661 return false;
13662
13663 // We only need to warn if the definition is in a header file, so wait to
13664 // diagnose until we've seen the definition.
13665 if (!Dcl->isThisDeclarationADefinition())
13666 return false;
13667
13668 // If an object is defined in a source file, its definition can't get
13669 // duplicated since it will never appear in more than one TU.
13671 return false;
13672
13673 // If the variable we're looking at is a static local, then we actually care
13674 // about the properties of the function containing it.
13675 const ValueDecl *Target = Dcl;
13676 // VarDecls and FunctionDecls have different functions for checking
13677 // inline-ness, and whether they were originally templated, so we have to
13678 // call the appropriate functions manually.
13679 bool TargetIsInline = Dcl->isInline();
13680 bool TargetWasTemplated =
13682
13683 // Update the Target and TargetIsInline property if necessary
13684 if (Dcl->isStaticLocal()) {
13685 const DeclContext *Ctx = Dcl->getDeclContext();
13686 if (!Ctx)
13687 return false;
13688
13689 const FunctionDecl *FunDcl =
13690 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13691 if (!FunDcl)
13692 return false;
13693
13694 Target = FunDcl;
13695 // IsInlined() checks for the C++ inline property
13696 TargetIsInline = FunDcl->isInlined();
13697 TargetWasTemplated =
13699 }
13700
13701 // Non-inline functions/variables can only legally appear in one TU
13702 // unless they were part of a template. Unfortunately, making complex
13703 // template instantiations visible is infeasible in practice, since
13704 // everything the template depends on also has to be visible. To avoid
13705 // giving impractical-to-fix warnings, don't warn if we're inside
13706 // something that was templated, even on inline stuff.
13707 if (!TargetIsInline || TargetWasTemplated)
13708 return false;
13709
13710 // If the object isn't hidden, the dynamic linker will prevent duplication.
13711 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13712
13713 // The target is "hidden" (from the dynamic linker) if:
13714 // 1. On posix, it has hidden visibility, or
13715 // 2. On windows, it has no import/export annotation, and neither does the
13716 // class which directly contains it.
13717 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13718 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13719 return false;
13720
13721 // If the variable isn't directly annotated, check to see if it's a member
13722 // of an annotated class.
13723 const CXXRecordDecl *Ctx =
13724 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13725 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13726 return false;
13727
13728 } else if (Lnk.getVisibility() != HiddenVisibility) {
13729 // Posix case
13730 return false;
13731 }
13732
13733 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13735 return false;
13736
13737 return true;
13738}
13739
13740// Determine whether the object seems mutable for the purpose of diagnosing
13741// possible unique object duplication, i.e. non-const-qualified, and
13742// not an always-constant type like a function.
13743// Not perfect: doesn't account for mutable members, for example, or
13744// elements of container types.
13745// For nested pointers, any individual level being non-const is sufficient.
13746static bool looksMutable(QualType T, const ASTContext &Ctx) {
13747 T = T.getNonReferenceType();
13748 if (T->isFunctionType())
13749 return false;
13750 if (!T.isConstant(Ctx))
13751 return true;
13752 if (T->isPointerType())
13753 return looksMutable(T->getPointeeType(), Ctx);
13754 return false;
13755}
13756
13758 // If this object has external linkage and hidden visibility, it might be
13759 // duplicated when built into a shared library, which causes problems if it's
13760 // mutable (since the copies won't be in sync) or its initialization has side
13761 // effects (since it will run once per copy instead of once globally).
13762
13763 // Don't diagnose if we're inside a template, because it's not practical to
13764 // fix the warning in most cases.
13765 if (!VD->isTemplated() &&
13767
13768 QualType Type = VD->getType();
13769 if (looksMutable(Type, VD->getASTContext())) {
13770 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13771 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13772 }
13773
13774 // To keep false positives low, only warn if we're certain that the
13775 // initializer has side effects. Don't warn on operator new, since a mutable
13776 // pointer will trigger the previous warning, and an immutable pointer
13777 // getting duplicated just results in a little extra memory usage.
13778 const Expr *Init = VD->getAnyInitializer();
13779 if (Init &&
13780 Init->HasSideEffects(VD->getASTContext(),
13781 /*IncludePossibleEffects=*/false) &&
13782 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13783 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13784 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13785 }
13786 }
13787}
13788
13790 auto ResetDeclForInitializer = llvm::make_scope_exit([this]() {
13791 if (this->ExprEvalContexts.empty())
13792 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13793 });
13794
13795 // If there is no declaration, there was an error parsing it. Just ignore
13796 // the initializer.
13797 if (!RealDecl) {
13798 return;
13799 }
13800
13801 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13802 if (!Method->isInvalidDecl()) {
13803 // Pure-specifiers are handled in ActOnPureSpecifier.
13804 Diag(Method->getLocation(), diag::err_member_function_initialization)
13805 << Method->getDeclName() << Init->getSourceRange();
13806 Method->setInvalidDecl();
13807 }
13808 return;
13809 }
13810
13811 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13812 if (!VDecl) {
13813 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13814 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13815 RealDecl->setInvalidDecl();
13816 return;
13817 }
13818
13819 if (VDecl->isInvalidDecl()) {
13820 ExprResult Recovery =
13821 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13822 if (Expr *E = Recovery.get())
13823 VDecl->setInit(E);
13824 return;
13825 }
13826
13827 // WebAssembly tables can't be used to initialise a variable.
13828 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13829 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13830 VDecl->setInvalidDecl();
13831 return;
13832 }
13833
13834 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13835 if (VDecl->getType()->isUndeducedType()) {
13836 if (Init->containsErrors()) {
13837 // Invalidate the decl as we don't know the type for recovery-expr yet.
13838 RealDecl->setInvalidDecl();
13839 VDecl->setInit(Init);
13840 return;
13841 }
13842
13844 return;
13845 }
13846
13847 this->CheckAttributesOnDeducedType(RealDecl);
13848
13849 // dllimport cannot be used on variable definitions.
13850 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13851 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13852 VDecl->setInvalidDecl();
13853 return;
13854 }
13855
13856 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13857 // the identifier has external or internal linkage, the declaration shall
13858 // have no initializer for the identifier.
13859 // C++14 [dcl.init]p5 is the same restriction for C++.
13860 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13861 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13862 VDecl->setInvalidDecl();
13863 return;
13864 }
13865
13866 if (!VDecl->getType()->isDependentType()) {
13867 // A definition must end up with a complete type, which means it must be
13868 // complete with the restriction that an array type might be completed by
13869 // the initializer; note that later code assumes this restriction.
13870 QualType BaseDeclType = VDecl->getType();
13871 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13872 BaseDeclType = Array->getElementType();
13873 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13874 diag::err_typecheck_decl_incomplete_type)) {
13875 RealDecl->setInvalidDecl();
13876 return;
13877 }
13878
13879 // The variable can not have an abstract class type.
13880 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13881 diag::err_abstract_type_in_decl,
13883 VDecl->setInvalidDecl();
13884 }
13885
13886 // C++ [module.import/6]
13887 // ...
13888 // A header unit shall not contain a definition of a non-inline function or
13889 // variable whose name has external linkage.
13890 //
13891 // We choose to allow weak & selectany definitions, as they are common in
13892 // headers, and have semantics similar to inline definitions which are allowed
13893 // in header units.
13894 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13895 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13896 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13897 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13899 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13900 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13901 VDecl->setInvalidDecl();
13902 }
13903
13904 // If adding the initializer will turn this declaration into a definition,
13905 // and we already have a definition for this variable, diagnose or otherwise
13906 // handle the situation.
13907 if (VarDecl *Def = VDecl->getDefinition())
13908 if (Def != VDecl &&
13909 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13911 checkVarDeclRedefinition(Def, VDecl))
13912 return;
13913
13914 if (getLangOpts().CPlusPlus) {
13915 // C++ [class.static.data]p4
13916 // If a static data member is of const integral or const
13917 // enumeration type, its declaration in the class definition can
13918 // specify a constant-initializer which shall be an integral
13919 // constant expression (5.19). In that case, the member can appear
13920 // in integral constant expressions. The member shall still be
13921 // defined in a namespace scope if it is used in the program and the
13922 // namespace scope definition shall not contain an initializer.
13923 //
13924 // We already performed a redefinition check above, but for static
13925 // data members we also need to check whether there was an in-class
13926 // declaration with an initializer.
13927 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13928 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13929 << VDecl->getDeclName();
13930 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13931 diag::note_previous_initializer)
13932 << 0;
13933 return;
13934 }
13935
13937 VDecl->setInvalidDecl();
13938 return;
13939 }
13940 }
13941
13942 // If the variable has an initializer and local storage, check whether
13943 // anything jumps over the initialization.
13944 if (VDecl->hasLocalStorage())
13946
13947 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13948 // a kernel function cannot be initialized."
13949 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13950 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13951 VDecl->setInvalidDecl();
13952 return;
13953 }
13954
13955 // The LoaderUninitialized attribute acts as a definition (of undef).
13956 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13957 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13958 VDecl->setInvalidDecl();
13959 return;
13960 }
13961
13962 if (getLangOpts().HLSL)
13963 if (!HLSL().handleInitialization(VDecl, Init))
13964 return;
13965
13966 // Get the decls type and save a reference for later, since
13967 // CheckInitializerTypes may change it.
13968 QualType DclT = VDecl->getType(), SavT = DclT;
13969
13970 // Expressions default to 'id' when we're in a debugger
13971 // and we are assigning it to a variable of Objective-C pointer type.
13972 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13973 Init->getType() == Context.UnknownAnyTy) {
13975 if (!Result.isUsable()) {
13976 VDecl->setInvalidDecl();
13977 return;
13978 }
13979 Init = Result.get();
13980 }
13981
13982 // Perform the initialization.
13983 bool InitializedFromParenListExpr = false;
13984 bool IsParenListInit = false;
13985 if (!VDecl->isInvalidDecl()) {
13988 VDecl->getLocation(), DirectInit, Init);
13989
13990 MultiExprArg Args = Init;
13991 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
13992 Args =
13993 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13994 InitializedFromParenListExpr = true;
13995 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
13996 Args = CXXDirectInit->getInitExprs();
13997 InitializedFromParenListExpr = true;
13998 }
13999
14000 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14001 /*TopLevelOfInitList=*/false,
14002 /*TreatUnavailableAsInvalid=*/false);
14003 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14004 if (!Result.isUsable()) {
14005 // If the provided initializer fails to initialize the var decl,
14006 // we attach a recovery expr for better recovery.
14007 auto RecoveryExpr =
14008 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14009 if (RecoveryExpr.get())
14010 VDecl->setInit(RecoveryExpr.get());
14011 // In general, for error recovery purposes, the initializer doesn't play
14012 // part in the valid bit of the declaration. There are a few exceptions:
14013 // 1) if the var decl has a deduced auto type, and the type cannot be
14014 // deduced by an invalid initializer;
14015 // 2) if the var decl is a decomposition decl with a non-deduced type,
14016 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14017 // Case 1) was already handled elsewhere.
14018 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14019 VDecl->setInvalidDecl();
14020 return;
14021 }
14022
14023 Init = Result.getAs<Expr>();
14024 IsParenListInit = !InitSeq.steps().empty() &&
14025 InitSeq.step_begin()->Kind ==
14027 QualType VDeclType = VDecl->getType();
14028 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14029 !VDeclType->isDependentType() &&
14030 Context.getAsIncompleteArrayType(VDeclType) &&
14031 Context.getAsIncompleteArrayType(Init->getType())) {
14032 // Bail out if it is not possible to deduce array size from the
14033 // initializer.
14034 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14035 << VDeclType;
14036 VDecl->setInvalidDecl();
14037 return;
14038 }
14039 }
14040
14041 // Check for self-references within variable initializers.
14042 // Variables declared within a function/method body (except for references)
14043 // are handled by a dataflow analysis.
14044 // This is undefined behavior in C++, but valid in C.
14045 if (getLangOpts().CPlusPlus)
14046 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14047 VDecl->getType()->isReferenceType())
14048 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14049
14050 // If the type changed, it means we had an incomplete type that was
14051 // completed by the initializer. For example:
14052 // int ary[] = { 1, 3, 5 };
14053 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14054 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14055 VDecl->setType(DclT);
14056
14057 if (!VDecl->isInvalidDecl()) {
14058 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14059
14060 if (VDecl->hasAttr<BlocksAttr>())
14061 ObjC().checkRetainCycles(VDecl, Init);
14062
14063 // It is safe to assign a weak reference into a strong variable.
14064 // Although this code can still have problems:
14065 // id x = self.weakProp;
14066 // id y = self.weakProp;
14067 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14068 // paths through the function. This should be revisited if
14069 // -Wrepeated-use-of-weak is made flow-sensitive.
14070 if (FunctionScopeInfo *FSI = getCurFunction())
14071 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14073 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14074 Init->getBeginLoc()))
14075 FSI->markSafeWeakUse(Init);
14076 }
14077
14078 // The initialization is usually a full-expression.
14079 //
14080 // FIXME: If this is a braced initialization of an aggregate, it is not
14081 // an expression, and each individual field initializer is a separate
14082 // full-expression. For instance, in:
14083 //
14084 // struct Temp { ~Temp(); };
14085 // struct S { S(Temp); };
14086 // struct T { S a, b; } t = { Temp(), Temp() }
14087 //
14088 // we should destroy the first Temp before constructing the second.
14091 /*DiscardedValue*/ false, VDecl->isConstexpr());
14092 if (!Result.isUsable()) {
14093 VDecl->setInvalidDecl();
14094 return;
14095 }
14096 Init = Result.get();
14097
14098 // Attach the initializer to the decl.
14099 VDecl->setInit(Init);
14100
14101 if (VDecl->isLocalVarDecl()) {
14102 // Don't check the initializer if the declaration is malformed.
14103 if (VDecl->isInvalidDecl()) {
14104 // do nothing
14105
14106 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14107 // This is true even in C++ for OpenCL.
14108 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14110
14111 // Otherwise, C++ does not restrict the initializer.
14112 } else if (getLangOpts().CPlusPlus) {
14113 // do nothing
14114
14115 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14116 // static storage duration shall be constant expressions or string literals.
14117 } else if (VDecl->getStorageClass() == SC_Static) {
14119
14120 // C89 is stricter than C99 for aggregate initializers.
14121 // C89 6.5.7p3: All the expressions [...] in an initializer list
14122 // for an object that has aggregate or union type shall be
14123 // constant expressions.
14124 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14126 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14127 }
14128
14129 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14130 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14131 if (VDecl->hasLocalStorage())
14132 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14133 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14134 VDecl->getLexicalDeclContext()->isRecord()) {
14135 // This is an in-class initialization for a static data member, e.g.,
14136 //
14137 // struct S {
14138 // static const int value = 17;
14139 // };
14140
14141 // C++ [class.mem]p4:
14142 // A member-declarator can contain a constant-initializer only
14143 // if it declares a static member (9.4) of const integral or
14144 // const enumeration type, see 9.4.2.
14145 //
14146 // C++11 [class.static.data]p3:
14147 // If a non-volatile non-inline const static data member is of integral
14148 // or enumeration type, its declaration in the class definition can
14149 // specify a brace-or-equal-initializer in which every initializer-clause
14150 // that is an assignment-expression is a constant expression. A static
14151 // data member of literal type can be declared in the class definition
14152 // with the constexpr specifier; if so, its declaration shall specify a
14153 // brace-or-equal-initializer in which every initializer-clause that is
14154 // an assignment-expression is a constant expression.
14155
14156 // Do nothing on dependent types.
14157 if (DclT->isDependentType()) {
14158
14159 // Allow any 'static constexpr' members, whether or not they are of literal
14160 // type. We separately check that every constexpr variable is of literal
14161 // type.
14162 } else if (VDecl->isConstexpr()) {
14163
14164 // Require constness.
14165 } else if (!DclT.isConstQualified()) {
14166 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14167 << Init->getSourceRange();
14168 VDecl->setInvalidDecl();
14169
14170 // We allow integer constant expressions in all cases.
14171 } else if (DclT->isIntegralOrEnumerationType()) {
14173 // In C++11, a non-constexpr const static data member with an
14174 // in-class initializer cannot be volatile.
14175 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14176
14177 // We allow foldable floating-point constants as an extension.
14178 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14179 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14180 // it anyway and provide a fixit to add the 'constexpr'.
14181 if (getLangOpts().CPlusPlus11) {
14182 Diag(VDecl->getLocation(),
14183 diag::ext_in_class_initializer_float_type_cxx11)
14184 << DclT << Init->getSourceRange();
14185 Diag(VDecl->getBeginLoc(),
14186 diag::note_in_class_initializer_float_type_cxx11)
14187 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14188 } else {
14189 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14190 << DclT << Init->getSourceRange();
14191
14192 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14193 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14194 << Init->getSourceRange();
14195 VDecl->setInvalidDecl();
14196 }
14197 }
14198
14199 // Suggest adding 'constexpr' in C++11 for literal types.
14200 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14201 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14202 << DclT << Init->getSourceRange()
14203 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14204 VDecl->setConstexpr(true);
14205
14206 } else {
14207 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14208 << DclT << Init->getSourceRange();
14209 VDecl->setInvalidDecl();
14210 }
14211 } else if (VDecl->isFileVarDecl()) {
14212 // In C, extern is typically used to avoid tentative definitions when
14213 // declaring variables in headers, but adding an initializer makes it a
14214 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14215 // In C++, extern is often used to give implicitly static const variables
14216 // external linkage, so don't warn in that case. If selectany is present,
14217 // this might be header code intended for C and C++ inclusion, so apply the
14218 // C++ rules.
14219 if (VDecl->getStorageClass() == SC_Extern &&
14220 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14221 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14222 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14224 Diag(VDecl->getLocation(), diag::warn_extern_init);
14225
14226 // In Microsoft C++ mode, a const variable defined in namespace scope has
14227 // external linkage by default if the variable is declared with
14228 // __declspec(dllexport).
14229 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14231 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14232 VDecl->setStorageClass(SC_Extern);
14233
14234 // C99 6.7.8p4. All file scoped initializers need to be constant.
14235 // Avoid duplicate diagnostics for constexpr variables.
14236 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14237 !VDecl->isConstexpr())
14239 }
14240
14241 QualType InitType = Init->getType();
14242 if (!InitType.isNull() &&
14246
14247 // We will represent direct-initialization similarly to copy-initialization:
14248 // int x(1); -as-> int x = 1;
14249 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14250 //
14251 // Clients that want to distinguish between the two forms, can check for
14252 // direct initializer using VarDecl::getInitStyle().
14253 // A major benefit is that clients that don't particularly care about which
14254 // exactly form was it (like the CodeGen) can handle both cases without
14255 // special case code.
14256
14257 // C++ 8.5p11:
14258 // The form of initialization (using parentheses or '=') matters
14259 // when the entity being initialized has class type.
14260 if (InitializedFromParenListExpr) {
14261 assert(DirectInit && "Call-style initializer must be direct init.");
14262 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14264 } else if (DirectInit) {
14265 // This must be list-initialization. No other way is direct-initialization.
14267 }
14268
14269 if (LangOpts.OpenMP &&
14270 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14271 VDecl->isFileVarDecl())
14272 DeclsToCheckForDeferredDiags.insert(VDecl);
14274
14275 if (LangOpts.OpenACC && !InitType.isNull())
14276 OpenACC().ActOnVariableInit(VDecl, InitType);
14277}
14278
14280 // Our main concern here is re-establishing invariants like "a
14281 // variable's type is either dependent or complete".
14282 if (!D || D->isInvalidDecl()) return;
14283
14284 VarDecl *VD = dyn_cast<VarDecl>(D);
14285 if (!VD) return;
14286
14287 // Bindings are not usable if we can't make sense of the initializer.
14288 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14289 for (auto *BD : DD->bindings())
14290 BD->setInvalidDecl();
14291
14292 // Auto types are meaningless if we can't make sense of the initializer.
14293 if (VD->getType()->isUndeducedType()) {
14294 D->setInvalidDecl();
14295 return;
14296 }
14297
14298 QualType Ty = VD->getType();
14299 if (Ty->isDependentType()) return;
14300
14301 // Require a complete type.
14303 Context.getBaseElementType(Ty),
14304 diag::err_typecheck_decl_incomplete_type)) {
14305 VD->setInvalidDecl();
14306 return;
14307 }
14308
14309 // Require a non-abstract type.
14310 if (RequireNonAbstractType(VD->getLocation(), Ty,
14311 diag::err_abstract_type_in_decl,
14313 VD->setInvalidDecl();
14314 return;
14315 }
14316
14317 // Don't bother complaining about constructors or destructors,
14318 // though.
14319}
14320
14322 // If there is no declaration, there was an error parsing it. Just ignore it.
14323 if (!RealDecl)
14324 return;
14325
14326 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14327 QualType Type = Var->getType();
14328
14329 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14330 if (isa<DecompositionDecl>(RealDecl)) {
14331 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14332 Var->setInvalidDecl();
14333 return;
14334 }
14335
14336 if (Type->isUndeducedType() &&
14337 DeduceVariableDeclarationType(Var, false, nullptr))
14338 return;
14339
14340 this->CheckAttributesOnDeducedType(RealDecl);
14341
14342 // C++11 [class.static.data]p3: A static data member can be declared with
14343 // the constexpr specifier; if so, its declaration shall specify
14344 // a brace-or-equal-initializer.
14345 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14346 // the definition of a variable [...] or the declaration of a static data
14347 // member.
14348 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14349 !Var->isThisDeclarationADemotedDefinition()) {
14350 if (Var->isStaticDataMember()) {
14351 // C++1z removes the relevant rule; the in-class declaration is always
14352 // a definition there.
14353 if (!getLangOpts().CPlusPlus17 &&
14354 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14355 Diag(Var->getLocation(),
14356 diag::err_constexpr_static_mem_var_requires_init)
14357 << Var;
14358 Var->setInvalidDecl();
14359 return;
14360 }
14361 } else {
14362 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14363 Var->setInvalidDecl();
14364 return;
14365 }
14366 }
14367
14368 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14369 // be initialized.
14370 if (!Var->isInvalidDecl() &&
14371 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14372 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14373 bool HasConstExprDefaultConstructor = false;
14374 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14375 for (auto *Ctor : RD->ctors()) {
14376 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14377 Ctor->getMethodQualifiers().getAddressSpace() ==
14379 HasConstExprDefaultConstructor = true;
14380 }
14381 }
14382 }
14383 if (!HasConstExprDefaultConstructor) {
14384 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14385 Var->setInvalidDecl();
14386 return;
14387 }
14388 }
14389
14390 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14391 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14392 Diag(Var->getLocation(), diag::err_specialization_const);
14393 Var->setInvalidDecl();
14394 return;
14395 }
14396
14397 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14398 if (Var->getStorageClass() == SC_Extern) {
14399 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14400 << Var;
14401 Var->setInvalidDecl();
14402 return;
14403 }
14404 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14405 diag::err_typecheck_decl_incomplete_type)) {
14406 Var->setInvalidDecl();
14407 return;
14408 }
14409 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14410 if (!RD->hasTrivialDefaultConstructor()) {
14411 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14412 Var->setInvalidDecl();
14413 return;
14414 }
14415 }
14416 // The declaration is uninitialized, no need for further checks.
14417 return;
14418 }
14419
14420 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14421 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14422 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14423 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14425 NTCUK_Init);
14426
14427 switch (DefKind) {
14429 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14430 break;
14431
14432 // We have an out-of-line definition of a static data member
14433 // that has an in-class initializer, so we type-check this like
14434 // a declaration.
14435 //
14436 [[fallthrough]];
14437
14439 // It's only a declaration.
14440
14441 // Block scope. C99 6.7p7: If an identifier for an object is
14442 // declared with no linkage (C99 6.2.2p6), the type for the
14443 // object shall be complete.
14444 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14445 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14446 RequireCompleteType(Var->getLocation(), Type,
14447 diag::err_typecheck_decl_incomplete_type))
14448 Var->setInvalidDecl();
14449
14450 // Make sure that the type is not abstract.
14451 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14452 RequireNonAbstractType(Var->getLocation(), Type,
14453 diag::err_abstract_type_in_decl,
14455 Var->setInvalidDecl();
14456 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14457 Var->getStorageClass() == SC_PrivateExtern) {
14458 Diag(Var->getLocation(), diag::warn_private_extern);
14459 Diag(Var->getLocation(), diag::note_private_extern);
14460 }
14461
14462 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14463 !Var->isInvalidDecl())
14464 ExternalDeclarations.push_back(Var);
14465
14466 return;
14467
14469 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14470 // object that has file scope without an initializer, and without a
14471 // storage-class specifier or with the storage-class specifier "static",
14472 // constitutes a tentative definition. Note: A tentative definition with
14473 // external linkage is valid (C99 6.2.2p5).
14474 if (!Var->isInvalidDecl()) {
14475 if (const IncompleteArrayType *ArrayT
14476 = Context.getAsIncompleteArrayType(Type)) {
14478 Var->getLocation(), ArrayT->getElementType(),
14479 diag::err_array_incomplete_or_sizeless_type))
14480 Var->setInvalidDecl();
14481 }
14482 if (Var->getStorageClass() == SC_Static) {
14483 // C99 6.9.2p3: If the declaration of an identifier for an object is
14484 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14485 // declared type shall not be an incomplete type.
14486 // NOTE: code such as the following
14487 // static struct s;
14488 // struct s { int a; };
14489 // is accepted by gcc. Hence here we issue a warning instead of
14490 // an error and we do not invalidate the static declaration.
14491 // NOTE: to avoid multiple warnings, only check the first declaration.
14492 if (Var->isFirstDecl())
14493 RequireCompleteType(Var->getLocation(), Type,
14494 diag::ext_typecheck_decl_incomplete_type,
14495 Type->isArrayType());
14496 }
14497 }
14498
14499 // Record the tentative definition; we're done.
14500 if (!Var->isInvalidDecl())
14501 TentativeDefinitions.push_back(Var);
14502 return;
14503 }
14504
14505 // Provide a specific diagnostic for uninitialized variable definitions
14506 // with incomplete array type, unless it is a global unbounded HLSL resource
14507 // array.
14508 if (Type->isIncompleteArrayType() &&
14509 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14511 if (Var->isConstexpr())
14512 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14513 << Var;
14514 else
14515 Diag(Var->getLocation(),
14516 diag::err_typecheck_incomplete_array_needs_initializer);
14517 Var->setInvalidDecl();
14518 return;
14519 }
14520
14521 // Provide a specific diagnostic for uninitialized variable
14522 // definitions with reference type.
14523 if (Type->isReferenceType()) {
14524 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14525 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14526 return;
14527 }
14528
14529 // Do not attempt to type-check the default initializer for a
14530 // variable with dependent type.
14531 if (Type->isDependentType())
14532 return;
14533
14534 if (Var->isInvalidDecl())
14535 return;
14536
14537 if (!Var->hasAttr<AliasAttr>()) {
14538 if (RequireCompleteType(Var->getLocation(),
14539 Context.getBaseElementType(Type),
14540 diag::err_typecheck_decl_incomplete_type)) {
14541 Var->setInvalidDecl();
14542 return;
14543 }
14544 } else {
14545 return;
14546 }
14547
14548 // The variable can not have an abstract class type.
14549 if (RequireNonAbstractType(Var->getLocation(), Type,
14550 diag::err_abstract_type_in_decl,
14552 Var->setInvalidDecl();
14553 return;
14554 }
14555
14556 // In C, if the definition is const-qualified and has no initializer, it
14557 // is left uninitialized unless it has static or thread storage duration.
14558 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14559 unsigned DiagID = diag::warn_default_init_const_unsafe;
14560 if (Var->getStorageDuration() == SD_Static ||
14561 Var->getStorageDuration() == SD_Thread)
14562 DiagID = diag::warn_default_init_const;
14563
14564 bool EmitCppCompat = !Diags.isIgnored(
14565 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14566 Var->getLocation());
14567
14568 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14569 }
14570
14571 // Check for jumps past the implicit initializer. C++0x
14572 // clarifies that this applies to a "variable with automatic
14573 // storage duration", not a "local variable".
14574 // C++11 [stmt.dcl]p3
14575 // A program that jumps from a point where a variable with automatic
14576 // storage duration is not in scope to a point where it is in scope is
14577 // ill-formed unless the variable has scalar type, class type with a
14578 // trivial default constructor and a trivial destructor, a cv-qualified
14579 // version of one of these types, or an array of one of the preceding
14580 // types and is declared without an initializer.
14581 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14582 if (const auto *CXXRecord =
14583 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14584 // Mark the function (if we're in one) for further checking even if the
14585 // looser rules of C++11 do not require such checks, so that we can
14586 // diagnose incompatibilities with C++98.
14587 if (!CXXRecord->isPOD())
14589 }
14590 }
14591 // In OpenCL, we can't initialize objects in the __local address space,
14592 // even implicitly, so don't synthesize an implicit initializer.
14593 if (getLangOpts().OpenCL &&
14594 Var->getType().getAddressSpace() == LangAS::opencl_local)
14595 return;
14596
14597 // Handle HLSL uninitialized decls
14598 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14599 return;
14600
14601 // HLSL input & push-constant variables are expected to be externally
14602 // initialized, even when marked `static`.
14603 if (getLangOpts().HLSL &&
14604 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14605 return;
14606
14607 // C++03 [dcl.init]p9:
14608 // If no initializer is specified for an object, and the
14609 // object is of (possibly cv-qualified) non-POD class type (or
14610 // array thereof), the object shall be default-initialized; if
14611 // the object is of const-qualified type, the underlying class
14612 // type shall have a user-declared default
14613 // constructor. Otherwise, if no initializer is specified for
14614 // a non- static object, the object and its subobjects, if
14615 // any, have an indeterminate initial value); if the object
14616 // or any of its subobjects are of const-qualified type, the
14617 // program is ill-formed.
14618 // C++0x [dcl.init]p11:
14619 // If no initializer is specified for an object, the object is
14620 // default-initialized; [...].
14623 = InitializationKind::CreateDefault(Var->getLocation());
14624
14625 InitializationSequence InitSeq(*this, Entity, Kind, {});
14626 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14627
14628 if (Init.get()) {
14629 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14630 // This is important for template substitution.
14631 Var->setInitStyle(VarDecl::CallInit);
14632 } else if (Init.isInvalid()) {
14633 // If default-init fails, attach a recovery-expr initializer to track
14634 // that initialization was attempted and failed.
14635 auto RecoveryExpr =
14636 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14637 if (RecoveryExpr.get())
14638 Var->setInit(RecoveryExpr.get());
14639 }
14640
14642 }
14643}
14644
14646 // If there is no declaration, there was an error parsing it. Ignore it.
14647 if (!D)
14648 return;
14649
14650 VarDecl *VD = dyn_cast<VarDecl>(D);
14651 if (!VD) {
14652 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14653 D->setInvalidDecl();
14654 return;
14655 }
14656
14657 VD->setCXXForRangeDecl(true);
14658
14659 // for-range-declaration cannot be given a storage class specifier.
14660 int Error = -1;
14661 switch (VD->getStorageClass()) {
14662 case SC_None:
14663 break;
14664 case SC_Extern:
14665 Error = 0;
14666 break;
14667 case SC_Static:
14668 Error = 1;
14669 break;
14670 case SC_PrivateExtern:
14671 Error = 2;
14672 break;
14673 case SC_Auto:
14674 Error = 3;
14675 break;
14676 case SC_Register:
14677 Error = 4;
14678 break;
14679 }
14680
14681 // for-range-declaration cannot be given a storage class specifier con't.
14682 switch (VD->getTSCSpec()) {
14683 case TSCS_thread_local:
14684 Error = 6;
14685 break;
14686 case TSCS___thread:
14687 case TSCS__Thread_local:
14688 case TSCS_unspecified:
14689 break;
14690 }
14691
14692 if (Error != -1) {
14693 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14694 << VD << Error;
14695 D->setInvalidDecl();
14696 }
14697}
14698
14700 IdentifierInfo *Ident,
14701 ParsedAttributes &Attrs) {
14702 // C++1y [stmt.iter]p1:
14703 // A range-based for statement of the form
14704 // for ( for-range-identifier : for-range-initializer ) statement
14705 // is equivalent to
14706 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14707 DeclSpec DS(Attrs.getPool().getFactory());
14708
14709 const char *PrevSpec;
14710 unsigned DiagID;
14711 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14713
14715 D.SetIdentifier(Ident, IdentLoc);
14716 D.takeAttributesAppending(Attrs);
14717
14718 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14719 IdentLoc);
14720 Decl *Var = ActOnDeclarator(S, D);
14721 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14723 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14724 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14725 : IdentLoc);
14726}
14727
14729 if (var->isInvalidDecl()) return;
14730
14732
14733 if (getLangOpts().OpenCL) {
14734 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14735 // initialiser
14736 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14737 !var->hasInit()) {
14738 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14739 << 1 /*Init*/;
14740 var->setInvalidDecl();
14741 return;
14742 }
14743 }
14744
14745 // In Objective-C, don't allow jumps past the implicit initialization of a
14746 // local retaining variable.
14747 if (getLangOpts().ObjC &&
14748 var->hasLocalStorage()) {
14749 switch (var->getType().getObjCLifetime()) {
14753 break;
14754
14758 break;
14759 }
14760 }
14761
14762 if (var->hasLocalStorage() &&
14763 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14765
14766 // Warn about externally-visible variables being defined without a
14767 // prior declaration. We only want to do this for global
14768 // declarations, but we also specifically need to avoid doing it for
14769 // class members because the linkage of an anonymous class can
14770 // change if it's later given a typedef name.
14771 if (var->isThisDeclarationADefinition() &&
14772 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14773 var->isExternallyVisible() && var->hasLinkage() &&
14774 !var->isInline() && !var->getDescribedVarTemplate() &&
14775 var->getStorageClass() != SC_Register &&
14777 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14778 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14779 var->getLocation())) {
14780 // Find a previous declaration that's not a definition.
14781 VarDecl *prev = var->getPreviousDecl();
14782 while (prev && prev->isThisDeclarationADefinition())
14783 prev = prev->getPreviousDecl();
14784
14785 if (!prev) {
14786 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14787 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14788 << /* variable */ 0;
14789 }
14790 }
14791
14792 // Cache the result of checking for constant initialization.
14793 std::optional<bool> CacheHasConstInit;
14794 const Expr *CacheCulprit = nullptr;
14795 auto checkConstInit = [&]() mutable {
14796 const Expr *Init = var->getInit();
14797 if (Init->isInstantiationDependent())
14798 return true;
14799
14800 if (!CacheHasConstInit)
14801 CacheHasConstInit = var->getInit()->isConstantInitializer(
14802 Context, var->getType()->isReferenceType(), &CacheCulprit);
14803 return *CacheHasConstInit;
14804 };
14805
14806 if (var->getTLSKind() == VarDecl::TLS_Static) {
14807 if (var->getType().isDestructedType()) {
14808 // GNU C++98 edits for __thread, [basic.start.term]p3:
14809 // The type of an object with thread storage duration shall not
14810 // have a non-trivial destructor.
14811 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14813 Diag(var->getLocation(), diag::note_use_thread_local);
14814 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14815 if (!checkConstInit()) {
14816 // GNU C++98 edits for __thread, [basic.start.init]p4:
14817 // An object of thread storage duration shall not require dynamic
14818 // initialization.
14819 // FIXME: Need strict checking here.
14820 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14821 << CacheCulprit->getSourceRange();
14823 Diag(var->getLocation(), diag::note_use_thread_local);
14824 }
14825 }
14826 }
14827
14828
14829 if (!var->getType()->isStructureType() && var->hasInit() &&
14830 isa<InitListExpr>(var->getInit())) {
14831 const auto *ILE = cast<InitListExpr>(var->getInit());
14832 unsigned NumInits = ILE->getNumInits();
14833 if (NumInits > 2)
14834 for (unsigned I = 0; I < NumInits; ++I) {
14835 const auto *Init = ILE->getInit(I);
14836 if (!Init)
14837 break;
14838 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14839 if (!SL)
14840 break;
14841
14842 unsigned NumConcat = SL->getNumConcatenated();
14843 // Diagnose missing comma in string array initialization.
14844 // Do not warn when all the elements in the initializer are concatenated
14845 // together. Do not warn for macros too.
14846 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14847 bool OnlyOneMissingComma = true;
14848 for (unsigned J = I + 1; J < NumInits; ++J) {
14849 const auto *Init = ILE->getInit(J);
14850 if (!Init)
14851 break;
14852 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14853 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14854 OnlyOneMissingComma = false;
14855 break;
14856 }
14857 }
14858
14859 if (OnlyOneMissingComma) {
14861 for (unsigned i = 0; i < NumConcat - 1; ++i)
14862 Hints.push_back(FixItHint::CreateInsertion(
14863 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14864
14865 Diag(SL->getStrTokenLoc(1),
14866 diag::warn_concatenated_literal_array_init)
14867 << Hints;
14868 Diag(SL->getBeginLoc(),
14869 diag::note_concatenated_string_literal_silence);
14870 }
14871 // In any case, stop now.
14872 break;
14873 }
14874 }
14875 }
14876
14877
14878 QualType type = var->getType();
14879
14880 if (var->hasAttr<BlocksAttr>())
14882
14883 Expr *Init = var->getInit();
14884 bool GlobalStorage = var->hasGlobalStorage();
14885 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14886 QualType baseType = Context.getBaseElementType(type);
14887 bool HasConstInit = true;
14888
14889 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14890 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14891 << var;
14892
14893 // Check whether the initializer is sufficiently constant.
14894 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14895 !type->isDependentType() && Init && !Init->isValueDependent() &&
14896 (GlobalStorage || var->isConstexpr() ||
14897 var->mightBeUsableInConstantExpressions(Context))) {
14898 // If this variable might have a constant initializer or might be usable in
14899 // constant expressions, check whether or not it actually is now. We can't
14900 // do this lazily, because the result might depend on things that change
14901 // later, such as which constexpr functions happen to be defined.
14903 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14904 // Prior to C++11, in contexts where a constant initializer is required,
14905 // the set of valid constant initializers is described by syntactic rules
14906 // in [expr.const]p2-6.
14907 // FIXME: Stricter checking for these rules would be useful for constinit /
14908 // -Wglobal-constructors.
14909 HasConstInit = checkConstInit();
14910
14911 // Compute and cache the constant value, and remember that we have a
14912 // constant initializer.
14913 if (HasConstInit) {
14914 if (var->isStaticDataMember() && !var->isInline() &&
14915 var->getLexicalDeclContext()->isRecord() &&
14916 type->isIntegralOrEnumerationType()) {
14917 // In C++98, in-class initialization for a static data member must
14918 // be an integer constant expression.
14919 if (!Init->isIntegerConstantExpr(Context)) {
14920 Diag(Init->getExprLoc(),
14921 diag::ext_in_class_initializer_non_constant)
14922 << Init->getSourceRange();
14923 }
14924 }
14925 (void)var->checkForConstantInitialization(Notes);
14926 Notes.clear();
14927 } else if (CacheCulprit) {
14928 Notes.emplace_back(CacheCulprit->getExprLoc(),
14929 PDiag(diag::note_invalid_subexpr_in_const_expr));
14930 Notes.back().second << CacheCulprit->getSourceRange();
14931 }
14932 } else {
14933 // Evaluate the initializer to see if it's a constant initializer.
14934 HasConstInit = var->checkForConstantInitialization(Notes);
14935 }
14936
14937 if (HasConstInit) {
14938 // FIXME: Consider replacing the initializer with a ConstantExpr.
14939 } else if (var->isConstexpr()) {
14940 SourceLocation DiagLoc = var->getLocation();
14941 // If the note doesn't add any useful information other than a source
14942 // location, fold it into the primary diagnostic.
14943 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14944 diag::note_invalid_subexpr_in_const_expr) {
14945 DiagLoc = Notes[0].first;
14946 Notes.clear();
14947 }
14948 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14949 << var << Init->getSourceRange();
14950 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14951 Diag(Notes[I].first, Notes[I].second);
14952 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14953 auto *Attr = var->getAttr<ConstInitAttr>();
14954 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14955 << Init->getSourceRange();
14956 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14957 << Attr->getRange() << Attr->isConstinit();
14958 for (auto &it : Notes)
14959 Diag(it.first, it.second);
14960 } else if (var->isStaticDataMember() && !var->isInline() &&
14961 var->getLexicalDeclContext()->isRecord()) {
14962 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
14963 << Init->getSourceRange();
14964 for (auto &it : Notes)
14965 Diag(it.first, it.second);
14966 var->setInvalidDecl();
14967 } else if (IsGlobal &&
14968 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14969 var->getLocation())) {
14970 // Warn about globals which don't have a constant initializer. Don't
14971 // warn about globals with a non-trivial destructor because we already
14972 // warned about them.
14973 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14974 if (!(RD && !RD->hasTrivialDestructor())) {
14975 // checkConstInit() here permits trivial default initialization even in
14976 // C++11 onwards, where such an initializer is not a constant initializer
14977 // but nonetheless doesn't require a global constructor.
14978 if (!checkConstInit())
14979 Diag(var->getLocation(), diag::warn_global_constructor)
14980 << Init->getSourceRange();
14981 }
14982 }
14983 }
14984
14985 // Apply section attributes and pragmas to global variables.
14986 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14988 PragmaStack<StringLiteral *> *Stack = nullptr;
14989 int SectionFlags = ASTContext::PSF_Read;
14990 bool MSVCEnv =
14991 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14992 std::optional<QualType::NonConstantStorageReason> Reason;
14993 if (HasConstInit &&
14994 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14995 Stack = &ConstSegStack;
14996 } else {
14997 SectionFlags |= ASTContext::PSF_Write;
14998 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14999 }
15000 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15001 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15002 SectionFlags |= ASTContext::PSF_Implicit;
15003 UnifySection(SA->getName(), SectionFlags, var);
15004 } else if (Stack->CurrentValue) {
15005 if (Stack != &ConstSegStack && MSVCEnv &&
15006 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15007 var->getType().isConstQualified()) {
15008 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15009 NonConstNonReferenceType) &&
15010 "This case should've already been handled elsewhere");
15011 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15012 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15014 : *Reason);
15015 }
15016 SectionFlags |= ASTContext::PSF_Implicit;
15017 auto SectionName = Stack->CurrentValue->getString();
15018 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15019 Stack->CurrentPragmaLocation,
15020 SectionAttr::Declspec_allocate));
15021 if (UnifySection(SectionName, SectionFlags, var))
15022 var->dropAttr<SectionAttr>();
15023 }
15024
15025 // Apply the init_seg attribute if this has an initializer. If the
15026 // initializer turns out to not be dynamic, we'll end up ignoring this
15027 // attribute.
15028 if (CurInitSeg && var->getInit())
15029 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15030 CurInitSegLoc));
15031 }
15032
15033 // All the following checks are C++ only.
15034 if (!getLangOpts().CPlusPlus) {
15035 // If this variable must be emitted, add it as an initializer for the
15036 // current module.
15037 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15038 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15039 return;
15040 }
15041
15043
15044 // Require the destructor.
15045 if (!type->isDependentType())
15046 if (auto *RD = baseType->getAsCXXRecordDecl())
15048
15049 // If this variable must be emitted, add it as an initializer for the current
15050 // module.
15051 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15052 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15053
15054 // Build the bindings if this is a structured binding declaration.
15055 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15057}
15058
15060 assert(VD->isStaticLocal());
15061
15062 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15063
15064 // Find outermost function when VD is in lambda function.
15065 while (FD && !getDLLAttr(FD) &&
15066 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15067 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15068 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15069 }
15070
15071 if (!FD)
15072 return;
15073
15074 // Static locals inherit dll attributes from their function.
15075 if (Attr *A = getDLLAttr(FD)) {
15076 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15077 NewAttr->setInherited(true);
15078 VD->addAttr(NewAttr);
15079 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15080 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15081 NewAttr->setInherited(true);
15082 VD->addAttr(NewAttr);
15083
15084 // Export this function to enforce exporting this static variable even
15085 // if it is not used in this compilation unit.
15086 if (!FD->hasAttr<DLLExportAttr>())
15087 FD->addAttr(NewAttr);
15088
15089 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15090 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15091 NewAttr->setInherited(true);
15092 VD->addAttr(NewAttr);
15093 }
15094}
15095
15097 assert(VD->getTLSKind());
15098
15099 // Perform TLS alignment check here after attributes attached to the variable
15100 // which may affect the alignment have been processed. Only perform the check
15101 // if the target has a maximum TLS alignment (zero means no constraints).
15102 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15103 // Protect the check so that it's not performed on dependent types and
15104 // dependent alignments (we can't determine the alignment in that case).
15105 if (!VD->hasDependentAlignment()) {
15106 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15107 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15108 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15109 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15110 << (unsigned)MaxAlignChars.getQuantity();
15111 }
15112 }
15113 }
15114}
15115
15117 // Note that we are no longer parsing the initializer for this declaration.
15118 ParsingInitForAutoVars.erase(ThisDecl);
15119
15120 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15121 if (!VD)
15122 return;
15123
15124 // Emit any deferred warnings for the variable's initializer, even if the
15125 // variable is invalid
15126 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15127
15128 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15130 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15131 if (PragmaClangBSSSection.Valid)
15132 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15133 Context, PragmaClangBSSSection.SectionName,
15134 PragmaClangBSSSection.PragmaLocation));
15135 if (PragmaClangDataSection.Valid)
15136 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15137 Context, PragmaClangDataSection.SectionName,
15138 PragmaClangDataSection.PragmaLocation));
15139 if (PragmaClangRodataSection.Valid)
15140 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15141 Context, PragmaClangRodataSection.SectionName,
15142 PragmaClangRodataSection.PragmaLocation));
15143 if (PragmaClangRelroSection.Valid)
15144 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15145 Context, PragmaClangRelroSection.SectionName,
15146 PragmaClangRelroSection.PragmaLocation));
15147 }
15148
15149 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15150 for (auto *BD : DD->bindings()) {
15152 }
15153 }
15154
15155 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15157
15158 checkAttributesAfterMerging(*this, *VD);
15159
15160 if (VD->isStaticLocal())
15162
15163 if (VD->getTLSKind())
15165
15166 // Perform check for initializers of device-side global variables.
15167 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15168 // 7.5). We must also apply the same checks to all __shared__
15169 // variables whether they are local or not. CUDA also allows
15170 // constant initializers for __constant__ and __device__ variables.
15171 if (getLangOpts().CUDA)
15173
15174 // Grab the dllimport or dllexport attribute off of the VarDecl.
15175 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15176
15177 // Imported static data members cannot be defined out-of-line.
15178 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15179 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15181 // We allow definitions of dllimport class template static data members
15182 // with a warning.
15185 bool IsClassTemplateMember =
15187 Context->getDescribedClassTemplate();
15188
15189 Diag(VD->getLocation(),
15190 IsClassTemplateMember
15191 ? diag::warn_attribute_dllimport_static_field_definition
15192 : diag::err_attribute_dllimport_static_field_definition);
15193 Diag(IA->getLocation(), diag::note_attribute);
15194 if (!IsClassTemplateMember)
15195 VD->setInvalidDecl();
15196 }
15197 }
15198
15199 // dllimport/dllexport variables cannot be thread local, their TLS index
15200 // isn't exported with the variable.
15201 if (DLLAttr && VD->getTLSKind()) {
15202 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15203 if (F && getDLLAttr(F)) {
15204 assert(VD->isStaticLocal());
15205 // But if this is a static local in a dlimport/dllexport function, the
15206 // function will never be inlined, which means the var would never be
15207 // imported, so having it marked import/export is safe.
15208 } else {
15209 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15210 << DLLAttr;
15211 VD->setInvalidDecl();
15212 }
15213 }
15214
15215 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15216 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15217 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15218 << Attr;
15219 VD->dropAttr<UsedAttr>();
15220 }
15221 }
15222 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15223 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15224 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15225 << Attr;
15226 VD->dropAttr<RetainAttr>();
15227 }
15228 }
15229
15230 const DeclContext *DC = VD->getDeclContext();
15231 // If there's a #pragma GCC visibility in scope, and this isn't a class
15232 // member, set the visibility of this variable.
15235
15236 // FIXME: Warn on unused var template partial specializations.
15239
15240 // Now we have parsed the initializer and can update the table of magic
15241 // tag values.
15242 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15244 return;
15245
15246 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15247 const Expr *MagicValueExpr = VD->getInit();
15248 if (!MagicValueExpr) {
15249 continue;
15250 }
15251 std::optional<llvm::APSInt> MagicValueInt;
15252 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15253 Diag(I->getRange().getBegin(),
15254 diag::err_type_tag_for_datatype_not_ice)
15255 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15256 continue;
15257 }
15258 if (MagicValueInt->getActiveBits() > 64) {
15259 Diag(I->getRange().getBegin(),
15260 diag::err_type_tag_for_datatype_too_large)
15261 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15262 continue;
15263 }
15264 uint64_t MagicValue = MagicValueInt->getZExtValue();
15265 RegisterTypeTagForDatatype(I->getArgumentKind(),
15266 MagicValue,
15267 I->getMatchingCType(),
15268 I->getLayoutCompatible(),
15269 I->getMustBeNull());
15270 }
15271}
15272
15274 auto *VD = dyn_cast<VarDecl>(DD);
15275 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15276}
15277
15279 ArrayRef<Decl *> Group) {
15281
15282 if (DS.isTypeSpecOwned())
15283 Decls.push_back(DS.getRepAsDecl());
15284
15285 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15286 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15287 bool DiagnosedMultipleDecomps = false;
15288 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15289 bool DiagnosedNonDeducedAuto = false;
15290
15291 for (Decl *D : Group) {
15292 if (!D)
15293 continue;
15294 // Check if the Decl has been declared in '#pragma omp declare target'
15295 // directive and has static storage duration.
15296 if (auto *VD = dyn_cast<VarDecl>(D);
15297 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15298 VD->hasGlobalStorage())
15300 // For declarators, there are some additional syntactic-ish checks we need
15301 // to perform.
15302 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15303 if (!FirstDeclaratorInGroup)
15304 FirstDeclaratorInGroup = DD;
15305 if (!FirstDecompDeclaratorInGroup)
15306 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15307 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15308 !hasDeducedAuto(DD))
15309 FirstNonDeducedAutoInGroup = DD;
15310
15311 if (FirstDeclaratorInGroup != DD) {
15312 // A decomposition declaration cannot be combined with any other
15313 // declaration in the same group.
15314 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15315 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15316 diag::err_decomp_decl_not_alone)
15317 << FirstDeclaratorInGroup->getSourceRange()
15318 << DD->getSourceRange();
15319 DiagnosedMultipleDecomps = true;
15320 }
15321
15322 // A declarator that uses 'auto' in any way other than to declare a
15323 // variable with a deduced type cannot be combined with any other
15324 // declarator in the same group.
15325 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15326 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15327 diag::err_auto_non_deduced_not_alone)
15328 << FirstNonDeducedAutoInGroup->getType()
15330 << FirstDeclaratorInGroup->getSourceRange()
15331 << DD->getSourceRange();
15332 DiagnosedNonDeducedAuto = true;
15333 }
15334 }
15335 }
15336
15337 Decls.push_back(D);
15338 }
15339
15341 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15342 handleTagNumbering(Tag, S);
15343 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15345 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15346 }
15347 }
15348
15349 return BuildDeclaratorGroup(Decls);
15350}
15351
15354 // C++14 [dcl.spec.auto]p7: (DR1347)
15355 // If the type that replaces the placeholder type is not the same in each
15356 // deduction, the program is ill-formed.
15357 if (Group.size() > 1) {
15358 QualType Deduced;
15359 VarDecl *DeducedDecl = nullptr;
15360 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15361 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15362 if (!D || D->isInvalidDecl())
15363 break;
15364 DeducedType *DT = D->getType()->getContainedDeducedType();
15365 if (!DT || DT->getDeducedType().isNull())
15366 continue;
15367 if (Deduced.isNull()) {
15368 Deduced = DT->getDeducedType();
15369 DeducedDecl = D;
15370 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15371 auto *AT = dyn_cast<AutoType>(DT);
15372 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15373 diag::err_auto_different_deductions)
15374 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15375 << DeducedDecl->getDeclName() << DT->getDeducedType()
15376 << D->getDeclName();
15377 if (DeducedDecl->hasInit())
15378 Dia << DeducedDecl->getInit()->getSourceRange();
15379 if (D->getInit())
15380 Dia << D->getInit()->getSourceRange();
15381 D->setInvalidDecl();
15382 break;
15383 }
15384 }
15385 }
15386
15388
15389 return DeclGroupPtrTy::make(
15390 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15391}
15392
15396
15398 // Don't parse the comment if Doxygen diagnostics are ignored.
15399 if (Group.empty() || !Group[0])
15400 return;
15401
15402 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15403 Group[0]->getLocation()) &&
15404 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15405 Group[0]->getLocation()))
15406 return;
15407
15408 if (Group.size() >= 2) {
15409 // This is a decl group. Normally it will contain only declarations
15410 // produced from declarator list. But in case we have any definitions or
15411 // additional declaration references:
15412 // 'typedef struct S {} S;'
15413 // 'typedef struct S *S;'
15414 // 'struct S *pS;'
15415 // FinalizeDeclaratorGroup adds these as separate declarations.
15416 Decl *MaybeTagDecl = Group[0];
15417 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15418 Group = Group.slice(1);
15419 }
15420 }
15421
15422 // FIMXE: We assume every Decl in the group is in the same file.
15423 // This is false when preprocessor constructs the group from decls in
15424 // different files (e. g. macros or #include).
15425 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15426}
15427
15429 // Check that there are no default arguments inside the type of this
15430 // parameter.
15431 if (getLangOpts().CPlusPlus)
15433
15434 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15435 if (D.getCXXScopeSpec().isSet()) {
15436 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15437 << D.getCXXScopeSpec().getRange();
15438 }
15439
15440 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15441 // simple identifier except [...irrelevant cases...].
15442 switch (D.getName().getKind()) {
15444 break;
15445
15453 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15455 break;
15456
15459 // GetNameForDeclarator would not produce a useful name in this case.
15460 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15461 break;
15462 }
15463}
15464
15466 // This only matters in C.
15467 if (getLangOpts().CPlusPlus)
15468 return;
15469
15470 // This only matters if the declaration has a type.
15471 const auto *VD = dyn_cast<ValueDecl>(D);
15472 if (!VD)
15473 return;
15474
15475 // Get the type, this only matters for tag types.
15476 QualType QT = VD->getType();
15477 const auto *TD = QT->getAsTagDecl();
15478 if (!TD)
15479 return;
15480
15481 // Check if the tag declaration is lexically declared somewhere different
15482 // from the lexical declaration of the given object, then it will be hidden
15483 // in C++ and we should warn on it.
15484 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15485 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15486 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15487 Diag(TD->getLocation(), diag::note_declared_at);
15488 }
15489}
15490
15492 SourceLocation ExplicitThisLoc) {
15493 if (!ExplicitThisLoc.isValid())
15494 return;
15495 assert(S.getLangOpts().CPlusPlus &&
15496 "explicit parameter in non-cplusplus mode");
15497 if (!S.getLangOpts().CPlusPlus23)
15498 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15499 << P->getSourceRange();
15500
15501 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15502 // parameter pack.
15503 if (P->isParameterPack()) {
15504 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15505 << P->getSourceRange();
15506 return;
15507 }
15508 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15509 if (LambdaScopeInfo *LSI = S.getCurLambda())
15510 LSI->ExplicitObjectParameter = P;
15511}
15512
15514 SourceLocation ExplicitThisLoc) {
15515 const DeclSpec &DS = D.getDeclSpec();
15516
15517 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15518 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15519 // except for the special case of a single unnamed parameter of type void
15520 // with no storage class specifier, no type qualifier, and no following
15521 // ellipsis terminator.
15522 // Clang applies the C2y rules for 'register void' in all C language modes,
15523 // same as GCC, because it's questionable what that could possibly mean.
15524
15525 // C++03 [dcl.stc]p2 also permits 'auto'.
15526 StorageClass SC = SC_None;
15528 SC = SC_Register;
15529 // In C++11, the 'register' storage class specifier is deprecated.
15530 // In C++17, it is not allowed, but we tolerate it as an extension.
15531 if (getLangOpts().CPlusPlus11) {
15533 ? diag::ext_register_storage_class
15534 : diag::warn_deprecated_register)
15536 } else if (!getLangOpts().CPlusPlus &&
15538 D.getNumTypeObjects() == 0) {
15540 diag::err_invalid_storage_class_in_func_decl)
15543 }
15544 } else if (getLangOpts().CPlusPlus &&
15546 SC = SC_Auto;
15549 diag::err_invalid_storage_class_in_func_decl);
15551 }
15552
15554 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15556 if (DS.isInlineSpecified())
15557 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15558 << getLangOpts().CPlusPlus17;
15559 if (DS.hasConstexprSpecifier())
15560 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15561 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15562
15564
15566
15568 QualType parmDeclType = TInfo->getType();
15569
15570 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15571 const IdentifierInfo *II = D.getIdentifier();
15572 if (II) {
15575 LookupName(R, S);
15576 if (!R.empty()) {
15577 NamedDecl *PrevDecl = *R.begin();
15578 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15579 // Maybe we will complain about the shadowed template parameter.
15581 // Just pretend that we didn't see the previous declaration.
15582 PrevDecl = nullptr;
15583 }
15584 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15585 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15586 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15587 // Recover by removing the name
15588 II = nullptr;
15589 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15590 D.setInvalidType(true);
15591 }
15592 }
15593 }
15594
15595 // Incomplete resource arrays are not allowed as function parameters in HLSL
15596 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15597 parmDeclType->isHLSLResourceRecordArray()) {
15599 diag::err_hlsl_incomplete_resource_array_in_function_param);
15600 D.setInvalidType(true);
15601 }
15602
15603 // Temporarily put parameter variables in the translation unit, not
15604 // the enclosing context. This prevents them from accidentally
15605 // looking like class members in C++.
15606 ParmVarDecl *New =
15607 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15608 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15609
15610 if (D.isInvalidType())
15611 New->setInvalidDecl();
15612
15613 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15614
15615 assert(S->isFunctionPrototypeScope());
15616 assert(S->getFunctionPrototypeDepth() >= 1);
15617 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15619
15621
15622 // Add the parameter declaration into this scope.
15623 S->AddDecl(New);
15624 if (II)
15625 IdResolver.AddDecl(New);
15626
15628
15630 Diag(New->getLocation(), diag::err_module_private_local)
15633
15634 if (New->hasAttr<BlocksAttr>()) {
15635 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15636 }
15637
15638 if (getLangOpts().OpenCL)
15640
15641 return New;
15642}
15643
15645 SourceLocation Loc,
15646 QualType T) {
15647 /* FIXME: setting StartLoc == Loc.
15648 Would it be worth to modify callers so as to provide proper source
15649 location for the unnamed parameters, embedding the parameter's type? */
15650 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15651 T, Context.getTrivialTypeSourceInfo(T, Loc),
15652 SC_None, nullptr);
15653 Param->setImplicit();
15654 return Param;
15655}
15656
15658 // Don't diagnose unused-parameter errors in template instantiations; we
15659 // will already have done so in the template itself.
15661 return;
15662
15663 for (const ParmVarDecl *Parameter : Parameters) {
15664 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15665 !Parameter->hasAttr<UnusedAttr>() &&
15666 !Parameter->getIdentifier()->isPlaceholder()) {
15667 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15668 << Parameter->getDeclName();
15669 }
15670 }
15671}
15672
15674 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15675 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15676 return;
15677
15678 // Warn if the return value is pass-by-value and larger than the specified
15679 // threshold.
15680 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15681 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15682 if (Size > LangOpts.NumLargeByValueCopy)
15683 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15684 }
15685
15686 // Warn if any parameter is pass-by-value and larger than the specified
15687 // threshold.
15688 for (const ParmVarDecl *Parameter : Parameters) {
15689 QualType T = Parameter->getType();
15690 if (T->isDependentType() || !T.isPODType(Context))
15691 continue;
15692 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15693 if (Size > LangOpts.NumLargeByValueCopy)
15694 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15695 << Parameter << Size;
15696 }
15697}
15698
15700 SourceLocation NameLoc,
15701 const IdentifierInfo *Name, QualType T,
15702 TypeSourceInfo *TSInfo, StorageClass SC) {
15703 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15704 if (getLangOpts().ObjCAutoRefCount &&
15705 T.getObjCLifetime() == Qualifiers::OCL_None &&
15706 T->isObjCLifetimeType()) {
15707
15708 Qualifiers::ObjCLifetime lifetime;
15709
15710 // Special cases for arrays:
15711 // - if it's const, use __unsafe_unretained
15712 // - otherwise, it's an error
15713 if (T->isArrayType()) {
15714 if (!T.isConstQualified()) {
15718 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15719 else
15720 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15721 << TSInfo->getTypeLoc().getSourceRange();
15722 }
15724 } else {
15725 lifetime = T->getObjCARCImplicitLifetime();
15726 }
15727 T = Context.getLifetimeQualifiedType(T, lifetime);
15728 }
15729
15730 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15731 Context.getAdjustedParameterType(T),
15732 TSInfo, SC, nullptr);
15733
15734 // Make a note if we created a new pack in the scope of a lambda, so that
15735 // we know that references to that pack must also be expanded within the
15736 // lambda scope.
15737 if (New->isParameterPack())
15738 if (auto *CSI = getEnclosingLambdaOrBlock())
15739 CSI->LocalPacks.push_back(New);
15740
15741 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15742 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15743 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15746
15747 // Parameter declarators cannot be interface types. All ObjC objects are
15748 // passed by reference.
15749 if (T->isObjCObjectType()) {
15750 SourceLocation TypeEndLoc =
15752 Diag(NameLoc,
15753 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15754 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15755 T = Context.getObjCObjectPointerType(T);
15756 New->setType(T);
15757 }
15758
15759 // __ptrauth is forbidden on parameters.
15760 if (T.getPointerAuth()) {
15761 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15762 New->setInvalidDecl();
15763 }
15764
15765 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15766 // duration shall not be qualified by an address-space qualifier."
15767 // Since all parameters have automatic store duration, they can not have
15768 // an address space.
15769 if (T.getAddressSpace() != LangAS::Default &&
15770 // OpenCL allows function arguments declared to be an array of a type
15771 // to be qualified with an address space.
15772 !(getLangOpts().OpenCL &&
15773 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15774 // WebAssembly allows reference types as parameters. Funcref in particular
15775 // lives in a different address space.
15776 !(T->isFunctionPointerType() &&
15777 T.getAddressSpace() == LangAS::wasm_funcref)) {
15778 Diag(NameLoc, diag::err_arg_with_address_space);
15779 New->setInvalidDecl();
15780 }
15781
15782 // PPC MMA non-pointer types are not allowed as function argument types.
15783 if (Context.getTargetInfo().getTriple().isPPC64() &&
15784 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15785 New->setInvalidDecl();
15786 }
15787
15788 return New;
15789}
15790
15792 SourceLocation LocAfterDecls) {
15794
15795 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15796 // in the declaration list shall have at least one declarator, those
15797 // declarators shall only declare identifiers from the identifier list, and
15798 // every identifier in the identifier list shall be declared.
15799 //
15800 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15801 // identifiers it names shall be declared in the declaration list."
15802 //
15803 // This is why we only diagnose in C99 and later. Note, the other conditions
15804 // listed are checked elsewhere.
15805 if (!FTI.hasPrototype) {
15806 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15807 --i;
15808 if (FTI.Params[i].Param == nullptr) {
15809 if (getLangOpts().C99) {
15810 SmallString<256> Code;
15811 llvm::raw_svector_ostream(Code)
15812 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15813 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15814 << FTI.Params[i].Ident
15815 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15816 }
15817
15818 // Implicitly declare the argument as type 'int' for lack of a better
15819 // type.
15820 AttributeFactory attrs;
15821 DeclSpec DS(attrs);
15822 const char* PrevSpec; // unused
15823 unsigned DiagID; // unused
15824 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15825 DiagID, Context.getPrintingPolicy());
15826 // Use the identifier location for the type source range.
15827 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15828 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15831 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15832 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15833 }
15834 }
15835 }
15836}
15837
15838Decl *
15840 MultiTemplateParamsArg TemplateParameterLists,
15841 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15842 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15843 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15844 Scope *ParentScope = FnBodyScope->getParent();
15845
15846 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15847 // we define a non-templated function definition, we will create a declaration
15848 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15849 // The base function declaration will have the equivalent of an `omp declare
15850 // variant` annotation which specifies the mangled definition as a
15851 // specialization function under the OpenMP context defined as part of the
15852 // `omp begin declare variant`.
15854 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15856 ParentScope, D, TemplateParameterLists, Bases);
15857
15859 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15860 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15861
15862 if (!Bases.empty())
15864 Bases);
15865
15866 return Dcl;
15867}
15868
15870 Consumer.HandleInlineFunctionDefinition(D);
15871}
15872
15874 const FunctionDecl *&PossiblePrototype) {
15875 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15876 Prev = Prev->getPreviousDecl()) {
15877 // Ignore any declarations that occur in function or method
15878 // scope, because they aren't visible from the header.
15879 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15880 continue;
15881
15882 PossiblePrototype = Prev;
15883 return Prev->getType()->isFunctionProtoType();
15884 }
15885 return false;
15886}
15887
15888static bool
15890 const FunctionDecl *&PossiblePrototype) {
15891 // Don't warn about invalid declarations.
15892 if (FD->isInvalidDecl())
15893 return false;
15894
15895 // Or declarations that aren't global.
15896 if (!FD->isGlobal())
15897 return false;
15898
15899 // Don't warn about C++ member functions.
15900 if (isa<CXXMethodDecl>(FD))
15901 return false;
15902
15903 // Don't warn about 'main'.
15905 if (IdentifierInfo *II = FD->getIdentifier())
15906 if (II->isStr("main") || II->isStr("efi_main"))
15907 return false;
15908
15909 if (FD->isMSVCRTEntryPoint())
15910 return false;
15911
15912 // Don't warn about inline functions.
15913 if (FD->isInlined())
15914 return false;
15915
15916 // Don't warn about function templates.
15918 return false;
15919
15920 // Don't warn about function template specializations.
15922 return false;
15923
15924 // Don't warn for OpenCL kernels.
15925 if (FD->hasAttr<DeviceKernelAttr>())
15926 return false;
15927
15928 // Don't warn on explicitly deleted functions.
15929 if (FD->isDeleted())
15930 return false;
15931
15932 // Don't warn on implicitly local functions (such as having local-typed
15933 // parameters).
15934 if (!FD->isExternallyVisible())
15935 return false;
15936
15937 // If we were able to find a potential prototype, don't warn.
15938 if (FindPossiblePrototype(FD, PossiblePrototype))
15939 return false;
15940
15941 return true;
15942}
15943
15944void
15946 const FunctionDecl *EffectiveDefinition,
15947 SkipBodyInfo *SkipBody) {
15948 const FunctionDecl *Definition = EffectiveDefinition;
15949 if (!Definition &&
15950 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15951 return;
15952
15953 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15954 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15955 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15956 // A merged copy of the same function, instantiated as a member of
15957 // the same class, is OK.
15958 if (declaresSameEntity(OrigFD, OrigDef) &&
15959 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15961 return;
15962 }
15963 }
15964 }
15965
15967 return;
15968
15969 // Don't emit an error when this is redefinition of a typo-corrected
15970 // definition.
15972 return;
15973
15974 bool DefinitionVisible = false;
15975 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
15976 (Definition->getFormalLinkage() == Linkage::Internal ||
15977 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15978 Definition->getNumTemplateParameterLists())) {
15979 SkipBody->ShouldSkip = true;
15980 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15981 if (!DefinitionVisible) {
15982 if (auto *TD = Definition->getDescribedFunctionTemplate())
15985 }
15986 return;
15987 }
15988
15989 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15990 Definition->getStorageClass() == SC_Extern)
15991 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15992 << FD << getLangOpts().CPlusPlus;
15993 else
15994 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15995
15996 Diag(Definition->getLocation(), diag::note_previous_definition);
15997 FD->setInvalidDecl();
15998}
15999
16001 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16002
16004 LSI->CallOperator = CallOperator;
16005 LSI->Lambda = LambdaClass;
16006 LSI->ReturnType = CallOperator->getReturnType();
16007 // When this function is called in situation where the context of the call
16008 // operator is not entered, we set AfterParameterList to false, so that
16009 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16010 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16011 // where we would set the CurContext to the lambda operator before
16012 // substituting into it. In this case the flag needs to be true such that
16013 // tryCaptureVariable can correctly handle potential captures thereof.
16014 LSI->AfterParameterList = CurContext == CallOperator;
16015
16016 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16017 // used at the point of dealing with potential captures.
16018 //
16019 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16020 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16021 // associated. (Technically, we could recover that list from their
16022 // instantiation patterns, but for now, the GLTemplateParameterList seems
16023 // unnecessary in these cases.)
16024 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16025 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16026 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16027
16028 if (LCD == LCD_None)
16030 else if (LCD == LCD_ByCopy)
16032 else if (LCD == LCD_ByRef)
16034 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16035
16037 LSI->Mutable = !CallOperator->isConst();
16038 if (CallOperator->isExplicitObjectMemberFunction())
16039 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16040
16041 // Add the captures to the LSI so they can be noted as already
16042 // captured within tryCaptureVar.
16043 auto I = LambdaClass->field_begin();
16044 for (const auto &C : LambdaClass->captures()) {
16045 if (C.capturesVariable()) {
16046 ValueDecl *VD = C.getCapturedVar();
16047 if (VD->isInitCapture())
16048 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16049 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16050 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16051 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16052 /*EllipsisLoc*/C.isPackExpansion()
16053 ? C.getEllipsisLoc() : SourceLocation(),
16054 I->getType(), /*Invalid*/false);
16055
16056 } else if (C.capturesThis()) {
16057 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16058 C.getCaptureKind() == LCK_StarThis);
16059 } else {
16060 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16061 I->getType());
16062 }
16063 ++I;
16064 }
16065 return LSI;
16066}
16067
16069 SkipBodyInfo *SkipBody,
16070 FnBodyKind BodyKind) {
16071 if (!D) {
16072 // Parsing the function declaration failed in some way. Push on a fake scope
16073 // anyway so we can try to parse the function body.
16076 return D;
16077 }
16078
16079 FunctionDecl *FD = nullptr;
16080
16081 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16082 FD = FunTmpl->getTemplatedDecl();
16083 else
16084 FD = cast<FunctionDecl>(D);
16085
16086 // Do not push if it is a lambda because one is already pushed when building
16087 // the lambda in ActOnStartOfLambdaDefinition().
16088 if (!isLambdaCallOperator(FD))
16090 FD);
16091
16092 // Check for defining attributes before the check for redefinition.
16093 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16094 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16095 FD->dropAttr<AliasAttr>();
16096 FD->setInvalidDecl();
16097 }
16098 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16099 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16100 FD->dropAttr<IFuncAttr>();
16101 FD->setInvalidDecl();
16102 }
16103 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16104 if (Context.getTargetInfo().getTriple().isAArch64() &&
16105 !Context.getTargetInfo().hasFeature("fmv") &&
16106 !Attr->isDefaultVersion()) {
16107 // If function multi versioning disabled skip parsing function body
16108 // defined with non-default target_version attribute
16109 if (SkipBody)
16110 SkipBody->ShouldSkip = true;
16111 return nullptr;
16112 }
16113 }
16114
16115 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16116 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16117 Ctor->isDefaultConstructor() &&
16118 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16119 // If this is an MS ABI dllexport default constructor, instantiate any
16120 // default arguments.
16122 }
16123 }
16124
16125 // See if this is a redefinition. If 'will have body' (or similar) is already
16126 // set, then these checks were already performed when it was set.
16127 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16129 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16130
16131 // If we're skipping the body, we're done. Don't enter the scope.
16132 if (SkipBody && SkipBody->ShouldSkip)
16133 return D;
16134 }
16135
16136 // Mark this function as "will have a body eventually". This lets users to
16137 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16138 // this function.
16139 FD->setWillHaveBody();
16140
16141 // If we are instantiating a generic lambda call operator, push
16142 // a LambdaScopeInfo onto the function stack. But use the information
16143 // that's already been calculated (ActOnLambdaExpr) to prime the current
16144 // LambdaScopeInfo.
16145 // When the template operator is being specialized, the LambdaScopeInfo,
16146 // has to be properly restored so that tryCaptureVariable doesn't try
16147 // and capture any new variables. In addition when calculating potential
16148 // captures during transformation of nested lambdas, it is necessary to
16149 // have the LSI properly restored.
16151 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16152 // instantiated, explicitly specialized.
16155 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16156 FD->setInvalidDecl();
16158 } else {
16159 assert(inTemplateInstantiation() &&
16160 "There should be an active template instantiation on the stack "
16161 "when instantiating a generic lambda!");
16163 }
16164 } else {
16165 // Enter a new function scope
16167 }
16168
16169 // Builtin functions cannot be defined.
16170 if (unsigned BuiltinID = FD->getBuiltinID()) {
16171 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16172 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16173 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16174 FD->setInvalidDecl();
16175 }
16176 }
16177
16178 // The return type of a function definition must be complete (C99 6.9.1p3).
16179 // C++23 [dcl.fct.def.general]/p2
16180 // The type of [...] the return for a function definition
16181 // shall not be a (possibly cv-qualified) class type that is incomplete
16182 // or abstract within the function body unless the function is deleted.
16183 QualType ResultType = FD->getReturnType();
16184 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16185 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16186 (RequireCompleteType(FD->getLocation(), ResultType,
16187 diag::err_func_def_incomplete_result) ||
16189 diag::err_abstract_type_in_decl,
16191 FD->setInvalidDecl();
16192
16193 if (FnBodyScope)
16194 PushDeclContext(FnBodyScope, FD);
16195
16196 // Check the validity of our function parameters
16197 if (BodyKind != FnBodyKind::Delete)
16199 /*CheckParameterNames=*/true);
16200
16201 // Add non-parameter declarations already in the function to the current
16202 // scope.
16203 if (FnBodyScope) {
16204 for (Decl *NPD : FD->decls()) {
16205 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16206 if (!NonParmDecl)
16207 continue;
16208 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16209 "parameters should not be in newly created FD yet");
16210
16211 // If the decl has a name, make it accessible in the current scope.
16212 if (NonParmDecl->getDeclName())
16213 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16214
16215 // Similarly, dive into enums and fish their constants out, making them
16216 // accessible in this scope.
16217 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16218 for (auto *EI : ED->enumerators())
16219 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16220 }
16221 }
16222 }
16223
16224 // Introduce our parameters into the function scope
16225 for (auto *Param : FD->parameters()) {
16226 Param->setOwningFunction(FD);
16227
16228 // If this has an identifier, add it to the scope stack.
16229 if (Param->getIdentifier() && FnBodyScope) {
16230 CheckShadow(FnBodyScope, Param);
16231
16232 PushOnScopeChains(Param, FnBodyScope);
16233 }
16234 }
16235
16236 // C++ [module.import/6]
16237 // ...
16238 // A header unit shall not contain a definition of a non-inline function or
16239 // variable whose name has external linkage.
16240 //
16241 // Deleted and Defaulted functions are implicitly inline (but the
16242 // inline state is not set at this point, so check the BodyKind explicitly).
16243 // We choose to allow weak & selectany definitions, as they are common in
16244 // headers, and have semantics similar to inline definitions which are allowed
16245 // in header units.
16246 // FIXME: Consider an alternate location for the test where the inlined()
16247 // state is complete.
16248 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16249 !FD->isInvalidDecl() && !FD->isInlined() &&
16250 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16251 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16252 !FD->isTemplateInstantiation() &&
16253 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16254 assert(FD->isThisDeclarationADefinition());
16255 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16256 FD->setInvalidDecl();
16257 }
16258
16259 // Ensure that the function's exception specification is instantiated.
16260 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16262
16263 // dllimport cannot be applied to non-inline function definitions.
16264 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16265 !FD->isTemplateInstantiation()) {
16266 assert(!FD->hasAttr<DLLExportAttr>());
16267 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16268 FD->setInvalidDecl();
16269 return D;
16270 }
16271
16272 // Some function attributes (like OptimizeNoneAttr) need actions before
16273 // parsing body started.
16275
16276 // We want to attach documentation to original Decl (which might be
16277 // a function template).
16279 if (getCurLexicalContext()->isObjCContainer() &&
16280 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16281 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16282 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16283
16285
16286 return D;
16287}
16288
16290 if (!FD || FD->isInvalidDecl())
16291 return;
16292 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16293 FD = TD->getTemplatedDecl();
16294 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16297 CurFPFeatures.applyChanges(FPO);
16298 FpPragmaStack.CurrentValue =
16299 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16300 }
16301}
16302
16304 ReturnStmt **Returns = Scope->Returns.data();
16305
16306 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16307 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16308 if (!NRVOCandidate->isNRVOVariable()) {
16309 Diag(Returns[I]->getRetValue()->getExprLoc(),
16310 diag::warn_not_eliding_copy_on_return);
16311 Returns[I]->setNRVOCandidate(nullptr);
16312 }
16313 }
16314 }
16315}
16316
16318 // We can't delay parsing the body of a constexpr function template (yet).
16320 return false;
16321
16322 // We can't delay parsing the body of a function template with a deduced
16323 // return type (yet).
16324 if (D.getDeclSpec().hasAutoTypeSpec()) {
16325 // If the placeholder introduces a non-deduced trailing return type,
16326 // we can still delay parsing it.
16327 if (D.getNumTypeObjects()) {
16328 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16329 if (Outer.Kind == DeclaratorChunk::Function &&
16330 Outer.Fun.hasTrailingReturnType()) {
16331 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16332 return Ty.isNull() || !Ty->isUndeducedType();
16333 }
16334 }
16335 return false;
16336 }
16337
16338 return true;
16339}
16340
16342 // We cannot skip the body of a function (or function template) which is
16343 // constexpr, since we may need to evaluate its body in order to parse the
16344 // rest of the file.
16345 // We cannot skip the body of a function with an undeduced return type,
16346 // because any callers of that function need to know the type.
16347 if (const FunctionDecl *FD = D->getAsFunction()) {
16348 if (FD->isConstexpr())
16349 return false;
16350 // We can't simply call Type::isUndeducedType here, because inside template
16351 // auto can be deduced to a dependent type, which is not considered
16352 // "undeduced".
16353 if (FD->getReturnType()->getContainedDeducedType())
16354 return false;
16355 }
16356 return Consumer.shouldSkipFunctionBody(D);
16357}
16358
16360 if (!Decl)
16361 return nullptr;
16362 if (FunctionDecl *FD = Decl->getAsFunction())
16363 FD->setHasSkippedBody();
16364 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16365 MD->setHasSkippedBody();
16366 return Decl;
16367}
16368
16369/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16370/// body.
16372public:
16373 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16375 if (!IsLambda)
16376 S.PopExpressionEvaluationContext();
16377 }
16378
16379private:
16380 Sema &S;
16381 bool IsLambda = false;
16382};
16383
16385 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16386
16387 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16388 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16389 if (!Inserted)
16390 return It->second;
16391
16392 bool R = false;
16393 const BlockDecl *CurBD = BD;
16394
16395 do {
16396 R = !CurBD->doesNotEscape();
16397 if (R)
16398 break;
16399 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16400 } while (CurBD);
16401
16402 return It->second = R;
16403 };
16404
16405 // If the location where 'self' is implicitly retained is inside a escaping
16406 // block, emit a diagnostic.
16407 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16409 if (IsOrNestedInEscapingBlock(P.second))
16410 S.Diag(P.first, diag::warn_implicitly_retains_self)
16411 << FixItHint::CreateInsertion(P.first, "self->");
16412}
16413
16414static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16415 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16416 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16417}
16418
16420 return methodHasName(FD, "get_return_object");
16421}
16422
16424 return FD->isStatic() &&
16425 methodHasName(FD, "get_return_object_on_allocation_failure");
16426}
16427
16430 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16431 return;
16432 // Allow some_promise_type::get_return_object().
16434 return;
16435 if (!FD->hasAttr<CoroWrapperAttr>())
16436 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16437}
16438
16439Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16440 bool RetainFunctionScopeInfo) {
16442 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16443
16444 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16445 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16446
16447 SourceLocation AnalysisLoc;
16448 if (Body)
16449 AnalysisLoc = Body->getEndLoc();
16450 else if (FD)
16451 AnalysisLoc = FD->getEndLoc();
16453 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16454 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16455
16456 // If we skip function body, we can't tell if a function is a coroutine.
16457 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16458 if (FSI->isCoroutine())
16460 else
16462 }
16463
16464 // Diagnose invalid SYCL kernel entry point function declarations
16465 // and build SYCLKernelCallStmts for valid ones.
16466 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16467 SYCLKernelEntryPointAttr *SKEPAttr =
16468 FD->getAttr<SYCLKernelEntryPointAttr>();
16469 if (FD->isDefaulted()) {
16470 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16471 << SKEPAttr << /*defaulted function*/ 3;
16472 SKEPAttr->setInvalidAttr();
16473 } else if (FD->isDeleted()) {
16474 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16475 << SKEPAttr << /*deleted function*/ 2;
16476 SKEPAttr->setInvalidAttr();
16477 } else if (FSI->isCoroutine()) {
16478 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16479 << SKEPAttr << /*coroutine*/ 7;
16480 SKEPAttr->setInvalidAttr();
16481 } else if (Body && isa<CXXTryStmt>(Body)) {
16482 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16483 << SKEPAttr << /*function defined with a function try block*/ 8;
16484 SKEPAttr->setInvalidAttr();
16485 }
16486
16487 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16488 StmtResult SR =
16490 if (SR.isInvalid())
16491 return nullptr;
16492 Body = SR.get();
16493 }
16494 }
16495
16496 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16497 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16498 if (FD->isDeletedAsWritten())
16499 Diag(SEAttr->getLocation(),
16500 diag::err_sycl_external_invalid_deleted_function)
16501 << SEAttr;
16502 }
16503
16504 {
16505 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16506 // one is already popped when finishing the lambda in BuildLambdaExpr().
16507 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16508 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16509 if (FD) {
16510 // The function body and the DefaultedOrDeletedInfo, if present, use
16511 // the same storage; don't overwrite the latter if the former is null
16512 // (the body is initialised to null anyway, so even if the latter isn't
16513 // present, this would still be a no-op).
16514 if (Body)
16515 FD->setBody(Body);
16516 FD->setWillHaveBody(false);
16517
16518 if (getLangOpts().CPlusPlus14) {
16519 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16520 FD->getReturnType()->isUndeducedType()) {
16521 // For a function with a deduced result type to return void,
16522 // the result type as written must be 'auto' or 'decltype(auto)',
16523 // possibly cv-qualified or constrained, but not ref-qualified.
16524 if (!FD->getReturnType()->getAs<AutoType>()) {
16525 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16526 << FD->getReturnType();
16527 FD->setInvalidDecl();
16528 } else {
16529 // Falling off the end of the function is the same as 'return;'.
16530 Expr *Dummy = nullptr;
16532 FD, dcl->getLocation(), Dummy,
16533 FD->getReturnType()->getAs<AutoType>()))
16534 FD->setInvalidDecl();
16535 }
16536 }
16537 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16538 // In C++11, we don't use 'auto' deduction rules for lambda call
16539 // operators because we don't support return type deduction.
16540 auto *LSI = getCurLambda();
16541 if (LSI->HasImplicitReturnType) {
16543
16544 // C++11 [expr.prim.lambda]p4:
16545 // [...] if there are no return statements in the compound-statement
16546 // [the deduced type is] the type void
16547 QualType RetType =
16548 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16549
16550 // Update the return type to the deduced type.
16551 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16552 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16553 Proto->getExtProtoInfo()));
16554 }
16555 }
16556
16557 // If the function implicitly returns zero (like 'main') or is naked,
16558 // don't complain about missing return statements.
16559 // Clang implicitly returns 0 in C89 mode, but that's considered an
16560 // extension. The check is necessary to ensure the expected extension
16561 // warning is emitted in C89 mode.
16562 if ((FD->hasImplicitReturnZero() &&
16563 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16564 FD->hasAttr<NakedAttr>())
16566
16567 // MSVC permits the use of pure specifier (=0) on function definition,
16568 // defined at class scope, warn about this non-standard construct.
16569 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16570 !FD->isOutOfLine())
16571 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16572
16573 if (!FD->isInvalidDecl()) {
16574 // Don't diagnose unused parameters of defaulted, deleted or naked
16575 // functions.
16576 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16577 !FD->hasAttr<NakedAttr>())
16580 FD->getReturnType(), FD);
16581
16582 // If this is a structor, we need a vtable.
16583 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16584 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16585 else if (CXXDestructorDecl *Destructor =
16586 dyn_cast<CXXDestructorDecl>(FD))
16587 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16588
16589 // Try to apply the named return value optimization. We have to check
16590 // if we can do this here because lambdas keep return statements around
16591 // to deduce an implicit return type.
16592 if (FD->getReturnType()->isRecordType() &&
16594 computeNRVO(Body, FSI);
16595 }
16596
16597 // GNU warning -Wmissing-prototypes:
16598 // Warn if a global function is defined without a previous
16599 // prototype declaration. This warning is issued even if the
16600 // definition itself provides a prototype. The aim is to detect
16601 // global functions that fail to be declared in header files.
16602 const FunctionDecl *PossiblePrototype = nullptr;
16603 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16604 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16605
16606 if (PossiblePrototype) {
16607 // We found a declaration that is not a prototype,
16608 // but that could be a zero-parameter prototype
16609 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16610 TypeLoc TL = TI->getTypeLoc();
16612 Diag(PossiblePrototype->getLocation(),
16613 diag::note_declaration_not_a_prototype)
16614 << (FD->getNumParams() != 0)
16616 FTL.getRParenLoc(), "void")
16617 : FixItHint{});
16618 }
16619 } else {
16620 // Returns true if the token beginning at this Loc is `const`.
16621 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16622 const LangOptions &LangOpts) {
16623 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16624 if (LocInfo.first.isInvalid())
16625 return false;
16626
16627 bool Invalid = false;
16628 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16629 if (Invalid)
16630 return false;
16631
16632 if (LocInfo.second > Buffer.size())
16633 return false;
16634
16635 const char *LexStart = Buffer.data() + LocInfo.second;
16636 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16637
16638 return StartTok.consume_front("const") &&
16639 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16640 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16641 };
16642
16643 auto findBeginLoc = [&]() {
16644 // If the return type has `const` qualifier, we want to insert
16645 // `static` before `const` (and not before the typename).
16646 if ((FD->getReturnType()->isAnyPointerType() &&
16649 // But only do this if we can determine where the `const` is.
16650
16651 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16652 getLangOpts()))
16653
16654 return FD->getBeginLoc();
16655 }
16656 return FD->getTypeSpecStartLoc();
16657 };
16659 diag::note_static_for_internal_linkage)
16660 << /* function */ 1
16661 << (FD->getStorageClass() == SC_None
16662 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16663 : FixItHint{});
16664 }
16665 }
16666
16667 // We might not have found a prototype because we didn't wish to warn on
16668 // the lack of a missing prototype. Try again without the checks for
16669 // whether we want to warn on the missing prototype.
16670 if (!PossiblePrototype)
16671 (void)FindPossiblePrototype(FD, PossiblePrototype);
16672
16673 // If the function being defined does not have a prototype, then we may
16674 // need to diagnose it as changing behavior in C23 because we now know
16675 // whether the function accepts arguments or not. This only handles the
16676 // case where the definition has no prototype but does have parameters
16677 // and either there is no previous potential prototype, or the previous
16678 // potential prototype also has no actual prototype. This handles cases
16679 // like:
16680 // void f(); void f(a) int a; {}
16681 // void g(a) int a; {}
16682 // See MergeFunctionDecl() for other cases of the behavior change
16683 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16684 // type without a prototype.
16685 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16686 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16687 !PossiblePrototype->isImplicit()))) {
16688 // The function definition has parameters, so this will change behavior
16689 // in C23. If there is a possible prototype, it comes before the
16690 // function definition.
16691 // FIXME: The declaration may have already been diagnosed as being
16692 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16693 // there's no way to test for the "changes behavior" condition in
16694 // SemaType.cpp when forming the declaration's function type. So, we do
16695 // this awkward dance instead.
16696 //
16697 // If we have a possible prototype and it declares a function with a
16698 // prototype, we don't want to diagnose it; if we have a possible
16699 // prototype and it has no prototype, it may have already been
16700 // diagnosed in SemaType.cpp as deprecated depending on whether
16701 // -Wstrict-prototypes is enabled. If we already warned about it being
16702 // deprecated, add a note that it also changes behavior. If we didn't
16703 // warn about it being deprecated (because the diagnostic is not
16704 // enabled), warn now that it is deprecated and changes behavior.
16705
16706 // This K&R C function definition definitely changes behavior in C23,
16707 // so diagnose it.
16708 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16709 << /*definition*/ 1 << /* not supported in C23 */ 0;
16710
16711 // If we have a possible prototype for the function which is a user-
16712 // visible declaration, we already tested that it has no prototype.
16713 // This will change behavior in C23. This gets a warning rather than a
16714 // note because it's the same behavior-changing problem as with the
16715 // definition.
16716 if (PossiblePrototype)
16717 Diag(PossiblePrototype->getLocation(),
16718 diag::warn_non_prototype_changes_behavior)
16719 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16720 << /*definition*/ 1;
16721 }
16722
16723 // Warn on CPUDispatch with an actual body.
16724 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16725 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16726 if (!CmpndBody->body_empty())
16727 Diag(CmpndBody->body_front()->getBeginLoc(),
16728 diag::warn_dispatch_body_ignored);
16729
16730 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16731 const CXXMethodDecl *KeyFunction;
16732 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16733 MD->isVirtual() &&
16734 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16735 MD == KeyFunction->getCanonicalDecl()) {
16736 // Update the key-function state if necessary for this ABI.
16737 if (FD->isInlined() &&
16738 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16739 Context.setNonKeyFunction(MD);
16740
16741 // If the newly-chosen key function is already defined, then we
16742 // need to mark the vtable as used retroactively.
16743 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16744 const FunctionDecl *Definition;
16745 if (KeyFunction && KeyFunction->isDefined(Definition))
16746 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16747 } else {
16748 // We just defined they key function; mark the vtable as used.
16749 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16750 }
16751 }
16752 }
16753
16754 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16755 "Function parsing confused");
16756 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16757 assert(MD == getCurMethodDecl() && "Method parsing confused");
16758 MD->setBody(Body);
16759 if (!MD->isInvalidDecl()) {
16761 MD->getReturnType(), MD);
16762
16763 if (Body)
16764 computeNRVO(Body, FSI);
16765 }
16766 if (FSI->ObjCShouldCallSuper) {
16767 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16768 << MD->getSelector().getAsString();
16769 FSI->ObjCShouldCallSuper = false;
16770 }
16772 const ObjCMethodDecl *InitMethod = nullptr;
16773 bool isDesignated =
16774 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16775 assert(isDesignated && InitMethod);
16776 (void)isDesignated;
16777
16778 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16779 auto IFace = MD->getClassInterface();
16780 if (!IFace)
16781 return false;
16782 auto SuperD = IFace->getSuperClass();
16783 if (!SuperD)
16784 return false;
16785 return SuperD->getIdentifier() ==
16786 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16787 };
16788 // Don't issue this warning for unavailable inits or direct subclasses
16789 // of NSObject.
16790 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16791 Diag(MD->getLocation(),
16792 diag::warn_objc_designated_init_missing_super_call);
16793 Diag(InitMethod->getLocation(),
16794 diag::note_objc_designated_init_marked_here);
16795 }
16797 }
16798 if (FSI->ObjCWarnForNoInitDelegation) {
16799 // Don't issue this warning for unavailable inits.
16800 if (!MD->isUnavailable())
16801 Diag(MD->getLocation(),
16802 diag::warn_objc_secondary_init_missing_init_call);
16803 FSI->ObjCWarnForNoInitDelegation = false;
16804 }
16805
16807 } else {
16808 // Parsing the function declaration failed in some way. Pop the fake scope
16809 // we pushed on.
16810 PopFunctionScopeInfo(ActivePolicy, dcl);
16811 return nullptr;
16812 }
16813
16814 if (Body && FSI->HasPotentialAvailabilityViolations)
16816
16817 assert(!FSI->ObjCShouldCallSuper &&
16818 "This should only be set for ObjC methods, which should have been "
16819 "handled in the block above.");
16820
16821 // Verify and clean out per-function state.
16822 if (Body && (!FD || !FD->isDefaulted())) {
16823 // C++ constructors that have function-try-blocks can't have return
16824 // statements in the handlers of that block. (C++ [except.handle]p14)
16825 // Verify this.
16826 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16828
16829 // Verify that gotos and switch cases don't jump into scopes illegally.
16830 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16832
16833 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16834 if (!Destructor->getParent()->isDependentType())
16836
16838 Destructor->getParent());
16839 }
16840
16841 // If any errors have occurred, clear out any temporaries that may have
16842 // been leftover. This ensures that these temporaries won't be picked up
16843 // for deletion in some later function.
16846 getDiagnostics().getSuppressAllDiagnostics()) {
16848 }
16850 // Since the body is valid, issue any analysis-based warnings that are
16851 // enabled.
16852 ActivePolicy = &WP;
16853 }
16854
16855 if (!IsInstantiation && FD &&
16856 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16857 !FD->isInvalidDecl() &&
16859 FD->setInvalidDecl();
16860
16861 if (FD && FD->hasAttr<NakedAttr>()) {
16862 for (const Stmt *S : Body->children()) {
16863 // Allow local register variables without initializer as they don't
16864 // require prologue.
16865 bool RegisterVariables = false;
16866 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16867 for (const auto *Decl : DS->decls()) {
16868 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16869 RegisterVariables =
16870 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16871 if (!RegisterVariables)
16872 break;
16873 }
16874 }
16875 }
16876 if (RegisterVariables)
16877 continue;
16878 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16879 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16880 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16881 FD->setInvalidDecl();
16882 break;
16883 }
16884 }
16885 }
16886
16887 assert(ExprCleanupObjects.size() ==
16888 ExprEvalContexts.back().NumCleanupObjects &&
16889 "Leftover temporaries in function");
16890 assert(!Cleanup.exprNeedsCleanups() &&
16891 "Unaccounted cleanups in function");
16892 assert(MaybeODRUseExprs.empty() &&
16893 "Leftover expressions for odr-use checking");
16894 }
16895 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16896 // the declaration context below. Otherwise, we're unable to transform
16897 // 'this' expressions when transforming immediate context functions.
16898
16899 if (FD)
16901
16902 if (!IsInstantiation)
16904
16905 if (!RetainFunctionScopeInfo)
16906 PopFunctionScopeInfo(ActivePolicy, dcl);
16907 // If any errors have occurred, clear out any temporaries that may have
16908 // been leftover. This ensures that these temporaries won't be picked up for
16909 // deletion in some later function.
16912 }
16913
16914 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16915 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16916 auto ES = getEmissionStatus(FD);
16920 }
16921
16922 if (FD && !FD->isDeleted())
16923 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16924
16925 return dcl;
16926}
16927
16928/// When we finish delayed parsing of an attribute, we must attach it to the
16929/// relevant Decl.
16931 ParsedAttributes &Attrs) {
16932 // Always attach attributes to the underlying decl.
16933 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16934 D = TD->getTemplatedDecl();
16935 ProcessDeclAttributeList(S, D, Attrs);
16936 ProcessAPINotes(D);
16937
16938 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16939 if (Method->isStatic())
16941}
16942
16944 IdentifierInfo &II, Scope *S) {
16945 // It is not valid to implicitly define a function in C23.
16946 assert(LangOpts.implicitFunctionsAllowed() &&
16947 "Implicit function declarations aren't allowed in this language mode");
16948
16949 // Find the scope in which the identifier is injected and the corresponding
16950 // DeclContext.
16951 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16952 // In that case, we inject the declaration into the translation unit scope
16953 // instead.
16954 Scope *BlockScope = S;
16955 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16956 BlockScope = BlockScope->getParent();
16957
16958 // Loop until we find a DeclContext that is either a function/method or the
16959 // translation unit, which are the only two valid places to implicitly define
16960 // a function. This avoids accidentally defining the function within a tag
16961 // declaration, for example.
16962 Scope *ContextScope = BlockScope;
16963 while (!ContextScope->getEntity() ||
16964 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16965 !ContextScope->getEntity()->isTranslationUnit()))
16966 ContextScope = ContextScope->getParent();
16967 ContextRAII SavedContext(*this, ContextScope->getEntity());
16968
16969 // Before we produce a declaration for an implicitly defined
16970 // function, see whether there was a locally-scoped declaration of
16971 // this name as a function or variable. If so, use that
16972 // (non-visible) declaration, and complain about it.
16973 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16974 if (ExternCPrev) {
16975 // We still need to inject the function into the enclosing block scope so
16976 // that later (non-call) uses can see it.
16977 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16978
16979 // C89 footnote 38:
16980 // If in fact it is not defined as having type "function returning int",
16981 // the behavior is undefined.
16982 if (!isa<FunctionDecl>(ExternCPrev) ||
16983 !Context.typesAreCompatible(
16984 cast<FunctionDecl>(ExternCPrev)->getType(),
16985 Context.getFunctionNoProtoType(Context.IntTy))) {
16986 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16987 << ExternCPrev << !getLangOpts().C99;
16988 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16989 return ExternCPrev;
16990 }
16991 }
16992
16993 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16994 unsigned diag_id;
16995 if (II.getName().starts_with("__builtin_"))
16996 diag_id = diag::warn_builtin_unknown;
16997 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16998 else if (getLangOpts().C99)
16999 diag_id = diag::ext_implicit_function_decl_c99;
17000 else
17001 diag_id = diag::warn_implicit_function_decl;
17002
17003 TypoCorrection Corrected;
17004 // Because typo correction is expensive, only do it if the implicit
17005 // function declaration is going to be treated as an error.
17006 //
17007 // Perform the correction before issuing the main diagnostic, as some
17008 // consumers use typo-correction callbacks to enhance the main diagnostic.
17009 if (S && !ExternCPrev &&
17010 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17012 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17013 S, nullptr, CCC, CorrectTypoKind::NonError);
17014 }
17015
17016 Diag(Loc, diag_id) << &II;
17017 if (Corrected) {
17018 // If the correction is going to suggest an implicitly defined function,
17019 // skip the correction as not being a particularly good idea.
17020 bool Diagnose = true;
17021 if (const auto *D = Corrected.getCorrectionDecl())
17022 Diagnose = !D->isImplicit();
17023 if (Diagnose)
17024 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17025 /*ErrorRecovery*/ false);
17026 }
17027
17028 // If we found a prior declaration of this function, don't bother building
17029 // another one. We've already pushed that one into scope, so there's nothing
17030 // more to do.
17031 if (ExternCPrev)
17032 return ExternCPrev;
17033
17034 // Set a Declarator for the implicit definition: int foo();
17035 const char *Dummy;
17036 AttributeFactory attrFactory;
17037 DeclSpec DS(attrFactory);
17038 unsigned DiagID;
17039 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17040 Context.getPrintingPolicy());
17041 (void)Error; // Silence warning.
17042 assert(!Error && "Error setting up implicit decl!");
17043 SourceLocation NoLoc;
17045 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17046 /*IsAmbiguous=*/false,
17047 /*LParenLoc=*/NoLoc,
17048 /*Params=*/nullptr,
17049 /*NumParams=*/0,
17050 /*EllipsisLoc=*/NoLoc,
17051 /*RParenLoc=*/NoLoc,
17052 /*RefQualifierIsLvalueRef=*/true,
17053 /*RefQualifierLoc=*/NoLoc,
17054 /*MutableLoc=*/NoLoc, EST_None,
17055 /*ESpecRange=*/SourceRange(),
17056 /*Exceptions=*/nullptr,
17057 /*ExceptionRanges=*/nullptr,
17058 /*NumExceptions=*/0,
17059 /*NoexceptExpr=*/nullptr,
17060 /*ExceptionSpecTokens=*/nullptr,
17061 /*DeclsInPrototype=*/{}, Loc, Loc,
17062 D),
17063 std::move(DS.getAttributes()), SourceLocation());
17064 D.SetIdentifier(&II, Loc);
17065
17066 // Insert this function into the enclosing block scope.
17067 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17068 FD->setImplicit();
17069
17071
17072 return FD;
17073}
17074
17076 FunctionDecl *FD) {
17077 if (FD->isInvalidDecl())
17078 return;
17079
17080 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17081 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17082 return;
17083
17084 UnsignedOrNone AlignmentParam = std::nullopt;
17085 bool IsNothrow = false;
17086 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17087 return;
17088
17089 // C++2a [basic.stc.dynamic.allocation]p4:
17090 // An allocation function that has a non-throwing exception specification
17091 // indicates failure by returning a null pointer value. Any other allocation
17092 // function never returns a null pointer value and indicates failure only by
17093 // throwing an exception [...]
17094 //
17095 // However, -fcheck-new invalidates this possible assumption, so don't add
17096 // NonNull when that is enabled.
17097 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17098 !getLangOpts().CheckNew)
17099 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17100
17101 // C++2a [basic.stc.dynamic.allocation]p2:
17102 // An allocation function attempts to allocate the requested amount of
17103 // storage. [...] If the request succeeds, the value returned by a
17104 // replaceable allocation function is a [...] pointer value p0 different
17105 // from any previously returned value p1 [...]
17106 //
17107 // However, this particular information is being added in codegen,
17108 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17109
17110 // C++2a [basic.stc.dynamic.allocation]p2:
17111 // An allocation function attempts to allocate the requested amount of
17112 // storage. If it is successful, it returns the address of the start of a
17113 // block of storage whose length in bytes is at least as large as the
17114 // requested size.
17115 if (!FD->hasAttr<AllocSizeAttr>()) {
17116 FD->addAttr(AllocSizeAttr::CreateImplicit(
17117 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17118 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17119 }
17120
17121 // C++2a [basic.stc.dynamic.allocation]p3:
17122 // For an allocation function [...], the pointer returned on a successful
17123 // call shall represent the address of storage that is aligned as follows:
17124 // (3.1) If the allocation function takes an argument of type
17125 // std​::​align_­val_­t, the storage will have the alignment
17126 // specified by the value of this argument.
17127 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17128 FD->addAttr(AllocAlignAttr::CreateImplicit(
17129 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17130 }
17131
17132 // FIXME:
17133 // C++2a [basic.stc.dynamic.allocation]p3:
17134 // For an allocation function [...], the pointer returned on a successful
17135 // call shall represent the address of storage that is aligned as follows:
17136 // (3.2) Otherwise, if the allocation function is named operator new[],
17137 // the storage is aligned for any object that does not have
17138 // new-extended alignment ([basic.align]) and is no larger than the
17139 // requested size.
17140 // (3.3) Otherwise, the storage is aligned for any object that does not
17141 // have new-extended alignment and is of the requested size.
17142}
17143
17145 if (FD->isInvalidDecl())
17146 return;
17147
17148 // If this is a built-in function, map its builtin attributes to
17149 // actual attributes.
17150 if (unsigned BuiltinID = FD->getBuiltinID()) {
17151 // Handle printf-formatting attributes.
17152 unsigned FormatIdx;
17153 bool HasVAListArg;
17154 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17155 if (!FD->hasAttr<FormatAttr>()) {
17156 const char *fmt = "printf";
17157 unsigned int NumParams = FD->getNumParams();
17158 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17159 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17160 fmt = "NSString";
17161 FD->addAttr(FormatAttr::CreateImplicit(Context,
17162 &Context.Idents.get(fmt),
17163 FormatIdx+1,
17164 HasVAListArg ? 0 : FormatIdx+2,
17165 FD->getLocation()));
17166 }
17167 }
17168 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17169 HasVAListArg)) {
17170 if (!FD->hasAttr<FormatAttr>())
17171 FD->addAttr(FormatAttr::CreateImplicit(Context,
17172 &Context.Idents.get("scanf"),
17173 FormatIdx+1,
17174 HasVAListArg ? 0 : FormatIdx+2,
17175 FD->getLocation()));
17176 }
17177
17178 // Handle automatically recognized callbacks.
17179 SmallVector<int, 4> Encoding;
17180 if (!FD->hasAttr<CallbackAttr>() &&
17181 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17182 FD->addAttr(CallbackAttr::CreateImplicit(
17183 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17184
17185 // Mark const if we don't care about errno and/or floating point exceptions
17186 // that are the only thing preventing the function from being const. This
17187 // allows IRgen to use LLVM intrinsics for such functions.
17188 bool NoExceptions =
17190 bool ConstWithoutErrnoAndExceptions =
17191 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17192 bool ConstWithoutExceptions =
17193 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17194 if (!FD->hasAttr<ConstAttr>() &&
17195 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17196 (!ConstWithoutErrnoAndExceptions ||
17197 (!getLangOpts().MathErrno && NoExceptions)) &&
17198 (!ConstWithoutExceptions || NoExceptions))
17199 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17200
17201 // We make "fma" on GNU or Windows const because we know it does not set
17202 // errno in those environments even though it could set errno based on the
17203 // C standard.
17204 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17205 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17206 !FD->hasAttr<ConstAttr>()) {
17207 switch (BuiltinID) {
17208 case Builtin::BI__builtin_fma:
17209 case Builtin::BI__builtin_fmaf:
17210 case Builtin::BI__builtin_fmal:
17211 case Builtin::BIfma:
17212 case Builtin::BIfmaf:
17213 case Builtin::BIfmal:
17214 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17215 break;
17216 default:
17217 break;
17218 }
17219 }
17220
17221 SmallVector<int, 4> Indxs;
17223 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17224 !FD->hasAttr<NonNullAttr>()) {
17226 for (int I : Indxs) {
17227 ParmVarDecl *PVD = FD->getParamDecl(I);
17228 QualType T = PVD->getType();
17229 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17230 PVD->setType(T);
17231 }
17232 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17234 for (int I : Indxs)
17235 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17236 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17237 ParamIndxs.size()));
17238 }
17239 }
17240 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17241 !FD->hasAttr<ReturnsTwiceAttr>())
17242 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17243 FD->getLocation()));
17244 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17245 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17246 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17247 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17248 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17249 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17250 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17251 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17252 // Add the appropriate attribute, depending on the CUDA compilation mode
17253 // and which target the builtin belongs to. For example, during host
17254 // compilation, aux builtins are __device__, while the rest are __host__.
17255 if (getLangOpts().CUDAIsDevice !=
17256 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17257 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17258 else
17259 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17260 }
17261
17262 // Add known guaranteed alignment for allocation functions.
17263 switch (BuiltinID) {
17264 case Builtin::BImemalign:
17265 case Builtin::BIaligned_alloc:
17266 if (!FD->hasAttr<AllocAlignAttr>())
17267 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17268 FD->getLocation()));
17269 break;
17270 default:
17271 break;
17272 }
17273
17274 // Add allocsize attribute for allocation functions.
17275 switch (BuiltinID) {
17276 case Builtin::BIcalloc:
17277 FD->addAttr(AllocSizeAttr::CreateImplicit(
17278 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17279 break;
17280 case Builtin::BImemalign:
17281 case Builtin::BIaligned_alloc:
17282 case Builtin::BIrealloc:
17283 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17284 ParamIdx(), FD->getLocation()));
17285 break;
17286 case Builtin::BImalloc:
17287 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17288 ParamIdx(), FD->getLocation()));
17289 break;
17290 default:
17291 break;
17292 }
17293 }
17294
17299
17300 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17301 // throw, add an implicit nothrow attribute to any extern "C" function we come
17302 // across.
17303 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17304 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17305 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17306 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17307 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17308 }
17309
17310 IdentifierInfo *Name = FD->getIdentifier();
17311 if (!Name)
17312 return;
17315 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17317 // Okay: this could be a libc/libm/Objective-C function we know
17318 // about.
17319 } else
17320 return;
17321
17322 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17323 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17324 // target-specific builtins, perhaps?
17325 if (!FD->hasAttr<FormatAttr>())
17326 FD->addAttr(FormatAttr::CreateImplicit(Context,
17327 &Context.Idents.get("printf"), 2,
17328 Name->isStr("vasprintf") ? 0 : 3,
17329 FD->getLocation()));
17330 }
17331
17332 if (Name->isStr("__CFStringMakeConstantString")) {
17333 // We already have a __builtin___CFStringMakeConstantString,
17334 // but builds that use -fno-constant-cfstrings don't go through that.
17335 if (!FD->hasAttr<FormatArgAttr>())
17336 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17337 FD->getLocation()));
17338 }
17339}
17340
17342 TypeSourceInfo *TInfo) {
17343 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17344 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17345
17346 if (!TInfo) {
17347 assert(D.isInvalidType() && "no declarator info for valid type");
17348 TInfo = Context.getTrivialTypeSourceInfo(T);
17349 }
17350
17351 // Scope manipulation handled by caller.
17352 TypedefDecl *NewTD =
17354 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17355
17356 // Bail out immediately if we have an invalid declaration.
17357 if (D.isInvalidType()) {
17358 NewTD->setInvalidDecl();
17359 return NewTD;
17360 }
17361
17363 if (CurContext->isFunctionOrMethod())
17364 Diag(NewTD->getLocation(), diag::err_module_private_local)
17365 << 2 << NewTD
17369 else
17370 NewTD->setModulePrivate();
17371 }
17372
17373 // C++ [dcl.typedef]p8:
17374 // If the typedef declaration defines an unnamed class (or
17375 // enum), the first typedef-name declared by the declaration
17376 // to be that class type (or enum type) is used to denote the
17377 // class type (or enum type) for linkage purposes only.
17378 // We need to check whether the type was declared in the declaration.
17379 switch (D.getDeclSpec().getTypeSpecType()) {
17380 case TST_enum:
17381 case TST_struct:
17382 case TST_interface:
17383 case TST_union:
17384 case TST_class: {
17385 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17386 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17387 break;
17388 }
17389
17390 default:
17391 break;
17392 }
17393
17394 return NewTD;
17395}
17396
17398 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17399 QualType T = TI->getType();
17400
17401 if (T->isDependentType())
17402 return false;
17403
17404 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17405 // integral type; any cv-qualification is ignored.
17406 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17407 // non-atomic version of the type specified by the type specifiers in the
17408 // specifier qualifier list.
17409 // Because of how odd C's rule is, we'll let the user know that operations
17410 // involving the enumeration type will be non-atomic.
17411 if (T->isAtomicType())
17412 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17413
17414 Qualifiers Q = T.getQualifiers();
17415 std::optional<unsigned> QualSelect;
17416 if (Q.hasConst() && Q.hasVolatile())
17417 QualSelect = diag::CVQualList::Both;
17418 else if (Q.hasConst())
17419 QualSelect = diag::CVQualList::Const;
17420 else if (Q.hasVolatile())
17421 QualSelect = diag::CVQualList::Volatile;
17422
17423 if (QualSelect)
17424 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17425
17426 T = T.getAtomicUnqualifiedType();
17427
17428 // This doesn't use 'isIntegralType' despite the error message mentioning
17429 // integral type because isIntegralType would also allow enum types in C.
17430 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17431 if (BT->isInteger())
17432 return false;
17433
17434 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17435 << T << T->isBitIntType();
17436}
17437
17439 QualType EnumUnderlyingTy, bool IsFixed,
17440 const EnumDecl *Prev) {
17441 if (IsScoped != Prev->isScoped()) {
17442 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17443 << Prev->isScoped();
17444 Diag(Prev->getLocation(), diag::note_previous_declaration);
17445 return true;
17446 }
17447
17448 if (IsFixed && Prev->isFixed()) {
17449 if (!EnumUnderlyingTy->isDependentType() &&
17450 !Prev->getIntegerType()->isDependentType() &&
17451 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17452 Prev->getIntegerType())) {
17453 // TODO: Highlight the underlying type of the redeclaration.
17454 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17455 << EnumUnderlyingTy << Prev->getIntegerType();
17456 Diag(Prev->getLocation(), diag::note_previous_declaration)
17457 << Prev->getIntegerTypeRange();
17458 return true;
17459 }
17460 } else if (IsFixed != Prev->isFixed()) {
17461 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17462 << Prev->isFixed();
17463 Diag(Prev->getLocation(), diag::note_previous_declaration);
17464 return true;
17465 }
17466
17467 return false;
17468}
17469
17470/// Get diagnostic %select index for tag kind for
17471/// redeclaration diagnostic message.
17472/// WARNING: Indexes apply to particular diagnostics only!
17473///
17474/// \returns diagnostic %select index.
17476 switch (Tag) {
17478 return 0;
17480 return 1;
17481 case TagTypeKind::Class:
17482 return 2;
17483 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17484 }
17485}
17486
17487/// Determine if tag kind is a class-key compatible with
17488/// class for redeclaration (class, struct, or __interface).
17489///
17490/// \returns true iff the tag kind is compatible.
17492{
17493 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17495}
17496
17498 if (isa<TypedefDecl>(PrevDecl))
17499 return NonTagKind::Typedef;
17500 else if (isa<TypeAliasDecl>(PrevDecl))
17501 return NonTagKind::TypeAlias;
17502 else if (isa<ClassTemplateDecl>(PrevDecl))
17503 return NonTagKind::Template;
17504 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17506 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17508 switch (TTK) {
17511 case TagTypeKind::Class:
17512 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17514 case TagTypeKind::Union:
17515 return NonTagKind::NonUnion;
17516 case TagTypeKind::Enum:
17517 return NonTagKind::NonEnum;
17518 }
17519 llvm_unreachable("invalid TTK");
17520}
17521
17523 TagTypeKind NewTag, bool isDefinition,
17524 SourceLocation NewTagLoc,
17525 const IdentifierInfo *Name) {
17526 // C++ [dcl.type.elab]p3:
17527 // The class-key or enum keyword present in the
17528 // elaborated-type-specifier shall agree in kind with the
17529 // declaration to which the name in the elaborated-type-specifier
17530 // refers. This rule also applies to the form of
17531 // elaborated-type-specifier that declares a class-name or
17532 // friend class since it can be construed as referring to the
17533 // definition of the class. Thus, in any
17534 // elaborated-type-specifier, the enum keyword shall be used to
17535 // refer to an enumeration (7.2), the union class-key shall be
17536 // used to refer to a union (clause 9), and either the class or
17537 // struct class-key shall be used to refer to a class (clause 9)
17538 // declared using the class or struct class-key.
17539 TagTypeKind OldTag = Previous->getTagKind();
17540 if (OldTag != NewTag &&
17542 return false;
17543
17544 // Tags are compatible, but we might still want to warn on mismatched tags.
17545 // Non-class tags can't be mismatched at this point.
17547 return true;
17548
17549 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17550 // by our warning analysis. We don't want to warn about mismatches with (eg)
17551 // declarations in system headers that are designed to be specialized, but if
17552 // a user asks us to warn, we should warn if their code contains mismatched
17553 // declarations.
17554 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17555 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17556 Loc);
17557 };
17558 if (IsIgnoredLoc(NewTagLoc))
17559 return true;
17560
17561 auto IsIgnored = [&](const TagDecl *Tag) {
17562 return IsIgnoredLoc(Tag->getLocation());
17563 };
17564 while (IsIgnored(Previous)) {
17565 Previous = Previous->getPreviousDecl();
17566 if (!Previous)
17567 return true;
17568 OldTag = Previous->getTagKind();
17569 }
17570
17571 bool isTemplate = false;
17572 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17573 isTemplate = Record->getDescribedClassTemplate();
17574
17576 if (OldTag != NewTag) {
17577 // In a template instantiation, do not offer fix-its for tag mismatches
17578 // since they usually mess up the template instead of fixing the problem.
17579 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17581 << getRedeclDiagFromTagKind(OldTag);
17582 // FIXME: Note previous location?
17583 }
17584 return true;
17585 }
17586
17587 if (isDefinition) {
17588 // On definitions, check all previous tags and issue a fix-it for each
17589 // one that doesn't match the current tag.
17590 if (Previous->getDefinition()) {
17591 // Don't suggest fix-its for redefinitions.
17592 return true;
17593 }
17594
17595 bool previousMismatch = false;
17596 for (const TagDecl *I : Previous->redecls()) {
17597 if (I->getTagKind() != NewTag) {
17598 // Ignore previous declarations for which the warning was disabled.
17599 if (IsIgnored(I))
17600 continue;
17601
17602 if (!previousMismatch) {
17603 previousMismatch = true;
17604 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17606 << getRedeclDiagFromTagKind(I->getTagKind());
17607 }
17608 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17610 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17612 }
17613 }
17614 return true;
17615 }
17616
17617 // Identify the prevailing tag kind: this is the kind of the definition (if
17618 // there is a non-ignored definition), or otherwise the kind of the prior
17619 // (non-ignored) declaration.
17620 const TagDecl *PrevDef = Previous->getDefinition();
17621 if (PrevDef && IsIgnored(PrevDef))
17622 PrevDef = nullptr;
17623 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17624 if (Redecl->getTagKind() != NewTag) {
17625 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17627 << getRedeclDiagFromTagKind(OldTag);
17628 Diag(Redecl->getLocation(), diag::note_previous_use);
17629
17630 // If there is a previous definition, suggest a fix-it.
17631 if (PrevDef) {
17632 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17636 }
17637 }
17638
17639 return true;
17640}
17641
17642/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17643/// from an outer enclosing namespace or file scope inside a friend declaration.
17644/// This should provide the commented out code in the following snippet:
17645/// namespace N {
17646/// struct X;
17647/// namespace M {
17648/// struct Y { friend struct /*N::*/ X; };
17649/// }
17650/// }
17652 SourceLocation NameLoc) {
17653 // While the decl is in a namespace, do repeated lookup of that name and see
17654 // if we get the same namespace back. If we do not, continue until
17655 // translation unit scope, at which point we have a fully qualified NNS.
17658 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17659 // This tag should be declared in a namespace, which can only be enclosed by
17660 // other namespaces. Bail if there's an anonymous namespace in the chain.
17661 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17662 if (!Namespace || Namespace->isAnonymousNamespace())
17663 return FixItHint();
17664 IdentifierInfo *II = Namespace->getIdentifier();
17665 Namespaces.push_back(II);
17666 NamedDecl *Lookup = SemaRef.LookupSingleName(
17667 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17668 if (Lookup == Namespace)
17669 break;
17670 }
17671
17672 // Once we have all the namespaces, reverse them to go outermost first, and
17673 // build an NNS.
17674 SmallString<64> Insertion;
17675 llvm::raw_svector_ostream OS(Insertion);
17676 if (DC->isTranslationUnit())
17677 OS << "::";
17678 std::reverse(Namespaces.begin(), Namespaces.end());
17679 for (auto *II : Namespaces)
17680 OS << II->getName() << "::";
17681 return FixItHint::CreateInsertion(NameLoc, Insertion);
17682}
17683
17684/// Determine whether a tag originally declared in context \p OldDC can
17685/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17686/// found a declaration in \p OldDC as a previous decl, perhaps through a
17687/// using-declaration).
17689 DeclContext *NewDC) {
17690 OldDC = OldDC->getRedeclContext();
17691 NewDC = NewDC->getRedeclContext();
17692
17693 if (OldDC->Equals(NewDC))
17694 return true;
17695
17696 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17697 // encloses the other).
17698 if (S.getLangOpts().MSVCCompat &&
17699 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17700 return true;
17701
17702 return false;
17703}
17704
17706Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17707 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17708 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17709 SourceLocation ModulePrivateLoc,
17710 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17711 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17712 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17713 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17714 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17715 // If this is not a definition, it must have a name.
17716 IdentifierInfo *OrigName = Name;
17717 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17718 "Nameless record must be a definition!");
17719 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17720
17721 OwnedDecl = false;
17723 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17724
17725 // FIXME: Check member specializations more carefully.
17726 bool isMemberSpecialization = false;
17727 bool IsInjectedClassName = false;
17728 bool Invalid = false;
17729
17730 // We only need to do this matching if we have template parameters
17731 // or a scope specifier, which also conveniently avoids this work
17732 // for non-C++ cases.
17733 if (TemplateParameterLists.size() > 0 ||
17734 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17735 TemplateParameterList *TemplateParams =
17737 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17738 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17739
17740 // C++23 [dcl.type.elab] p2:
17741 // If an elaborated-type-specifier is the sole constituent of a
17742 // declaration, the declaration is ill-formed unless it is an explicit
17743 // specialization, an explicit instantiation or it has one of the
17744 // following forms: [...]
17745 // C++23 [dcl.enum] p1:
17746 // If the enum-head-name of an opaque-enum-declaration contains a
17747 // nested-name-specifier, the declaration shall be an explicit
17748 // specialization.
17749 //
17750 // FIXME: Class template partial specializations can be forward declared
17751 // per CWG2213, but the resolution failed to allow qualified forward
17752 // declarations. This is almost certainly unintentional, so we allow them.
17753 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17754 !isMemberSpecialization)
17755 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17757
17758 if (TemplateParams) {
17759 if (Kind == TagTypeKind::Enum) {
17760 Diag(KWLoc, diag::err_enum_template);
17761 return true;
17762 }
17763
17764 if (TemplateParams->size() > 0) {
17765 // This is a declaration or definition of a class template (which may
17766 // be a member of another template).
17767
17768 if (Invalid)
17769 return true;
17770
17771 OwnedDecl = false;
17773 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17774 AS, ModulePrivateLoc,
17775 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17776 TemplateParameterLists.data(), SkipBody);
17777 return Result.get();
17778 } else {
17779 // The "template<>" header is extraneous.
17780 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17781 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17782 isMemberSpecialization = true;
17783 }
17784 }
17785
17786 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17787 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17788 return true;
17789 }
17790
17791 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17792 // C++23 [dcl.type.elab]p4:
17793 // If an elaborated-type-specifier appears with the friend specifier as
17794 // an entire member-declaration, the member-declaration shall have one
17795 // of the following forms:
17796 // friend class-key nested-name-specifier(opt) identifier ;
17797 // friend class-key simple-template-id ;
17798 // friend class-key nested-name-specifier template(opt)
17799 // simple-template-id ;
17800 //
17801 // Since enum is not a class-key, so declarations like "friend enum E;"
17802 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17803 // invalid, most implementations accept so we issue a pedantic warning.
17804 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17805 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17806 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17807 Diag(KWLoc, diag::note_enum_friend)
17808 << (ScopedEnum + ScopedEnumUsesClassTag);
17809 }
17810
17811 // Figure out the underlying type if this a enum declaration. We need to do
17812 // this early, because it's needed to detect if this is an incompatible
17813 // redeclaration.
17814 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17815 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17816
17817 if (Kind == TagTypeKind::Enum) {
17818 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17819 // No underlying type explicitly specified, or we failed to parse the
17820 // type, default to int.
17821 EnumUnderlying = Context.IntTy.getTypePtr();
17822 } else if (UnderlyingType.get()) {
17823 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17824 // integral type; any cv-qualification is ignored.
17825 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17826 // unqualified, non-atomic version of the type specified by the type
17827 // specifiers in the specifier qualifier list.
17828 TypeSourceInfo *TI = nullptr;
17829 GetTypeFromParser(UnderlyingType.get(), &TI);
17830 EnumUnderlying = TI;
17831
17833 // Recover by falling back to int.
17834 EnumUnderlying = Context.IntTy.getTypePtr();
17835
17838 EnumUnderlying = Context.IntTy.getTypePtr();
17839
17840 // If the underlying type is atomic, we need to adjust the type before
17841 // continuing. This only happens in the case we stored a TypeSourceInfo
17842 // into EnumUnderlying because the other cases are error recovery up to
17843 // this point. But because it's not possible to gin up a TypeSourceInfo
17844 // for a non-atomic type from an atomic one, we'll store into the Type
17845 // field instead. FIXME: it would be nice to have an easy way to get a
17846 // derived TypeSourceInfo which strips qualifiers including the weird
17847 // ones like _Atomic where it forms a different type.
17848 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17849 TI && TI->getType()->isAtomicType())
17850 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17851
17852 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17853 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17854 // of 'int'. However, if this is an unfixed forward declaration, don't set
17855 // the underlying type unless the user enables -fms-compatibility. This
17856 // makes unfixed forward declared enums incomplete and is more conforming.
17857 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17858 EnumUnderlying = Context.IntTy.getTypePtr();
17859 }
17860 }
17861
17862 DeclContext *SearchDC = CurContext;
17863 DeclContext *DC = CurContext;
17864 bool isStdBadAlloc = false;
17865 bool isStdAlignValT = false;
17866
17868 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17870
17871 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17872 /// implemented asks for structural equivalence checking, the returned decl
17873 /// here is passed back to the parser, allowing the tag body to be parsed.
17874 auto createTagFromNewDecl = [&]() -> TagDecl * {
17875 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17876 // If there is an identifier, use the location of the identifier as the
17877 // location of the decl, otherwise use the location of the struct/union
17878 // keyword.
17879 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17880 TagDecl *New = nullptr;
17881
17882 if (Kind == TagTypeKind::Enum) {
17883 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17884 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17885 // If this is an undefined enum, bail.
17886 if (TUK != TagUseKind::Definition && !Invalid)
17887 return nullptr;
17888 if (EnumUnderlying) {
17890 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17892 else
17893 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17894 QualType EnumTy = ED->getIntegerType();
17895 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17896 ? Context.getPromotedIntegerType(EnumTy)
17897 : EnumTy);
17898 }
17899 } else { // struct/union
17900 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17901 nullptr);
17902 }
17903
17904 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17905 // Add alignment attributes if necessary; these attributes are checked
17906 // when the ASTContext lays out the structure.
17907 //
17908 // It is important for implementing the correct semantics that this
17909 // happen here (in ActOnTag). The #pragma pack stack is
17910 // maintained as a result of parser callbacks which can occur at
17911 // many points during the parsing of a struct declaration (because
17912 // the #pragma tokens are effectively skipped over during the
17913 // parsing of the struct).
17914 if (TUK == TagUseKind::Definition &&
17915 (!SkipBody || !SkipBody->ShouldSkip)) {
17916 if (LangOpts.HLSL)
17917 RD->addAttr(PackedAttr::CreateImplicit(Context));
17920 }
17921 }
17922 New->setLexicalDeclContext(CurContext);
17923 return New;
17924 };
17925
17926 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17927 if (Name && SS.isNotEmpty()) {
17928 // We have a nested-name tag ('struct foo::bar').
17929
17930 // Check for invalid 'foo::'.
17931 if (SS.isInvalid()) {
17932 Name = nullptr;
17933 goto CreateNewDecl;
17934 }
17935
17936 // If this is a friend or a reference to a class in a dependent
17937 // context, don't try to make a decl for it.
17938 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17939 DC = computeDeclContext(SS, false);
17940 if (!DC) {
17941 IsDependent = true;
17942 return true;
17943 }
17944 } else {
17945 DC = computeDeclContext(SS, true);
17946 if (!DC) {
17947 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17948 << SS.getRange();
17949 return true;
17950 }
17951 }
17952
17953 if (RequireCompleteDeclContext(SS, DC))
17954 return true;
17955
17956 SearchDC = DC;
17957 // Look-up name inside 'foo::'.
17959
17960 if (Previous.isAmbiguous())
17961 return true;
17962
17963 if (Previous.empty()) {
17964 // Name lookup did not find anything. However, if the
17965 // nested-name-specifier refers to the current instantiation,
17966 // and that current instantiation has any dependent base
17967 // classes, we might find something at instantiation time: treat
17968 // this as a dependent elaborated-type-specifier.
17969 // But this only makes any sense for reference-like lookups.
17970 if (Previous.wasNotFoundInCurrentInstantiation() &&
17971 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17972 IsDependent = true;
17973 return true;
17974 }
17975
17976 // A tag 'foo::bar' must already exist.
17977 Diag(NameLoc, diag::err_not_tag_in_scope)
17978 << Kind << Name << DC << SS.getRange();
17979 Name = nullptr;
17980 Invalid = true;
17981 goto CreateNewDecl;
17982 }
17983 } else if (Name) {
17984 // C++14 [class.mem]p14:
17985 // If T is the name of a class, then each of the following shall have a
17986 // name different from T:
17987 // -- every member of class T that is itself a type
17988 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17989 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17990 return true;
17991
17992 // If this is a named struct, check to see if there was a previous forward
17993 // declaration or definition.
17994 // FIXME: We're looking into outer scopes here, even when we
17995 // shouldn't be. Doing so can result in ambiguities that we
17996 // shouldn't be diagnosing.
17997 LookupName(Previous, S);
17998
17999 // When declaring or defining a tag, ignore ambiguities introduced
18000 // by types using'ed into this scope.
18001 if (Previous.isAmbiguous() &&
18003 LookupResult::Filter F = Previous.makeFilter();
18004 while (F.hasNext()) {
18005 NamedDecl *ND = F.next();
18006 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18007 SearchDC->getRedeclContext()))
18008 F.erase();
18009 }
18010 F.done();
18011 }
18012
18013 // C++11 [namespace.memdef]p3:
18014 // If the name in a friend declaration is neither qualified nor
18015 // a template-id and the declaration is a function or an
18016 // elaborated-type-specifier, the lookup to determine whether
18017 // the entity has been previously declared shall not consider
18018 // any scopes outside the innermost enclosing namespace.
18019 //
18020 // MSVC doesn't implement the above rule for types, so a friend tag
18021 // declaration may be a redeclaration of a type declared in an enclosing
18022 // scope. They do implement this rule for friend functions.
18023 //
18024 // Does it matter that this should be by scope instead of by
18025 // semantic context?
18026 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18027 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18028 LookupResult::Filter F = Previous.makeFilter();
18029 bool FriendSawTagOutsideEnclosingNamespace = false;
18030 while (F.hasNext()) {
18031 NamedDecl *ND = F.next();
18033 if (DC->isFileContext() &&
18034 !EnclosingNS->Encloses(ND->getDeclContext())) {
18035 if (getLangOpts().MSVCCompat)
18036 FriendSawTagOutsideEnclosingNamespace = true;
18037 else
18038 F.erase();
18039 }
18040 }
18041 F.done();
18042
18043 // Diagnose this MSVC extension in the easy case where lookup would have
18044 // unambiguously found something outside the enclosing namespace.
18045 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18046 NamedDecl *ND = Previous.getFoundDecl();
18047 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18048 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18049 }
18050 }
18051
18052 // Note: there used to be some attempt at recovery here.
18053 if (Previous.isAmbiguous())
18054 return true;
18055
18056 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18057 // FIXME: This makes sure that we ignore the contexts associated
18058 // with C structs, unions, and enums when looking for a matching
18059 // tag declaration or definition. See the similar lookup tweak
18060 // in Sema::LookupName; is there a better way to deal with this?
18062 SearchDC = SearchDC->getParent();
18063 } else if (getLangOpts().CPlusPlus) {
18064 // Inside ObjCContainer want to keep it as a lexical decl context but go
18065 // past it (most often to TranslationUnit) to find the semantic decl
18066 // context.
18067 while (isa<ObjCContainerDecl>(SearchDC))
18068 SearchDC = SearchDC->getParent();
18069 }
18070 } else if (getLangOpts().CPlusPlus) {
18071 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18072 // TagDecl the same way as we skip it for named TagDecl.
18073 while (isa<ObjCContainerDecl>(SearchDC))
18074 SearchDC = SearchDC->getParent();
18075 }
18076
18077 if (Previous.isSingleResult() &&
18078 Previous.getFoundDecl()->isTemplateParameter()) {
18079 // Maybe we will complain about the shadowed template parameter.
18080 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18081 // Just pretend that we didn't see the previous declaration.
18082 Previous.clear();
18083 }
18084
18085 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18086 DC->Equals(getStdNamespace())) {
18087 if (Name->isStr("bad_alloc")) {
18088 // This is a declaration of or a reference to "std::bad_alloc".
18089 isStdBadAlloc = true;
18090
18091 // If std::bad_alloc has been implicitly declared (but made invisible to
18092 // name lookup), fill in this implicit declaration as the previous
18093 // declaration, so that the declarations get chained appropriately.
18094 if (Previous.empty() && StdBadAlloc)
18095 Previous.addDecl(getStdBadAlloc());
18096 } else if (Name->isStr("align_val_t")) {
18097 isStdAlignValT = true;
18098 if (Previous.empty() && StdAlignValT)
18099 Previous.addDecl(getStdAlignValT());
18100 }
18101 }
18102
18103 // If we didn't find a previous declaration, and this is a reference
18104 // (or friend reference), move to the correct scope. In C++, we
18105 // also need to do a redeclaration lookup there, just in case
18106 // there's a shadow friend decl.
18107 if (Name && Previous.empty() &&
18108 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18109 IsTemplateParamOrArg)) {
18110 if (Invalid) goto CreateNewDecl;
18111 assert(SS.isEmpty());
18112
18113 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18114 // C++ [basic.scope.pdecl]p5:
18115 // -- for an elaborated-type-specifier of the form
18116 //
18117 // class-key identifier
18118 //
18119 // if the elaborated-type-specifier is used in the
18120 // decl-specifier-seq or parameter-declaration-clause of a
18121 // function defined in namespace scope, the identifier is
18122 // declared as a class-name in the namespace that contains
18123 // the declaration; otherwise, except as a friend
18124 // declaration, the identifier is declared in the smallest
18125 // non-class, non-function-prototype scope that contains the
18126 // declaration.
18127 //
18128 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18129 // C structs and unions.
18130 //
18131 // It is an error in C++ to declare (rather than define) an enum
18132 // type, including via an elaborated type specifier. We'll
18133 // diagnose that later; for now, declare the enum in the same
18134 // scope as we would have picked for any other tag type.
18135 //
18136 // GNU C also supports this behavior as part of its incomplete
18137 // enum types extension, while GNU C++ does not.
18138 //
18139 // Find the context where we'll be declaring the tag.
18140 // FIXME: We would like to maintain the current DeclContext as the
18141 // lexical context,
18142 SearchDC = getTagInjectionContext(SearchDC);
18143
18144 // Find the scope where we'll be declaring the tag.
18146 } else {
18147 assert(TUK == TagUseKind::Friend);
18148 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18149
18150 // C++ [namespace.memdef]p3:
18151 // If a friend declaration in a non-local class first declares a
18152 // class or function, the friend class or function is a member of
18153 // the innermost enclosing namespace.
18154 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18155 : SearchDC->getEnclosingNamespaceContext();
18156 }
18157
18158 // In C++, we need to do a redeclaration lookup to properly
18159 // diagnose some problems.
18160 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18161 // hidden declaration so that we don't get ambiguity errors when using a
18162 // type declared by an elaborated-type-specifier. In C that is not correct
18163 // and we should instead merge compatible types found by lookup.
18164 if (getLangOpts().CPlusPlus) {
18165 // FIXME: This can perform qualified lookups into function contexts,
18166 // which are meaningless.
18167 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18168 LookupQualifiedName(Previous, SearchDC);
18169 } else {
18170 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18171 LookupName(Previous, S);
18172 }
18173 }
18174
18175 // If we have a known previous declaration to use, then use it.
18176 if (Previous.empty() && SkipBody && SkipBody->Previous)
18177 Previous.addDecl(SkipBody->Previous);
18178
18179 if (!Previous.empty()) {
18180 NamedDecl *PrevDecl = Previous.getFoundDecl();
18181 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18182
18183 // It's okay to have a tag decl in the same scope as a typedef
18184 // which hides a tag decl in the same scope. Finding this
18185 // with a redeclaration lookup can only actually happen in C++.
18186 //
18187 // This is also okay for elaborated-type-specifiers, which is
18188 // technically forbidden by the current standard but which is
18189 // okay according to the likely resolution of an open issue;
18190 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18191 if (getLangOpts().CPlusPlus) {
18192 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18193 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18194 if (Tag->getDeclName() == Name &&
18195 Tag->getDeclContext()->getRedeclContext()
18196 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18197 PrevDecl = Tag;
18198 Previous.clear();
18199 Previous.addDecl(Tag);
18200 Previous.resolveKind();
18201 }
18202 }
18203 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18204 TUK == TagUseKind::Reference && RD &&
18205 RD->isInjectedClassName()) {
18206 // If lookup found the injected class name, the previous declaration is
18207 // the class being injected into.
18208 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18209 Previous.clear();
18210 Previous.addDecl(PrevDecl);
18211 Previous.resolveKind();
18212 IsInjectedClassName = true;
18213 }
18214 }
18215
18216 // If this is a redeclaration of a using shadow declaration, it must
18217 // declare a tag in the same context. In MSVC mode, we allow a
18218 // redefinition if either context is within the other.
18219 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18220 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18221 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18222 TUK != TagUseKind::Friend &&
18223 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18224 !(OldTag && isAcceptableTagRedeclContext(
18225 *this, OldTag->getDeclContext(), SearchDC))) {
18226 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18227 Diag(Shadow->getTargetDecl()->getLocation(),
18228 diag::note_using_decl_target);
18229 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18230 << 0;
18231 // Recover by ignoring the old declaration.
18232 Previous.clear();
18233 goto CreateNewDecl;
18234 }
18235 }
18236
18237 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18238 // If this is a use of a previous tag, or if the tag is already declared
18239 // in the same scope (so that the definition/declaration completes or
18240 // rementions the tag), reuse the decl.
18241 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18242 isDeclInScope(DirectPrevDecl, SearchDC, S,
18243 SS.isNotEmpty() || isMemberSpecialization)) {
18244 // Make sure that this wasn't declared as an enum and now used as a
18245 // struct or something similar.
18246 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18247 TUK == TagUseKind::Definition, KWLoc,
18248 Name)) {
18249 bool SafeToContinue =
18250 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18251 Kind != TagTypeKind::Enum);
18252 if (SafeToContinue)
18253 Diag(KWLoc, diag::err_use_with_wrong_tag)
18254 << Name
18256 PrevTagDecl->getKindName());
18257 else
18258 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18259 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18260
18261 if (SafeToContinue)
18262 Kind = PrevTagDecl->getTagKind();
18263 else {
18264 // Recover by making this an anonymous redefinition.
18265 Name = nullptr;
18266 Previous.clear();
18267 Invalid = true;
18268 }
18269 }
18270
18271 if (Kind == TagTypeKind::Enum &&
18272 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18273 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18274 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18275 return PrevTagDecl;
18276
18277 QualType EnumUnderlyingTy;
18278 if (TypeSourceInfo *TI =
18279 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18280 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18281 else if (const Type *T =
18282 dyn_cast_if_present<const Type *>(EnumUnderlying))
18283 EnumUnderlyingTy = QualType(T, 0);
18284
18285 // All conflicts with previous declarations are recovered by
18286 // returning the previous declaration, unless this is a definition,
18287 // in which case we want the caller to bail out.
18288 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18289 ScopedEnum, EnumUnderlyingTy,
18290 IsFixed, PrevEnum))
18291 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18292 }
18293
18294 // C++11 [class.mem]p1:
18295 // A member shall not be declared twice in the member-specification,
18296 // except that a nested class or member class template can be declared
18297 // and then later defined.
18298 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18299 S->isDeclScope(PrevDecl)) {
18300 Diag(NameLoc, diag::ext_member_redeclared);
18301 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18302 }
18303
18304 if (!Invalid) {
18305 // If this is a use, just return the declaration we found, unless
18306 // we have attributes.
18307 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18308 if (!Attrs.empty()) {
18309 // FIXME: Diagnose these attributes. For now, we create a new
18310 // declaration to hold them.
18311 } else if (TUK == TagUseKind::Reference &&
18312 (PrevTagDecl->getFriendObjectKind() ==
18314 PrevDecl->getOwningModule() != getCurrentModule()) &&
18315 SS.isEmpty()) {
18316 // This declaration is a reference to an existing entity, but
18317 // has different visibility from that entity: it either makes
18318 // a friend visible or it makes a type visible in a new module.
18319 // In either case, create a new declaration. We only do this if
18320 // the declaration would have meant the same thing if no prior
18321 // declaration were found, that is, if it was found in the same
18322 // scope where we would have injected a declaration.
18323 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18324 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18325 return PrevTagDecl;
18326 // This is in the injected scope, create a new declaration in
18327 // that scope.
18329 } else {
18330 return PrevTagDecl;
18331 }
18332 }
18333
18334 // Diagnose attempts to redefine a tag.
18335 if (TUK == TagUseKind::Definition) {
18336 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18337 // If the type is currently being defined, complain
18338 // about a nested redefinition.
18339 if (Def->isBeingDefined()) {
18340 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18341 Diag(PrevTagDecl->getLocation(),
18342 diag::note_previous_definition);
18343 Name = nullptr;
18344 Previous.clear();
18345 Invalid = true;
18346 } else {
18347 // If we're defining a specialization and the previous
18348 // definition is from an implicit instantiation, don't emit an
18349 // error here; we'll catch this in the general case below.
18350 bool IsExplicitSpecializationAfterInstantiation = false;
18351 if (isMemberSpecialization) {
18352 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18353 IsExplicitSpecializationAfterInstantiation =
18354 RD->getTemplateSpecializationKind() !=
18356 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18357 IsExplicitSpecializationAfterInstantiation =
18358 ED->getTemplateSpecializationKind() !=
18360 }
18361
18362 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18363 // do not keep more that one definition around (merge them).
18364 // However, ensure the decl passes the structural compatibility
18365 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18366 NamedDecl *Hidden = nullptr;
18367 bool HiddenDefVisible = false;
18368 if (SkipBody &&
18369 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18370 getLangOpts().C23)) {
18371 // There is a definition of this tag, but it is not visible.
18372 // We explicitly make use of C++'s one definition rule here,
18373 // and assume that this definition is identical to the hidden
18374 // one we already have. Make the existing definition visible
18375 // and use it in place of this one.
18376 if (!getLangOpts().CPlusPlus) {
18377 // Postpone making the old definition visible until after we
18378 // complete parsing the new one and do the structural
18379 // comparison.
18380 SkipBody->CheckSameAsPrevious = true;
18381 SkipBody->New = createTagFromNewDecl();
18382 SkipBody->Previous = Def;
18383
18384 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18385 return Def;
18386 }
18387
18388 SkipBody->ShouldSkip = true;
18389 SkipBody->Previous = Def;
18390 if (!HiddenDefVisible && Hidden)
18392 // Carry on and handle it like a normal definition. We'll
18393 // skip starting the definition later.
18394
18395 } else if (!IsExplicitSpecializationAfterInstantiation) {
18396 // A redeclaration in function prototype scope in C isn't
18397 // visible elsewhere, so merely issue a warning.
18398 if (!getLangOpts().CPlusPlus &&
18400 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18401 << Name;
18402 else
18403 Diag(NameLoc, diag::err_redefinition) << Name;
18405 NameLoc.isValid() ? NameLoc : KWLoc);
18406 // If this is a redefinition, recover by making this
18407 // struct be anonymous, which will make any later
18408 // references get the previous definition.
18409 Name = nullptr;
18410 Previous.clear();
18411 Invalid = true;
18412 }
18413 }
18414 }
18415
18416 // Okay, this is definition of a previously declared or referenced
18417 // tag. We're going to create a new Decl for it.
18418 }
18419
18420 // Okay, we're going to make a redeclaration. If this is some kind
18421 // of reference, make sure we build the redeclaration in the same DC
18422 // as the original, and ignore the current access specifier.
18423 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18424 SearchDC = PrevTagDecl->getDeclContext();
18425 AS = AS_none;
18426 }
18427 }
18428 // If we get here we have (another) forward declaration or we
18429 // have a definition. Just create a new decl.
18430
18431 } else {
18432 // If we get here, this is a definition of a new tag type in a nested
18433 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18434 // new decl/type. We set PrevDecl to NULL so that the entities
18435 // have distinct types.
18436 Previous.clear();
18437 }
18438 // If we get here, we're going to create a new Decl. If PrevDecl
18439 // is non-NULL, it's a definition of the tag declared by
18440 // PrevDecl. If it's NULL, we have a new definition.
18441
18442 // Otherwise, PrevDecl is not a tag, but was found with tag
18443 // lookup. This is only actually possible in C++, where a few
18444 // things like templates still live in the tag namespace.
18445 } else {
18446 // Use a better diagnostic if an elaborated-type-specifier
18447 // found the wrong kind of type on the first
18448 // (non-redeclaration) lookup.
18449 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18450 !Previous.isForRedeclaration()) {
18451 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18452 Diag(NameLoc, diag::err_tag_reference_non_tag)
18453 << PrevDecl << NTK << Kind;
18454 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18455 Invalid = true;
18456
18457 // Otherwise, only diagnose if the declaration is in scope.
18458 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18459 SS.isNotEmpty() || isMemberSpecialization)) {
18460 // do nothing
18461
18462 // Diagnose implicit declarations introduced by elaborated types.
18463 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18464 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18465 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18466 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18467 Invalid = true;
18468
18469 // Otherwise it's a declaration. Call out a particularly common
18470 // case here.
18471 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18472 unsigned Kind = 0;
18473 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18474 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18475 << Name << Kind << TND->getUnderlyingType();
18476 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18477 Invalid = true;
18478
18479 // Otherwise, diagnose.
18480 } else {
18481 // The tag name clashes with something else in the target scope,
18482 // issue an error and recover by making this tag be anonymous.
18483 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18484 notePreviousDefinition(PrevDecl, NameLoc);
18485 Name = nullptr;
18486 Invalid = true;
18487 }
18488
18489 // The existing declaration isn't relevant to us; we're in a
18490 // new scope, so clear out the previous declaration.
18491 Previous.clear();
18492 }
18493 }
18494
18495CreateNewDecl:
18496
18497 TagDecl *PrevDecl = nullptr;
18498 if (Previous.isSingleResult())
18499 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18500
18501 // If there is an identifier, use the location of the identifier as the
18502 // location of the decl, otherwise use the location of the struct/union
18503 // keyword.
18504 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18505
18506 // Otherwise, create a new declaration. If there is a previous
18507 // declaration of the same entity, the two will be linked via
18508 // PrevDecl.
18509 TagDecl *New;
18510
18511 if (Kind == TagTypeKind::Enum) {
18512 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18513 // enum X { A, B, C } D; D should chain to X.
18514 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18515 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18516 ScopedEnumUsesClassTag, IsFixed);
18517
18520 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18521
18522 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18524
18525 // If this is an undefined enum, warn.
18526 if (TUK != TagUseKind::Definition && !Invalid) {
18527 TagDecl *Def;
18528 if (IsFixed && ED->isFixed()) {
18529 // C++0x: 7.2p2: opaque-enum-declaration.
18530 // Conflicts are diagnosed above. Do nothing.
18531 } else if (PrevDecl &&
18532 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18533 Diag(Loc, diag::ext_forward_ref_enum_def)
18534 << New;
18535 Diag(Def->getLocation(), diag::note_previous_definition);
18536 } else {
18537 unsigned DiagID = diag::ext_forward_ref_enum;
18538 if (getLangOpts().MSVCCompat)
18539 DiagID = diag::ext_ms_forward_ref_enum;
18540 else if (getLangOpts().CPlusPlus)
18541 DiagID = diag::err_forward_ref_enum;
18542 Diag(Loc, DiagID);
18543 }
18544 }
18545
18546 if (EnumUnderlying) {
18548 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18550 else
18551 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18552 QualType EnumTy = ED->getIntegerType();
18553 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18554 ? Context.getPromotedIntegerType(EnumTy)
18555 : EnumTy);
18556 assert(ED->isComplete() && "enum with type should be complete");
18557 }
18558 } else {
18559 // struct/union/class
18560
18561 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18562 // struct X { int A; } D; D should chain to X.
18563 if (getLangOpts().CPlusPlus) {
18564 // FIXME: Look for a way to use RecordDecl for simple structs.
18565 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18566 cast_or_null<CXXRecordDecl>(PrevDecl));
18567
18568 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18570 } else
18571 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18572 cast_or_null<RecordDecl>(PrevDecl));
18573 }
18574
18575 // Only C23 and later allow defining new types in 'offsetof()'.
18576 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18578 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18579 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18580
18581 // C++11 [dcl.type]p3:
18582 // A type-specifier-seq shall not define a class or enumeration [...].
18583 if (!Invalid && getLangOpts().CPlusPlus &&
18584 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18585 TUK == TagUseKind::Definition) {
18586 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18587 << Context.getCanonicalTagType(New);
18588 Invalid = true;
18589 }
18590
18592 DC->getDeclKind() == Decl::Enum) {
18593 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18594 << Context.getCanonicalTagType(New);
18595 Invalid = true;
18596 }
18597
18598 // Maybe add qualifier info.
18599 if (SS.isNotEmpty()) {
18600 if (SS.isSet()) {
18601 // If this is either a declaration or a definition, check the
18602 // nested-name-specifier against the current context.
18603 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18604 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18605 /*TemplateId=*/nullptr,
18606 isMemberSpecialization))
18607 Invalid = true;
18608
18609 New->setQualifierInfo(SS.getWithLocInContext(Context));
18610 if (TemplateParameterLists.size() > 0) {
18611 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18612 }
18613 }
18614 else
18615 Invalid = true;
18616 }
18617
18618 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18619 // Add alignment attributes if necessary; these attributes are checked when
18620 // the ASTContext lays out the structure.
18621 //
18622 // It is important for implementing the correct semantics that this
18623 // happen here (in ActOnTag). The #pragma pack stack is
18624 // maintained as a result of parser callbacks which can occur at
18625 // many points during the parsing of a struct declaration (because
18626 // the #pragma tokens are effectively skipped over during the
18627 // parsing of the struct).
18628 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18629 if (LangOpts.HLSL)
18630 RD->addAttr(PackedAttr::CreateImplicit(Context));
18633 }
18634 }
18635
18636 if (ModulePrivateLoc.isValid()) {
18637 if (isMemberSpecialization)
18638 Diag(New->getLocation(), diag::err_module_private_specialization)
18639 << 2
18640 << FixItHint::CreateRemoval(ModulePrivateLoc);
18641 // __module_private__ does not apply to local classes. However, we only
18642 // diagnose this as an error when the declaration specifiers are
18643 // freestanding. Here, we just ignore the __module_private__.
18644 else if (!SearchDC->isFunctionOrMethod())
18645 New->setModulePrivate();
18646 }
18647
18648 // If this is a specialization of a member class (of a class template),
18649 // check the specialization.
18650 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18651 Invalid = true;
18652
18653 // If we're declaring or defining a tag in function prototype scope in C,
18654 // note that this type can only be used within the function and add it to
18655 // the list of decls to inject into the function definition scope. However,
18656 // in C23 and later, while the type is only visible within the function, the
18657 // function can be called with a compatible type defined in the same TU, so
18658 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18659 if ((Name || Kind == TagTypeKind::Enum) &&
18660 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18661 if (getLangOpts().CPlusPlus) {
18662 // C++ [dcl.fct]p6:
18663 // Types shall not be defined in return or parameter types.
18664 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18665 Diag(Loc, diag::err_type_defined_in_param_type)
18666 << Name;
18667 Invalid = true;
18668 }
18669 if (TUK == TagUseKind::Declaration)
18670 Invalid = true;
18671 } else if (!PrevDecl) {
18672 // In C23 mode, if the declaration is complete, we do not want to
18673 // diagnose.
18674 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18675 Diag(Loc, diag::warn_decl_in_param_list)
18676 << Context.getCanonicalTagType(New);
18677 }
18678 }
18679
18680 if (Invalid)
18681 New->setInvalidDecl();
18682
18683 // Set the lexical context. If the tag has a C++ scope specifier, the
18684 // lexical context will be different from the semantic context.
18685 New->setLexicalDeclContext(CurContext);
18686
18687 // Mark this as a friend decl if applicable.
18688 // In Microsoft mode, a friend declaration also acts as a forward
18689 // declaration so we always pass true to setObjectOfFriendDecl to make
18690 // the tag name visible.
18691 if (TUK == TagUseKind::Friend)
18692 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18693
18694 // Set the access specifier.
18695 if (!Invalid && SearchDC->isRecord())
18696 SetMemberAccessSpecifier(New, PrevDecl, AS);
18697
18698 if (PrevDecl)
18700
18701 if (TUK == TagUseKind::Definition) {
18702 if (!SkipBody || !SkipBody->ShouldSkip) {
18703 New->startDefinition();
18704 } else {
18705 New->setCompleteDefinition();
18706 New->demoteThisDefinitionToDeclaration();
18707 }
18708 }
18709
18710 ProcessDeclAttributeList(S, New, Attrs);
18712
18713 // If this has an identifier, add it to the scope stack.
18714 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18715 // We might be replacing an existing declaration in the lookup tables;
18716 // if so, borrow its access specifier.
18717 if (PrevDecl)
18718 New->setAccess(PrevDecl->getAccess());
18719
18720 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18722 if (Name) // can be null along some error paths
18723 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18724 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18725 } else if (Name) {
18726 S = getNonFieldDeclScope(S);
18727 PushOnScopeChains(New, S, true);
18728 } else {
18729 CurContext->addDecl(New);
18730 }
18731
18732 // If this is the C FILE type, notify the AST context.
18733 if (IdentifierInfo *II = New->getIdentifier())
18734 if (!New->isInvalidDecl() &&
18735 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18736 II->isStr("FILE"))
18737 Context.setFILEDecl(New);
18738
18739 if (PrevDecl)
18740 mergeDeclAttributes(New, PrevDecl);
18741
18742 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18745 }
18746
18747 // If there's a #pragma GCC visibility in scope, set the visibility of this
18748 // record.
18750
18751 // If this is not a definition, process API notes for it now.
18752 if (TUK != TagUseKind::Definition)
18754
18755 if (isMemberSpecialization && !New->isInvalidDecl())
18757
18758 OwnedDecl = true;
18759 // In C++, don't return an invalid declaration. We can't recover well from
18760 // the cases where we make the type anonymous.
18761 if (Invalid && getLangOpts().CPlusPlus) {
18762 if (New->isBeingDefined())
18763 if (auto RD = dyn_cast<RecordDecl>(New))
18764 RD->completeDefinition();
18765 return true;
18766 } else if (SkipBody && SkipBody->ShouldSkip) {
18767 return SkipBody->Previous;
18768 } else {
18769 return New;
18770 }
18771}
18772
18775 TagDecl *Tag = cast<TagDecl>(TagD);
18776
18777 // Enter the tag context.
18778 PushDeclContext(S, Tag);
18779
18781
18782 // If there's a #pragma GCC visibility in scope, set the visibility of this
18783 // record.
18785}
18786
18788 SkipBodyInfo &SkipBody) {
18789 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18790 return false;
18791
18792 // Make the previous decl visible.
18794 CleanupMergedEnum(S, SkipBody.New);
18795 return true;
18796}
18797
18799 SourceLocation FinalLoc,
18800 bool IsFinalSpelledSealed,
18801 bool IsAbstract,
18802 SourceLocation TriviallyRelocatable,
18803 SourceLocation LBraceLoc) {
18806
18807 FieldCollector->StartClass();
18808
18809 if (!Record->getIdentifier())
18810 return;
18811
18812 if (IsAbstract)
18813 Record->markAbstract();
18814
18815 if (FinalLoc.isValid()) {
18816 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18817 IsFinalSpelledSealed
18818 ? FinalAttr::Keyword_sealed
18819 : FinalAttr::Keyword_final));
18820 }
18821
18822 if (TriviallyRelocatable.isValid())
18823 Record->addAttr(
18824 TriviallyRelocatableAttr::Create(Context, TriviallyRelocatable));
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.
Defines helper utilities for supporting the HLSL runtime environment.
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:179
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:234
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:834
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:598
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:617
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:849
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:851
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:790
const LangOptions & getLangOpts() const
Definition ASTContext.h:944
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:909
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:3490
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:3723
QualType getElementType() const
Definition TypeBase.h:3735
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:4507
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4495
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
Expr * getLHS() const
Definition Expr.h:4088
StringRef getOpcodeStr() const
Definition Expr.h:4104
Expr * getRHS() const
Definition Expr.h:4090
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4179
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:3165
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:3147
bool isCallToStdMove() const
Definition Expr.cpp:3623
Expr * getCallee()
Definition Expr.h:3090
arg_range arguments()
Definition Expr.h:3195
CastKind getCastKind() const
Definition Expr.h:3720
Expr * getSubExpr()
Definition Expr.h:3726
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:3761
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:215
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:255
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3817
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:5205
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5237
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5672
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5069
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
unsigned getNumParams() const
Definition TypeBase.h:5547
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5766
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5582
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5554
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:4576
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4688
CallingConv getCC() const
Definition TypeBase.h:4635
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4654
unsigned getRegParm() const
Definition TypeBase.h:4628
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4624
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4647
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4668
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4682
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
ExtInfo getExtInfo() const
Definition TypeBase.h:4821
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3578
unsigned getRegParmType() const
Definition TypeBase.h:4808
CallingConv getCallConv() const
Definition TypeBase.h:4820
QualType getReturnType() const
Definition TypeBase.h:4805
bool getCmseNSCallAttr() const
Definition TypeBase.h:4819
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:3910
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:5498
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:3447
Expr * getBase() const
Definition Expr.h:3441
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
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:3303
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:8111
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:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
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:8377
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8371
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:2921
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:110
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:2970
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8293
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8419
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:8333
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8345
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8387
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:2954
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:8366
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1671
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:8350
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:2695
@ 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:8233
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8240
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4660
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:7455
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:3574
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3151
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3194
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:12432
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12466
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:855
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:13026
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:8230
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6293
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9311
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9315
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9334
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9350
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9347
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9323
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9318
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:4730
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:6485
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)
Preprocessor & getPreprocessor() const
Definition Sema.h:925
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:675
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:923
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:79
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:926
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:699
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:12132
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8348
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:4568
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:921
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:14357
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14360
@ UPPC_Initializer
An initializer.
Definition Sema.h:14372
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14366
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14345
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14384
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14369
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14348
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14351
const LangOptions & getLangOpts() const
Definition Sema.h:919
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2443
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:15435
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:15611
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:6949
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:898
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:4745
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:6946
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:15429
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:9841
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:13905
SourceManager & getSourceManager() const
Definition Sema.h:924
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:6746
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:6507
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:627
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:274
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:4631
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6953
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:9869
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:8303
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:920
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:11564
@ TPC_ClassTemplateMember
Definition Sema.h:11562
@ TPC_FunctionTemplate
Definition Sema.h:11561
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11565
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:6523
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.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation TriviallyRelocatable, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
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:6217
@ AbstractReturnType
Definition Sema.h:6215
@ AbstractFieldType
Definition Sema.h:6218
@ AbstractIvarType
Definition Sema.h:6219
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:8352
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:6404
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:718
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:147
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:8311
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
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8643
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:8264
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:8275
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:679
bool isDependentSizedArrayType() const
Definition TypeBase.h:8649
bool isVoidType() const
Definition TypeBase.h:8892
bool isBooleanType() const
Definition TypeBase.h:9022
bool isFunctionReferenceType() const
Definition TypeBase.h:8604
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9072
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2994
bool isIncompleteArrayType() const
Definition TypeBase.h:8637
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9188
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:8633
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9052
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8629
bool isFunctionPointerType() const
Definition TypeBase.h:8597
bool isPointerType() const
Definition TypeBase.h:8530
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9179
bool isReferenceType() const
Definition TypeBase.h:8554
bool isScalarType() const
Definition TypeBase.h:8994
bool isVariableArrayType() const
Definition TypeBase.h:8641
bool isClkEventT() const
Definition TypeBase.h:8778
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2104
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9010
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:8790
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2900
bool isPipeType() const
Definition TypeBase.h:8797
bool isOpenCLSpecificType() const
Definition TypeBase.h:8826
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2412
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8896
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2057
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2777
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9065
bool isAtomicType() const
Definition TypeBase.h:8718
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isObjCIdType() const
Definition TypeBase.h:8738
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2801
bool isObjCObjectType() const
Definition TypeBase.h:8709
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9028
bool isEventT() const
Definition TypeBase.h:8774
bool isPointerOrReferenceType() const
Definition TypeBase.h:8534
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition TypeBase.h:9129
bool isFunctionType() const
Definition TypeBase.h:8526
bool isObjCObjectPointerType() const
Definition TypeBase.h:8705
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8615
bool isFloatingType() const
Definition Type.cpp:2305
bool isAnyPointerType() const
Definition TypeBase.h:8538
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2062
bool isSamplerT() const
Definition TypeBase.h:8770
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9112
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isNullPtrType() const
Definition TypeBase.h:8929
bool isRecordType() const
Definition TypeBase.h:8657
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5367
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5015
bool isUnionType() const
Definition Type.cpp:719
bool isFunctionNoProtoType() const
Definition TypeBase.h:2600
bool isReserveIDT() const
Definition TypeBase.h:8786
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:6114
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:3967
Expr * getSizeExpr() const
Definition TypeBase.h:3981
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.
constexpr bool isInitializedByPipeline(LangAS AS)
Definition HLSLRuntime.h:34
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:821
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:817
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:813
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:603
@ TemplateTemplateArgument
Definition Sema.h:612
NonTrivialCUnionContext
Definition Sema.h:531
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:627
@ None
Don't merge availability attributes at all.
Definition Sema.h:629
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:635
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:641
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:632
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:638
@ 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:615
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:450
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5893
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5898
@ Struct
The "struct" keyword.
Definition TypeBase.h:5895
@ Class
The "class" keyword.
Definition TypeBase.h:5904
@ Union
The "union" keyword.
Definition TypeBase.h:5901
@ Enum
The "enum" keyword.
Definition TypeBase.h:5907
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:426
@ 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:368
@ Success
Template argument deduction was successful.
Definition Sema.h:370
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:422
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:827
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:5889
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5882
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5886
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:5354
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5381
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5932
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3241
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:354
NamedDecl * Previous
Definition Sema.h:355
NamedDecl * New
Definition Sema.h:356
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